Browse Source
Don't add SRFormer because the code license is incompatible with the GPL. Remove MAT because it's unused and the license is incompatible with GPL.pull/1414/head
comfyanonymous
1 year ago
12 changed files with 2084 additions and 2511 deletions
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,201 @@
|
||||
Apache License |
||||
Version 2.0, January 2004 |
||||
http://www.apache.org/licenses/ |
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION |
||||
|
||||
1. Definitions. |
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, |
||||
and distribution as defined by Sections 1 through 9 of this document. |
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by |
||||
the copyright owner that is granting the License. |
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all |
||||
other entities that control, are controlled by, or are under common |
||||
control with that entity. For the purposes of this definition, |
||||
"control" means (i) the power, direct or indirect, to cause the |
||||
direction or management of such entity, whether by contract or |
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the |
||||
outstanding shares, or (iii) beneficial ownership of such entity. |
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity |
||||
exercising permissions granted by this License. |
||||
|
||||
"Source" form shall mean the preferred form for making modifications, |
||||
including but not limited to software source code, documentation |
||||
source, and configuration files. |
||||
|
||||
"Object" form shall mean any form resulting from mechanical |
||||
transformation or translation of a Source form, including but |
||||
not limited to compiled object code, generated documentation, |
||||
and conversions to other media types. |
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or |
||||
Object form, made available under the License, as indicated by a |
||||
copyright notice that is included in or attached to the work |
||||
(an example is provided in the Appendix below). |
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object |
||||
form, that is based on (or derived from) the Work and for which the |
||||
editorial revisions, annotations, elaborations, or other modifications |
||||
represent, as a whole, an original work of authorship. For the purposes |
||||
of this License, Derivative Works shall not include works that remain |
||||
separable from, or merely link (or bind by name) to the interfaces of, |
||||
the Work and Derivative Works thereof. |
||||
|
||||
"Contribution" shall mean any work of authorship, including |
||||
the original version of the Work and any modifications or additions |
||||
to that Work or Derivative Works thereof, that is intentionally |
||||
submitted to Licensor for inclusion in the Work by the copyright owner |
||||
or by an individual or Legal Entity authorized to submit on behalf of |
||||
the copyright owner. For the purposes of this definition, "submitted" |
||||
means any form of electronic, verbal, or written communication sent |
||||
to the Licensor or its representatives, including but not limited to |
||||
communication on electronic mailing lists, source code control systems, |
||||
and issue tracking systems that are managed by, or on behalf of, the |
||||
Licensor for the purpose of discussing and improving the Work, but |
||||
excluding communication that is conspicuously marked or otherwise |
||||
designated in writing by the copyright owner as "Not a Contribution." |
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity |
||||
on behalf of whom a Contribution has been received by Licensor and |
||||
subsequently incorporated within the Work. |
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of |
||||
this License, each Contributor hereby grants to You a perpetual, |
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
||||
copyright license to reproduce, prepare Derivative Works of, |
||||
publicly display, publicly perform, sublicense, and distribute the |
||||
Work and such Derivative Works in Source or Object form. |
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of |
||||
this License, each Contributor hereby grants to You a perpetual, |
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
||||
(except as stated in this section) patent license to make, have made, |
||||
use, offer to sell, sell, import, and otherwise transfer the Work, |
||||
where such license applies only to those patent claims licensable |
||||
by such Contributor that are necessarily infringed by their |
||||
Contribution(s) alone or by combination of their Contribution(s) |
||||
with the Work to which such Contribution(s) was submitted. If You |
||||
institute patent litigation against any entity (including a |
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work |
||||
or a Contribution incorporated within the Work constitutes direct |
||||
or contributory patent infringement, then any patent licenses |
||||
granted to You under this License for that Work shall terminate |
||||
as of the date such litigation is filed. |
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the |
||||
Work or Derivative Works thereof in any medium, with or without |
||||
modifications, and in Source or Object form, provided that You |
||||
meet the following conditions: |
||||
|
||||
(a) You must give any other recipients of the Work or |
||||
Derivative Works a copy of this License; and |
||||
|
||||
(b) You must cause any modified files to carry prominent notices |
||||
stating that You changed the files; and |
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works |
||||
that You distribute, all copyright, patent, trademark, and |
||||
attribution notices from the Source form of the Work, |
||||
excluding those notices that do not pertain to any part of |
||||
the Derivative Works; and |
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its |
||||
distribution, then any Derivative Works that You distribute must |
||||
include a readable copy of the attribution notices contained |
||||
within such NOTICE file, excluding those notices that do not |
||||
pertain to any part of the Derivative Works, in at least one |
||||
of the following places: within a NOTICE text file distributed |
||||
as part of the Derivative Works; within the Source form or |
||||
documentation, if provided along with the Derivative Works; or, |
||||
within a display generated by the Derivative Works, if and |
||||
wherever such third-party notices normally appear. The contents |
||||
of the NOTICE file are for informational purposes only and |
||||
do not modify the License. You may add Your own attribution |
||||
notices within Derivative Works that You distribute, alongside |
||||
or as an addendum to the NOTICE text from the Work, provided |
||||
that such additional attribution notices cannot be construed |
||||
as modifying the License. |
||||
|
||||
You may add Your own copyright statement to Your modifications and |
||||
may provide additional or different license terms and conditions |
||||
for use, reproduction, or distribution of Your modifications, or |
||||
for any such Derivative Works as a whole, provided Your use, |
||||
reproduction, and distribution of the Work otherwise complies with |
||||
the conditions stated in this License. |
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, |
||||
any Contribution intentionally submitted for inclusion in the Work |
||||
by You to the Licensor shall be under the terms and conditions of |
||||
this License, without any additional terms or conditions. |
||||
Notwithstanding the above, nothing herein shall supersede or modify |
||||
the terms of any separate license agreement you may have executed |
||||
with Licensor regarding such Contributions. |
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade |
||||
names, trademarks, service marks, or product names of the Licensor, |
||||
except as required for reasonable and customary use in describing the |
||||
origin of the Work and reproducing the content of the NOTICE file. |
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or |
||||
agreed to in writing, Licensor provides the Work (and each |
||||
Contributor provides its Contributions) on an "AS IS" BASIS, |
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
||||
implied, including, without limitation, any warranties or conditions |
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A |
||||
PARTICULAR PURPOSE. You are solely responsible for determining the |
||||
appropriateness of using or redistributing the Work and assume any |
||||
risks associated with Your exercise of permissions under this License. |
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, |
||||
whether in tort (including negligence), contract, or otherwise, |
||||
unless required by applicable law (such as deliberate and grossly |
||||
negligent acts) or agreed to in writing, shall any Contributor be |
||||
liable to You for damages, including any direct, indirect, special, |
||||
incidental, or consequential damages of any character arising as a |
||||
result of this License or out of the use or inability to use the |
||||
Work (including but not limited to damages for loss of goodwill, |
||||
work stoppage, computer failure or malfunction, or any and all |
||||
other commercial damages or losses), even if such Contributor |
||||
has been advised of the possibility of such damages. |
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing |
||||
the Work or Derivative Works thereof, You may choose to offer, |
||||
and charge a fee for, acceptance of support, warranty, indemnity, |
||||
or other liability obligations and/or rights consistent with this |
||||
License. However, in accepting such obligations, You may act only |
||||
on Your own behalf and on Your sole responsibility, not on behalf |
||||
of any other Contributor, and only if You agree to indemnify, |
||||
defend, and hold each Contributor harmless for any liability |
||||
incurred by, or claims asserted against, such Contributor by reason |
||||
of your accepting any such warranty or additional liability. |
||||
|
||||
END OF TERMS AND CONDITIONS |
||||
|
||||
APPENDIX: How to apply the Apache License to your work. |
||||
|
||||
To apply the Apache License to your work, attach the following |
||||
boilerplate notice, with the fields enclosed by brackets "[]" |
||||
replaced with your own identifying information. (Don't include |
||||
the brackets!) The text should be enclosed in the appropriate |
||||
comment syntax for the file format. We also recommend that a |
||||
file or class name and description of purpose be included on the |
||||
same "printed page" as the copyright notice for easier |
||||
identification within third-party archives. |
||||
|
||||
Copyright [yyyy] [name of copyright owner] |
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); |
||||
you may not use this file except in compliance with the License. |
||||
You may obtain a copy of the License at |
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0 |
||||
|
||||
Unless required by applicable law or agreed to in writing, software |
||||
distributed under the License is distributed on an "AS IS" BASIS, |
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
See the License for the specific language governing permissions and |
||||
limitations under the License. |
@ -0,0 +1,201 @@
|
||||
Apache License |
||||
Version 2.0, January 2004 |
||||
http://www.apache.org/licenses/ |
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION |
||||
|
||||
1. Definitions. |
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, |
||||
and distribution as defined by Sections 1 through 9 of this document. |
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by |
||||
the copyright owner that is granting the License. |
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all |
||||
other entities that control, are controlled by, or are under common |
||||
control with that entity. For the purposes of this definition, |
||||
"control" means (i) the power, direct or indirect, to cause the |
||||
direction or management of such entity, whether by contract or |
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the |
||||
outstanding shares, or (iii) beneficial ownership of such entity. |
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity |
||||
exercising permissions granted by this License. |
||||
|
||||
"Source" form shall mean the preferred form for making modifications, |
||||
including but not limited to software source code, documentation |
||||
source, and configuration files. |
||||
|
||||
"Object" form shall mean any form resulting from mechanical |
||||
transformation or translation of a Source form, including but |
||||
not limited to compiled object code, generated documentation, |
||||
and conversions to other media types. |
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or |
||||
Object form, made available under the License, as indicated by a |
||||
copyright notice that is included in or attached to the work |
||||
(an example is provided in the Appendix below). |
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object |
||||
form, that is based on (or derived from) the Work and for which the |
||||
editorial revisions, annotations, elaborations, or other modifications |
||||
represent, as a whole, an original work of authorship. For the purposes |
||||
of this License, Derivative Works shall not include works that remain |
||||
separable from, or merely link (or bind by name) to the interfaces of, |
||||
the Work and Derivative Works thereof. |
||||
|
||||
"Contribution" shall mean any work of authorship, including |
||||
the original version of the Work and any modifications or additions |
||||
to that Work or Derivative Works thereof, that is intentionally |
||||
submitted to Licensor for inclusion in the Work by the copyright owner |
||||
or by an individual or Legal Entity authorized to submit on behalf of |
||||
the copyright owner. For the purposes of this definition, "submitted" |
||||
means any form of electronic, verbal, or written communication sent |
||||
to the Licensor or its representatives, including but not limited to |
||||
communication on electronic mailing lists, source code control systems, |
||||
and issue tracking systems that are managed by, or on behalf of, the |
||||
Licensor for the purpose of discussing and improving the Work, but |
||||
excluding communication that is conspicuously marked or otherwise |
||||
designated in writing by the copyright owner as "Not a Contribution." |
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity |
||||
on behalf of whom a Contribution has been received by Licensor and |
||||
subsequently incorporated within the Work. |
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of |
||||
this License, each Contributor hereby grants to You a perpetual, |
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
||||
copyright license to reproduce, prepare Derivative Works of, |
||||
publicly display, publicly perform, sublicense, and distribute the |
||||
Work and such Derivative Works in Source or Object form. |
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of |
||||
this License, each Contributor hereby grants to You a perpetual, |
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
||||
(except as stated in this section) patent license to make, have made, |
||||
use, offer to sell, sell, import, and otherwise transfer the Work, |
||||
where such license applies only to those patent claims licensable |
||||
by such Contributor that are necessarily infringed by their |
||||
Contribution(s) alone or by combination of their Contribution(s) |
||||
with the Work to which such Contribution(s) was submitted. If You |
||||
institute patent litigation against any entity (including a |
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work |
||||
or a Contribution incorporated within the Work constitutes direct |
||||
or contributory patent infringement, then any patent licenses |
||||
granted to You under this License for that Work shall terminate |
||||
as of the date such litigation is filed. |
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the |
||||
Work or Derivative Works thereof in any medium, with or without |
||||
modifications, and in Source or Object form, provided that You |
||||
meet the following conditions: |
||||
|
||||
(a) You must give any other recipients of the Work or |
||||
Derivative Works a copy of this License; and |
||||
|
||||
(b) You must cause any modified files to carry prominent notices |
||||
stating that You changed the files; and |
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works |
||||
that You distribute, all copyright, patent, trademark, and |
||||
attribution notices from the Source form of the Work, |
||||
excluding those notices that do not pertain to any part of |
||||
the Derivative Works; and |
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its |
||||
distribution, then any Derivative Works that You distribute must |
||||
include a readable copy of the attribution notices contained |
||||
within such NOTICE file, excluding those notices that do not |
||||
pertain to any part of the Derivative Works, in at least one |
||||
of the following places: within a NOTICE text file distributed |
||||
as part of the Derivative Works; within the Source form or |
||||
documentation, if provided along with the Derivative Works; or, |
||||
within a display generated by the Derivative Works, if and |
||||
wherever such third-party notices normally appear. The contents |
||||
of the NOTICE file are for informational purposes only and |
||||
do not modify the License. You may add Your own attribution |
||||
notices within Derivative Works that You distribute, alongside |
||||
or as an addendum to the NOTICE text from the Work, provided |
||||
that such additional attribution notices cannot be construed |
||||
as modifying the License. |
||||
|
||||
You may add Your own copyright statement to Your modifications and |
||||
may provide additional or different license terms and conditions |
||||
for use, reproduction, or distribution of Your modifications, or |
||||
for any such Derivative Works as a whole, provided Your use, |
||||
reproduction, and distribution of the Work otherwise complies with |
||||
the conditions stated in this License. |
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, |
||||
any Contribution intentionally submitted for inclusion in the Work |
||||
by You to the Licensor shall be under the terms and conditions of |
||||
this License, without any additional terms or conditions. |
||||
Notwithstanding the above, nothing herein shall supersede or modify |
||||
the terms of any separate license agreement you may have executed |
||||
with Licensor regarding such Contributions. |
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade |
||||
names, trademarks, service marks, or product names of the Licensor, |
||||
except as required for reasonable and customary use in describing the |
||||
origin of the Work and reproducing the content of the NOTICE file. |
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or |
||||
agreed to in writing, Licensor provides the Work (and each |
||||
Contributor provides its Contributions) on an "AS IS" BASIS, |
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
||||
implied, including, without limitation, any warranties or conditions |
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A |
||||
PARTICULAR PURPOSE. You are solely responsible for determining the |
||||
appropriateness of using or redistributing the Work and assume any |
||||
risks associated with Your exercise of permissions under this License. |
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, |
||||
whether in tort (including negligence), contract, or otherwise, |
||||
unless required by applicable law (such as deliberate and grossly |
||||
negligent acts) or agreed to in writing, shall any Contributor be |
||||
liable to You for damages, including any direct, indirect, special, |
||||
incidental, or consequential damages of any character arising as a |
||||
result of this License or out of the use or inability to use the |
||||
Work (including but not limited to damages for loss of goodwill, |
||||
work stoppage, computer failure or malfunction, or any and all |
||||
other commercial damages or losses), even if such Contributor |
||||
has been advised of the possibility of such damages. |
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing |
||||
the Work or Derivative Works thereof, You may choose to offer, |
||||
and charge a fee for, acceptance of support, warranty, indemnity, |
||||
or other liability obligations and/or rights consistent with this |
||||
License. However, in accepting such obligations, You may act only |
||||
on Your own behalf and on Your sole responsibility, not on behalf |
||||
of any other Contributor, and only if You agree to indemnify, |
||||
defend, and hold each Contributor harmless for any liability |
||||
incurred by, or claims asserted against, such Contributor by reason |
||||
of your accepting any such warranty or additional liability. |
||||
|
||||
END OF TERMS AND CONDITIONS |
||||
|
||||
APPENDIX: How to apply the Apache License to your work. |
||||
|
||||
To apply the Apache License to your work, attach the following |
||||
boilerplate notice, with the fields enclosed by brackets "[]" |
||||
replaced with your own identifying information. (Don't include |
||||
the brackets!) The text should be enclosed in the appropriate |
||||
comment syntax for the file format. We also recommend that a |
||||
file or class name and description of purpose be included on the |
||||
same "printed page" as the copyright notice for easier |
||||
identification within third-party archives. |
||||
|
||||
Copyright 2022 Kai Zhang (cskaizhang@gmail.com, https://cszn.github.io/). All rights reserved. |
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); |
||||
you may not use this file except in compliance with the License. |
||||
You may obtain a copy of the License at |
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0 |
||||
|
||||
Unless required by applicable law or agreed to in writing, software |
||||
distributed under the License is distributed on an "AS IS" BASIS, |
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
See the License for the specific language governing permissions and |
||||
limitations under the License. |
@ -1,161 +0,0 @@
|
||||
## creative commons |
||||
|
||||
# Attribution-NonCommercial 4.0 International |
||||
|
||||
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. |
||||
|
||||
### Using Creative Commons Public Licenses |
||||
|
||||
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. |
||||
|
||||
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). |
||||
|
||||
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). |
||||
|
||||
## Creative Commons Attribution-NonCommercial 4.0 International Public License |
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. |
||||
|
||||
### Section 1 – Definitions. |
||||
|
||||
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. |
||||
|
||||
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. |
||||
|
||||
c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. |
||||
|
||||
d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. |
||||
|
||||
e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. |
||||
|
||||
f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. |
||||
|
||||
g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. |
||||
|
||||
h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. |
||||
|
||||
i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. |
||||
|
||||
j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. |
||||
|
||||
k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. |
||||
|
||||
l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. |
||||
|
||||
### Section 2 – Scope. |
||||
|
||||
a. ___License grant.___ |
||||
|
||||
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: |
||||
|
||||
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and |
||||
|
||||
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. |
||||
|
||||
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. |
||||
|
||||
3. __Term.__ The term of this Public License is specified in Section 6(a). |
||||
|
||||
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. |
||||
|
||||
5. __Downstream recipients.__ |
||||
|
||||
A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. |
||||
|
||||
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. |
||||
|
||||
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). |
||||
|
||||
b. ___Other rights.___ |
||||
|
||||
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. |
||||
|
||||
2. Patent and trademark rights are not licensed under this Public License. |
||||
|
||||
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. |
||||
|
||||
### Section 3 – License Conditions. |
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the following conditions. |
||||
|
||||
a. ___Attribution.___ |
||||
|
||||
1. If You Share the Licensed Material (including in modified form), You must: |
||||
|
||||
A. retain the following if it is supplied by the Licensor with the Licensed Material: |
||||
|
||||
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); |
||||
|
||||
ii. a copyright notice; |
||||
|
||||
iii. a notice that refers to this Public License; |
||||
|
||||
iv. a notice that refers to the disclaimer of warranties; |
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; |
||||
|
||||
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and |
||||
|
||||
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. |
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. |
||||
|
||||
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. |
||||
|
||||
4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. |
||||
|
||||
### Section 4 – Sui Generis Database Rights. |
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: |
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; |
||||
|
||||
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and |
||||
|
||||
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. |
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. |
||||
|
||||
### Section 5 – Disclaimer of Warranties and Limitation of Liability. |
||||
|
||||
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ |
||||
|
||||
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ |
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. |
||||
|
||||
### Section 6 – Term and Termination. |
||||
|
||||
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. |
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: |
||||
|
||||
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or |
||||
|
||||
2. upon express reinstatement by the Licensor. |
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. |
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. |
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. |
||||
|
||||
### Section 7 – Other Terms and Conditions. |
||||
|
||||
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. |
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. |
||||
|
||||
### Section 8 – Interpretation. |
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. |
||||
|
||||
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. |
||||
|
||||
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. |
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. |
||||
|
||||
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. |
||||
> |
||||
> Creative Commons may be contacted at creativecommons.org |
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,455 @@
|
||||
# pylint: skip-file |
||||
# ----------------------------------------------------------------------------------- |
||||
# SCUNet: Practical Blind Denoising via Swin-Conv-UNet and Data Synthesis, https://arxiv.org/abs/2203.13278 |
||||
# Zhang, Kai and Li, Yawei and Liang, Jingyun and Cao, Jiezhang and Zhang, Yulun and Tang, Hao and Timofte, Radu and Van Gool, Luc |
||||
# ----------------------------------------------------------------------------------- |
||||
|
||||
import numpy as np |
||||
import torch |
||||
import torch.nn as nn |
||||
import torch.nn.functional as F |
||||
from einops import rearrange |
||||
from einops.layers.torch import Rearrange |
||||
|
||||
from .timm.drop import DropPath |
||||
from .timm.weight_init import trunc_normal_ |
||||
|
||||
|
||||
# Borrowed from https://github.com/cszn/SCUNet/blob/main/models/network_scunet.py |
||||
class WMSA(nn.Module): |
||||
"""Self-attention module in Swin Transformer""" |
||||
|
||||
def __init__(self, input_dim, output_dim, head_dim, window_size, type): |
||||
super(WMSA, self).__init__() |
||||
self.input_dim = input_dim |
||||
self.output_dim = output_dim |
||||
self.head_dim = head_dim |
||||
self.scale = self.head_dim**-0.5 |
||||
self.n_heads = input_dim // head_dim |
||||
self.window_size = window_size |
||||
self.type = type |
||||
self.embedding_layer = nn.Linear(self.input_dim, 3 * self.input_dim, bias=True) |
||||
|
||||
self.relative_position_params = nn.Parameter( |
||||
torch.zeros((2 * window_size - 1) * (2 * window_size - 1), self.n_heads) |
||||
) |
||||
# TODO recover |
||||
# self.relative_position_params = nn.Parameter(torch.zeros(self.n_heads, 2 * window_size - 1, 2 * window_size -1)) |
||||
self.relative_position_params = nn.Parameter( |
||||
torch.zeros((2 * window_size - 1) * (2 * window_size - 1), self.n_heads) |
||||
) |
||||
|
||||
self.linear = nn.Linear(self.input_dim, self.output_dim) |
||||
|
||||
trunc_normal_(self.relative_position_params, std=0.02) |
||||
self.relative_position_params = torch.nn.Parameter( |
||||
self.relative_position_params.view( |
||||
2 * window_size - 1, 2 * window_size - 1, self.n_heads |
||||
) |
||||
.transpose(1, 2) |
||||
.transpose(0, 1) |
||||
) |
||||
|
||||
def generate_mask(self, h, w, p, shift): |
||||
"""generating the mask of SW-MSA |
||||
Args: |
||||
shift: shift parameters in CyclicShift. |
||||
Returns: |
||||
attn_mask: should be (1 1 w p p), |
||||
""" |
||||
# supporting square. |
||||
attn_mask = torch.zeros( |
||||
h, |
||||
w, |
||||
p, |
||||
p, |
||||
p, |
||||
p, |
||||
dtype=torch.bool, |
||||
device=self.relative_position_params.device, |
||||
) |
||||
if self.type == "W": |
||||
return attn_mask |
||||
|
||||
s = p - shift |
||||
attn_mask[-1, :, :s, :, s:, :] = True |
||||
attn_mask[-1, :, s:, :, :s, :] = True |
||||
attn_mask[:, -1, :, :s, :, s:] = True |
||||
attn_mask[:, -1, :, s:, :, :s] = True |
||||
attn_mask = rearrange( |
||||
attn_mask, "w1 w2 p1 p2 p3 p4 -> 1 1 (w1 w2) (p1 p2) (p3 p4)" |
||||
) |
||||
return attn_mask |
||||
|
||||
def forward(self, x): |
||||
"""Forward pass of Window Multi-head Self-attention module. |
||||
Args: |
||||
x: input tensor with shape of [b h w c]; |
||||
attn_mask: attention mask, fill -inf where the value is True; |
||||
Returns: |
||||
output: tensor shape [b h w c] |
||||
""" |
||||
if self.type != "W": |
||||
x = torch.roll( |
||||
x, |
||||
shifts=(-(self.window_size // 2), -(self.window_size // 2)), |
||||
dims=(1, 2), |
||||
) |
||||
|
||||
x = rearrange( |
||||
x, |
||||
"b (w1 p1) (w2 p2) c -> b w1 w2 p1 p2 c", |
||||
p1=self.window_size, |
||||
p2=self.window_size, |
||||
) |
||||
h_windows = x.size(1) |
||||
w_windows = x.size(2) |
||||
# square validation |
||||
# assert h_windows == w_windows |
||||
|
||||
x = rearrange( |
||||
x, |
||||
"b w1 w2 p1 p2 c -> b (w1 w2) (p1 p2) c", |
||||
p1=self.window_size, |
||||
p2=self.window_size, |
||||
) |
||||
qkv = self.embedding_layer(x) |
||||
q, k, v = rearrange( |
||||
qkv, "b nw np (threeh c) -> threeh b nw np c", c=self.head_dim |
||||
).chunk(3, dim=0) |
||||
sim = torch.einsum("hbwpc,hbwqc->hbwpq", q, k) * self.scale |
||||
# Adding learnable relative embedding |
||||
sim = sim + rearrange(self.relative_embedding(), "h p q -> h 1 1 p q") |
||||
# Using Attn Mask to distinguish different subwindows. |
||||
if self.type != "W": |
||||
attn_mask = self.generate_mask( |
||||
h_windows, w_windows, self.window_size, shift=self.window_size // 2 |
||||
) |
||||
sim = sim.masked_fill_(attn_mask, float("-inf")) |
||||
|
||||
probs = nn.functional.softmax(sim, dim=-1) |
||||
output = torch.einsum("hbwij,hbwjc->hbwic", probs, v) |
||||
output = rearrange(output, "h b w p c -> b w p (h c)") |
||||
output = self.linear(output) |
||||
output = rearrange( |
||||
output, |
||||
"b (w1 w2) (p1 p2) c -> b (w1 p1) (w2 p2) c", |
||||
w1=h_windows, |
||||
p1=self.window_size, |
||||
) |
||||
|
||||
if self.type != "W": |
||||
output = torch.roll( |
||||
output, |
||||
shifts=(self.window_size // 2, self.window_size // 2), |
||||
dims=(1, 2), |
||||
) |
||||
|
||||
return output |
||||
|
||||
def relative_embedding(self): |
||||
cord = torch.tensor( |
||||
np.array( |
||||
[ |
||||
[i, j] |
||||
for i in range(self.window_size) |
||||
for j in range(self.window_size) |
||||
] |
||||
) |
||||
) |
||||
relation = cord[:, None, :] - cord[None, :, :] + self.window_size - 1 |
||||
# negative is allowed |
||||
return self.relative_position_params[ |
||||
:, relation[:, :, 0].long(), relation[:, :, 1].long() |
||||
] |
||||
|
||||
|
||||
class Block(nn.Module): |
||||
def __init__( |
||||
self, |
||||
input_dim, |
||||
output_dim, |
||||
head_dim, |
||||
window_size, |
||||
drop_path, |
||||
type="W", |
||||
input_resolution=None, |
||||
): |
||||
"""SwinTransformer Block""" |
||||
super(Block, self).__init__() |
||||
self.input_dim = input_dim |
||||
self.output_dim = output_dim |
||||
assert type in ["W", "SW"] |
||||
self.type = type |
||||
if input_resolution <= window_size: |
||||
self.type = "W" |
||||
|
||||
self.ln1 = nn.LayerNorm(input_dim) |
||||
self.msa = WMSA(input_dim, input_dim, head_dim, window_size, self.type) |
||||
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() |
||||
self.ln2 = nn.LayerNorm(input_dim) |
||||
self.mlp = nn.Sequential( |
||||
nn.Linear(input_dim, 4 * input_dim), |
||||
nn.GELU(), |
||||
nn.Linear(4 * input_dim, output_dim), |
||||
) |
||||
|
||||
def forward(self, x): |
||||
x = x + self.drop_path(self.msa(self.ln1(x))) |
||||
x = x + self.drop_path(self.mlp(self.ln2(x))) |
||||
return x |
||||
|
||||
|
||||
class ConvTransBlock(nn.Module): |
||||
def __init__( |
||||
self, |
||||
conv_dim, |
||||
trans_dim, |
||||
head_dim, |
||||
window_size, |
||||
drop_path, |
||||
type="W", |
||||
input_resolution=None, |
||||
): |
||||
"""SwinTransformer and Conv Block""" |
||||
super(ConvTransBlock, self).__init__() |
||||
self.conv_dim = conv_dim |
||||
self.trans_dim = trans_dim |
||||
self.head_dim = head_dim |
||||
self.window_size = window_size |
||||
self.drop_path = drop_path |
||||
self.type = type |
||||
self.input_resolution = input_resolution |
||||
|
||||
assert self.type in ["W", "SW"] |
||||
if self.input_resolution <= self.window_size: |
||||
self.type = "W" |
||||
|
||||
self.trans_block = Block( |
||||
self.trans_dim, |
||||
self.trans_dim, |
||||
self.head_dim, |
||||
self.window_size, |
||||
self.drop_path, |
||||
self.type, |
||||
self.input_resolution, |
||||
) |
||||
self.conv1_1 = nn.Conv2d( |
||||
self.conv_dim + self.trans_dim, |
||||
self.conv_dim + self.trans_dim, |
||||
1, |
||||
1, |
||||
0, |
||||
bias=True, |
||||
) |
||||
self.conv1_2 = nn.Conv2d( |
||||
self.conv_dim + self.trans_dim, |
||||
self.conv_dim + self.trans_dim, |
||||
1, |
||||
1, |
||||
0, |
||||
bias=True, |
||||
) |
||||
|
||||
self.conv_block = nn.Sequential( |
||||
nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False), |
||||
nn.ReLU(True), |
||||
nn.Conv2d(self.conv_dim, self.conv_dim, 3, 1, 1, bias=False), |
||||
) |
||||
|
||||
def forward(self, x): |
||||
conv_x, trans_x = torch.split( |
||||
self.conv1_1(x), (self.conv_dim, self.trans_dim), dim=1 |
||||
) |
||||
conv_x = self.conv_block(conv_x) + conv_x |
||||
trans_x = Rearrange("b c h w -> b h w c")(trans_x) |
||||
trans_x = self.trans_block(trans_x) |
||||
trans_x = Rearrange("b h w c -> b c h w")(trans_x) |
||||
res = self.conv1_2(torch.cat((conv_x, trans_x), dim=1)) |
||||
x = x + res |
||||
|
||||
return x |
||||
|
||||
|
||||
class SCUNet(nn.Module): |
||||
def __init__( |
||||
self, |
||||
state_dict, |
||||
in_nc=3, |
||||
config=[4, 4, 4, 4, 4, 4, 4], |
||||
dim=64, |
||||
drop_path_rate=0.0, |
||||
input_resolution=256, |
||||
): |
||||
super(SCUNet, self).__init__() |
||||
self.model_arch = "SCUNet" |
||||
self.sub_type = "SR" |
||||
|
||||
self.num_filters: int = 0 |
||||
|
||||
self.state = state_dict |
||||
self.config = config |
||||
self.dim = dim |
||||
self.head_dim = 32 |
||||
self.window_size = 8 |
||||
|
||||
self.in_nc = in_nc |
||||
self.out_nc = self.in_nc |
||||
self.scale = 1 |
||||
self.supports_fp16 = True |
||||
|
||||
# drop path rate for each layer |
||||
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(config))] |
||||
|
||||
self.m_head = [nn.Conv2d(in_nc, dim, 3, 1, 1, bias=False)] |
||||
|
||||
begin = 0 |
||||
self.m_down1 = [ |
||||
ConvTransBlock( |
||||
dim // 2, |
||||
dim // 2, |
||||
self.head_dim, |
||||
self.window_size, |
||||
dpr[i + begin], |
||||
"W" if not i % 2 else "SW", |
||||
input_resolution, |
||||
) |
||||
for i in range(config[0]) |
||||
] + [nn.Conv2d(dim, 2 * dim, 2, 2, 0, bias=False)] |
||||
|
||||
begin += config[0] |
||||
self.m_down2 = [ |
||||
ConvTransBlock( |
||||
dim, |
||||
dim, |
||||
self.head_dim, |
||||
self.window_size, |
||||
dpr[i + begin], |
||||
"W" if not i % 2 else "SW", |
||||
input_resolution // 2, |
||||
) |
||||
for i in range(config[1]) |
||||
] + [nn.Conv2d(2 * dim, 4 * dim, 2, 2, 0, bias=False)] |
||||
|
||||
begin += config[1] |
||||
self.m_down3 = [ |
||||
ConvTransBlock( |
||||
2 * dim, |
||||
2 * dim, |
||||
self.head_dim, |
||||
self.window_size, |
||||
dpr[i + begin], |
||||
"W" if not i % 2 else "SW", |
||||
input_resolution // 4, |
||||
) |
||||
for i in range(config[2]) |
||||
] + [nn.Conv2d(4 * dim, 8 * dim, 2, 2, 0, bias=False)] |
||||
|
||||
begin += config[2] |
||||
self.m_body = [ |
||||
ConvTransBlock( |
||||
4 * dim, |
||||
4 * dim, |
||||
self.head_dim, |
||||
self.window_size, |
||||
dpr[i + begin], |
||||
"W" if not i % 2 else "SW", |
||||
input_resolution // 8, |
||||
) |
||||
for i in range(config[3]) |
||||
] |
||||
|
||||
begin += config[3] |
||||
self.m_up3 = [ |
||||
nn.ConvTranspose2d(8 * dim, 4 * dim, 2, 2, 0, bias=False), |
||||
] + [ |
||||
ConvTransBlock( |
||||
2 * dim, |
||||
2 * dim, |
||||
self.head_dim, |
||||
self.window_size, |
||||
dpr[i + begin], |
||||
"W" if not i % 2 else "SW", |
||||
input_resolution // 4, |
||||
) |
||||
for i in range(config[4]) |
||||
] |
||||
|
||||
begin += config[4] |
||||
self.m_up2 = [ |
||||
nn.ConvTranspose2d(4 * dim, 2 * dim, 2, 2, 0, bias=False), |
||||
] + [ |
||||
ConvTransBlock( |
||||
dim, |
||||
dim, |
||||
self.head_dim, |
||||
self.window_size, |
||||
dpr[i + begin], |
||||
"W" if not i % 2 else "SW", |
||||
input_resolution // 2, |
||||
) |
||||
for i in range(config[5]) |
||||
] |
||||
|
||||
begin += config[5] |
||||
self.m_up1 = [ |
||||
nn.ConvTranspose2d(2 * dim, dim, 2, 2, 0, bias=False), |
||||
] + [ |
||||
ConvTransBlock( |
||||
dim // 2, |
||||
dim // 2, |
||||
self.head_dim, |
||||
self.window_size, |
||||
dpr[i + begin], |
||||
"W" if not i % 2 else "SW", |
||||
input_resolution, |
||||
) |
||||
for i in range(config[6]) |
||||
] |
||||
|
||||
self.m_tail = [nn.Conv2d(dim, in_nc, 3, 1, 1, bias=False)] |
||||
|
||||
self.m_head = nn.Sequential(*self.m_head) |
||||
self.m_down1 = nn.Sequential(*self.m_down1) |
||||
self.m_down2 = nn.Sequential(*self.m_down2) |
||||
self.m_down3 = nn.Sequential(*self.m_down3) |
||||
self.m_body = nn.Sequential(*self.m_body) |
||||
self.m_up3 = nn.Sequential(*self.m_up3) |
||||
self.m_up2 = nn.Sequential(*self.m_up2) |
||||
self.m_up1 = nn.Sequential(*self.m_up1) |
||||
self.m_tail = nn.Sequential(*self.m_tail) |
||||
# self.apply(self._init_weights) |
||||
self.load_state_dict(state_dict, strict=True) |
||||
|
||||
def check_image_size(self, x): |
||||
_, _, h, w = x.size() |
||||
mod_pad_h = (64 - h % 64) % 64 |
||||
mod_pad_w = (64 - w % 64) % 64 |
||||
x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), "reflect") |
||||
return x |
||||
|
||||
def forward(self, x0): |
||||
h, w = x0.size()[-2:] |
||||
x0 = self.check_image_size(x0) |
||||
|
||||
x1 = self.m_head(x0) |
||||
x2 = self.m_down1(x1) |
||||
x3 = self.m_down2(x2) |
||||
x4 = self.m_down3(x3) |
||||
x = self.m_body(x4) |
||||
x = self.m_up3(x + x4) |
||||
x = self.m_up2(x + x3) |
||||
x = self.m_up1(x + x2) |
||||
x = self.m_tail(x + x1) |
||||
|
||||
x = x[:, :, :h, :w] |
||||
return x |
||||
|
||||
def _init_weights(self, m): |
||||
if isinstance(m, nn.Linear): |
||||
trunc_normal_(m.weight, std=0.02) |
||||
if 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) |
@ -1,698 +0,0 @@
|
||||
"""Code used for this implementation of the MAT helper utils is modified from |
||||
lama-cleaner, copyright of Sanster: https://github.com/fenglinglwb/MAT""" |
||||
|
||||
import collections |
||||
from itertools import repeat |
||||
from typing import Any |
||||
|
||||
import numpy as np |
||||
import torch |
||||
from torch import conv2d, conv_transpose2d |
||||
|
||||
|
||||
def normalize_2nd_moment(x, dim=1, eps=1e-8): |
||||
return x * (x.square().mean(dim=dim, keepdim=True) + eps).rsqrt() |
||||
|
||||
|
||||
class EasyDict(dict): |
||||
"""Convenience class that behaves like a dict but allows access with the attribute syntax.""" |
||||
|
||||
def __getattr__(self, name: str) -> Any: |
||||
try: |
||||
return self[name] |
||||
except KeyError: |
||||
raise AttributeError(name) |
||||
|
||||
def __setattr__(self, name: str, value: Any) -> None: |
||||
self[name] = value |
||||
|
||||
def __delattr__(self, name: str) -> None: |
||||
del self[name] |
||||
|
||||
|
||||
activation_funcs = { |
||||
"linear": EasyDict( |
||||
func=lambda x, **_: x, |
||||
def_alpha=0, |
||||
def_gain=1, |
||||
cuda_idx=1, |
||||
ref="", |
||||
has_2nd_grad=False, |
||||
), |
||||
"relu": EasyDict( |
||||
func=lambda x, **_: torch.nn.functional.relu(x), |
||||
def_alpha=0, |
||||
def_gain=np.sqrt(2), |
||||
cuda_idx=2, |
||||
ref="y", |
||||
has_2nd_grad=False, |
||||
), |
||||
"lrelu": EasyDict( |
||||
func=lambda x, alpha, **_: torch.nn.functional.leaky_relu(x, alpha), |
||||
def_alpha=0.2, |
||||
def_gain=np.sqrt(2), |
||||
cuda_idx=3, |
||||
ref="y", |
||||
has_2nd_grad=False, |
||||
), |
||||
"tanh": EasyDict( |
||||
func=lambda x, **_: torch.tanh(x), |
||||
def_alpha=0, |
||||
def_gain=1, |
||||
cuda_idx=4, |
||||
ref="y", |
||||
has_2nd_grad=True, |
||||
), |
||||
"sigmoid": EasyDict( |
||||
func=lambda x, **_: torch.sigmoid(x), |
||||
def_alpha=0, |
||||
def_gain=1, |
||||
cuda_idx=5, |
||||
ref="y", |
||||
has_2nd_grad=True, |
||||
), |
||||
"elu": EasyDict( |
||||
func=lambda x, **_: torch.nn.functional.elu(x), |
||||
def_alpha=0, |
||||
def_gain=1, |
||||
cuda_idx=6, |
||||
ref="y", |
||||
has_2nd_grad=True, |
||||
), |
||||
"selu": EasyDict( |
||||
func=lambda x, **_: torch.nn.functional.selu(x), |
||||
def_alpha=0, |
||||
def_gain=1, |
||||
cuda_idx=7, |
||||
ref="y", |
||||
has_2nd_grad=True, |
||||
), |
||||
"softplus": EasyDict( |
||||
func=lambda x, **_: torch.nn.functional.softplus(x), |
||||
def_alpha=0, |
||||
def_gain=1, |
||||
cuda_idx=8, |
||||
ref="y", |
||||
has_2nd_grad=True, |
||||
), |
||||
"swish": EasyDict( |
||||
func=lambda x, **_: torch.sigmoid(x) * x, |
||||
def_alpha=0, |
||||
def_gain=np.sqrt(2), |
||||
cuda_idx=9, |
||||
ref="x", |
||||
has_2nd_grad=True, |
||||
), |
||||
} |
||||
|
||||
|
||||
def _bias_act_ref(x, b=None, dim=1, act="linear", alpha=None, gain=None, clamp=None): |
||||
"""Slow reference implementation of `bias_act()` using standard TensorFlow ops.""" |
||||
assert isinstance(x, torch.Tensor) |
||||
assert clamp is None or clamp >= 0 |
||||
spec = activation_funcs[act] |
||||
alpha = float(alpha if alpha is not None else spec.def_alpha) |
||||
gain = float(gain if gain is not None else spec.def_gain) |
||||
clamp = float(clamp if clamp is not None else -1) |
||||
|
||||
# Add bias. |
||||
if b is not None: |
||||
assert isinstance(b, torch.Tensor) and b.ndim == 1 |
||||
assert 0 <= dim < x.ndim |
||||
assert b.shape[0] == x.shape[dim] |
||||
x = x + b.reshape([-1 if i == dim else 1 for i in range(x.ndim)]).to(x.device) |
||||
|
||||
# Evaluate activation function. |
||||
alpha = float(alpha) |
||||
x = spec.func(x, alpha=alpha) |
||||
|
||||
# Scale by gain. |
||||
gain = float(gain) |
||||
if gain != 1: |
||||
x = x * gain |
||||
|
||||
# Clamp. |
||||
if clamp >= 0: |
||||
x = x.clamp(-clamp, clamp) # pylint: disable=invalid-unary-operand-type |
||||
return x |
||||
|
||||
|
||||
def bias_act( |
||||
x, b=None, dim=1, act="linear", alpha=None, gain=None, clamp=None, impl="ref" |
||||
): |
||||
r"""Fused bias and activation function. |
||||
Adds bias `b` to activation tensor `x`, evaluates activation function `act`, |
||||
and scales the result by `gain`. Each of the steps is optional. In most cases, |
||||
the fused op is considerably more efficient than performing the same calculation |
||||
using standard PyTorch ops. It supports first and second order gradients, |
||||
but not third order gradients. |
||||
Args: |
||||
x: Input activation tensor. Can be of any shape. |
||||
b: Bias vector, or `None` to disable. Must be a 1D tensor of the same type |
||||
as `x`. The shape must be known, and it must match the dimension of `x` |
||||
corresponding to `dim`. |
||||
dim: The dimension in `x` corresponding to the elements of `b`. |
||||
The value of `dim` is ignored if `b` is not specified. |
||||
act: Name of the activation function to evaluate, or `"linear"` to disable. |
||||
Can be e.g. `"relu"`, `"lrelu"`, `"tanh"`, `"sigmoid"`, `"swish"`, etc. |
||||
See `activation_funcs` for a full list. `None` is not allowed. |
||||
alpha: Shape parameter for the activation function, or `None` to use the default. |
||||
gain: Scaling factor for the output tensor, or `None` to use default. |
||||
See `activation_funcs` for the default scaling of each activation function. |
||||
If unsure, consider specifying 1. |
||||
clamp: Clamp the output values to `[-clamp, +clamp]`, or `None` to disable |
||||
the clamping (default). |
||||
impl: Name of the implementation to use. Can be `"ref"` or `"cuda"` (default). |
||||
Returns: |
||||
Tensor of the same shape and datatype as `x`. |
||||
""" |
||||
assert isinstance(x, torch.Tensor) |
||||
assert impl in ["ref", "cuda"] |
||||
return _bias_act_ref( |
||||
x=x, b=b, dim=dim, act=act, alpha=alpha, gain=gain, clamp=clamp |
||||
) |
||||
|
||||
|
||||
def setup_filter( |
||||
f, |
||||
device=torch.device("cpu"), |
||||
normalize=True, |
||||
flip_filter=False, |
||||
gain=1, |
||||
separable=None, |
||||
): |
||||
r"""Convenience function to setup 2D FIR filter for `upfirdn2d()`. |
||||
Args: |
||||
f: Torch tensor, numpy array, or python list of the shape |
||||
`[filter_height, filter_width]` (non-separable), |
||||
`[filter_taps]` (separable), |
||||
`[]` (impulse), or |
||||
`None` (identity). |
||||
device: Result device (default: cpu). |
||||
normalize: Normalize the filter so that it retains the magnitude |
||||
for constant input signal (DC)? (default: True). |
||||
flip_filter: Flip the filter? (default: False). |
||||
gain: Overall scaling factor for signal magnitude (default: 1). |
||||
separable: Return a separable filter? (default: select automatically). |
||||
Returns: |
||||
Float32 tensor of the shape |
||||
`[filter_height, filter_width]` (non-separable) or |
||||
`[filter_taps]` (separable). |
||||
""" |
||||
# Validate. |
||||
if f is None: |
||||
f = 1 |
||||
f = torch.as_tensor(f, dtype=torch.float32) |
||||
assert f.ndim in [0, 1, 2] |
||||
assert f.numel() > 0 |
||||
if f.ndim == 0: |
||||
f = f[np.newaxis] |
||||
|
||||
# Separable? |
||||
if separable is None: |
||||
separable = f.ndim == 1 and f.numel() >= 8 |
||||
if f.ndim == 1 and not separable: |
||||
f = f.ger(f) |
||||
assert f.ndim == (1 if separable else 2) |
||||
|
||||
# Apply normalize, flip, gain, and device. |
||||
if normalize: |
||||
f /= f.sum() |
||||
if flip_filter: |
||||
f = f.flip(list(range(f.ndim))) |
||||
f = f * (gain ** (f.ndim / 2)) |
||||
f = f.to(device=device) |
||||
return f |
||||
|
||||
|
||||
def _get_filter_size(f): |
||||
if f is None: |
||||
return 1, 1 |
||||
|
||||
assert isinstance(f, torch.Tensor) and f.ndim in [1, 2] |
||||
fw = f.shape[-1] |
||||
fh = f.shape[0] |
||||
|
||||
fw = int(fw) |
||||
fh = int(fh) |
||||
assert fw >= 1 and fh >= 1 |
||||
return fw, fh |
||||
|
||||
|
||||
def _get_weight_shape(w): |
||||
shape = [int(sz) for sz in w.shape] |
||||
return shape |
||||
|
||||
|
||||
def _parse_scaling(scaling): |
||||
if isinstance(scaling, int): |
||||
scaling = [scaling, scaling] |
||||
assert isinstance(scaling, (list, tuple)) |
||||
assert all(isinstance(x, int) for x in scaling) |
||||
sx, sy = scaling |
||||
assert sx >= 1 and sy >= 1 |
||||
return sx, sy |
||||
|
||||
|
||||
def _parse_padding(padding): |
||||
if isinstance(padding, int): |
||||
padding = [padding, padding] |
||||
assert isinstance(padding, (list, tuple)) |
||||
assert all(isinstance(x, int) for x in padding) |
||||
if len(padding) == 2: |
||||
padx, pady = padding |
||||
padding = [padx, padx, pady, pady] |
||||
padx0, padx1, pady0, pady1 = padding |
||||
return padx0, padx1, pady0, pady1 |
||||
|
||||
|
||||
def _ntuple(n): |
||||
def parse(x): |
||||
if isinstance(x, collections.abc.Iterable): |
||||
return x |
||||
return tuple(repeat(x, n)) |
||||
|
||||
return parse |
||||
|
||||
|
||||
to_2tuple = _ntuple(2) |
||||
|
||||
|
||||
def _upfirdn2d_ref(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1): |
||||
"""Slow reference implementation of `upfirdn2d()` using standard PyTorch ops.""" |
||||
# Validate arguments. |
||||
assert isinstance(x, torch.Tensor) and x.ndim == 4 |
||||
if f is None: |
||||
f = torch.ones([1, 1], dtype=torch.float32, device=x.device) |
||||
assert isinstance(f, torch.Tensor) and f.ndim in [1, 2] |
||||
assert f.dtype == torch.float32 and not f.requires_grad |
||||
batch_size, num_channels, in_height, in_width = x.shape |
||||
# upx, upy = _parse_scaling(up) |
||||
# downx, downy = _parse_scaling(down) |
||||
|
||||
upx, upy = up, up |
||||
downx, downy = down, down |
||||
|
||||
# padx0, padx1, pady0, pady1 = _parse_padding(padding) |
||||
padx0, padx1, pady0, pady1 = padding[0], padding[1], padding[2], padding[3] |
||||
|
||||
# Upsample by inserting zeros. |
||||
x = x.reshape([batch_size, num_channels, in_height, 1, in_width, 1]) |
||||
x = torch.nn.functional.pad(x, [0, upx - 1, 0, 0, 0, upy - 1]) |
||||
x = x.reshape([batch_size, num_channels, in_height * upy, in_width * upx]) |
||||
|
||||
# Pad or crop. |
||||
x = torch.nn.functional.pad( |
||||
x, [max(padx0, 0), max(padx1, 0), max(pady0, 0), max(pady1, 0)] |
||||
) |
||||
x = x[ |
||||
:, |
||||
:, |
||||
max(-pady0, 0) : x.shape[2] - max(-pady1, 0), |
||||
max(-padx0, 0) : x.shape[3] - max(-padx1, 0), |
||||
] |
||||
|
||||
# Setup filter. |
||||
f = f * (gain ** (f.ndim / 2)) |
||||
f = f.to(x.dtype) |
||||
if not flip_filter: |
||||
f = f.flip(list(range(f.ndim))) |
||||
|
||||
# Convolve with the filter. |
||||
f = f[np.newaxis, np.newaxis].repeat([num_channels, 1] + [1] * f.ndim) |
||||
if f.ndim == 4: |
||||
x = conv2d(input=x, weight=f, groups=num_channels) |
||||
else: |
||||
x = conv2d(input=x, weight=f.unsqueeze(2), groups=num_channels) |
||||
x = conv2d(input=x, weight=f.unsqueeze(3), groups=num_channels) |
||||
|
||||
# Downsample by throwing away pixels. |
||||
x = x[:, :, ::downy, ::downx] |
||||
return x |
||||
|
||||
|
||||
def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1, impl="cuda"): |
||||
r"""Pad, upsample, filter, and downsample a batch of 2D images. |
||||
Performs the following sequence of operations for each channel: |
||||
1. Upsample the image by inserting N-1 zeros after each pixel (`up`). |
||||
2. Pad the image with the specified number of zeros on each side (`padding`). |
||||
Negative padding corresponds to cropping the image. |
||||
3. Convolve the image with the specified 2D FIR filter (`f`), shrinking it |
||||
so that the footprint of all output pixels lies within the input image. |
||||
4. Downsample the image by keeping every Nth pixel (`down`). |
||||
This sequence of operations bears close resemblance to scipy.signal.upfirdn(). |
||||
The fused op is considerably more efficient than performing the same calculation |
||||
using standard PyTorch ops. It supports gradients of arbitrary order. |
||||
Args: |
||||
x: Float32/float64/float16 input tensor of the shape |
||||
`[batch_size, num_channels, in_height, in_width]`. |
||||
f: Float32 FIR filter of the shape |
||||
`[filter_height, filter_width]` (non-separable), |
||||
`[filter_taps]` (separable), or |
||||
`None` (identity). |
||||
up: Integer upsampling factor. Can be a single int or a list/tuple |
||||
`[x, y]` (default: 1). |
||||
down: Integer downsampling factor. Can be a single int or a list/tuple |
||||
`[x, y]` (default: 1). |
||||
padding: Padding with respect to the upsampled image. Can be a single number |
||||
or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` |
||||
(default: 0). |
||||
flip_filter: False = convolution, True = correlation (default: False). |
||||
gain: Overall scaling factor for signal magnitude (default: 1). |
||||
impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). |
||||
Returns: |
||||
Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. |
||||
""" |
||||
# assert isinstance(x, torch.Tensor) |
||||
# assert impl in ['ref', 'cuda'] |
||||
return _upfirdn2d_ref( |
||||
x, f, up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain |
||||
) |
||||
|
||||
|
||||
def upsample2d(x, f, up=2, padding=0, flip_filter=False, gain=1, impl="cuda"): |
||||
r"""Upsample a batch of 2D images using the given 2D FIR filter. |
||||
By default, the result is padded so that its shape is a multiple of the input. |
||||
User-specified padding is applied on top of that, with negative values |
||||
indicating cropping. Pixels outside the image are assumed to be zero. |
||||
Args: |
||||
x: Float32/float64/float16 input tensor of the shape |
||||
`[batch_size, num_channels, in_height, in_width]`. |
||||
f: Float32 FIR filter of the shape |
||||
`[filter_height, filter_width]` (non-separable), |
||||
`[filter_taps]` (separable), or |
||||
`None` (identity). |
||||
up: Integer upsampling factor. Can be a single int or a list/tuple |
||||
`[x, y]` (default: 1). |
||||
padding: Padding with respect to the output. Can be a single number or a |
||||
list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` |
||||
(default: 0). |
||||
flip_filter: False = convolution, True = correlation (default: False). |
||||
gain: Overall scaling factor for signal magnitude (default: 1). |
||||
impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). |
||||
Returns: |
||||
Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. |
||||
""" |
||||
upx, upy = _parse_scaling(up) |
||||
# upx, upy = up, up |
||||
padx0, padx1, pady0, pady1 = _parse_padding(padding) |
||||
# padx0, padx1, pady0, pady1 = padding, padding, padding, padding |
||||
fw, fh = _get_filter_size(f) |
||||
p = [ |
||||
padx0 + (fw + upx - 1) // 2, |
||||
padx1 + (fw - upx) // 2, |
||||
pady0 + (fh + upy - 1) // 2, |
||||
pady1 + (fh - upy) // 2, |
||||
] |
||||
return upfirdn2d( |
||||
x, |
||||
f, |
||||
up=up, |
||||
padding=p, |
||||
flip_filter=flip_filter, |
||||
gain=gain * upx * upy, |
||||
impl=impl, |
||||
) |
||||
|
||||
|
||||
class FullyConnectedLayer(torch.nn.Module): |
||||
def __init__( |
||||
self, |
||||
in_features, # Number of input features. |
||||
out_features, # Number of output features. |
||||
bias=True, # Apply additive bias before the activation function? |
||||
activation="linear", # Activation function: 'relu', 'lrelu', etc. |
||||
lr_multiplier=1, # Learning rate multiplier. |
||||
bias_init=0, # Initial value for the additive bias. |
||||
): |
||||
super().__init__() |
||||
self.weight = torch.nn.Parameter( |
||||
torch.randn([out_features, in_features]) / lr_multiplier |
||||
) |
||||
self.bias = ( |
||||
torch.nn.Parameter(torch.full([out_features], np.float32(bias_init))) |
||||
if bias |
||||
else None |
||||
) |
||||
self.activation = activation |
||||
|
||||
self.weight_gain = lr_multiplier / np.sqrt(in_features) |
||||
self.bias_gain = lr_multiplier |
||||
|
||||
def forward(self, x): |
||||
w = self.weight * self.weight_gain |
||||
b = self.bias |
||||
if b is not None and self.bias_gain != 1: |
||||
b = b * self.bias_gain |
||||
|
||||
if self.activation == "linear" and b is not None: |
||||
# out = torch.addmm(b.unsqueeze(0), x, w.t()) |
||||
x = x.matmul(w.t().to(x.device)) |
||||
out = x + b.reshape( |
||||
[-1 if i == x.ndim - 1 else 1 for i in range(x.ndim)] |
||||
).to(x.device) |
||||
else: |
||||
x = x.matmul(w.t().to(x.device)) |
||||
out = bias_act(x, b, act=self.activation, dim=x.ndim - 1).to(x.device) |
||||
return out |
||||
|
||||
|
||||
def _conv2d_wrapper( |
||||
x, w, stride=1, padding=0, groups=1, transpose=False, flip_weight=True |
||||
): |
||||
"""Wrapper for the underlying `conv2d()` and `conv_transpose2d()` implementations.""" |
||||
out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w) |
||||
|
||||
# Flip weight if requested. |
||||
if ( |
||||
not flip_weight |
||||
): # conv2d() actually performs correlation (flip_weight=True) not convolution (flip_weight=False). |
||||
w = w.flip([2, 3]) |
||||
|
||||
# Workaround performance pitfall in cuDNN 8.0.5, triggered when using |
||||
# 1x1 kernel + memory_format=channels_last + less than 64 channels. |
||||
if ( |
||||
kw == 1 |
||||
and kh == 1 |
||||
and stride == 1 |
||||
and padding in [0, [0, 0], (0, 0)] |
||||
and not transpose |
||||
): |
||||
if x.stride()[1] == 1 and min(out_channels, in_channels_per_group) < 64: |
||||
if out_channels <= 4 and groups == 1: |
||||
in_shape = x.shape |
||||
x = w.squeeze(3).squeeze(2) @ x.reshape( |
||||
[in_shape[0], in_channels_per_group, -1] |
||||
) |
||||
x = x.reshape([in_shape[0], out_channels, in_shape[2], in_shape[3]]) |
||||
else: |
||||
x = x.to(memory_format=torch.contiguous_format) |
||||
w = w.to(memory_format=torch.contiguous_format) |
||||
x = conv2d(x, w, groups=groups) |
||||
return x.to(memory_format=torch.channels_last) |
||||
|
||||
# Otherwise => execute using conv2d_gradfix. |
||||
op = conv_transpose2d if transpose else conv2d |
||||
return op(x, w, stride=stride, padding=padding, groups=groups) |
||||
|
||||
|
||||
def conv2d_resample( |
||||
x, w, f=None, up=1, down=1, padding=0, groups=1, flip_weight=True, flip_filter=False |
||||
): |
||||
r"""2D convolution with optional up/downsampling. |
||||
Padding is performed only once at the beginning, not between the operations. |
||||
Args: |
||||
x: Input tensor of shape |
||||
`[batch_size, in_channels, in_height, in_width]`. |
||||
w: Weight tensor of shape |
||||
`[out_channels, in_channels//groups, kernel_height, kernel_width]`. |
||||
f: Low-pass filter for up/downsampling. Must be prepared beforehand by |
||||
calling setup_filter(). None = identity (default). |
||||
up: Integer upsampling factor (default: 1). |
||||
down: Integer downsampling factor (default: 1). |
||||
padding: Padding with respect to the upsampled image. Can be a single number |
||||
or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` |
||||
(default: 0). |
||||
groups: Split input channels into N groups (default: 1). |
||||
flip_weight: False = convolution, True = correlation (default: True). |
||||
flip_filter: False = convolution, True = correlation (default: False). |
||||
Returns: |
||||
Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. |
||||
""" |
||||
# Validate arguments. |
||||
assert isinstance(x, torch.Tensor) and (x.ndim == 4) |
||||
assert isinstance(w, torch.Tensor) and (w.ndim == 4) and (w.dtype == x.dtype) |
||||
assert f is None or ( |
||||
isinstance(f, torch.Tensor) and f.ndim in [1, 2] and f.dtype == torch.float32 |
||||
) |
||||
assert isinstance(up, int) and (up >= 1) |
||||
assert isinstance(down, int) and (down >= 1) |
||||
# assert isinstance(groups, int) and (groups >= 1), f"!!!!!! groups: {groups} isinstance(groups, int) {isinstance(groups, int)} {type(groups)}" |
||||
out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w) |
||||
fw, fh = _get_filter_size(f) |
||||
# px0, px1, py0, py1 = _parse_padding(padding) |
||||
px0, px1, py0, py1 = padding, padding, padding, padding |
||||
|
||||
# Adjust padding to account for up/downsampling. |
||||
if up > 1: |
||||
px0 += (fw + up - 1) // 2 |
||||
px1 += (fw - up) // 2 |
||||
py0 += (fh + up - 1) // 2 |
||||
py1 += (fh - up) // 2 |
||||
if down > 1: |
||||
px0 += (fw - down + 1) // 2 |
||||
px1 += (fw - down) // 2 |
||||
py0 += (fh - down + 1) // 2 |
||||
py1 += (fh - down) // 2 |
||||
|
||||
# Fast path: 1x1 convolution with downsampling only => downsample first, then convolve. |
||||
if kw == 1 and kh == 1 and (down > 1 and up == 1): |
||||
x = upfirdn2d( |
||||
x=x, f=f, down=down, padding=[px0, px1, py0, py1], flip_filter=flip_filter |
||||
) |
||||
x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) |
||||
return x |
||||
|
||||
# Fast path: 1x1 convolution with upsampling only => convolve first, then upsample. |
||||
if kw == 1 and kh == 1 and (up > 1 and down == 1): |
||||
x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) |
||||
x = upfirdn2d( |
||||
x=x, |
||||
f=f, |
||||
up=up, |
||||
padding=[px0, px1, py0, py1], |
||||
gain=up**2, |
||||
flip_filter=flip_filter, |
||||
) |
||||
return x |
||||
|
||||
# Fast path: downsampling only => use strided convolution. |
||||
if down > 1 and up == 1: |
||||
x = upfirdn2d(x=x, f=f, padding=[px0, px1, py0, py1], flip_filter=flip_filter) |
||||
x = _conv2d_wrapper( |
||||
x=x, w=w, stride=down, groups=groups, flip_weight=flip_weight |
||||
) |
||||
return x |
||||
|
||||
# Fast path: upsampling with optional downsampling => use transpose strided convolution. |
||||
if up > 1: |
||||
if groups == 1: |
||||
w = w.transpose(0, 1) |
||||
else: |
||||
w = w.reshape(groups, out_channels // groups, in_channels_per_group, kh, kw) |
||||
w = w.transpose(1, 2) |
||||
w = w.reshape( |
||||
groups * in_channels_per_group, out_channels // groups, kh, kw |
||||
) |
||||
px0 -= kw - 1 |
||||
px1 -= kw - up |
||||
py0 -= kh - 1 |
||||
py1 -= kh - up |
||||
pxt = max(min(-px0, -px1), 0) |
||||
pyt = max(min(-py0, -py1), 0) |
||||
x = _conv2d_wrapper( |
||||
x=x, |
||||
w=w, |
||||
stride=up, |
||||
padding=[pyt, pxt], |
||||
groups=groups, |
||||
transpose=True, |
||||
flip_weight=(not flip_weight), |
||||
) |
||||
x = upfirdn2d( |
||||
x=x, |
||||
f=f, |
||||
padding=[px0 + pxt, px1 + pxt, py0 + pyt, py1 + pyt], |
||||
gain=up**2, |
||||
flip_filter=flip_filter, |
||||
) |
||||
if down > 1: |
||||
x = upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter) |
||||
return x |
||||
|
||||
# Fast path: no up/downsampling, padding supported by the underlying implementation => use plain conv2d. |
||||
if up == 1 and down == 1: |
||||
if px0 == px1 and py0 == py1 and px0 >= 0 and py0 >= 0: |
||||
return _conv2d_wrapper( |
||||
x=x, w=w, padding=[py0, px0], groups=groups, flip_weight=flip_weight |
||||
) |
||||
|
||||
# Fallback: Generic reference implementation. |
||||
x = upfirdn2d( |
||||
x=x, |
||||
f=(f if up > 1 else None), |
||||
up=up, |
||||
padding=[px0, px1, py0, py1], |
||||
gain=up**2, |
||||
flip_filter=flip_filter, |
||||
) |
||||
x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) |
||||
if down > 1: |
||||
x = upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter) |
||||
return x |
||||
|
||||
|
||||
class Conv2dLayer(torch.nn.Module): |
||||
def __init__( |
||||
self, |
||||
in_channels, # Number of input channels. |
||||
out_channels, # Number of output channels. |
||||
kernel_size, # Width and height of the convolution kernel. |
||||
bias=True, # Apply additive bias before the activation function? |
||||
activation="linear", # Activation function: 'relu', 'lrelu', etc. |
||||
up=1, # Integer upsampling factor. |
||||
down=1, # Integer downsampling factor. |
||||
resample_filter=[ |
||||
1, |
||||
3, |
||||
3, |
||||
1, |
||||
], # Low-pass filter to apply when resampling activations. |
||||
conv_clamp=None, # Clamp the output to +-X, None = disable clamping. |
||||
channels_last=False, # Expect the input to have memory_format=channels_last? |
||||
trainable=True, # Update the weights of this layer during training? |
||||
): |
||||
super().__init__() |
||||
self.activation = activation |
||||
self.up = up |
||||
self.down = down |
||||
self.register_buffer("resample_filter", setup_filter(resample_filter)) |
||||
self.conv_clamp = conv_clamp |
||||
self.padding = kernel_size // 2 |
||||
self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2)) |
||||
self.act_gain = activation_funcs[activation].def_gain |
||||
|
||||
memory_format = ( |
||||
torch.channels_last if channels_last else torch.contiguous_format |
||||
) |
||||
weight = torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to( |
||||
memory_format=memory_format |
||||
) |
||||
bias = torch.zeros([out_channels]) if bias else None |
||||
if trainable: |
||||
self.weight = torch.nn.Parameter(weight) |
||||
self.bias = torch.nn.Parameter(bias) if bias is not None else None |
||||
else: |
||||
self.register_buffer("weight", weight) |
||||
if bias is not None: |
||||
self.register_buffer("bias", bias) |
||||
else: |
||||
self.bias = None |
||||
|
||||
def forward(self, x, gain=1): |
||||
w = self.weight * self.weight_gain |
||||
x = conv2d_resample( |
||||
x=x, |
||||
w=w, |
||||
f=self.resample_filter, |
||||
up=self.up, |
||||
down=self.down, |
||||
padding=self.padding, |
||||
) |
||||
|
||||
act_gain = self.act_gain * gain |
||||
act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None |
||||
out = bias_act( |
||||
x, self.bias, act=self.activation, gain=act_gain, clamp=act_clamp |
||||
) |
||||
return out |
Loading…
Reference in new issue