Showing preview only (587K chars total). Download the full file or copy to clipboard to get everything.
Repository: JCBrouwer/maua-stylegan2
Branch: master
Commit: 7f9282141053
Files: 86
Total size: 560.8 KB
Directory structure:
gitextract_lesmzkyd/
├── .gitignore
├── LICENSE/
│ ├── LICENSE-AUDIOREACTIVE
│ ├── LICENSE-AUTOENCODER
│ ├── LICENSE-CONTRASTIVE-LEARNER
│ ├── LICENSE-FID
│ ├── LICENSE-LPIPS
│ ├── LICENSE-LUCIDRAINS
│ ├── LICENSE-NVIDIA
│ ├── LICENSE-ROSINALITY
│ └── LICENSE-VGG
├── README.md
├── accelerate/
│ ├── accelerate_inception.py
│ ├── accelerate_logcosh.py
│ └── accelerate_segnet.py
├── audioreactive/
│ ├── __init__.py
│ ├── bend.py
│ ├── examples/
│ │ ├── __init__.py
│ │ ├── default.py
│ │ ├── kelp.py
│ │ ├── tauceti.py
│ │ └── temper.py
│ ├── latent.py
│ ├── signal.py
│ └── util.py
├── augment.py
├── contrastive_learner.py
├── convert_weight.py
├── dataset.py
├── distributed.py
├── generate.py
├── generate_audiovisual.py
├── generate_video.py
├── gpu_profile.py
├── gpumon.py
├── lightning.py
├── lookahead_minimax.py
├── lucidrains.py
├── models/
│ ├── autoencoder.py
│ ├── stylegan1.py
│ └── stylegan2.py
├── op/
│ ├── __init__.py
│ ├── fused_act.py
│ ├── fused_bias_act.cpp
│ ├── fused_bias_act_kernel.cu
│ ├── upfirdn2d.cpp
│ ├── upfirdn2d.py
│ └── upfirdn2d_kernel.cu
├── prepare_data.py
├── prepare_vae_codes.py
├── projector.py
├── render.py
├── requirements.txt
├── select_latents.py
├── train.py
├── train_profile.py
├── validation/
│ ├── __init__.py
│ ├── calc_fid.py
│ ├── calc_inception.py
│ ├── calc_ppl.py
│ ├── inception.py
│ ├── lpips/
│ │ ├── __init__.py
│ │ ├── base_model.py
│ │ ├── dist_model.py
│ │ ├── networks_basic.py
│ │ ├── pretrained_networks.py
│ │ ├── util.py
│ │ └── weights/
│ │ ├── v0.0/
│ │ │ ├── alex.pth
│ │ │ ├── squeeze.pth
│ │ │ └── vgg.pth
│ │ └── v0.1/
│ │ ├── alex.pth
│ │ ├── squeeze.pth
│ │ └── vgg.pth
│ ├── metrics.py
│ └── spectral_norm.py
└── workspace/
├── naamloos_average_pitch.npy
├── naamloos_bass_sum.npy
├── naamloos_drop_latents.npy
├── naamloos_drop_latents_1.npy
├── naamloos_high_average_pitch.npy
├── naamloos_high_pitches_mean.npy
├── naamloos_intro_latents.npy
├── naamloos_metadata.json
├── naamloos_onsets.npy
├── naamloos_params.json
├── naamloos_pitches_mean.npy
└── naamloos_rms.npy
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
pretrained_models/
wandb
wandb/
*.lmdb/
*.pkl
checkpoints/
maua-stylegan/
.vscode
output/
workspace/*
!workspace
output/*
!output
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
================================================
FILE: LICENSE/LICENSE-AUDIOREACTIVE
================================================
Code for Audio-reactive Latent Interpolations with StyleGAN
Including the folder audioreactive/, generate_audiovisual.py, generate_video.py, select_latents.py, and render.py
Copyright (C) 2020 Hans Brouwer
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.
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
================================================
FILE: LICENSE/LICENSE-AUTOENCODER
================================================
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.
================================================
FILE: LICENSE/LICENSE-CONTRASTIVE-LEARNER
================================================
MIT License
Copyright (c) 2020 Phil Wang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: LICENSE/LICENSE-FID
================================================
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.
================================================
FILE: LICENSE/LICENSE-LPIPS
================================================
Copyright (c) 2018, Richard Zhang, Phillip Isola, Alexei A. Efros, Eli Shechtman, Oliver Wang
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: LICENSE/LICENSE-LUCIDRAINS
================================================
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>.
================================================
FILE: LICENSE/LICENSE-NVIDIA
================================================
Copyright (c) 2019, NVIDIA Corporation. All rights reserved.
Nvidia Source Code License-NC
=======================================================================
1. Definitions
"Licensor" means any person or entity that distributes its Work.
"Software" means the original work of authorship made available under
this License.
"Work" means the Software and any additions to or derivative works of
the Software that are made available under this License.
"Nvidia Processors" means any central processing unit (CPU), graphics
processing unit (GPU), field-programmable gate array (FPGA),
application-specific integrated circuit (ASIC) or any combination
thereof designed, made, sold, or provided by Nvidia or its affiliates.
The terms "reproduce," "reproduction," "derivative works," and
"distribution" have the meaning as provided under U.S. copyright law;
provided, however, that 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.
Works, including the Software, are "made available" under this License
by including in or with the Work either (a) a copyright notice
referencing the applicability of this License to the Work, or (b) a
copy of this License.
2. License Grants
2.1 Copyright Grant. Subject to the terms and conditions of this
License, each Licensor grants to you a perpetual, worldwide,
non-exclusive, royalty-free, copyright license to reproduce,
prepare derivative works of, publicly display, publicly perform,
sublicense and distribute its Work and any resulting derivative
works in any form.
3. Limitations
3.1 Redistribution. You may reproduce or distribute the Work only
if (a) you do so under this License, (b) you include a complete
copy of this License with your distribution, and (c) you retain
without modification any copyright, patent, trademark, or
attribution notices that are present in the Work.
3.2 Derivative Works. You may specify that additional or different
terms apply to the use, reproduction, and distribution of your
derivative works of the Work ("Your Terms") only if (a) Your Terms
provide that the use limitation in Section 3.3 applies to your
derivative works, and (b) you identify the specific derivative
works that are subject to Your Terms. Notwithstanding Your Terms,
this License (including the redistribution requirements in Section
3.1) will continue to apply to the Work itself.
3.3 Use Limitation. The Work and any derivative works thereof only
may be used or intended for use non-commercially. The Work or
derivative works thereof may be used or intended for use by Nvidia
or its affiliates commercially or non-commercially. As used herein,
"non-commercially" means for research or evaluation purposes only.
3.4 Patent Claims. If you bring or threaten to bring a patent claim
against any Licensor (including any claim, cross-claim or
counterclaim in a lawsuit) to enforce any patents that you allege
are infringed by any Work, then your rights under this License from
such Licensor (including the grants in Sections 2.1 and 2.2) will
terminate immediately.
3.5 Trademarks. This License does not grant any rights to use any
Licensor's or its affiliates' names, logos, or trademarks, except
as necessary to reproduce the notices described in this License.
3.6 Termination. If you violate any term of this License, then your
rights under this License (including the grants in Sections 2.1 and
2.2) will terminate immediately.
4. Disclaimer of Warranty.
THE WORK IS PROVIDED "AS IS" WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR
NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER
THIS LICENSE.
5. Limitation of Liability.
EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL
THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE
SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF
OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK
(INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION,
LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER
COMMERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF
THE POSSIBILITY OF SUCH DAMAGES.
=======================================================================
================================================
FILE: LICENSE/LICENSE-ROSINALITY
================================================
MIT License
Copyright (c) 2019 Kim Seonghyeon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: LICENSE/LICENSE-VGG
================================================
Copyright (C) 2019 NVIDIA Corporation. Ting-Chun Wang, Ming-Yu Liu, Jun-Yan Zhu.
BSD License. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY PARTICULAR PURPOSE.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------- LICENSE FOR pytorch-CycleGAN-and-pix2pix ----------------
Copyright (c) 2017, Jun-Yan Zhu and Taesung Park
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: README.md
================================================
# maua-stylegan2
This is the repo for my experiments with StyleGAN2. There are many like it, but this one is mine.
It contains the code for [Audio-reactive Latent Interpolations with StyleGAN](https://wavefunk.xyz/assets/audio-reactive-stylegan/paper.pdf) for the NeurIPS 2020 [Workshop on Machine Learning for Creativity and Design](https://neurips2020creativity.github.io/).
The original base is [Kim Seonghyeon's excellent implementation](https://github.com/rosinality/stylegan2-pytorch), but I've gathered code from multiple different repositories or other places online and hacked/grafted it all together. License information for the code should all be in the LICENSE folder, but if you find anything missing or incorrect please let me know and I'll fix it immediately. Tread carefully when trying to distribute any code from this repo, it's meant for research and demonstration.
The files/folders of interest and their purpose are:
| File/Folder | Description
| :--- | :----------
| generate_audiovisual.py | used to generate audio-reactive interpolations
| audioreactive/ | contains the main functions needed for audioreactiveness + examples demonstrating how they can be used
| render.py | renders interpolations using ffmpeg
| select_latents.py | GUI for selecting latents, left click to add to top set, right click to add to bottom
| models/ | StyleGAN networks
| workspace/ | place to store intermediate results, latents, or inputs, etc.
| output/ | default generated output folder
| train.py | code for training models
The rest of the code is experimental, probably broken, and unsupported.
## Installation
```bash
git clone https://github.com/JCBrouwer/maua-stylegan2
cd maua-stylegan2
pip install -r requirements.txt
```
Alternatively, check out this [Colab Notebook](https://colab.research.google.com/drive/1Ig1EXfmBC01qik11Q32P0ZffFtNipiBR)
## Generating audio-reactive interpolations
The simplest way to get started is to try either (in shell):
```bash
python generate_audiovisual.py --ckpt "/path/to/model.pt" --audio_file "/path/to/audio.wav"
```
or (in e.g. a jupyter notebook):
```python
from generate_audiovisual import generate
generate("/path/to/model.pt", "/path/to/audio.wav")
```
This will use the default audio-reactive settings (which aren't great).
To customize the generated interpolation, more functions can be defined to generate latents, noise, network bends, model rewrites, and truncation.
```python
import audioreactive as ar
from generate_audiovisual import generate
def initialize(args):
args.onsets = ar.onsets(args.audio, args.sr, ...)
args.chroma = ar.chroma(args.audio, args.sr, ...)
return args
def get_latents(selection, args):
latents = ar.chroma_weight_latents(args.chroma, selection)
return latents
def get_noise(height, width, scale, num_scales, args):
noise = ar.perlin_noise(...)
noise *= 1 + args.onsets
return noise
generate(ckpt="/path/to/model.pt", audio_file="/path/to/audio.wav", initialize=initialize, get_latents=get_latents, get_noise=get_noise)
```
When running from command line, the `generate()` call at the end can be left out and the interpolation can be generated with:
```bash
python generate_audiovisual.py --ckpt "/path/to/model.pt" --audio_file "/path/to/audio.wav" --audioreactive_file "/path/to/the/code_above.py"
```
This lets you change arguments on the command line rather than having to add them to the `generate()` call in you python file (use whatever you prefer).
Within these functions, you can execute any python code to make the inputs to the network react to the music. There are a number of useful functions provided in `audioreactive/` (imported above as `ar`).
Examples showing how to use the library and demonstrating some of the techniques discussed in the paper can be found in `audioreactive/examples/`. A playlist with example results can be found [here](https://www.youtube.com/watch?v=2LxHRGppdpA&list=PLkain1QGMwiWndQwr3U4shvNpoFC21E3a).
One important thing to note is that the outputs of the functions must adhere strictly to the expected formats.
Each of the functions is called with all of the arguments from the command line (or `generate()`) in the `args` variable. On top of the arguments, `args` also contains:
- audio: raw audio signal
- sr: sampling rate of audio
- n_frames: total number of interpolation frames
- duration: length of audio in seconds
```python
def initialize(args):
# intialize values used in multiple of the following functions here
# e.g. onsets, chroma, RMS, segmentations, bpms, etc.
# this is useful to prevent duplicate computations (get_noise is called for each noise size)
# remember to store them back in args
...
return args
def get_latents(selection, args):
# selection holds some latent vectors (generated randomly or from a file)
# generate an audioreactive latent tensor of shape [n_frames, layers, latent_dim]
...
return latents
def get_noise(height, width, scale, num_scales, args):
# height and width are the spatial dimensions of the current noise layer
# scale is the index and num_scales the total number of noise layers
# generate an audioreactive noise tensor of shape [n_frames, 1, height, width]
...
return noise
def get_bends(args):
# generate a list of dictionaries specifying network bends
# these must follow one of two forms:
#
# either: {
# "layer": layer index to apply bend to,
# "transform": torch.nn.Module that applies the transformation,
# }
# or: {
# "layer": layer index to apply bend to,
# "modulation": time dependent modulation of the transformation, shape=(n_frames, ...),
# "transform": function that takes a batch of modulation and returns a torch.nn.Module
# that applies the transformation (given the modulation batch),
# }
# (The second one is technical debt in a nutshell. It's a workaround to get kornia transforms
# to play nicely. You're probably better off using the first option with a th.nn.Module that
# has its modulation as an attribute and keeps count of which frame it's rendering internally).
...
return bends
def get_rewrites(args):
# generate a dictionary specifying model rewrites
# each key value pair should follow:
# param_name -> [transform, modulation]
# where: param_name is the fully-qualified parameter name (see generator.named_children())
# transform & modulation follow the form of the second network bending dict option above
...
return rewrites
def get_truncation(args):
# generate a sequence of truncation values of shape (n_frames,)
...
return truncation
```
The arguments to `generate_audiovisual.py` are as follows. The first two are required, and the remaining are optional.
```bash
generate_audiovisual.py
--ckpt CKPT # path to model checkpoint
--audio_file AUDIO_FILE # path to audio file to react to
--audioreactive_file AUDIOREACTIVE_FILE # file with audio-reactive functions defined (as above)
--output_dir OUTPUT_DIR # path to output dir
--offset OFFSET # starting time in audio in seconds (defaults to 0)
--duration DURATION # duration of interpolation to generate in seconds (leave empty for length of audiofile)
--latent_file LATENT_FILE # path to latents saved as numpy array
--shuffle_latents # whether to shuffle the supplied latents or not
--out_size OUT_SIZE # ouput video size: [512, 1024, or 1920]
--fps FPS # output video framerate
--batch BATCH # batch size to render with
--truncation TRUNCATION # truncation to render with (leave empty if get_truncations() is in --audioreactive_file)
--randomize_noise # whether to randomize noise
--dataparallel # whether to use data parallel rendering
--stylegan1 # if the model checkpoint is StyleGAN1
--G_res G_RES # training resolution of the generator
--base_res_factor BASE_RES_FACTOR # factor to increase generator noise maps by (useful when e.g. doubling 512px net to 1024px)
--noconst # whether the generator was trained without a constant input layer
--latent_dim LATENT_DIM # latent vector size of the generator
--n_mlp N_MLP # number of mapping network layers
--channel_multiplier CHANNEL_MULTIPLIER # generator's channel scaling multiplier
```
Alternatively, `generate()` can be called directly from python. It takes the same arguments as generate_audiovisual.py except instead of supplying an audioreactive_file, the functions should be supplied directly (i.e. initialize, get_latents, get_noise, get_bends, get_rewrites, and get_truncation as arguments).
Model checkpoints can be converted from tensorflow .pkl's with [Kim Seonghyeon's script](https://github.com/rosinality/stylegan2-pytorch/blob/master/convert_weight.py) (the one in this repo is broken). Both StyleGAN2 and StyleGAN2-ADA tensorflow checkpoints should work once converted. A good place to find models is [this repo](https://github.com/justinpinkney/awesome-pretrained-stylegan2).
There is minimal support for rendering with StyleGAN1 checkpoints as well, although only with latent and noise (no network bending or model rewriting).
## Citation
If you use the techniques introduced in the paper or the code in this repository for your research, please cite the paper:
```
@InProceedings{Brouwer_2020_NeurIPS_Workshops},
author = {Brouwer, Hans},
title = {Audio-reactive Latent Interpolations with StyleGAN},
booktitle = {Proceedings of the 4th Workshop on Machine Learning for Creativity and Design at NeurIPS 2020},
month = {December},
year = {2020},
url={https://jcbrouwer.github.io/assets/audio-reactive-stylegan/paper.pdf}
}
```
================================================
FILE: accelerate/accelerate_inception.py
================================================
import os
import gc
import wandb
import argparse
import torch as th
from tqdm import tqdm
from torch.utils import data
import torch.nn.functional as F
from inception_vae import InceptionVAE
from dataset import MultiResolutionDataset
from torchvision import transforms, utils, models
def info(x):
print(x.shape, x.detach().cpu().min(), x.detach().cpu().mean(), x.detach().cpu().max())
def sample_data(loader):
while True:
for batch in loader:
yield batch
class VGG19(th.nn.Module):
"""
Adapted from https://github.com/NVIDIA/pix2pixHD
See LICENSE-VGG
"""
def __init__(self, requires_grad=False):
super(VGG19, self).__init__()
vgg_pretrained_features = models.vgg19(pretrained=True).features
self.slice1 = th.nn.Sequential()
self.slice2 = th.nn.Sequential()
self.slice3 = th.nn.Sequential()
self.slice4 = th.nn.Sequential()
self.slice5 = th.nn.Sequential()
for x in range(2):
self.slice1.add_module(str(x), vgg_pretrained_features[x])
for x in range(2, 7):
self.slice2.add_module(str(x), vgg_pretrained_features[x])
for x in range(7, 12):
self.slice3.add_module(str(x), vgg_pretrained_features[x])
for x in range(12, 21):
self.slice4.add_module(str(x), vgg_pretrained_features[x])
for x in range(21, 30):
self.slice5.add_module(str(x), vgg_pretrained_features[x])
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
def forward(self, X):
h_relu1 = self.slice1(X)
h_relu2 = self.slice2(h_relu1)
h_relu3 = self.slice3(h_relu2)
h_relu4 = self.slice4(h_relu3)
h_relu5 = self.slice5(h_relu4)
out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]
return out
class VGGLoss(th.nn.Module):
"""
Adapted from https://github.com/NVIDIA/pix2pixHD
See LICENSE-VGG
"""
def __init__(self):
super(VGGLoss, self).__init__()
self.vgg = VGG19().cuda()
self.criterion = th.nn.L1Loss()
self.weights = [1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0]
def forward(self, x, y):
x_vgg, y_vgg = self.vgg(x), self.vgg(y)
loss = 0
for i in range(len(x_vgg)):
loss += self.weights[i] * self.criterion(x_vgg[i], y_vgg[i].detach())
return loss
def train(latent_dim, num_repeats, learning_rate, lambda_vgg, lambda_mse):
print(
f"latent_dim={latent_dim:.4f}",
f"num_repeats={num_repeats:.4f}",
f"learning_rate={learning_rate:.4f}",
f"lambda_vgg={lambda_vgg:.4f}",
f"lambda_mse={lambda_mse:.4f}",
)
transform = transforms.Compose(
[
transforms.Resize(128),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
# transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True),
]
)
batch_size = 72
data_path = "/home/hans/trainsets/cyphis"
name = os.path.splitext(os.path.basename(data_path))[0]
dataset = MultiResolutionDataset(data_path, transform, 256)
dataloader = data.DataLoader(
dataset, batch_size=batch_size, sampler=data.RandomSampler(dataset), num_workers=12, drop_last=True,
)
loader = sample_data(dataloader)
sample_imgs = next(loader)[:24]
wandb.log({"Real Images": [wandb.Image(utils.make_grid(sample_imgs, nrow=6, normalize=True, range=(0, 1)))]})
vae, vae_optim = None, None
vae = InceptionVAE(latent_dim=latent_dim, repeat_per_block=num_repeats).to(device)
vae_optim = th.optim.Adam(vae.parameters(), lr=learning_rate)
vgg = VGGLoss()
# sample_z = th.randn(size=(24, 512))
scores = []
num_iters = 100_000
pbar = tqdm(range(num_iters), smoothing=0.1)
for i in pbar:
vae.train()
real = next(loader).to(device)
fake, mu, log_var = vae(real)
bce = F.binary_cross_entropy(fake, real, size_average=False)
kld = -0.5 * th.sum(1 + log_var - mu.pow(2) - log_var.exp())
vgg_loss = vgg(fake, real)
mse_loss = th.sqrt((fake - real).pow(2).mean())
loss = bce + kld + lambda_vgg * vgg_loss + lambda_mse * mse_loss
loss_dict = {
"Total": loss,
"BCE": bce,
"Kullback Leibler Divergence": kld,
"MSE": mse_loss,
"VGG": vgg_loss,
}
vae.zero_grad()
loss.backward()
vae_optim.step()
wandb.log(loss_dict)
with th.no_grad():
if i % int(num_iters / 100) == 0 or i + 1 == num_iters:
vae.eval()
sample, _, _ = vae(sample_imgs.to(device))
grid = utils.make_grid(sample, nrow=6, normalize=True, range=(0, 1))
del sample
wandb.log({"Reconstructed Images VAE": [wandb.Image(grid, caption=f"Step {i}")]})
sample = vae.sampling()
grid = utils.make_grid(sample, nrow=6, normalize=True, range=(0, 1))
del sample
wandb.log({"Generated Images VAE": [wandb.Image(grid, caption=f"Step {i}")]})
gc.collect()
th.cuda.empty_cache()
th.save(
{"vae": vae.state_dict(), "vae_optim": vae_optim.state_dict()},
f"/home/hans/modelzoo/maua-sg2/vae-{name}-{wandb.run.dir.split('/')[-1].split('-')[-1]}.pt",
)
if th.isnan(loss).any() or th.isinf(loss).any():
print("NaN losses, exiting...")
print(
{
"Total": loss,
"\nBCE": bce,
"\nKullback Leibler Divergence": kld,
"\nMSE": mse_loss,
"\nVGG": vgg_loss,
}
)
wandb.log({"Total": 27000})
return
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--latent_dim", type=float, default=512)
parser.add_argument("--num_repeats", type=float, default=1)
parser.add_argument("--learning_rate", type=float, default=0.005)
parser.add_argument("--lambda_vgg", type=float, default=1.0)
parser.add_argument("--lambda_mse", type=float, default=1.0)
args = parser.parse_args()
device = "cuda"
th.backends.cudnn.benchmark = True
wandb.init(project=f"maua-stylegan")
train(
args.latent_dim, args.num_repeats, args.learning_rate, args.lambda_vgg, args.lambda_mse,
)
================================================
FILE: accelerate/accelerate_logcosh.py
================================================
import os
import gc
import wandb
import argparse
import validation
import torch as th
from tqdm import tqdm
from torch.utils import data
from autoencoder import LogCoshVAE
from dataset import MultiResolutionDataset
from torchvision import transforms, utils, models
def data_sampler(dataset, shuffle, distributed):
if distributed:
return data.distributed.DistributedSampler(dataset, shuffle=shuffle)
if shuffle:
return data.RandomSampler(dataset)
else:
return data.SequentialSampler(dataset)
def sample_data(loader):
while True:
for batch in loader:
yield batch
class VGG19(th.nn.Module):
"""
Adapted from https://github.com/NVIDIA/pix2pixHD
See LICENSE-VGG
"""
def __init__(self, requires_grad=False):
super(VGG19, self).__init__()
vgg_pretrained_features = models.vgg19(pretrained=True).features
self.slice1 = th.nn.Sequential()
self.slice2 = th.nn.Sequential()
self.slice3 = th.nn.Sequential()
self.slice4 = th.nn.Sequential()
self.slice5 = th.nn.Sequential()
for x in range(2):
self.slice1.add_module(str(x), vgg_pretrained_features[x])
for x in range(2, 7):
self.slice2.add_module(str(x), vgg_pretrained_features[x])
for x in range(7, 12):
self.slice3.add_module(str(x), vgg_pretrained_features[x])
for x in range(12, 21):
self.slice4.add_module(str(x), vgg_pretrained_features[x])
for x in range(21, 30):
self.slice5.add_module(str(x), vgg_pretrained_features[x])
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
def forward(self, X):
h_relu1 = self.slice1(X)
h_relu2 = self.slice2(h_relu1)
h_relu3 = self.slice3(h_relu2)
h_relu4 = self.slice4(h_relu3)
h_relu5 = self.slice5(h_relu4)
out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]
return out
class VGGLoss(th.nn.Module):
"""
Adapted from https://github.com/NVIDIA/pix2pixHD
See LICENSE-VGG
"""
def __init__(self):
super(VGGLoss, self).__init__()
self.vgg = VGG19().cuda()
self.criterion = th.nn.L1Loss()
self.weights = [1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0]
def forward(self, x, y):
x_vgg, y_vgg = self.vgg(x), self.vgg(y)
loss = 0
for i in range(len(x_vgg)):
loss += self.weights[i] * self.criterion(x_vgg[i], y_vgg[i].detach())
return loss
device = "cuda"
th.backends.cudnn.benchmark = True
wandb.init(project=f"maua-stylegan")
def train(latent_dim, learning_rate, number_filters, vae_alpha, vae_beta, kl_divergence_weight):
print(
f"latent_dim={latent_dim}",
f"learning_rate={learning_rate}",
f"number_filters={number_filters}",
f"vae_alpha={vae_alpha}",
f"vae_beta={vae_beta}",
f"kl_divergence_weight={kl_divergence_weight}",
)
batch_size = 64
i = None
while batch_size >= 1:
try:
transform = transforms.Compose(
[
transforms.Resize(128),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True),
]
)
data_path = "/home/hans/trainsets/cyphis"
name = os.path.splitext(os.path.basename(data_path))[0]
dataset = MultiResolutionDataset(data_path, transform, 256)
dataloader = data.DataLoader(
dataset,
batch_size=int(batch_size),
sampler=data_sampler(dataset, shuffle=True, distributed=False),
num_workers=12,
drop_last=True,
)
loader = sample_data(dataloader)
sample_imgs = next(loader)[:24]
wandb.log(
{"Real Images": [wandb.Image(utils.make_grid(sample_imgs, nrow=6, normalize=True, range=(-1, 1)))]}
)
hidden_dims = [min(int(number_filters) * 2 ** i, latent_dim) for i in range(5)] + [latent_dim]
vae, vae_optim = None, None
vae = LogCoshVAE(
3, latent_dim, hidden_dims=hidden_dims, alpha=vae_alpha, beta=vae_beta, kld_weight=kl_divergence_weight,
).to(device)
vae.train()
vae_optim = th.optim.Adam(vae.parameters(), lr=learning_rate)
mse_loss = th.nn.MSELoss()
vgg = VGGLoss()
sample_z = th.randn(size=(24, latent_dim))
scores = []
num_iters = 100_000
pbar = range(num_iters)
pbar = tqdm(pbar, smoothing=0.1)
for i in pbar:
vae.train()
real = next(loader).to(device)
fake, mu, log_var = vae(real)
loss_dict = vae.loss(real, fake, mu, log_var)
vgg_loss = vgg(fake, real)
loss = loss_dict["Total"] + vgg_loss
vae.zero_grad()
loss.backward()
vae_optim.step()
wandb.log(
{
"Total": loss,
"VGG": vgg_loss,
"Reconstruction": loss_dict["Reconstruction"],
"Kullback Leibler Divergence": loss_dict["Kullback Leibler Divergence"],
}
)
if i % int(num_iters / 1000) == 0 or i + 1 == num_iters:
with th.no_grad():
vae.eval()
sample, _, _ = vae(sample_imgs.to(device))
grid = utils.make_grid(sample, nrow=6, normalize=True, range=(-1, 1),)
del sample
wandb.log({"Reconstructed Images VAE": [wandb.Image(grid, caption=f"Step {i}")]})
sample = vae.decode(sample_z.to(device))
grid = utils.make_grid(sample, nrow=6, normalize=True, range=(-1, 1),)
del sample
wandb.log({"Generated Images VAE": [wandb.Image(grid, caption=f"Step {i}")]})
if i % int(num_iters / 40) == 0 or i + 1 == num_iters:
with th.no_grad():
fid_dict = validation.vae_fid(vae, int(batch_size), (latent_dim,), 5000, name)
wandb.log(fid_dict)
mse = mse_loss(fake, real) * 5000
score = fid_dict["FID"] + mse + 1000 * vgg_loss
wandb.log({"Score": score})
pbar.set_description(f"FID: {fid_dict['FID']:.2f} MSE: {mse:.2f} VGG: {1000 * vgg_loss:.2f}")
if i >= num_iters / 2:
scores.append(score)
if th.isnan(loss).any() or th.isinf(loss).any():
print("NaN losses, exiting...")
print(
{
"Total": loss.detach().cpu().item(),
"\nVGG": vgg_loss.detach().cpu().item(),
"\nReconstruction": loss_dict["Reconstruction"].detach().cpu().item(),
"\nKullback Leibler Divergence": loss_dict["Kullback Leibler Divergence"]
.detach()
.cpu()
.item(),
}
)
wandb.log({"Score": 27000})
return
return
except RuntimeError as e:
if "CUDA out of memory" in str(e):
batch_size = batch_size / 2
if batch_size < 1:
print("This configuration does not fit into memory, exiting...")
wandb.log({"Score": 27000})
return
print(f"Out of memory, halving batch size... {batch_size}")
if vae is not None:
del vae
if vae_optim is not None:
del vae_optim
gc.collect()
th.cuda.empty_cache()
else:
print(e)
return
parser = argparse.ArgumentParser()
parser.add_argument("--latent_dim", type=int, default=1024)
parser.add_argument("--learning_rate", type=float, default=0.005)
parser.add_argument("--number_filters", type=int, default=64)
parser.add_argument("--vae_alpha", type=float, default=10.0)
parser.add_argument("--vae_beta", type=float, default=1.0)
parser.add_argument("--kl_divergence_weight", type=float, default=1.0)
args = parser.parse_args()
train(
args.latent_dim, args.learning_rate, args.number_filters, args.vae_alpha, args.vae_beta, args.kl_divergence_weight,
)
================================================
FILE: accelerate/accelerate_segnet.py
================================================
import os
import gc
import wandb
import argparse
import torch as th
from tqdm import tqdm
from torch.utils import data
from autoencoder import ConvSegNet
from dataset import MultiResolutionDataset
from torchvision import transforms, utils, models
def info(x):
print(x.shape, x.detach().cpu().min(), x.detach().cpu().mean(), x.detach().cpu().max())
def sample_data(loader):
while True:
for batch in loader:
yield batch
class VGG19(th.nn.Module):
"""
Adapted from https://github.com/NVIDIA/pix2pixHD
See LICENSE-VGG
"""
def __init__(self, requires_grad=False):
super(VGG19, self).__init__()
vgg_pretrained_features = models.vgg19(pretrained=True).features
self.slice1 = th.nn.Sequential()
self.slice2 = th.nn.Sequential()
self.slice3 = th.nn.Sequential()
self.slice4 = th.nn.Sequential()
self.slice5 = th.nn.Sequential()
for x in range(2):
self.slice1.add_module(str(x), vgg_pretrained_features[x])
for x in range(2, 7):
self.slice2.add_module(str(x), vgg_pretrained_features[x])
for x in range(7, 12):
self.slice3.add_module(str(x), vgg_pretrained_features[x])
for x in range(12, 21):
self.slice4.add_module(str(x), vgg_pretrained_features[x])
for x in range(21, 30):
self.slice5.add_module(str(x), vgg_pretrained_features[x])
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
def forward(self, X):
h_relu1 = self.slice1(X)
h_relu2 = self.slice2(h_relu1)
h_relu3 = self.slice3(h_relu2)
h_relu4 = self.slice4(h_relu3)
h_relu5 = self.slice5(h_relu4)
out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]
return out
class VGGLoss(th.nn.Module):
"""
Adapted from https://github.com/NVIDIA/pix2pixHD
See LICENSE-VGG
"""
def __init__(self):
super(VGGLoss, self).__init__()
self.vgg = VGG19().cuda()
self.criterion = th.nn.L1Loss()
self.weights = [1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0]
def forward(self, x, y):
x_vgg, y_vgg = self.vgg(x), self.vgg(y)
loss = 0
for i in range(len(x_vgg)):
loss += self.weights[i] * self.criterion(x_vgg[i], y_vgg[i].detach())
return loss
def align(x, y, alpha=2):
return (x - y).norm(p=2, dim=1).pow(alpha).mean()
def uniform(x, t=2):
return (th.pdist(x.view(x.size(0), -1), p=2).pow(2).mul(-t).exp().mean() + 1e-27).log()
def train(learning_rate, lambda_mse):
print(
f"learning_rate={learning_rate:.4f}", f"lambda_mse={lambda_mse:.4f}",
)
transform = transforms.Compose(
[
transforms.Resize(128),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True),
]
)
batch_size = 72
data_path = "/home/hans/trainsets/cyphis"
name = os.path.splitext(os.path.basename(data_path))[0]
dataset = MultiResolutionDataset(data_path, transform, 256)
dataloader = data.DataLoader(
dataset, batch_size=batch_size, sampler=data.RandomSampler(dataset), num_workers=12, drop_last=True,
)
loader = sample_data(dataloader)
sample_imgs = next(loader)[:24]
wandb.log({"Real Images": [wandb.Image(utils.make_grid(sample_imgs, nrow=6, normalize=True, range=(-1, 1)))]})
vae, vae_optim = None, None
vae = ConvSegNet().to(device)
vae_optim = th.optim.Adam(vae.parameters(), lr=learning_rate)
vgg = VGGLoss()
sample_z = th.randn(size=(24, 512, 16, 16))
sample_z /= sample_z.abs().max()
scores = []
num_iters = 100_000
pbar = tqdm(range(num_iters), smoothing=0.1)
for i in pbar:
vae.train()
real = next(loader).to(device)
z = vae.encode(real)
fake = vae.decode(z)
vgg_loss = vgg(fake, real)
mse_loss = th.sqrt((fake - real).pow(2).mean())
# diff = fake - real
# recons_loss = recons_alpha * diff + th.log(1.0 + th.exp(-2 * recons_alpha * diff)) - th.log(th.tensor(2.0))
# recons_loss = (1.0 / recons_alpha) * recons_loss.mean()
# recons_loss = recons_loss if not th.isinf(recons_loss).any() else 0
# x, y = z.chunk(2)
# align_loss = align(x, y, alpha=align_alpha)
# unif_loss = -(uniform(x, t=unif_t) + uniform(y, t=unif_t)) / 2.0
loss = (
vgg_loss
+ lambda_mse * mse_loss
# + lambda_recons * recons_loss
# + lambda_align * align_loss
# + lambda_unif * unif_loss
)
# print(vgg_loss.detach().cpu().item())
# print(lambda_mse * mse_loss.detach().cpu().item())
# # print(lambda_recons * recons_loss.detach().cpu().item())
# print(lambda_align * align_loss.detach().cpu().item())
# print(lambda_unif * unif_loss.detach().cpu().item())
loss_dict = {
"Total": loss,
"MSE": mse_loss,
"VGG": vgg_loss,
# "Reconstruction": recons_loss,
# "Alignment": align_loss,
# "Uniformity": unif_loss,
}
vae.zero_grad()
loss.backward()
vae_optim.step()
wandb.log(loss_dict)
# pbar.set_description(" ".join())
with th.no_grad():
if i % int(num_iters / 100) == 0 or i + 1 == num_iters:
vae.eval()
sample = vae(sample_imgs.to(device))
grid = utils.make_grid(sample, nrow=6, normalize=True, range=(-1, 1))
del sample
wandb.log({"Reconstructed Images VAE": [wandb.Image(grid, caption=f"Step {i}")]})
sample = vae.decode(sample_z.to(device))
grid = utils.make_grid(sample, nrow=6, normalize=True, range=(-1, 1))
del sample
wandb.log({"Generated Images VAE": [wandb.Image(grid, caption=f"Step {i}")]})
gc.collect()
th.cuda.empty_cache()
th.save(
{"vae": vae.state_dict(), "vae_optim": vae_optim.state_dict()},
f"/home/hans/modelzoo/maua-sg2/vae-{name}-{wandb.run.dir.split('/')[-1].split('-')[-1]}.pt",
)
if th.isnan(loss).any():
print("NaN losses, exiting...")
wandb.log({"Total": 27000})
return
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--learning_rate", type=float, default=0.005)
parser.add_argument("--lambda_mse", type=float, default=1.0)
# parser.add_argument("--lambda_recons", type=float, default=0.0)
# parser.add_argument("--recons_alpha", type=float, default=5.0)
# parser.add_argument("--lambda_align", type=float, default=1.0)
# parser.add_argument("--align_alpha", type=float, default=2.0)
# parser.add_argument("--lambda_unif", type=float, default=1.0)
# parser.add_argument("--unif_t", type=float, default=0.001)
args = parser.parse_args()
device = "cuda"
th.backends.cudnn.benchmark = True
wandb.init(project=f"maua-stylegan")
train(
args.learning_rate,
args.lambda_mse,
# args.lambda_recons,
# args.recons_alpha,
# args.lambda_align,
# args.align_alpha,
# args.lambda_unif,
# args.unif_t,
)
================================================
FILE: audioreactive/__init__.py
================================================
from .bend import *
from .examples import *
from .latent import *
from .signal import *
from .util import *
================================================
FILE: audioreactive/bend.py
================================================
import math
import kornia.augmentation as kA
import kornia.geometry.transform as kT
import torch as th
# ====================================================================================
# ================================= network bending ==================================
# ====================================================================================
class NetworkBend(th.nn.Module):
"""Base network bending class
Args:
sequential_fn (function): Function that takes a batch of modulation and creates th.nn.Sequential
modulation (th.tensor): Modulation batch
"""
def __init__(self, sequential_fn, modulation):
super(NetworkBend, self).__init__()
self.sequential = sequential_fn(modulation)
def forward(self, x):
return self.sequential(x)
class AddNoise(th.nn.Module):
"""Adds static noise to output
Args:
noise (th.tensor): Noise to be added
"""
def __init__(self, noise):
super(AddNoise, self).__init__()
self.noise = noise
def forward(self, x):
return x + self.noise.to(x.device)
class Print(th.nn.Module):
"""Prints intermediate feature statistics (useful for debugging complicated network bends)."""
def forward(self, x):
print(x.shape, [x.min().item(), x.mean().item(), x.max().item()], th.std(x).item())
return x
class Translate(NetworkBend):
"""Creates horizontal translating effect where repeated linear interpolations from 0 to 1 (saw tooth wave) creates seamless scrolling effect.
Args:
modulation (th.tensor): [0.0-1.0]. Batch of modulation
h (int): Height of intermediate features that the network bend is applied to
w (int): Width of intermediate features that the network bend is applied to
noise (int): Noise to be added (must be 5 * width wide)
"""
def __init__(self, modulation, h, w, noise):
sequential_fn = lambda b: th.nn.Sequential(
th.nn.ReflectionPad2d((int(w / 2), int(w / 2), 0, 0)),
th.nn.ReflectionPad2d((w, w, 0, 0)),
th.nn.ReflectionPad2d((w, 0, 0, 0)),
AddNoise(noise),
kT.Translate(b),
kA.CenterCrop((h, w)),
)
super(Translate, self).__init__(sequential_fn, modulation)
class Zoom(NetworkBend):
"""Creates zooming effect.
Args:
modulation (th.tensor): [0.0-1.0]. Batch of modulation
h (int): height of intermediate features that the network bend is applied to
w (int): width of intermediate features that the network bend is applied to
"""
def __init__(self, modulation, h, w):
padding = int(max(h, w)) - 1
sequential_fn = lambda b: th.nn.Sequential(th.nn.ReflectionPad2d(padding), kT.Scale(b), kA.CenterCrop((h, w)))
super(Zoom, self).__init__(sequential_fn, modulation)
class Rotate(NetworkBend):
"""Creates rotation effect.
Args:
modulation (th.tensor): [0.0-1.0]. Batch of modulation
h (int): height of intermediate features that the network bend is applied to
w (int): width of intermediate features that the network bend is applied to
"""
def __init__(self, modulation, h, w):
# worst case rotation brings sqrt(2) * max_side_length out-of-frame pixels into frame
# padding should cover that exactly
padding = int(max(h, w) * (1 - math.sqrt(2) / 2))
sequential_fn = lambda b: th.nn.Sequential(th.nn.ReflectionPad2d(padding), kT.Rotate(b), kA.CenterCrop((h, w)))
super(Rotate, self).__init__(sequential_fn, modulation)
================================================
FILE: audioreactive/examples/__init__.py
================================================
from . import *
================================================
FILE: audioreactive/examples/default.py
================================================
import torch as th
import audioreactive as ar
def initialize(args):
args.lo_onsets = ar.onsets(args.audio, args.sr, args.n_frames, fmax=150, smooth=5, clip=97, power=2)
args.hi_onsets = ar.onsets(args.audio, args.sr, args.n_frames, fmin=500, smooth=5, clip=99, power=2)
return args
def get_latents(selection, args):
chroma = ar.chroma(args.audio, args.sr, args.n_frames)
chroma_latents = ar.chroma_weight_latents(chroma, selection)
latents = ar.gaussian_filter(chroma_latents, 4)
lo_onsets = args.lo_onsets[:, None, None]
hi_onsets = args.hi_onsets[:, None, None]
latents = hi_onsets * selection[[-4]] + (1 - hi_onsets) * latents
latents = lo_onsets * selection[[-7]] + (1 - lo_onsets) * latents
latents = ar.gaussian_filter(latents, 2, causal=0.2)
return latents
def get_noise(height, width, scale, num_scales, args):
if width > 256:
return None
lo_onsets = args.lo_onsets[:, None, None, None].cuda()
hi_onsets = args.hi_onsets[:, None, None, None].cuda()
noise_noisy = ar.gaussian_filter(th.randn((args.n_frames, 1, height, width), device="cuda"), 5)
noise = ar.gaussian_filter(th.randn((args.n_frames, 1, height, width), device="cuda"), 128)
if width < 128:
noise = lo_onsets * noise_noisy + (1 - lo_onsets) * noise
if width > 32:
noise = hi_onsets * noise_noisy + (1 - hi_onsets) * noise
noise /= noise.std() * 2.5
return noise.cpu()
================================================
FILE: audioreactive/examples/kelp.py
================================================
"""
This file shows an example of a loop based interpolation
Here sections are identified with laplacian segmentation and looping latents are generated for each section
The noise is looping perlin noise
Long term section analysis is done with the RMS to interpolate between latent sequences for the intro/outro and drop
"""
import librosa as rosa
import torch as th
import audioreactive as ar
OVERRIDE = dict(audio_file="audioreactive/examples/Wavefunk - Dwelling in the Kelp.mp3", out_size=1920)
BPM = 130
def initialize(args):
# RMS can be used to distinguish between the drop sections and intro/outros
rms = ar.rms(args.audio, args.sr, args.n_frames, smooth=10, clip=60, power=1)
rms = ar.expand(rms, threshold=0.8, ratio=10)
rms = ar.gaussian_filter(rms, 4)
rms = ar.normalize(rms)
args.rms = rms
# cheating a little here, this my song so I have the multitracks
# this is much easier than fiddling with onsets until you have envelopes that dance nicely to the drums
audio, sr = rosa.load("workspace/kelpkick.wav", offset=args.offset, duration=args.duration)
args.kick_onsets = ar.onsets(audio, sr, args.n_frames, margin=1, smooth=4)
audio, sr = rosa.load("workspace/kelpsnare.wav", offset=args.offset, duration=args.duration)
args.snare_onsets = ar.onsets(audio, sr, args.n_frames, margin=1, smooth=4)
ar.plot_signals([args.rms, args.kick_onsets, args.snare_onsets])
return args
def get_latents(selection, args):
# expand envelopes to latent shape
rms = args.rms[:, None, None]
low_onsets = args.kick_onsets[:, None, None]
high_onsets = args.snare_onsets[:, None, None]
# get timestamps and labels with laplacian segmentation
# k is the number of labels the algorithm may use
# try multiple values with plot=True to see which value correlates best with the sections of the song
timestamps, labels = ar.laplacian_segmentation(args.audio, args.sr, k=7)
# a second set of latents for the drop section, the 'selection' variable is the other set for the intro
drop_selection = ar.load_latents("workspace/cyphept_kelp_drop_latents.npy")
color_layer = 9
latents = []
for (start, stop), l in zip(zip(timestamps, timestamps[1:]), labels):
start_frame = int(round(start / args.duration * args.n_frames))
stop_frame = int(round(stop / args.duration * args.n_frames))
section_frames = stop_frame - start_frame
section_bars = (stop - start) * (BPM / 60) / 4
# get portion of latent selection (wrapping around to start)
latent_selection_slice = ar.wrapping_slice(selection, l, 4)
# spline interpolation loops through selection slice
latent_section = ar.spline_loops(latent_selection_slice, n_frames=section_frames, n_loops=section_bars / 4)
# set the color with laplacian segmentation label, (1 latent repeated for entire section in upper layers)
latent_section[:, color_layer:] = th.cat([selection[[l], color_layer:]] * section_frames)
# same as above but for the drop latents (with faster loops)
drop_selection_slice = ar.wrapping_slice(drop_selection, l, 4)
drop_section = ar.spline_loops(drop_selection_slice, n_frames=section_frames, n_loops=section_bars / 2)
drop_section[:, color_layer:] = th.cat([drop_selection[[l], color_layer:]] * section_frames)
# merged based on RMS (drop section or not)
latents.append((1 - rms[start_frame:stop_frame]) * latent_section + rms[start_frame:stop_frame] * drop_section)
# concatenate latents to correct length & smooth over the junctions
len_latents = sum([len(l) for l in latents])
if len_latents != args.n_frames:
latents.append(th.cat([latents[-1][[-1]]] * (args.n_frames - len_latents)))
latents = th.cat(latents).float()
latents = ar.gaussian_filter(latents, 3)
# use onsets to modulate towards latents
latents = 0.666 * low_onsets * selection[[2]] + (1 - 0.666 * low_onsets) * latents
latents = 0.666 * high_onsets * selection[[1]] + (1 - 0.666 * high_onsets) * latents
latents = ar.gaussian_filter(latents, 1, causal=0.2)
return latents
def get_noise(height, width, scale, num_scales, args):
if width > 512: # larger sizes don't fit in VRAM, just use default or randomize
return
num_bars = int(round(args.duration * (BPM / 60) / 4))
frames_per_loop = int(args.n_frames / num_bars * 2) # loop every 2 bars
def perlin_pls(resolution):
perlin = ar.perlin_noise(shape=(frames_per_loop, height, width), res=resolution)[:, None, ...].cpu()
perlin = th.cat([perlin] * int(num_bars / 2)) # concatenate multiple copies for looping
if args.n_frames - len(perlin) > 0:
perlin = th.cat([perlin, th.cat([perlin[[-1]]] * (args.n_frames - len(perlin)))]) # fix up rounding errors
return perlin
smooth = perlin_pls(resolution=(1, 1, 1)) # (time res, x res, y res)
noise = perlin_pls(resolution=(8, 4, 4)) # higher resolution => higher frequency noise => more movement in video
rms = args.rms[:, None, None, None]
noise = rms * noise + (1 - rms) * smooth # blend between noises based on drop (high rms) or not
return noise
def get_bends(args):
# repeat the intermediate features outwards on both sides (2:1 aspect ratio)
# + add some noise to give the whole thing a little variation (disguises the repetition)
transform = th.nn.Sequential(
th.nn.ReplicationPad2d((2, 2, 0, 0)), ar.AddNoise(0.025 * th.randn(size=(1, 1, 4, 8), device="cuda")),
)
bends = [{"layer": 0, "transform": transform}]
return bends
================================================
FILE: audioreactive/examples/tauceti.py
================================================
"""
This file shows an example of network bending
The latents and noise are similar to temper.py (although without spatial noise controls)
The latents cycle through different colors for different sections of the drop
During the drop, a translation is applied which makes the video seem to scroll endlessly
"""
from functools import partial
import numpy as np
import torch as th
import audioreactive as ar
OVERRIDE = dict(
audio_file="audioreactive/examples/Wavefunk - Tau Ceti Alpha.mp3",
out_size=1920, # get bends assumes 1920x1080 output size
dataparallel=False, # makes use of a kornia transform during network bending => not compatible with dataparallel
fps=30, # 5591 magic number below is based on number of frames in output video with fps of 30
)
def initialize(args):
args.low_onsets = ar.onsets(args.audio, args.sr, args.n_frames, fmax=150, smooth=5, clip=97, power=2)
args.high_onsets = ar.onsets(args.audio, args.sr, args.n_frames, fmin=500, smooth=5, clip=99, power=2)
return args
def get_latents(selection, args):
chroma = ar.chroma(args.audio, args.sr, args.n_frames)
chroma_latents = ar.chroma_weight_latents(chroma, selection[:12]) # shape [n_frames, 18, 512]
latents = ar.gaussian_filter(chroma_latents, 5)
lo_onsets = args.low_onsets[:, None, None] # expand to same shape as latents [n_frames, 1, 1]
hi_onsets = args.high_onsets[:, None, None]
latents = hi_onsets * selection[[-4]] + (1 - hi_onsets) * latents
latents = lo_onsets * selection[[-7]] + (1 - lo_onsets) * latents
latents = ar.gaussian_filter(latents, 5, causal=0)
# cheating a little, you could probably do this with laplacian segmentation, but is it worth the effort?
drop_start = int(5591 * (45 / args.duration))
drop_end = int(5591 * (135 / args.duration))
# selection of latents with different colors (chosen with select_latents.py)
color_latent_selection = th.from_numpy(np.load("workspace/cyphept-multicolor-latents.npy"))
# build sequence of latents for just the upper layers
color_layer = 9
color_latents = [latents[:drop_start, color_layer:]]
# for 4 different sections in the drop, use a different color latent
drop_length = drop_end - drop_start
section_length = int(drop_length / 4)
for i, section_start in enumerate(range(0, drop_length, section_length)):
if i > 3:
break
color_latents.append(th.cat([color_latent_selection[[i], color_layer:]] * section_length))
# ensure color sequence is correct length and concatenate
if drop_length - 4 * section_length != 0:
color_latents.append(th.cat([color_latent_selection[[i], color_layer:]] * (drop_length - 4 * section_length)))
color_latents.append(latents[drop_end:, color_layer:])
color_latents = th.cat(color_latents, axis=0)
color_latents = ar.gaussian_filter(color_latents, 5)
# set upper layers of latent sequence to the colored sequence
latents[:, color_layer:] = color_latents
return latents
def get_noise(height, width, scale, num_scales, args):
if width > 256:
return None
lo_onsets = 1.25 * args.low_onsets[:, None, None, None].cuda()
hi_onsets = 1.25 * args.high_onsets[:, None, None, None].cuda()
noise_noisy = ar.gaussian_filter(th.randn((args.n_frames, 1, height, width), device="cuda"), 5)
noise = ar.gaussian_filter(th.randn((args.n_frames, 1, height, width), device="cuda"), 128)
if width > 8:
noise = lo_onsets * noise_noisy + (1 - lo_onsets) * noise
noise = hi_onsets * noise_noisy + (1 - hi_onsets) * noise
noise /= noise.std() * 2.5
return noise.cpu()
def get_bends(args):
# repeat the intermediate features outwards on both sides (2:1 aspect ratio)
# + add some noise to give the whole thing a little variation (disguises the repetition)
transform = th.nn.Sequential(
th.nn.ReplicationPad2d((2, 2, 0, 0)), ar.AddNoise(0.025 * th.randn(size=(1, 1, 4, 8), device="cuda")),
)
bends = [{"layer": 0, "transform": transform}]
# during the drop, create scrolling effect
drop_start = int(5591 * (45 / args.duration))
drop_end = int(5591 * (135 / args.duration))
# calculate length of loops, number of loops, and remainder at end of drop
scroll_loop_length = int(6 * args.fps)
scroll_loop_num = int((drop_end - drop_start) / scroll_loop_length)
scroll_trunc = (drop_end - drop_start) - scroll_loop_num * scroll_loop_length
# apply network bending to 4th layer in StyleGAN
# lower layer network bends have more fluid outcomes
tl = 4
h = 2 ** tl
w = 2 * h
# create values between 0 and 1 corresponding to fraction of scroll from left to right completed
# all 0s during intro
intro_tl8 = np.zeros(drop_start)
# repeating linear interpolation from 0 to 1 during drop
loops_tl8 = np.concatenate([np.linspace(0, w, scroll_loop_length)] * scroll_loop_num)
# truncated interp
last_loop_tl8 = np.linspace(0, w, scroll_loop_length)[:scroll_trunc]
# static at final truncated value during outro
outro_tl8 = np.ones(args.n_frames - drop_end) * np.linspace(0, w, scroll_loop_length)[scroll_trunc + 1]
# create 2D array of translations in x and y directions
x_tl8 = np.concatenate([intro_tl8, loops_tl8, last_loop_tl8, outro_tl8])
y_tl8 = np.zeros(args.n_frames)
translation = (th.tensor([x_tl8, y_tl8]).float().T)[: args.n_frames]
# smooth the transition from intro to drop to prevent jerk
translation.T[0, drop_start - args.fps : drop_start + args.fps] = ar.gaussian_filter(
translation.T[0, drop_start - 5 * args.fps : drop_start + 5 * args.fps], 5
)[4 * args.fps : -4 * args.fps]
class Translate(NetworkBend):
"""From audioreactive/examples/bend.py"""
def __init__(self, modulation, h, w, noise):
sequential_fn = lambda b: th.nn.Sequential(
th.nn.ReflectionPad2d((int(w / 2), int(w / 2), 0, 0)), # < Reflect out to 5x width (so that after
th.nn.ReflectionPad2d((w, w, 0, 0)), # < translating w pixels, center crop gives
th.nn.ReflectionPad2d((w, 0, 0, 0)), # < same features as translating 0 pixels)
AddNoise(noise), # add some noise to disguise reflections
kT.Translate(b),
kA.CenterCrop((h, w)),
)
super(Translate, self).__init__(sequential_fn, modulation)
# create static noise for translate bend
noise = 0.2 * th.randn((1, 1, h, 5 * w), device="cuda")
# create function which returns an initialized Translate object when fed a batch of modulation
# this is so that creation of the object is delayed until the specific batch is sent into the generator
# (there's probably an easier way to do this without the kornia transforms, e.g. using Broad et al.'s transform implementations)
transform = lambda batch: partial(Translate, h=h, w=w, noise=noise)(batch)
bends += [{"layer": tl, "transform": transform, "modulation": translation}] # add network bend to list dict
return bends
================================================
FILE: audioreactive/examples/temper.py
================================================
"""
This file shows an example of spatial control of the noise using a simple circular mask
The latents are a chromagram weighted sequence, modulated by drum onsets
"""
import scipy.ndimage.filters as ndi
import torch as th
import audioreactive as ar
OVERRIDE = dict(audio_file="audioreactive/examples/Wavefunk - Temper.mp3", out_size=1024)
def initialize(args):
# these onsets can definitely use some tweaking, the drum reactivity isn't great for this one
# the main bass makes it hard to identify both the kick and the snare because it is so loud and covers the whole spectrum
args.lo_onsets = ar.onsets(args.audio, args.sr, args.n_frames, fmax=150, smooth=5, clip=97, power=2)
args.hi_onsets = ar.onsets(args.audio, args.sr, args.n_frames, fmin=500, smooth=5, clip=99, power=2)
return args
def get_latents(selection, args):
# create chromagram weighted sequence
chroma = ar.chroma(args.audio, args.sr, args.n_frames)
chroma_latents = ar.chroma_weight_latents(chroma, selection)
latents = ar.gaussian_filter(chroma_latents, 4)
# expand onsets to latent shape
lo_onsets = args.lo_onsets[:, None, None]
hi_onsets = args.hi_onsets[:, None, None]
# modulate latents to specific latent vectors
latents = hi_onsets * selection[[-4]] + (1 - hi_onsets) * latents
latents = lo_onsets * selection[[-7]] + (1 - lo_onsets) * latents
latents = ar.gaussian_filter(latents, 2, causal=0.2)
return latents
def circular_mask(h, w, center=None, radius=None, soft=0):
if center is None: # use the middle of the image
center = (int(w / 2), int(h / 2))
if radius is None: # use the smallest distance between the center and image walls
radius = min(center[0], center[1], w - center[0], h - center[1])
Y, X = np.ogrid[:h, :w]
dist_from_center = np.sqrt((X - center[0]) ** 2 + (Y - center[1]) ** 2)
mask = dist_from_center <= radius
if soft > 0:
mask = ndi.gaussian_filter(mask, sigma=int(round(soft))) # blur mask for smoother transition
return th.from_numpy(mask)
def get_noise(height, width, scale, num_scales, args):
if width > 256: # larger sizes don't fit in VRAM, just use default or randomize
return None
# expand onsets to noise shape
# send to GPU as gaussian_filter on large noise tensors with high standard deviation is slow
lo_onsets = args.lo_onsets[:, None, None, None].cuda()
hi_onsets = args.hi_onsets[:, None, None, None].cuda()
# 1s inside circle of radius, 0s outside
mask = circular_mask(height, width, radius=int(width / 2), soft=2)[None, None, ...].float().cuda()
# create noise which changes quickly (small standard deviation smoothing)
noise_noisy = ar.gaussian_filter(th.randn((args.n_frames, 1, height, width), device="cuda"), 5)
# create noise which changes slowly (large standard deviation smoothing)
noise = ar.gaussian_filter(th.randn((args.n_frames, 1, height, width), device="cuda"), 128)
# for lower layers, noise inside circle are affected by low onsets
if width < 128:
noise = 2 * mask * lo_onsets * noise_noisy + (1 - mask) * (1 - lo_onsets) * noise
# for upper layers, noise outside circle are affected by high onsets
if width > 32:
noise = 0.75 * (1 - mask) * hi_onsets * noise_noisy + mask * (1 - 0.75 * hi_onsets) * noise
# ensure amplitude of noise is close to standard normal distribution (dividing by std. dev. gets it exactly there)
noise /= noise.std() * 2
return noise.cpu()
================================================
FILE: audioreactive/latent.py
================================================
import gc
import numpy as np
import torch as th
from scipy import interpolate
from models.stylegan2 import Generator
from .signal import gaussian_filter
# ====================================================================================
# ================================= latent/noise ops =================================
# ====================================================================================
def chroma_weight_latents(chroma, latents):
"""Creates chromagram weighted latent sequence
Args:
chroma (th.tensor): Chromagram
latents (th.tensor): Latents (must have same number as number of notes in chromagram)
Returns:
th.tensor: Chromagram weighted latent sequence
"""
base_latents = (chroma[..., None, None] * latents[None, ...]).sum(1)
return base_latents
def slerp(val, low, high):
"""Interpolation along geodesic of n-dimensional unit sphere
from https://github.com/soumith/dcgan.torch/issues/14#issuecomment-200025792
Args:
val (float): Value between 0 and 1 representing fraction of interpolation completed
low (float): Starting value
high (float): Ending value
Returns:
float: Interpolated value
"""
omega = np.arccos(np.clip(np.dot(low / np.linalg.norm(low), high / np.linalg.norm(high)), -1, 1))
so = np.sin(omega)
if so == 0:
return (1.0 - val) * low + val * high # L'Hopital's rule/LERP
return np.sin((1.0 - val) * omega) / so * low + np.sin(val * omega) / so * high
def slerp_loops(latent_selection, n_frames, n_loops, smoothing=1, loop=True):
"""Get looping latents using geodesic interpolation. Total length of n_frames with n_loops repeats.
Args:
latent_selection (th.tensor): Set of latents to loop between (in order)
n_frames (int): Total length of output looping sequence
n_loops (int): Number of times to loop
smoothing (int, optional): Standard deviation of gaussian smoothing kernel. Defaults to 1.
loop (bool, optional): Whether to return to first latent. Defaults to True.
Returns:
th.tensor: Sequence of smoothly looping latents
"""
if loop:
latent_selection = np.concatenate([latent_selection, latent_selection[[0]]])
base_latents = []
for n in range(len(latent_selection)):
for val in np.linspace(0.0, 1.0, int(n_frames // max(1, n_loops) // len(latent_selection))):
base_latents.append(
th.from_numpy(
slerp(
val,
latent_selection[n % len(latent_selection)][0],
latent_selection[(n + 1) % len(latent_selection)][0],
)
)
)
base_latents = th.stack(base_latents)
base_latents = gaussian_filter(base_latents, smoothing)
base_latents = th.cat([base_latents] * int(n_frames / len(base_latents)), axis=0)
base_latents = th.cat([base_latents[:, None, :]] * 18, axis=1)
if n_frames - len(base_latents) != 0:
base_latents = th.cat([base_latents, base_latents[0 : n_frames - len(base_latents)]])
return base_latents
def spline_loops(latent_selection, n_frames, n_loops, loop=True):
"""Get looping latents using spline interpolation. Total length of n_frames with n_loops repeats.
Args:
latent_selection (th.tensor): Set of latents to loop between (in order)
n_frames (int): Total length of output looping sequence
n_loops (int): Number of times to loop
loop (bool, optional): Whether to return to first latent. Defaults to True.
Returns:
th.tensor: Sequence of smoothly looping latents
"""
if loop:
latent_selection = np.concatenate([latent_selection, latent_selection[[0]]])
x = np.linspace(0, 1, int(n_frames // max(1, n_loops)))
base_latents = np.zeros((len(x), *latent_selection.shape[1:]))
for lay in range(latent_selection.shape[1]):
for lat in range(latent_selection.shape[2]):
tck = interpolate.splrep(np.linspace(0, 1, latent_selection.shape[0]), latent_selection[:, lay, lat])
base_latents[:, lay, lat] = interpolate.splev(x, tck)
base_latents = th.cat([th.from_numpy(base_latents)] * int(n_frames / len(base_latents)), axis=0)
if n_frames - len(base_latents) > 0:
base_latents = th.cat([base_latents, base_latents[0 : n_frames - len(base_latents)]])
return base_latents[:n_frames]
def wrapping_slice(tensor, start, length, return_indices=False):
"""Gets slice of tensor of a given length that wraps around to beginning
Args:
tensor (th.tensor): Tensor to slice
start (int): Starting index
length (int): Size of slice
return_indices (bool, optional): Whether to return indices rather than values. Defaults to False.
Returns:
th.tensor: Values or indices of slice
"""
if start + length <= tensor.shape[0]:
indices = th.arange(start, start + length)
else:
indices = th.cat((th.arange(start, tensor.shape[0]), th.arange(0, (start + length) % tensor.shape[0])))
if tensor.shape[0] == 1:
indices = th.zeros(1, dtype=th.int64)
if return_indices:
return indices
return tensor[indices]
def generate_latents(n_latents, ckpt, G_res, noconst=False, latent_dim=512, n_mlp=8, channel_multiplier=2):
"""Generates random, mapped latents
Args:
n_latents (int): Number of mapped latents to generate
ckpt (str): Generator checkpoint to use
G_res (int): Generator's training resolution
noconst (bool, optional): Whether the generator was trained without constant starting layer. Defaults to False.
latent_dim (int, optional): Size of generator's latent vectors. Defaults to 512.
n_mlp (int, optional): Number of layers in the generator's mapping network. Defaults to 8.
channel_multiplier (int, optional): Scaling multiplier for generator's channel depth. Defaults to 2.
Returns:
th.tensor: Set of mapped latents
"""
generator = Generator(
G_res, latent_dim, n_mlp, channel_multiplier=channel_multiplier, constant_input=not noconst, checkpoint=ckpt,
).cuda()
zs = th.randn((n_latents, latent_dim), device="cuda")
latent_selection = generator(zs, map_latents=True).cpu()
del generator, zs
gc.collect()
th.cuda.empty_cache()
return latent_selection
def save_latents(latents, filename):
"""Saves latent vectors to file
Args:
latents (th.tensor): Latent vector(s) to save
filename (str): Filename to save to
"""
np.save(filename, latents)
def load_latents(filename):
"""Load latents from numpy file
Args:
filename (str): Filename to load from
Returns:
th.tensor: Latent vectors
"""
return th.from_numpy(np.load(filename))
def _perlinterpolant(t):
return t * t * t * (t * (t * 6 - 15) + 10)
def perlin_noise(shape, res, tileable=(True, False, False), interpolant=_perlinterpolant):
"""Generate a 3D tensor of perlin noise.
Args:
shape: The shape of the generated tensor (tuple of three ints). This must be a multiple of res.
res: The number of periods of noise to generate along each axis (tuple of three ints). Note shape must be a multiple of res.
tileable: If the noise should be tileable along each axis (tuple of three bools). Defaults to (False, False, False).
interpolant: The interpolation function, defaults to t*t*t*(t*(t*6 - 15) + 10).
Returns:
A tensor of shape shape with the generated noise.
Raises:
ValueError: If shape is not a multiple of res.
"""
delta = (res[0] / shape[0], res[1] / shape[1], res[2] / shape[2])
d = (shape[0] // res[0], shape[1] // res[1], shape[2] // res[2])
grid = np.mgrid[0 : res[0] : delta[0], 0 : res[1] : delta[1], 0 : res[2] : delta[2]]
grid = grid.transpose(1, 2, 3, 0) % 1
grid = th.from_numpy(grid).cuda()
# Gradients
theta = 2 * np.pi * np.random.rand(res[0] + 1, res[1] + 1, res[2] + 1)
phi = 2 * np.pi * np.random.rand(res[0] + 1, res[1] + 1, res[2] + 1)
gradients = np.stack((np.sin(phi) * np.cos(theta), np.sin(phi) * np.sin(theta), np.cos(phi)), axis=3)
if tileable[0]:
gradients[-1, :, :] = gradients[0, :, :]
if tileable[1]:
gradients[:, -1, :] = gradients[:, 0, :]
if tileable[2]:
gradients[:, :, -1] = gradients[:, :, 0]
gradients = gradients.repeat(d[0], 0).repeat(d[1], 1).repeat(d[2], 2)
gradients = th.from_numpy(gradients).cuda()
g000 = gradients[: -d[0], : -d[1], : -d[2]]
g100 = gradients[d[0] :, : -d[1], : -d[2]]
g010 = gradients[: -d[0], d[1] :, : -d[2]]
g110 = gradients[d[0] :, d[1] :, : -d[2]]
g001 = gradients[: -d[0], : -d[1], d[2] :]
g101 = gradients[d[0] :, : -d[1], d[2] :]
g011 = gradients[: -d[0], d[1] :, d[2] :]
g111 = gradients[d[0] :, d[1] :, d[2] :]
# Ramps
n000 = th.sum(th.stack((grid[:, :, :, 0], grid[:, :, :, 1], grid[:, :, :, 2]), axis=3) * g000, 3)
n100 = th.sum(th.stack((grid[:, :, :, 0] - 1, grid[:, :, :, 1], grid[:, :, :, 2]), axis=3) * g100, 3)
n010 = th.sum(th.stack((grid[:, :, :, 0], grid[:, :, :, 1] - 1, grid[:, :, :, 2]), axis=3) * g010, 3)
n110 = th.sum(th.stack((grid[:, :, :, 0] - 1, grid[:, :, :, 1] - 1, grid[:, :, :, 2]), axis=3) * g110, 3)
n001 = th.sum(th.stack((grid[:, :, :, 0], grid[:, :, :, 1], grid[:, :, :, 2] - 1), axis=3) * g001, 3)
n101 = th.sum(th.stack((grid[:, :, :, 0] - 1, grid[:, :, :, 1], grid[:, :, :, 2] - 1), axis=3) * g101, 3)
n011 = th.sum(th.stack((grid[:, :, :, 0], grid[:, :, :, 1] - 1, grid[:, :, :, 2] - 1), axis=3) * g011, 3)
n111 = th.sum(th.stack((grid[:, :, :, 0] - 1, grid[:, :, :, 1] - 1, grid[:, :, :, 2] - 1), axis=3) * g111, 3)
# Interpolation
t = interpolant(grid)
n00 = n000 * (1 - t[:, :, :, 0]) + t[:, :, :, 0] * n100
n10 = n010 * (1 - t[:, :, :, 0]) + t[:, :, :, 0] * n110
n01 = n001 * (1 - t[:, :, :, 0]) + t[:, :, :, 0] * n101
n11 = n011 * (1 - t[:, :, :, 0]) + t[:, :, :, 0] * n111
n0 = (1 - t[:, :, :, 1]) * n00 + t[:, :, :, 1] * n10
n1 = (1 - t[:, :, :, 1]) * n01 + t[:, :, :, 1] * n11
perlin = (1 - t[:, :, :, 2]) * n0 + t[:, :, :, 2] * n1
return perlin * 2 - 1 # stretch from -1 to 1
================================================
FILE: audioreactive/signal.py
================================================
import os
import warnings
from pathlib import Path
import joblib
import librosa as rosa
import librosa.display
import madmom as mm
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import scipy
import scipy.signal as signal
import sklearn.cluster
import torch as th
import torch.nn.functional as F
SMF = 1 # this is set by generate_audiovisual.py based on rendering fps
def set_SMF(smf):
global SMF
SMF = smf
# ====================================================================================
# ==================================== signal ops ====================================
# ====================================================================================
def onsets(audio, sr, n_frames, margin=8, fmin=20, fmax=8000, smooth=1, clip=100, power=1, type="mm"):
"""Creates onset envelope from audio
Args:
audio (np.array): Audio signal
sr (int): Sampling rate of the audio
n_frames (int): Total number of frames to resample envelope to
margin (int, optional): For percussive source separation, higher values create more extreme separations. Defaults to 8.
fmin (int, optional): Minimum frequency for onset analysis. Defaults to 20.
fmax (int, optional): Maximum frequency for onset analysis. Defaults to 8000.
smooth (int, optional): Standard deviation of gaussian kernel to smooth with. Defaults to 1.
clip (int, optional): Percentile to clip onset signal to. Defaults to 100.
power (int, optional): Exponent to raise onset signal to. Defaults to 1.
type (str, optional): ["rosa", "mm"]. Whether to use librosa or madmom for onset analysis. Madmom is slower but often more accurate. Defaults to "mm".
Returns:
th.tensor, shape=(n_frames,): Onset envelope
"""
y_perc = rosa.effects.percussive(y=audio, margin=margin)
if type == "rosa":
onset = rosa.onset.onset_strength(y=y_perc, sr=sr, fmin=fmin, fmax=fmax)
elif type == "mm":
sig = mm.audio.signal.Signal(y_perc, num_channels=1, sample_rate=sr)
sig_frames = mm.audio.signal.FramedSignal(sig, frame_size=2048, hop_size=441)
stft = mm.audio.stft.ShortTimeFourierTransform(sig_frames, circular_shift=True)
spec = mm.audio.spectrogram.Spectrogram(stft, circular_shift=True)
filt_spec = mm.audio.spectrogram.FilteredSpectrogram(spec, num_bands=24, fmin=fmin, fmax=fmax)
onset = np.sum(
[
mm.features.onsets.spectral_diff(filt_spec),
mm.features.onsets.spectral_flux(filt_spec),
mm.features.onsets.superflux(filt_spec),
mm.features.onsets.complex_flux(filt_spec),
mm.features.onsets.modified_kullback_leibler(filt_spec),
],
axis=0,
)
onset = np.clip(signal.resample(onset, n_frames), onset.min(), onset.max())
onset = th.from_numpy(onset).float()
onset = gaussian_filter(onset, smooth, causal=0)
onset = percentile_clip(onset, clip)
onset = onset ** power
return onset
def rms(y, sr, n_frames, fmin=20, fmax=8000, smooth=180, clip=50, power=6):
"""Creates RMS envelope from audio
Args:
audio (np.array): Audio signal
sr (int): Sampling rate of the audio
n_frames (int): Total number of frames to resample envelope to
fmin (int, optional): Minimum frequency for onset analysis. Defaults to 20.
fmax (int, optional): Maximum frequency for onset analysis. Defaults to 8000.
smooth (int, optional): Standard deviation of gaussian kernel to smooth with. Defaults to 180.
clip (int, optional): Percentile to clip onset signal to. Defaults to 50.
power (int, optional): Exponent to raise onset signal to. Defaults to 6.
Returns:
th.tensor, shape=(n_frames,): RMS envelope
"""
y_filt = signal.sosfilt(signal.butter(12, [fmin, fmax], "bp", fs=sr, output="sos"), y)
rms = rosa.feature.rms(S=np.abs(rosa.stft(y=y_filt, hop_length=512)))[0]
rms = np.clip(signal.resample(rms, n_frames), rms.min(), rms.max())
rms = th.from_numpy(rms).float()
rms = gaussian_filter(rms, smooth, causal=0.05)
rms = percentile_clip(rms, clip)
rms = rms ** power
return rms
def raw_chroma(audio, sr, type="cens", nearest_neighbor=True):
"""Creates chromagram
Args:
audio (np.array): Audio signal
sr (int): Sampling rate of the audio
type (str, optional): ["cens", "cqt", "stft", "deep", "clp"]. Which strategy to use to calculate the chromagram. Defaults to "cens".
nearest_neighbor (bool, optional): Whether to post process using nearest neighbor smoothing. Defaults to True.
Returns:
np.array, shape=(12, n_frames): Chromagram
"""
if type == "cens":
ch = rosa.feature.chroma_cens(y=audio, sr=sr)
elif type == "cqt":
ch = rosa.feature.chroma_cqt(y=audio, sr=sr)
elif type == "stft":
ch = rosa.feature.chroma_stft(y=audio, sr=sr)
elif type == "deep":
sig = mm.audio.signal.Signal(audio, num_channels=1, sample_rate=sr)
ch = mm.audio.chroma.DeepChromaProcessor().process(sig).T
elif type == "clp":
sig = mm.audio.signal.Signal(audio, num_channels=1, sample_rate=sr)
ch = mm.audio.chroma.CLPChromaProcessor().process(sig).T
else:
print("chroma type not recognized, options are: [cens, cqt, deep, clp, or stft]. defaulting to cens...")
ch = rosa.feature.chroma_cens(y=audio, sr=sr)
if nearest_neighbor:
ch = np.minimum(ch, rosa.decompose.nn_filter(ch, aggregate=np.median, metric="cosine"))
return ch
def chroma(audio, sr, n_frames, margin=16, type="cens", notes=12):
"""Creates chromagram for the harmonic component of the audio
Args:
audio (np.array): Audio signal
sr (int): Sampling rate of the audio
n_frames (int): Total number of frames to resample envelope to
margin (int, optional): For harmonic source separation, higher values create more extreme separations. Defaults to 16.
type (str, optional): ["cens", "cqt", "stft", "deep", "clp"]. Which strategy to use to calculate the chromagram. Defaults to "cens".
notes (int, optional): Number of notes to use in output chromagram (e.g. 5 for pentatonic scale, 7 for standard western scales). Defaults to 12.
Returns:
th.tensor, shape=(n_frames, 12): Chromagram
"""
y_harm = rosa.effects.harmonic(y=audio, margin=margin)
chroma = raw_chroma(y_harm, sr, type=type).T
chroma = signal.resample(chroma, n_frames)
notes_indices = np.argsort(np.median(chroma, axis=0))[:notes]
chroma = chroma[:, notes_indices]
chroma = th.from_numpy(chroma / chroma.sum(1)[:, None]).float()
return chroma
def laplacian_segmentation(signal, sr, k=5, plot=False):
"""Segments the audio with pattern recurrence analysis
From https://librosa.org/doc/latest/auto_examples/plot_segmentation.html#sphx-glr-auto-examples-plot-segmentation-py%22
Args:
signal (np.array): Audio signal
sr (int): Sampling rate of the audio
k (int, optional): Number of labels to use during segmentation. Defaults to 5.
plot (bool, optional): Whether to show plot of found segmentation. Defaults to False.
Returns:
tuple(list, list): List of starting timestamps and labels of found segments
"""
BINS_PER_OCTAVE = 12 * 3
N_OCTAVES = 7
C = librosa.amplitude_to_db(
np.abs(librosa.cqt(y=signal, sr=sr, bins_per_octave=BINS_PER_OCTAVE, n_bins=N_OCTAVES * BINS_PER_OCTAVE)),
ref=np.max,
)
# make CQT beat-synchronous to reduce dimensionality
tempo, beats = librosa.beat.beat_track(y=signal, sr=sr, trim=False)
Csync = librosa.util.sync(C, beats, aggregate=np.median)
# build a weighted recurrence matrix using beat-synchronous CQT
R = librosa.segment.recurrence_matrix(Csync, width=3, mode="affinity", sym=True)
# enhance diagonals with a median filter
df = librosa.segment.timelag_filter(scipy.ndimage.median_filter)
Rf = df(R, size=(1, 7))
# build the sequence matrix using mfcc-similarity
mfcc = librosa.feature.mfcc(y=signal, sr=sr)
Msync = librosa.util.sync(mfcc, beats)
path_distance = np.sum(np.diff(Msync, axis=1) ** 2, axis=0)
sigma = np.median(path_distance)
path_sim = np.exp(-path_distance / sigma)
R_path = np.diag(path_sim, k=1) + np.diag(path_sim, k=-1)
# compute the balanced combination
deg_path = np.sum(R_path, axis=1)
deg_rec = np.sum(Rf, axis=1)
mu = deg_path.dot(deg_path + deg_rec) / np.sum((deg_path + deg_rec) ** 2)
A = mu * Rf + (1 - mu) * R_path
# compute the normalized laplacian and its spectral decomposition
L = scipy.sparse.csgraph.laplacian(A, normed=True)
evals, evecs = scipy.linalg.eigh(L)
# median filter to smooth over small discontinuities
evecs = scipy.ndimage.median_filter(evecs, size=(9, 1))
# cumulative normalization for symmetric normalized laplacian eigenvectors
Cnorm = np.cumsum(evecs ** 2, axis=1) ** 0.5
X = evecs[:, :k] / Cnorm[:, k - 1 : k]
# use first k components to cluster beats into segments
seg_ids = sklearn.cluster.KMeans(n_clusters=k).fit_predict(X)
bound_beats = 1 + np.flatnonzero(seg_ids[:-1] != seg_ids[1:]) # locate segment boundaries from the label sequence
bound_beats = librosa.util.fix_frames(bound_beats, x_min=0) # count beat 0 as a boundary
bound_segs = list(seg_ids[bound_beats]) # compute the segment label for each boundary
bound_frames = beats[bound_beats] # convert beat indices to frames
bound_frames = librosa.util.fix_frames(bound_frames, x_min=None, x_max=C.shape[1] - 1)
bound_times = librosa.frames_to_time(bound_frames)
if bound_times[0] != 0:
bound_times[0] = 0
if plot:
freqs = librosa.cqt_frequencies(
n_bins=C.shape[0], fmin=librosa.note_to_hz("C1"), bins_per_octave=BINS_PER_OCTAVE
)
fig, ax = plt.subplots()
colors = plt.get_cmap("Paired", k)
librosa.display.specshow(C, y_axis="cqt_hz", sr=sr, bins_per_octave=BINS_PER_OCTAVE, x_axis="time", ax=ax)
for interval, label in zip(zip(bound_times, bound_times[1:]), bound_segs):
ax.add_patch(
patches.Rectangle(
(interval[0], freqs[0]), interval[1] - interval[0], freqs[-1], facecolor=colors(label), alpha=0.50
)
)
plt.show()
return list(bound_times), list(bound_segs)
def normalize(signal):
"""Normalize signal between 0 and 1
Args:
signal (np.array/th.tensor): Signal to normalize
Returns:
np.array/th.tensor: Normalized signal
"""
signal -= signal.min()
signal /= signal.max()
return signal
def percentile(signal, p):
"""Calculate percentile of signal
Args:
signal (np.array/th.tensor): Signal to normalize
p (int): [0-100]. Percentile to find
Returns:
int: Percentile signal value
"""
k = 1 + round(0.01 * float(p) * (signal.numel() - 1))
return signal.view(-1).kthvalue(k).values.item()
def percentile_clip(signal, p):
"""Normalize signal between 0 and 1, clipping peak values above given percentile
Args:
signal (th.tensor): Signal to normalize
p (int): [0-100]. Percentile to clip to
Returns:
th.tensor: Clipped signal
"""
locs = th.arange(0, signal.shape[0])
peaks = th.ones(signal.shape, dtype=bool)
main = signal.take(locs)
plus = signal.take((locs + 1).clamp(0, signal.shape[0] - 1))
minus = signal.take((locs - 1).clamp(0, signal.shape[0] - 1))
peaks &= th.gt(main, plus)
peaks &= th.gt(main, minus)
signal = signal.clamp(0, percentile(signal[peaks], p))
signal /= signal.max()
return signal
def compress(signal, threshold, ratio, invert=False):
"""Expand or compress signal. Values above/below (depending on invert) threshold are multiplied by ratio.
Args:
signal (th.tensor): Signal to normalize
threshold (int): Signal value above/below which to change signal
ratio (float): Value to multiply signal with
invert (bool, optional): Specifies if values above or below threshold are affected. Defaults to False.
Returns:
th.tensor: Compressed/expanded signal
"""
if invert:
signal[signal < threshold] *= ratio
else:
signal[signal > threshold] *= ratio
return normalize(signal)
def expand(signal, threshold, ratio, invert=False):
"""Alias for compress. Whether compression or expansion occurs is determined by values of threshold and ratio"""
return compress(signal, threshold, ratio, invert)
def gaussian_filter(x, sigma, causal=None):
"""Smooth tensors along time (first) axis with gaussian kernel.
Args:
x (th.tensor): Tensor to be smoothed
sigma (float): Standard deviation for gaussian kernel (higher value gives smoother result)
causal (float, optional): Factor to multiply right side of gaussian kernel with. Lower value decreases effect of "future" values. Defaults to None.
Returns:
th.tensor: Smoothed tensor
"""
dim = len(x.shape)
n_frames = x.shape[0]
while len(x.shape) < 3:
x = x[:, None]
radius = min(int(sigma * 4 * SMF), 3 * len(x))
channels = x.shape[1]
kernel = th.arange(-radius, radius + 1, dtype=th.float32, device=x.device)
kernel = th.exp(-0.5 / sigma ** 2 * kernel ** 2)
if causal is not None:
kernel[radius + 1 :] *= 0 if not isinstance(causal, float) else causal
kernel = kernel / kernel.sum()
kernel = kernel.view(1, 1, len(kernel)).repeat(channels, 1, 1)
if dim == 4:
t, c, h, w = x.shape
x = x.view(t, c, h * w)
x = x.transpose(0, 2)
if radius > n_frames: # prevent padding errors on short sequences
x = F.pad(x, (n_frames, n_frames), mode="circular")
print(
f"WARNING: Gaussian filter radius ({int(sigma * 4 * SMF)}) is larger than number of frames ({n_frames}).\n\t Filter size has been lowered to ({radius}). You might want to consider lowering sigma ({sigma})."
)
x = F.pad(x, (radius - n_frames, radius - n_frames), mode="constant")
else:
x = F.pad(x, (radius, radius), mode="circular")
x = F.conv1d(x, weight=kernel, groups=channels)
x = x.transpose(0, 2)
if dim == 4:
x = x.view(t, c, h, w)
if len(x.shape) > dim:
x = x.squeeze()
return x
def load_audio(audio_file, offset=0, duration=-1, cache=True):
"""Handles loading of audio files. Automatically caches to .npy files to increase loading speed.
Args:
audio_file (str): Path to audio file to load
offset (float, optional): Time (in seconds) to start from. Defaults to 0.
duration (float, optional): Length of time to load in. Defaults to -1 (full duration).
cache (bool): Whether to cache the raw audio file or not
Returns:
audio : audio signal
sr : sample rate of audio
duration: duration of audio in seconds
"""
audio_dur = rosa.get_duration(filename=audio_file)
if duration == -1 or audio_dur < duration:
duration = audio_dur
if offset != 0:
duration -= offset
cache_file = (
f"workspace/{Path(audio_file).stem}"
+ ("" if duration == -1 else f"_length{duration}")
+ ("" if offset == 0 else f"_start{offset}")
+ ".npy"
)
if cache and not os.path.exists(cache_file):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="PySoundFile failed. Trying audioread instead.")
audio, sr = rosa.load(audio_file, offset=offset, duration=duration)
joblib.dump((audio, sr), cache_file)
else:
audio, sr = joblib.load(cache_file)
return audio, sr, duration
================================================
FILE: audioreactive/util.py
================================================
import librosa as rosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
# ====================================================================================
# ==================================== utilities =====================================
# ====================================================================================
def info(arr):
"""Shows statistics and shape information of (lists of) np.arrays/th.tensors
Args:
arr (np.array/th.tensor/list): List of or single np.array or th.tensor
"""
if isinstance(arr, list):
print([(list(a.shape), f"{a.min():.2f}", f"{a.mean():.2f}", f"{a.max():.2f}") for a in arr])
else:
print(list(arr.shape), f"{arr.min():.2f}", f"{arr.mean():.2f}", f"{arr.max():.2f}")
def plot_signals(signals):
"""Shows plot of (multiple) 1D signals
Args:
signals (np.array/th.tensor): List of signals (1 non-unit dimension)
"""
plt.figure(figsize=(16, 4 * len(signals)))
for sbplt, y in enumerate(signals):
try:
signal = signal.cpu().numpy()
except:
pass
plt.subplot(len(signals), 1, sbplt + 1)
plt.plot(y.squeeze())
plt.tight_layout()
plt.show()
def plot_spectra(spectra, chroma=False):
"""Shows plot of (multiple) spectrograms
Args:
spectra (np.array/th.tensor): List of spectrograms
chroma (bool, optional): Whether to plot with chromagram y-axis label. Defaults to False.
"""
fig, axes = plt.subplots(len(spectra), 1, figsize=(16, 4 * len(spectra)))
for ax, spectrum in zip(axes if len(spectra) > 1 else [axes], spectra):
try:
spectrum = spectrum.cpu().numpy()
except:
pass
if spectrum.shape[1] == 12:
spectrum = spectrum.T
rosa.display.specshow(spectrum, y_axis="chroma" if chroma else None, x_axis="time", ax=ax)
plt.tight_layout()
plt.show()
def plot_audio(audio, sr):
"""Shows spectrogram of audio signal
Args:
audio (np.array): Audio signal to be plotted
sr (int): Sampling rate of the audio
"""
plt.figure(figsize=(16, 9))
rosa.display.specshow(
rosa.power_to_db(rosa.feature.melspectrogram(y=audio, sr=sr), ref=np.max), y_axis="mel", x_axis="time"
)
plt.colorbar(format="%+2.f dB")
plt.tight_layout()
plt.show()
def plot_chroma_comparison(audio, sr):
"""Shows plot comparing different chromagram strategies.
Args:
audio (np.array): Audio signal to be plotted
sr (int): Sampling rate of the audio
"""
fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(16, 9))
for col, types in enumerate([["cens", "cqt"], ["deep", "clp"], ["stft"]]):
for row, type in enumerate(types):
ch = raw_chroma(audio, sr, type=type)
if ch.shape[1] == 12:
ch = ch.T
librosa.display.specshow(ch, y_axis="chroma", x_axis="time", ax=ax[row, col])
ax[row, col].set(title=type)
ax[row, col].label_outer()
plt.tight_layout()
plt.show()
================================================
FILE: augment.py
================================================
import math
import torch
from torch.nn import functional as F
from op import upfirdn2d
SYM6 = (
0.015404109327027373,
0.0034907120842174702,
-0.11799011114819057,
-0.048311742585633,
0.4910559419267466,
0.787641141030194,
0.3379294217276218,
-0.07263752278646252,
-0.021060292512300564,
0.04472490177066578,
0.0017677118642428036,
-0.007800708325034148,
)
def translate_mat(t_x, t_y):
batch = t_x.shape[0]
mat = torch.eye(3).unsqueeze(0).repeat(batch, 1, 1)
translate = torch.stack((t_x, t_y), 1)
mat[:, :2, 2] = translate
return mat
def rotate_mat(theta):
batch = theta.shape[0]
mat = torch.eye(3).unsqueeze(0).repeat(batch, 1, 1)
sin_t = torch.sin(theta)
cos_t = torch.cos(theta)
rot = torch.stack((cos_t, -sin_t, sin_t, cos_t), 1).view(batch, 2, 2)
mat[:, :2, :2] = rot
return mat
def scale_mat(s_x, s_y):
batch = s_x.shape[0]
mat = torch.eye(3).unsqueeze(0).repeat(batch, 1, 1)
mat[:, 0, 0] = s_x
mat[:, 1, 1] = s_y
return mat
def translate3d_mat(t_x, t_y, t_z):
batch = t_x.shape[0]
mat = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1)
translate = torch.stack((t_x, t_y, t_z), 1)
mat[:, :3, 3] = translate
return mat
def rotate3d_mat(axis, theta):
batch = theta.shape[0]
u_x, u_y, u_z = axis
eye = torch.eye(3).unsqueeze(0)
cross = torch.tensor([(0, -u_z, u_y), (u_z, 0, -u_x), (-u_y, u_x, 0)]).unsqueeze(0)
outer = torch.tensor(axis)
outer = (outer.unsqueeze(1) * outer).unsqueeze(0)
sin_t = torch.sin(theta).view(-1, 1, 1)
cos_t = torch.cos(theta).view(-1, 1, 1)
rot = cos_t * eye + sin_t * cross + (1 - cos_t) * outer
eye_4 = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1)
eye_4[:, :3, :3] = rot
return eye_4
def scale3d_mat(s_x, s_y, s_z):
batch = s_x.shape[0]
mat = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1)
mat[:, 0, 0] = s_x
mat[:, 1, 1] = s_y
mat[:, 2, 2] = s_z
return mat
def luma_flip_mat(axis, i):
batch = i.shape[0]
eye = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1)
axis = torch.tensor(axis + (0,))
flip = 2 * torch.ger(axis, axis) * i.view(-1, 1, 1)
return eye - flip
def saturation_mat(axis, i):
batch = i.shape[0]
eye = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1)
axis = torch.tensor(axis + (0,))
axis = torch.ger(axis, axis)
saturate = axis + (eye - axis) * i.view(-1, 1, 1)
return saturate
def lognormal_sample(size, mean=0, std=1):
return torch.empty(size).log_normal_(mean=mean, std=std)
def category_sample(size, categories):
category = torch.tensor(categories)
sample = torch.randint(high=len(categories), size=(size,))
return category[sample]
def uniform_sample(size, low, high):
return torch.empty(size).uniform_(low, high)
def normal_sample(size, mean=0, std=1):
return torch.empty(size).normal_(mean, std)
def bernoulli_sample(size, p):
return torch.empty(size).bernoulli_(p)
def random_mat_apply(p, transform, prev, eye):
size = transform.shape[0]
select = bernoulli_sample(size, p).view(size, 1, 1)
select_transform = select * transform + (1 - select) * eye
return select_transform @ prev
def sample_affine(p, size, height, width):
G = torch.eye(3).unsqueeze(0).repeat(size, 1, 1)
eye = G
# flip
param = category_sample(size, (0, 1))
Gc = scale_mat(1 - 2.0 * param, torch.ones(size))
G = random_mat_apply(p, Gc, G, eye)
# print('flip', G, scale_mat(1 - 2.0 * param, torch.ones(size)), sep='\n')
# 90 rotate
param = category_sample(size, (0, 3))
Gc = rotate_mat(-math.pi / 2 * param)
G = random_mat_apply(p, Gc, G, eye)
# print('90 rotate', G, rotate_mat(-math.pi / 2 * param), sep='\n')
# integer translate
param = uniform_sample(size, -0.125, 0.125)
param_height = torch.round(param * height) / height
param_width = torch.round(param * width) / width
Gc = translate_mat(param_width, param_height)
G = random_mat_apply(p, Gc, G, eye)
# print('integer translate', G, translate_mat(param_width, param_height), sep='\n')
# isotropic scale
param = lognormal_sample(size, std=0.2 * math.log(2))
Gc = scale_mat(param, param)
G = random_mat_apply(p, Gc, G, eye)
# print('isotropic scale', G, scale_mat(param, param), sep='\n')
p_rot = 1 - math.sqrt(1 - p)
# pre-rotate
param = uniform_sample(size, -math.pi, math.pi)
Gc = rotate_mat(-param)
G = random_mat_apply(p_rot, Gc, G, eye)
# print('pre-rotate', G, rotate_mat(-param), sep='\n')
# anisotropic scale
param = lognormal_sample(size, std=0.2 * math.log(2))
Gc = scale_mat(param, 1 / param)
G = random_mat_apply(p, Gc, G, eye)
# print('anisotropic scale', G, scale_mat(param, 1 / param), sep='\n')
# post-rotate
param = uniform_sample(size, -math.pi, math.pi)
Gc = rotate_mat(-param)
G = random_mat_apply(p_rot, Gc, G, eye)
# print('post-rotate', G, rotate_mat(-param), sep='\n')
# fractional translate
param = normal_sample(size, std=0.125)
Gc = translate_mat(param, param)
G = random_mat_apply(p, Gc, G, eye)
# print('fractional translate', G, translate_mat(param, param), sep='\n')
return G
def sample_color(p, size):
C = torch.eye(4).unsqueeze(0).repeat(size, 1, 1)
eye = C
axis_val = 1 / math.sqrt(3)
axis = (axis_val, axis_val, axis_val)
# brightness
param = normal_sample(size, std=0.2)
Cc = translate3d_mat(param, param, param)
C = random_mat_apply(p, Cc, C, eye)
# contrast
param = lognormal_sample(size, std=0.5 * math.log(2))
Cc = scale3d_mat(param, param, param)
C = random_mat_apply(p, Cc, C, eye)
# luma flip
param = category_sample(size, (0, 1))
Cc = luma_flip_mat(axis, param)
C = random_mat_apply(p, Cc, C, eye)
# hue rotation
param = uniform_sample(size, -math.pi, math.pi)
Cc = rotate3d_mat(axis, param)
C = random_mat_apply(p, Cc, C, eye)
# saturation
param = lognormal_sample(size, std=1 * math.log(2))
Cc = saturation_mat(axis, param)
C = random_mat_apply(p, Cc, C, eye)
return C
def make_grid(shape, x0, x1, y0, y1, device):
n, c, h, w = shape
grid = torch.empty(n, h, w, 3, device=device)
grid[:, :, :, 0] = torch.linspace(x0, x1, w, device=device)
grid[:, :, :, 1] = torch.linspace(y0, y1, h, device=device).unsqueeze(-1)
grid[:, :, :, 2] = 1
return grid
def affine_grid(grid, mat):
n, h, w, _ = grid.shape
return (grid.view(n, h * w, 3) @ mat.transpose(1, 2)).view(n, h, w, 2)
def get_padding(G, height, width):
extreme = G[:, :2, :] @ torch.tensor([(-1.0, -1, 1), (-1, 1, 1), (1, -1, 1), (1, 1, 1)]).t()
size = torch.tensor((width, height))
pad_low = ((extreme.min(-1).values + 1) * size).clamp(max=0).abs().ceil().max(0).values.to(torch.int64).tolist()
pad_high = (extreme.max(-1).values * size - size).clamp(min=0).ceil().max(0).values.to(torch.int64).tolist()
return pad_low[0], pad_high[0], pad_low[1], pad_high[1]
def try_sample_affine_and_pad(img, p, pad_k, G=None):
batch, _, height, width = img.shape
G_try = G
while True:
if G is None:
G_try = sample_affine(p, batch, height, width)
pad_x1, pad_x2, pad_y1, pad_y2 = get_padding(torch.inverse(G_try), height, width)
try:
img_pad = F.pad(img, (pad_x1 + pad_k, pad_x2 + pad_k, pad_y1 + pad_k, pad_y2 + pad_k), mode="reflect",)
except RuntimeError:
continue
break
return img_pad, G_try, (pad_x1, pad_x2, pad_y1, pad_y2)
def random_apply_affine(img, p, G=None, antialiasing_kernel=SYM6):
kernel = antialiasing_kernel
len_k = len(kernel)
pad_k = (len_k + 1) // 2
kernel = torch.as_tensor(kernel)
kernel = torch.ger(kernel, kernel).to(img)
kernel_flip = torch.flip(kernel, (0, 1))
img_pad, G, (pad_x1, pad_x2, pad_y1, pad_y2) = try_sample_affine_and_pad(img, p, pad_k, G)
p_ux1 = pad_x1
p_ux2 = pad_x2 + 1
p_uy1 = pad_y1
p_uy2 = pad_y2 + 1
w_p = img_pad.shape[3] - len_k + 1
h_p = img_pad.shape[2] - len_k + 1
h_o = img.shape[2]
w_o = img.shape[3]
img_2x = upfirdn2d(img_pad, kernel_flip, up=2)
grid = make_grid(
img_2x.shape,
-2 * p_ux1 / w_o - 1,
2 * (w_p - p_ux1) / w_o - 1,
-2 * p_uy1 / h_o - 1,
2 * (h_p - p_uy1) / h_o - 1,
device=img_2x.device,
).to(img_2x)
grid = affine_grid(grid, torch.inverse(G)[:, :2, :].to(img_2x))
grid = grid * torch.tensor([w_o / w_p, h_o / h_p], device=grid.device) + torch.tensor(
[(w_o + 2 * p_ux1) / w_p - 1, (h_o + 2 * p_uy1) / h_p - 1], device=grid.device
)
img_affine = F.grid_sample(img_2x, grid, mode="bilinear", align_corners=False, padding_mode="zeros")
img_down = upfirdn2d(img_affine, kernel, down=2)
end_y = -pad_y2 - 1
if end_y == 0:
end_y = img_down.shape[2]
end_x = -pad_x2 - 1
if end_x == 0:
end_x = img_down.shape[3]
img = img_down[:, :, pad_y1:end_y, pad_x1:end_x]
return img, G
def apply_color(img, mat):
batch = img.shape[0]
img = img.permute(0, 2, 3, 1)
mat_mul = mat[:, :3, :3].transpose(1, 2).view(batch, 1, 3, 3)
mat_add = mat[:, :3, 3].view(batch, 1, 1, 3)
img = img @ mat_mul + mat_add
img = img.permute(0, 3, 1, 2)
return img
def random_apply_color(img, p, C=None):
if C is None:
C = sample_color(p, img.shape[0])
img = apply_color(img, C.to(img))
return img, C
def augment(img, p, transform_matrix=(None, None)):
img, G = random_apply_affine(img, p, transform_matrix[0])
img, C = random_apply_color(img, p, transform_matrix[1])
return img, (G, C)
================================================
FILE: contrastive_learner.py
================================================
import copy
import random
from functools import wraps
import torch
from torch import nn
import torch.nn.functional as F
def identity(x):
return x
def default(val, def_val):
return def_val if val is None else val
def flatten(t):
return t.reshape(t.shape[0], -1)
def safe_concat(arr, el, dim=0):
if arr is None:
return el
return torch.cat((arr, el), dim=dim)
def singleton(cache_key):
def inner_fn(fn):
@wraps(fn)
def wrapper(self, *args, **kwargs):
instance = getattr(self, cache_key)
if instance is not None:
return instance
instance = fn(self, *args, **kwargs)
setattr(self, cache_key, instance)
return instance
return wrapper
return inner_fn
# losses
def contrastive_loss(queries, keys, temperature=0.1):
b, device = queries.shape[0], queries.device
logits = queries @ keys.t()
logits = logits - logits.max(dim=-1, keepdim=True).values
logits /= temperature
return F.cross_entropy(logits, torch.arange(b, device=device))
def nt_xent_loss(queries, keys, temperature=0.1):
b, device = queries.shape[0], queries.device
n = b * 2
projs = torch.cat((queries, keys))
logits = projs @ projs.t()
mask = torch.eye(n, device=device).bool()
logits = logits[~mask].reshape(n, n - 1)
logits /= temperature
labels = torch.cat(((torch.arange(b, device=device) + b - 1), torch.arange(b, device=device)), dim=0)
loss = F.cross_entropy(logits, labels, reduction="sum")
loss /= 2 * (b - 1)
return loss
# augmentation utils
class RandomApply(nn.Module):
def __init__(self, fn, p):
super().__init__()
self.fn = fn
self.p = p
def forward(self, x):
x_out = []
for ex in x:
if random.random() > self.p:
x_out.append(ex[None, :])
else:
x_out.append(self.fn(ex))
return torch.cat(x_out)
# exponential moving average
class EMA:
def __init__(self, beta):
super(
gitextract_lesmzkyd/
├── .gitignore
├── LICENSE/
│ ├── LICENSE-AUDIOREACTIVE
│ ├── LICENSE-AUTOENCODER
│ ├── LICENSE-CONTRASTIVE-LEARNER
│ ├── LICENSE-FID
│ ├── LICENSE-LPIPS
│ ├── LICENSE-LUCIDRAINS
│ ├── LICENSE-NVIDIA
│ ├── LICENSE-ROSINALITY
│ └── LICENSE-VGG
├── README.md
├── accelerate/
│ ├── accelerate_inception.py
│ ├── accelerate_logcosh.py
│ └── accelerate_segnet.py
├── audioreactive/
│ ├── __init__.py
│ ├── bend.py
│ ├── examples/
│ │ ├── __init__.py
│ │ ├── default.py
│ │ ├── kelp.py
│ │ ├── tauceti.py
│ │ └── temper.py
│ ├── latent.py
│ ├── signal.py
│ └── util.py
├── augment.py
├── contrastive_learner.py
├── convert_weight.py
├── dataset.py
├── distributed.py
├── generate.py
├── generate_audiovisual.py
├── generate_video.py
├── gpu_profile.py
├── gpumon.py
├── lightning.py
├── lookahead_minimax.py
├── lucidrains.py
├── models/
│ ├── autoencoder.py
│ ├── stylegan1.py
│ └── stylegan2.py
├── op/
│ ├── __init__.py
│ ├── fused_act.py
│ ├── fused_bias_act.cpp
│ ├── fused_bias_act_kernel.cu
│ ├── upfirdn2d.cpp
│ ├── upfirdn2d.py
│ └── upfirdn2d_kernel.cu
├── prepare_data.py
├── prepare_vae_codes.py
├── projector.py
├── render.py
├── requirements.txt
├── select_latents.py
├── train.py
├── train_profile.py
├── validation/
│ ├── __init__.py
│ ├── calc_fid.py
│ ├── calc_inception.py
│ ├── calc_ppl.py
│ ├── inception.py
│ ├── lpips/
│ │ ├── __init__.py
│ │ ├── base_model.py
│ │ ├── dist_model.py
│ │ ├── networks_basic.py
│ │ ├── pretrained_networks.py
│ │ ├── util.py
│ │ └── weights/
│ │ ├── v0.0/
│ │ │ ├── alex.pth
│ │ │ ├── squeeze.pth
│ │ │ └── vgg.pth
│ │ └── v0.1/
│ │ ├── alex.pth
│ │ ├── squeeze.pth
│ │ └── vgg.pth
│ ├── metrics.py
│ └── spectral_norm.py
└── workspace/
├── naamloos_average_pitch.npy
├── naamloos_bass_sum.npy
├── naamloos_drop_latents.npy
├── naamloos_drop_latents_1.npy
├── naamloos_high_average_pitch.npy
├── naamloos_high_pitches_mean.npy
├── naamloos_intro_latents.npy
├── naamloos_metadata.json
├── naamloos_onsets.npy
├── naamloos_params.json
├── naamloos_pitches_mean.npy
└── naamloos_rms.npy
SYMBOL INDEX (689 symbols across 50 files)
FILE: accelerate/accelerate_inception.py
function info (line 14) | def info(x):
function sample_data (line 18) | def sample_data(loader):
class VGG19 (line 24) | class VGG19(th.nn.Module):
method __init__ (line 30) | def __init__(self, requires_grad=False):
method forward (line 52) | def forward(self, X):
class VGGLoss (line 62) | class VGGLoss(th.nn.Module):
method __init__ (line 68) | def __init__(self):
method forward (line 74) | def forward(self, x, y):
function train (line 82) | def train(latent_dim, num_repeats, learning_rate, lambda_vgg, lambda_mse):
FILE: accelerate/accelerate_logcosh.py
function data_sampler (line 14) | def data_sampler(dataset, shuffle, distributed):
function sample_data (line 23) | def sample_data(loader):
class VGG19 (line 29) | class VGG19(th.nn.Module):
method __init__ (line 35) | def __init__(self, requires_grad=False):
method forward (line 57) | def forward(self, X):
class VGGLoss (line 67) | class VGGLoss(th.nn.Module):
method __init__ (line 73) | def __init__(self):
method forward (line 79) | def forward(self, x, y):
function train (line 93) | def train(latent_dim, learning_rate, number_filters, vae_alpha, vae_beta...
FILE: accelerate/accelerate_segnet.py
function info (line 13) | def info(x):
function sample_data (line 17) | def sample_data(loader):
class VGG19 (line 23) | class VGG19(th.nn.Module):
method __init__ (line 29) | def __init__(self, requires_grad=False):
method forward (line 51) | def forward(self, X):
class VGGLoss (line 61) | class VGGLoss(th.nn.Module):
method __init__ (line 67) | def __init__(self):
method forward (line 73) | def forward(self, x, y):
function align (line 81) | def align(x, y, alpha=2):
function uniform (line 85) | def uniform(x, t=2):
function train (line 89) | def train(learning_rate, lambda_mse):
FILE: audioreactive/bend.py
class NetworkBend (line 12) | class NetworkBend(th.nn.Module):
method __init__ (line 20) | def __init__(self, sequential_fn, modulation):
method forward (line 24) | def forward(self, x):
class AddNoise (line 28) | class AddNoise(th.nn.Module):
method __init__ (line 35) | def __init__(self, noise):
method forward (line 39) | def forward(self, x):
class Print (line 43) | class Print(th.nn.Module):
method forward (line 46) | def forward(self, x):
class Translate (line 51) | class Translate(NetworkBend):
method __init__ (line 61) | def __init__(self, modulation, h, w, noise):
class Zoom (line 73) | class Zoom(NetworkBend):
method __init__ (line 82) | def __init__(self, modulation, h, w):
class Rotate (line 88) | class Rotate(NetworkBend):
method __init__ (line 97) | def __init__(self, modulation, h, w):
FILE: audioreactive/examples/default.py
function initialize (line 6) | def initialize(args):
function get_latents (line 12) | def get_latents(selection, args):
function get_noise (line 28) | def get_noise(height, width, scale, num_scales, args):
FILE: audioreactive/examples/kelp.py
function initialize (line 18) | def initialize(args):
function get_latents (line 38) | def get_latents(selection, args):
function get_noise (line 90) | def get_noise(height, width, scale, num_scales, args):
function get_bends (line 113) | def get_bends(args):
FILE: audioreactive/examples/tauceti.py
function initialize (line 23) | def initialize(args):
function get_latents (line 29) | def get_latents(selection, args):
function get_noise (line 75) | def get_noise(height, width, scale, num_scales, args):
function get_bends (line 94) | def get_bends(args):
FILE: audioreactive/examples/temper.py
function initialize (line 14) | def initialize(args):
function get_latents (line 22) | def get_latents(selection, args):
function circular_mask (line 41) | def circular_mask(h, w, center=None, radius=None, soft=0):
function get_noise (line 57) | def get_noise(height, width, scale, num_scales, args):
FILE: audioreactive/latent.py
function chroma_weight_latents (line 15) | def chroma_weight_latents(chroma, latents):
function slerp (line 29) | def slerp(val, low, high):
function slerp_loops (line 48) | def slerp_loops(latent_selection, n_frames, n_loops, smoothing=1, loop=T...
function spline_loops (line 85) | def spline_loops(latent_selection, n_frames, n_loops, loop=True):
function wrapping_slice (line 113) | def wrapping_slice(tensor, start, length, return_indices=False):
function generate_latents (line 136) | def generate_latents(n_latents, ckpt, G_res, noconst=False, latent_dim=5...
function save_latents (line 162) | def save_latents(latents, filename):
function load_latents (line 172) | def load_latents(filename):
function _perlinterpolant (line 184) | def _perlinterpolant(t):
function perlin_noise (line 188) | def perlin_noise(shape, res, tileable=(True, False, False), interpolant=...
FILE: audioreactive/signal.py
function set_SMF (line 21) | def set_SMF(smf):
function onsets (line 31) | def onsets(audio, sr, n_frames, margin=8, fmin=20, fmax=8000, smooth=1, ...
function rms (line 76) | def rms(y, sr, n_frames, fmin=20, fmax=8000, smooth=180, clip=50, power=6):
function raw_chroma (line 102) | def raw_chroma(audio, sr, type="cens", nearest_neighbor=True):
function chroma (line 136) | def chroma(audio, sr, n_frames, margin=16, type="cens", notes=12):
function laplacian_segmentation (line 159) | def laplacian_segmentation(signal, sr, k=5, plot=False):
function normalize (line 243) | def normalize(signal):
function percentile (line 257) | def percentile(signal, p):
function percentile_clip (line 271) | def percentile_clip(signal, p):
function compress (line 295) | def compress(signal, threshold, ratio, invert=False):
function expand (line 314) | def expand(signal, threshold, ratio, invert=False):
function gaussian_filter (line 319) | def gaussian_filter(x, sigma, causal=None):
function load_audio (line 371) | def load_audio(audio_file, offset=0, duration=-1, cache=True):
FILE: audioreactive/util.py
function info (line 11) | def info(arr):
function plot_signals (line 23) | def plot_signals(signals):
function plot_spectra (line 41) | def plot_spectra(spectra, chroma=False):
function plot_audio (line 61) | def plot_audio(audio, sr):
function plot_chroma_comparison (line 77) | def plot_chroma_comparison(audio, sr):
FILE: augment.py
function translate_mat (line 25) | def translate_mat(t_x, t_y):
function rotate_mat (line 35) | def rotate_mat(theta):
function scale_mat (line 47) | def scale_mat(s_x, s_y):
function translate3d_mat (line 57) | def translate3d_mat(t_x, t_y, t_z):
function rotate3d_mat (line 67) | def rotate3d_mat(axis, theta):
function scale3d_mat (line 88) | def scale3d_mat(s_x, s_y, s_z):
function luma_flip_mat (line 99) | def luma_flip_mat(axis, i):
function saturation_mat (line 109) | def saturation_mat(axis, i):
function lognormal_sample (line 120) | def lognormal_sample(size, mean=0, std=1):
function category_sample (line 124) | def category_sample(size, categories):
function uniform_sample (line 131) | def uniform_sample(size, low, high):
function normal_sample (line 135) | def normal_sample(size, mean=0, std=1):
function bernoulli_sample (line 139) | def bernoulli_sample(size, p):
function random_mat_apply (line 143) | def random_mat_apply(p, transform, prev, eye):
function sample_affine (line 151) | def sample_affine(p, size, height, width):
function sample_color (line 210) | def sample_color(p, size):
function make_grid (line 244) | def make_grid(shape, x0, x1, y0, y1, device):
function affine_grid (line 254) | def affine_grid(grid, mat):
function get_padding (line 259) | def get_padding(G, height, width):
function try_sample_affine_and_pad (line 270) | def try_sample_affine_and_pad(img, p, pad_k, G=None):
function random_apply_affine (line 292) | def random_apply_affine(img, p, G=None, antialiasing_kernel=SYM6):
function apply_color (line 344) | def apply_color(img, mat):
function random_apply_color (line 355) | def random_apply_color(img, p, C=None):
function augment (line 364) | def augment(img, p, transform_matrix=(None, None)):
FILE: contrastive_learner.py
function identity (line 10) | def identity(x):
function default (line 14) | def default(val, def_val):
function flatten (line 18) | def flatten(t):
function safe_concat (line 22) | def safe_concat(arr, el, dim=0):
function singleton (line 28) | def singleton(cache_key):
function contrastive_loss (line 48) | def contrastive_loss(queries, keys, temperature=0.1):
function nt_xent_loss (line 56) | def nt_xent_loss(queries, keys, temperature=0.1):
class RandomApply (line 76) | class RandomApply(nn.Module):
method __init__ (line 77) | def __init__(self, fn, p):
method forward (line 82) | def forward(self, x):
class EMA (line 95) | class EMA:
method __init__ (line 96) | def __init__(self, beta):
method update_average (line 100) | def update_average(self, old, new):
function update_moving_average (line 106) | def update_moving_average(ema_updater, ma_model, current_model):
class OutputHiddenLayer (line 115) | class OutputHiddenLayer(nn.Module):
method __init__ (line 116) | def __init__(self, net, layer=-2):
method _find_layer (line 124) | def _find_layer(self):
method _register_hook (line 137) | def _register_hook(self):
method forward (line 145) | def forward(self, x):
class ContrastiveLearner (line 156) | class ContrastiveLearner(nn.Module):
method __init__ (line 157) | def __init__(
method _get_key_encoder (line 197) | def _get_key_encoder(self):
method _get_bilinear (line 203) | def _get_bilinear(self, hidden):
method _get_projection_fn (line 208) | def _get_projection_fn(self, hidden):
method reset_moving_average (line 214) | def reset_moving_average(self):
method update_moving_average (line 219) | def update_moving_average(self):
method calculate_loss (line 223) | def calculate_loss(self):
method forward (line 230) | def forward(self, x, aug_x, accumulate=False):
FILE: convert_weight.py
function convert_modconv (line 14) | def convert_modconv(vars, source_name, target_name, flip=False):
function convert_conv (line 40) | def convert_conv(vars, source_name, target_name, bias=True, start=0):
function convert_torgb (line 58) | def convert_torgb(vars, source_name, target_name):
function convert_dense (line 79) | def convert_dense(vars, source_name, target_name):
function update (line 93) | def update(state_dict, new):
function discriminator_fill_statedict (line 104) | def discriminator_fill_statedict(statedict, vars, size):
function fill_statedict (line 131) | def fill_statedict(state_dict, vars, size):
FILE: dataset.py
class MultiResolutionDataset (line 10) | class MultiResolutionDataset(Dataset):
method __init__ (line 11) | def __init__(self, path, transform, resolution=256):
method __len__ (line 23) | def __len__(self):
method __getitem__ (line 26) | def __getitem__(self, index):
FILE: distributed.py
function get_rank (line 7) | def get_rank():
function synchronize (line 17) | def synchronize():
function get_world_size (line 32) | def get_world_size():
function reduce_sum (line 42) | def reduce_sum(tensor):
function gather_grad (line 55) | def gather_grad(params):
function all_gather (line 67) | def all_gather(data):
function reduce_loss_dict (line 102) | def reduce_loss_dict(loss_dict):
FILE: generate.py
function generate (line 8) | def generate(args, g_ema, device, mean_latent):
FILE: generate_audiovisual.py
function get_noise_range (line 22) | def get_noise_range(out_size, generator_resolution, is_stylegan1):
function load_generator (line 37) | def load_generator(
function generate (line 59) | def generate(
FILE: generate_video.py
function gaussian_filter (line 14) | def gaussian_filter(x, sigma):
function slerp (line 42) | def slerp(val, low, high):
function lerp (line 50) | def lerp(val, low, high):
function interpolant (line 54) | def interpolant(t):
function perlin_noise (line 58) | def perlin_noise(shape, res, tileable=(True, False, False), interpolant=...
function spline_loops (line 126) | def spline_loops(base_latent_selection, loop_starting_latents, n_frames,...
function get_latent_loops (line 145) | def get_latent_loops(base_latent_selection, loop_starting_latents, n_fra...
function create_circular_mask (line 277) | def create_circular_mask(h, w, center=None, radius=None):
class addNoise (line 462) | class addNoise(th.nn.Module):
method __init__ (line 463) | def __init__(self, noise):
method forward (line 467) | def forward(self, x):
FILE: gpu_profile.py
function gpu_profile (line 28) | def gpu_profile(frame, event, arg):
function get_tensors (line 95) | def get_tensors(gpu_only=True):
FILE: gpumon.py
function enqueue_output (line 26) | def enqueue_output(out, queue):
FILE: lightning.py
function requires_grad (line 20) | def requires_grad(model, flag=True):
function get_spectral_norms (line 25) | def get_spectral_norms(model):
class StyleGAN2 (line 33) | class StyleGAN2(pl.LightningModule):
method __init__ (line 34) | def __init__(self, hparams):
method forward (line 50) | def forward(self, z):
method accumulate_g (line 53) | def accumulate_g(self, decay=0.5 ** (32.0 / (10_000))):
method configure_optimizers (line 59) | def configure_optimizers(self):
method configure_apex (line 72) | def configure_apex(self, amp, model, optimizers, amp_level):
method train_dataloader (line 83) | def train_dataloader(self):
method d_logistic_loss (line 96) | def d_logistic_loss(self, real_pred, fake_pred):
method d_r1_loss (line 101) | def d_r1_loss(self, real_pred, real_img):
method g_nonsaturating_loss (line 106) | def g_nonsaturating_loss(self, fake_pred):
method g_path_regularize (line 110) | def g_path_regularize(self, fake_img, latents, mean_path_length, decay...
method make_noise (line 119) | def make_noise(self, batch, batch_size=None):
method training_step (line 127) | def training_step(self, real_img, batch_idx, optimizer_idx):
method backward (line 202) | def backward(self, trainer, loss, optimizer, optimizer_idx):
method optimizer_step (line 212) | def optimizer_step(self, cur_epoch, batch_idx, optimizer, optimizer_id...
method prepare_data (line 224) | def prepare_data(self):
method val_dataloader (line 227) | def val_dataloader(self):
method validation_step (line 230) | def validation_step(self, batch, batch_idx):
method validation_epoch_end (line 250) | def validation_epoch_end(self, outputs):
FILE: lookahead_minimax.py
class LookaheadMinimax (line 7) | class LookaheadMinimax(Optimizer):
method __init__ (line 19) | def __init__(self, G_optimizer, D_optimizer, la_steps=5, la_alpha=0.5,...
method __getstate__ (line 59) | def __getstate__(self):
method zero_grad (line 70) | def zero_grad(self):
method get_la_step (line 73) | def get_la_step(self):
method state_dict (line 76) | def state_dict(self):
method load_state_dict (line 79) | def load_state_dict(self, G_state_dict, D_state_dict):
method _backup_and_load_cache (line 100) | def _backup_and_load_cache(self):
method _clear_and_load_backup (line 118) | def _clear_and_load_backup(self):
method param_groups (line 132) | def param_groups(self):
method step (line 135) | def step(self, closure=None):
FILE: lucidrains.py
class NanException (line 59) | class NanException(Exception):
class EMA (line 63) | class EMA:
method __init__ (line 64) | def __init__(self, beta):
method update_average (line 68) | def update_average(self, old, new):
class Flatten (line 74) | class Flatten(nn.Module):
method forward (line 75) | def forward(self, x):
class Residual (line 79) | class Residual(nn.Module):
method __init__ (line 80) | def __init__(self, fn):
method forward (line 84) | def forward(self, x):
class Rezero (line 88) | class Rezero(nn.Module):
method __init__ (line 89) | def __init__(self, fn):
method forward (line 94) | def forward(self, x):
class PermuteToFrom (line 98) | class PermuteToFrom(nn.Module):
method __init__ (line 99) | def __init__(self, fn):
method forward (line 103) | def forward(self, x):
function default (line 113) | def default(value, d):
function cycle (line 117) | def cycle(iterable):
function cast_list (line 123) | def cast_list(el):
function is_empty (line 127) | def is_empty(t):
function raise_if_nan (line 133) | def raise_if_nan(t):
function loss_backwards (line 138) | def loss_backwards(fp16, loss, optimizer, **kwargs):
function gradient_penalty (line 146) | def gradient_penalty(images, output, weight=10):
function noise (line 161) | def noise(n, latent_dim):
function noise_list (line 165) | def noise_list(n, layers, latent_dim):
function mixed_list (line 169) | def mixed_list(n, layers, latent_dim):
function latent_to_w (line 174) | def latent_to_w(style_vectorizer, latent_descr):
function image_noise (line 178) | def image_noise(n, im_size):
function leaky_relu (line 182) | def leaky_relu(p=0.2):
function evaluate_in_chunks (line 186) | def evaluate_in_chunks(max_batch_size, model, *args):
function styles_def_to_tensor (line 194) | def styles_def_to_tensor(styles_def):
function set_requires_grad (line 198) | def set_requires_grad(model, bool):
function convert_rgb_to_transparent (line 206) | def convert_rgb_to_transparent(image):
function convert_transparent_to_rgb (line 212) | def convert_transparent_to_rgb(image):
class expand_greyscale (line 218) | class expand_greyscale(object):
method __init__ (line 219) | def __init__(self, num_channels):
method __call__ (line 222) | def __call__(self, tensor):
function resize_to_minimum_size (line 226) | def resize_to_minimum_size(min_size, image):
class Dataset (line 232) | class Dataset(data.Dataset):
method __init__ (line 233) | def __init__(self, folder, image_size, transparent=False):
method __len__ (line 254) | def __len__(self):
method __getitem__ (line 257) | def __getitem__(self, index):
class StyleVectorizer (line 266) | class StyleVectorizer(nn.Module):
method __init__ (line 267) | def __init__(self, emb, depth):
method forward (line 276) | def forward(self, x):
class RGBBlock (line 280) | class RGBBlock(nn.Module):
method __init__ (line 281) | def __init__(self, latent_dim, input_channel, upsample, rgba=False):
method forward (line 291) | def forward(self, x, prev_rgb, istyle):
class Conv2DMod (line 305) | class Conv2DMod(nn.Module):
method __init__ (line 306) | def __init__(self, in_chan, out_chan, kernel, demod=True, stride=1, di...
method _get_same_padding (line 316) | def _get_same_padding(self, size, kernel, dilation, stride):
method forward (line 319) | def forward(self, x, y):
class GeneratorBlock (line 342) | class GeneratorBlock(nn.Module):
method __init__ (line 343) | def __init__(self, latent_dim, input_channels, filters, upsample=True,...
method forward (line 358) | def forward(self, x, prev_rgb, istyle, inoise):
class DiscriminatorBlock (line 378) | class DiscriminatorBlock(nn.Module):
method __init__ (line 379) | def __init__(self, input_channels, filters, downsample=True):
method forward (line 392) | def forward(self, x):
class Generator (line 401) | class Generator(nn.Module):
method __init__ (line 402) | def __init__(self, image_size, latent_dim, network_capacity=16, transp...
method forward (line 434) | def forward(self, styles, input_noise):
class Discriminator (line 449) | class Discriminator(nn.Module):
method __init__ (line 450) | def __init__(
method forward (line 492) | def forward(self, x):
class StyleGAN2 (line 512) | class StyleGAN2(nn.Module):
method __init__ (line 513) | def __init__(
method _init_weights (line 597) | def _init_weights(self):
method EMA (line 608) | def EMA(self):
method reset_parameter_averaging (line 617) | def reset_parameter_averaging(self):
method forward (line 621) | def forward(self, x):
class Trainer (line 625) | class Trainer:
method __init__ (line 626) | def __init__(
method init_GAN (line 702) | def init_GAN(self):
method write_config (line 718) | def write_config(self):
method load_config (line 721) | def load_config(self):
method config (line 732) | def config(self):
method set_data_src (line 742) | def set_data_src(self, folder):
method train (line 756) | def train(self):
method evaluate (line 947) | def evaluate(self, num=0, num_image_tiles=8):
method calculate_fid (line 993) | def calculate_fid(self):
method calculate_ppl (line 1045) | def calculate_ppl(self):
method generate_truncated (line 1099) | def generate_truncated(self, S, G, style, noi, trunc_psi=0.75, num_ima...
method print_log (line 1119) | def print_log(self):
method model_name (line 1124) | def model_name(self, num):
method init_folders (line 1127) | def init_folders(self):
method clear (line 1131) | def clear(self):
method save (line 1137) | def save(self, num):
method load (line 1141) | def load(self, num=-1):
FILE: models/autoencoder.py
function info (line 13) | def info(x):
class PrintShape (line 17) | class PrintShape(th.nn.Module):
method __init__ (line 18) | def __init__(self):
method forward (line 21) | def forward(self, x):
class Flatten (line 26) | class Flatten(th.nn.Module):
method forward (line 27) | def forward(self, x):
class UnFlatten (line 31) | class UnFlatten(th.nn.Module):
method __init__ (line 32) | def __init__(self, channels, size):
method forward (line 37) | def forward(self, x):
class LogCoshVAE (line 41) | class LogCoshVAE(th.nn.Module):
method __init__ (line 47) | def __init__(self, in_channels, latent_dim, hidden_dims=None, alpha=10...
method encode (line 104) | def encode(self, input):
method decode (line 113) | def decode(self, z):
method reparameterize (line 120) | def reparameterize(self, mu, logvar):
method forward (line 125) | def forward(self, input):
method loss (line 130) | def loss(self, real, fake, mu, log_var):
class conv2DBatchNormRelu (line 143) | class conv2DBatchNormRelu(th.nn.Module):
method __init__ (line 144) | def __init__(
method forward (line 166) | def forward(self, inputs):
class segnetDown2 (line 171) | class segnetDown2(th.nn.Module):
method __init__ (line 172) | def __init__(self, in_size, out_size):
method forward (line 178) | def forward(self, inputs):
class segnetDown3 (line 186) | class segnetDown3(th.nn.Module):
method __init__ (line 187) | def __init__(self, in_size, out_size):
method forward (line 194) | def forward(self, inputs):
class segnetUp2 (line 203) | class segnetUp2(th.nn.Module):
method __init__ (line 204) | def __init__(self, in_size, out_size):
method forward (line 210) | def forward(self, inputs, indices, output_shape):
class segnetUp3 (line 217) | class segnetUp3(th.nn.Module):
method __init__ (line 218) | def __init__(self, in_size, out_size):
method forward (line 225) | def forward(self, inputs, indices, output_shape):
class SegNet (line 233) | class SegNet(th.nn.Module):
method __init__ (line 239) | def __init__(self, in_channels=3):
method random_indices (line 254) | def random_indices(self, shape):
method encode (line 261) | def encode(self, inputs):
method decode (line 269) | def decode(self, inp):
method forward (line 286) | def forward(self, inputs):
method init_vgg16_params (line 301) | def init_vgg16_params(self, vgg16):
class ConvSegNet (line 337) | class ConvSegNet(th.nn.Module):
method __init__ (line 343) | def __init__(self, in_channels=3):
method encode (line 389) | def encode(self, inputs):
method decode (line 392) | def decode(self, inputs):
method forward (line 395) | def forward(self, inputs):
class VariationalConvSegNet (line 401) | class VariationalConvSegNet(th.nn.Module):
method __init__ (line 407) | def __init__(self, in_channels=3):
method reparameterize (line 459) | def reparameterize(self, mu, log_var):
method encode (line 464) | def encode(self, inputs):
method decode (line 472) | def decode(self, inputs):
method forward (line 475) | def forward(self, inputs):
function create_encoder_single_conv (line 481) | def create_encoder_single_conv(in_chs, out_chs, kernel):
class EncoderInceptionModuleSignle (line 490) | class EncoderInceptionModuleSignle(th.nn.Module):
method __init__ (line 491) | def __init__(self, channels):
method forward (line 506) | def forward(self, x):
class EncoderModule (line 513) | class EncoderModule(th.nn.Module):
method __init__ (line 514) | def __init__(self, chs, repeat_num, use_inception):
method forward (line 522) | def forward(self, x):
class Encoder (line 526) | class Encoder(th.nn.Module):
method __init__ (line 527) | def __init__(self, use_inception, repeat_per_module):
method _create_downsampling_module (line 539) | def _create_downsampling_module(self, input_channels, pooling_kenel):
method forward (line 547) | def forward(self, x):
function create_decoder_single_conv (line 563) | def create_decoder_single_conv(in_chs, out_chs, kernel):
class DecoderInceptionModuleSingle (line 572) | class DecoderInceptionModuleSingle(th.nn.Module):
method __init__ (line 573) | def __init__(self, channels):
method forward (line 588) | def forward(self, x):
class DecoderModule (line 595) | class DecoderModule(th.nn.Module):
method __init__ (line 596) | def __init__(self, chs, repeat_num, use_inception):
method forward (line 604) | def forward(self, x):
class Decoder (line 608) | class Decoder(th.nn.Module):
method __init__ (line 609) | def __init__(self, use_inception, repeat_per_module):
method _create_upsampling_module (line 622) | def _create_upsampling_module(self, input_channels, pooling_kenel):
method forward (line 629) | def forward(self, x):
class InceptionVAE (line 639) | class InceptionVAE(th.nn.Module):
method __init__ (line 644) | def __init__(self, latent_dim=512, repeat_per_block=1, use_inception=T...
method _reparameterize (line 659) | def _reparameterize(self, mu, logvar):
method _bottleneck (line 665) | def _bottleneck(self, h):
method sampling (line 670) | def sampling(self):
method forward (line 677) | def forward(self, x):
FILE: models/stylegan1.py
class MyLinear (line 12) | class MyLinear(nn.Module):
method __init__ (line 15) | def __init__(
method forward (line 34) | def forward(self, x):
class MyConv2d (line 41) | class MyConv2d(nn.Module):
method __init__ (line 44) | def __init__(
method forward (line 77) | def forward(self, x):
class NoiseLayer (line 108) | class NoiseLayer(nn.Module):
method __init__ (line 111) | def __init__(self, channels):
method forward (line 116) | def forward(self, x):
class StyleMod (line 126) | class StyleMod(nn.Module):
method __init__ (line 127) | def __init__(self, latent_size, channels, use_wscale):
method forward (line 131) | def forward(self, x, latent):
class PixelNormLayer (line 139) | class PixelNormLayer(nn.Module):
method __init__ (line 140) | def __init__(self, epsilon=1e-8):
method forward (line 144) | def forward(self, x):
class BlurLayer (line 148) | class BlurLayer(nn.Module):
method __init__ (line 149) | def __init__(self, kernel=[1, 2, 1], normalize=True, flip=False, strid...
method forward (line 162) | def forward(self, x):
function upscale2d (line 169) | def upscale2d(x, factor=2, gain=1):
class Upscale2d (line 180) | class Upscale2d(nn.Module):
method __init__ (line 181) | def __init__(self, factor=2, gain=1):
method forward (line 187) | def forward(self, x):
class G_mapping (line 191) | class G_mapping(nn.Sequential):
method __init__ (line 192) | def __init__(self, nonlinearity="lrelu", use_wscale=True):
method forward (line 217) | def forward(self, x):
class Truncation (line 224) | class Truncation(nn.Module):
method __init__ (line 225) | def __init__(self, avg_latent, max_layer=8, threshold=0.7):
method forward (line 231) | def forward(self, x):
class LayerEpilogue (line 238) | class LayerEpilogue(nn.Module):
method __init__ (line 241) | def __init__(
method forward (line 290) | def forward(self, x, dlatents_in_slice, noise):
class InputBlock (line 318) | class InputBlock(nn.Module):
method __init__ (line 319) | def __init__(
method forward (line 351) | def forward(self, dlatents_in_range, noise):
class GSynthesisBlock (line 364) | class GSynthesisBlock(nn.Module):
method __init__ (line 365) | def __init__(
method forward (line 410) | def forward(self, x, dlatents_in_range, noise):
class G_synthesis (line 418) | class G_synthesis(nn.Module):
method __init__ (line 419) | def __init__(
method forward (line 497) | def forward(self, dlatents_in, noise):
class G_style (line 509) | class G_style(nn.Sequential):
method __init__ (line 510) | def __init__(self, output_size=1920, checkpoint=None):
method mean_latent (line 576) | def mean_latent(self, n_latent):
method forward (line 581) | def forward(
FILE: models/stylegan2.py
class PixelNorm (line 15) | class PixelNorm(nn.Module):
method __init__ (line 16) | def __init__(self):
method forward (line 19) | def forward(self, inputs):
function make_kernel (line 23) | def make_kernel(k):
class Upsample (line 34) | class Upsample(nn.Module):
method __init__ (line 35) | def __init__(self, kernel, factor=2):
method forward (line 49) | def forward(self, inputs):
class Downsample (line 55) | class Downsample(nn.Module):
method __init__ (line 56) | def __init__(self, kernel, factor=2):
method forward (line 70) | def forward(self, inputs):
class Blur (line 76) | class Blur(nn.Module):
method __init__ (line 77) | def __init__(self, kernel, pad, upsample_factor=1):
method forward (line 89) | def forward(self, inputs):
class EqualConv2d (line 95) | class EqualConv2d(nn.Module):
method __init__ (line 96) | def __init__(self, in_channel, out_channel, kernel_size, stride=1, pad...
method forward (line 111) | def forward(self, inputs):
method __repr__ (line 116) | def __repr__(self):
class EqualLinear (line 123) | class EqualLinear(nn.Module):
method __init__ (line 124) | def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, ...
method forward (line 140) | def forward(self, inputs):
method __repr__ (line 148) | def __repr__(self):
class ScaledLeakyReLU (line 152) | class ScaledLeakyReLU(nn.Module):
method __init__ (line 153) | def __init__(self, negative_slope=0.2):
method forward (line 158) | def forward(self, inputs):
class ModulatedConv2d (line 164) | class ModulatedConv2d(nn.Module):
method __init__ (line 165) | def __init__(
method __repr__ (line 211) | def __repr__(self):
method forward (line 217) | def forward(self, inputs, style):
class NoiseInjection (line 257) | class NoiseInjection(nn.Module):
method __init__ (line 258) | def __init__(self):
method forward (line 262) | def forward(self, image, noise=None):
class ConstantInput (line 269) | class ConstantInput(nn.Module):
method __init__ (line 270) | def __init__(self, channel, size=4):
method forward (line 275) | def forward(self, inputs):
class LatentInput (line 281) | class LatentInput(nn.Module):
method __init__ (line 282) | def __init__(self, latent_dim, channel, size=4):
method forward (line 290) | def forward(self, inputs):
class ManipulationLayer (line 297) | class ManipulationLayer(th.nn.Module):
method __init__ (line 298) | def __init__(self, layer):
method forward (line 302) | def forward(self, input, tranforms_dict_list):
class StyledConv (line 310) | class StyledConv(nn.Module):
method __init__ (line 311) | def __init__(
method forward (line 338) | def forward(self, inputs, style, noise=None, transform_dict_list=[]):
class ToRGB (line 346) | class ToRGB(nn.Module):
method __init__ (line 347) | def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=[...
method forward (line 356) | def forward(self, inputs, style, skip=None):
class Generator (line 368) | class Generator(nn.Module):
method __init__ (line 369) | def __init__(
method make_noise (line 472) | def make_noise(self):
method mean_latent (line 483) | def mean_latent(self, n_latent):
method get_latent (line 489) | def get_latent(self, inputs):
method forward (line 492) | def forward(
class ConvLayer (line 579) | class ConvLayer(nn.Sequential):
method __init__ (line 580) | def __init__(
class ResBlock (line 623) | class ResBlock(nn.Module):
method __init__ (line 624) | def __init__(self, in_channel, out_channel, blur_kernel=[1, 3, 3, 1], ...
method forward (line 635) | def forward(self, inputs):
class Discriminator (line 646) | class Discriminator(nn.Module):
method __init__ (line 647) | def __init__(self, size, channel_multiplier=2, blur_kernel=[1, 3, 3, 1...
method forward (line 685) | def forward(self, inputs):
FILE: op/fused_act.py
class FusedLeakyReLUFunctionBackward (line 20) | class FusedLeakyReLUFunctionBackward(Function):
method forward (line 22) | def forward(ctx, grad_output, out, negative_slope, scale):
method backward (line 43) | def backward(ctx, gradgrad_input, gradgrad_bias):
class FusedLeakyReLUFunction (line 52) | class FusedLeakyReLUFunction(Function):
method forward (line 54) | def forward(ctx, input, bias, negative_slope, scale):
method backward (line 64) | def backward(ctx, grad_output):
class FusedLeakyReLU (line 74) | class FusedLeakyReLU(nn.Module):
method __init__ (line 75) | def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5):
method forward (line 82) | def forward(self, input):
function fused_leaky_relu (line 86) | def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5):
FILE: op/fused_bias_act.cpp
function fused_bias_act (line 11) | torch::Tensor fused_bias_act(const torch::Tensor& input, const torch::Te...
function PYBIND11_MODULE (line 19) | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
FILE: op/upfirdn2d.cpp
function upfirdn2d (line 12) | torch::Tensor upfirdn2d(const torch::Tensor& input, const torch::Tensor&...
function PYBIND11_MODULE (line 21) | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
FILE: op/upfirdn2d.py
class UpFirDn2dBackward (line 19) | class UpFirDn2dBackward(Function):
method forward (line 21) | def forward(
method backward (line 63) | def backward(ctx, gradgrad_input):
class UpFirDn2d (line 88) | class UpFirDn2d(Function):
method forward (line 90) | def forward(ctx, input, kernel, up, down, pad):
method backward (line 127) | def backward(ctx, grad_output):
function upfirdn2d (line 145) | def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
function upfirdn2d_native (line 159) | def upfirdn2d_native(
FILE: prepare_data.py
function resize_and_convert (line 16) | def resize_and_convert(img, size, resample, quality=100):
function resize_multiple (line 26) | def resize_multiple(img, sizes=(128, 256, 512, 1024), resample=Image.LAN...
function resize_worker (line 35) | def resize_worker(img_file, sizes, resample):
function prepare (line 47) | def prepare(env, dataset, n_worker, sizes=(128, 256, 512, 1024), resampl...
FILE: prepare_vae_codes.py
function lmdmb_write_worker (line 15) | def lmdmb_write_worker(i_code, env, size):
function prepare (line 22) | def prepare(env, vae, loader, total, batch_size, n_worker, size=1024):
FILE: projector.py
function noise_regularize (line 16) | def noise_regularize(noises):
function noise_normalize_ (line 39) | def noise_normalize_(noises):
function get_lr (line 47) | def get_lr(t, initial_lr, rampdown=0.25, rampup=0.05):
function latent_noise (line 55) | def latent_noise(latent, strength):
function make_image (line 61) | def make_image(tensor):
FILE: render.py
function render (line 14) | def render(
function write_video (line 195) | def write_video(arr, output_file, fps):
FILE: select_latents.py
class HoverButton (line 29) | class HoverButton(tk.Button):
method __init__ (line 30) | def __init__(self, master, **kw):
method on_enter (line 36) | def on_enter(self, e):
method on_leave (line 39) | def on_leave(self, e):
class InvisibleScrollbar (line 43) | class InvisibleScrollbar(Scrollbar):
method set (line 44) | def set(self, lo, hi):
class Mousewheel_Support (line 49) | class Mousewheel_Support(object):
method __new__ (line 53) | def __new__(cls, *args, **kwargs):
method __init__ (line 58) | def __init__(self, root, horizontal_factor=1, vertical_factor=1):
method _on_mousewheel (line 75) | def _on_mousewheel(self, event):
method _mousewheel_bind (line 79) | def _mousewheel_bind(self, widget):
method _mousewheel_unbind (line 82) | def _mousewheel_unbind(self):
method add_support_to (line 85) | def add_support_to(
method _make_mouse_wheel_handler (line 114) | def _make_mouse_wheel_handler(widget, orient, factor=1 / 120, what="un...
class Scrolling_Area (line 137) | class Scrolling_Area(Frame, object):
method __init__ (line 138) | def __init__(
method width (line 189) | def width(self):
method width (line 193) | def width(self, width):
method height (line 197) | def height(self):
method height (line 201) | def height(self, height):
method set_size (line 204) | def set_size(self, width, height):
method _on_canvas_configure (line 207) | def _on_canvas_configure(self, event):
method update_viewport (line 213) | def update_viewport(self):
function generate_images (line 262) | def generate_images(n):
function render_latents (line 299) | def render_latents(latents):
function save (line 318) | def save():
function add_intro (line 374) | def add_intro(label):
function remove_intro (line 390) | def remove_intro(label):
function add_drop (line 403) | def add_drop(label):
function remove_drop (line 419) | def remove_drop(label):
function add_images (line 432) | def add_images(n):
FILE: train.py
function data_sampler (line 31) | def data_sampler(dataset, shuffle, distributed):
function requires_grad (line 40) | def requires_grad(model, flag=True):
function accumulate (line 45) | def accumulate(model1, model2, decay=0.5 ** (32.0 / 10_000)):
function sample_data (line 52) | def sample_data(loader):
function make_noise (line 58) | def make_noise(batch_size, latent_dim, prob):
function d_logistic_loss (line 65) | def d_logistic_loss(real_pred, fake_pred):
function d_r1_penalty (line 71) | def d_r1_penalty(real_img, real_pred, args):
function g_non_saturating_loss (line 78) | def g_non_saturating_loss(fake_pred):
function g_path_length_regularization (line 82) | def g_path_length_regularization(generator, mean_path_length, args):
function train (line 105) | def train(args, loader, generator, discriminator, contrast_learner, g_op...
FILE: train_profile.py
function data_sampler (line 32) | def data_sampler(dataset, shuffle, distributed):
function requires_grad (line 41) | def requires_grad(model, flag=True):
function accumulate (line 46) | def accumulate(model1, model2, decay=0.5 ** (32.0 / 10_000)):
function sample_data (line 53) | def sample_data(loader):
function make_noise (line 59) | def make_noise(batch_size, latent_dim, prob):
function d_logistic_loss (line 66) | def d_logistic_loss(real_pred, fake_pred):
function d_r1_penalty (line 72) | def d_r1_penalty(real_img, real_pred, args):
function g_non_saturating_loss (line 79) | def g_non_saturating_loss(fake_pred):
function g_path_length_regularization (line 83) | def g_path_length_regularization(generator, mean_path_length, args):
function train (line 110) | def train(args, loader, generator, discriminator, contrast_learner, g_op...
FILE: validation/calc_fid.py
function extract_feature_from_samples (line 15) | def extract_feature_from_samples(generator, inception, truncation, trunc...
function calc_fid (line 32) | def calc_fid(sample_mean, sample_cov, real_mean, real_cov, eps=1e-6):
FILE: validation/calc_inception.py
class Inception3Feature (line 18) | class Inception3Feature(Inception3):
method forward (line 19) | def forward(self, x):
function load_patched_inception_v3 (line 51) | def load_patched_inception_v3():
function extract_features (line 61) | def extract_features(loader, inception, device):
FILE: validation/calc_ppl.py
function normalize (line 12) | def normalize(x):
function slerp (line 16) | def slerp(a, b, t):
function lerp (line 27) | def lerp(a, b, t):
FILE: validation/inception.py
class InceptionV3 (line 18) | class InceptionV3(nn.Module):
method __init__ (line 33) | def __init__(
method forward (line 129) | def forward(self, inp):
function fid_inception_v3 (line 163) | def fid_inception_v3():
class FIDInceptionA (line 188) | class FIDInceptionA(models.inception.InceptionA):
method __init__ (line 191) | def __init__(self, in_channels, pool_features):
method forward (line 194) | def forward(self, x):
class FIDInceptionC (line 213) | class FIDInceptionC(models.inception.InceptionC):
method __init__ (line 216) | def __init__(self, in_channels, channels_7x7):
method forward (line 219) | def forward(self, x):
class FIDInceptionE_1 (line 241) | class FIDInceptionE_1(models.inception.InceptionE):
method __init__ (line 244) | def __init__(self, in_channels):
method forward (line 247) | def forward(self, x):
class FIDInceptionE_2 (line 274) | class FIDInceptionE_2(models.inception.InceptionE):
method __init__ (line 277) | def __init__(self, in_channels):
method forward (line 280) | def forward(self, x):
FILE: validation/lpips/__init__.py
class PerceptualLoss (line 13) | class PerceptualLoss(torch.nn.Module):
method __init__ (line 14) | def __init__(
method forward (line 30) | def forward(self, pred, target, normalize=False):
FILE: validation/lpips/base_model.py
class BaseModel (line 5) | class BaseModel:
method __init__ (line 6) | def __init__(self):
method name (line 9) | def name(self):
method initialize (line 12) | def initialize(self, use_gpu=True, gpu_ids=[0]):
method forward (line 16) | def forward(self):
method get_image_paths (line 19) | def get_image_paths(self):
method optimize_parameters (line 22) | def optimize_parameters(self):
method get_current_visuals (line 25) | def get_current_visuals(self):
method get_current_errors (line 28) | def get_current_errors(self):
method save (line 31) | def save(self, label):
method save_network (line 35) | def save_network(self, network, path, network_label, epoch_label):
method load_network (line 41) | def load_network(self, network, network_label, epoch_label):
method update_learning_rate (line 47) | def update_learning_rate():
method get_image_paths (line 50) | def get_image_paths(self):
method save_done (line 53) | def save_done(self, flag=False):
FILE: validation/lpips/dist_model.py
class DistModel (line 15) | class DistModel(BaseModel):
method name (line 16) | def name(self):
method initialize (line 19) | def initialize(
method forward (line 124) | def forward(self, in0, in1, retPerLayer=False):
method optimize_parameters (line 135) | def optimize_parameters(self):
method clamp_weights (line 142) | def clamp_weights(self):
method set_input (line 147) | def set_input(self, data):
method forward_train (line 163) | def forward_train(self): # run forward pass
method backward_train (line 177) | def backward_train(self):
method compute_accuracy (line 180) | def compute_accuracy(self, d0, d1, judge):
method get_current_errors (line 186) | def get_current_errors(self):
method get_current_visuals (line 194) | def get_current_visuals(self):
method save (line 207) | def save(self, path, label):
method update_learning_rate (line 214) | def update_learning_rate(self, nepoch_decay):
function score_2afc_dataset (line 225) | def score_2afc_dataset(data_loader, func, name=""):
function score_jnd_dataset (line 261) | def score_jnd_dataset(data_loader, func, name=""):
FILE: validation/lpips/networks_basic.py
function spatial_average (line 9) | def spatial_average(in_tens, keepdim=True):
function upsample (line 13) | def upsample(in_tens, out_H=64): # assumes scale factor is same for H a...
class PNetLin (line 21) | class PNetLin(nn.Module):
method __init__ (line 22) | def __init__(
method forward (line 67) | def forward(self, in0, in1, retPerLayer=False):
class ScalingLayer (line 100) | class ScalingLayer(nn.Module):
method __init__ (line 101) | def __init__(self):
method forward (line 106) | def forward(self, inp):
class NetLinLayer (line 110) | class NetLinLayer(nn.Module):
method __init__ (line 113) | def __init__(self, chn_in, chn_out=1, use_dropout=False):
class Dist2LogitLayer (line 123) | class Dist2LogitLayer(nn.Module):
method __init__ (line 126) | def __init__(self, chn_mid=32, use_sigmoid=True):
method forward (line 150) | def forward(self, d0, d1, eps=0.1):
class BCERankingLoss (line 154) | class BCERankingLoss(nn.Module):
method __init__ (line 155) | def __init__(self, chn_mid=32):
method forward (line 161) | def forward(self, d0, d1, judge):
class FakeNet (line 168) | class FakeNet(nn.Module):
method __init__ (line 169) | def __init__(self, use_gpu=True, colorspace="Lab"):
class L2 (line 175) | class L2(FakeNet):
method forward (line 176) | def forward(self, in0, in1, retPerLayer=None):
class DSSIM (line 197) | class DSSIM(FakeNet):
method forward (line 198) | def forward(self, in0, in1, retPerLayer=None):
function print_network (line 217) | def print_network(net):
FILE: validation/lpips/pretrained_networks.py
class squeezenet (line 6) | class squeezenet(torch.nn.Module):
method __init__ (line 7) | def __init__(self, requires_grad=False, pretrained=True):
method forward (line 36) | def forward(self, X):
class alexnet (line 57) | class alexnet(torch.nn.Module):
method __init__ (line 58) | def __init__(self, requires_grad=False, pretrained=True):
method forward (line 81) | def forward(self, X):
class vgg16 (line 98) | class vgg16(torch.nn.Module):
method __init__ (line 99) | def __init__(self, requires_grad=False, pretrained=True):
method forward (line 122) | def forward(self, X):
class resnet (line 139) | class resnet(torch.nn.Module):
method __init__ (line 140) | def __init__(self, requires_grad=False, pretrained=True, num=18):
method forward (line 163) | def forward(self, X):
FILE: validation/lpips/util.py
function normalize_tensor (line 10) | def normalize_tensor(in_feat, eps=1e-10):
function l2 (line 15) | def l2(p0, p1, range=255.0):
function psnr (line 19) | def psnr(p0, p1, peak=255.0):
function dssim (line 23) | def dssim(p0, p1, range=255.0):
function rgb2lab (line 27) | def rgb2lab(in_img, mean_cent=False):
function tensor2np (line 36) | def tensor2np(tensor_obj):
function np2tensor (line 41) | def np2tensor(np_obj):
function tensor2tensorlab (line 46) | def tensor2tensorlab(image_tensor, to_norm=True, mc_only=False):
function tensorlab2tensor (line 61) | def tensorlab2tensor(lab_tensor, return_inbnd=False):
function rgb2lab (line 81) | def rgb2lab(input):
function tensor2im (line 87) | def tensor2im(image_tensor, imtype=np.uint8, cent=1.0, factor=255.0 / 2.0):
function im2tensor (line 93) | def im2tensor(image, imtype=np.uint8, cent=1.0, factor=255.0 / 2.0):
function tensor2vec (line 97) | def tensor2vec(vector_tensor):
function voc_ap (line 101) | def voc_ap(rec, prec, use_07_metric=False):
function tensor2im (line 135) | def tensor2im(image_tensor, imtype=np.uint8, cent=1.0, factor=255.0 / 2.0):
function im2tensor (line 142) | def im2tensor(image, imtype=np.uint8, cent=1.0, factor=255.0 / 2.0):
FILE: validation/metrics.py
function vae_fid (line 17) | def vae_fid(vae, batch_size, latent_dim, n_sample, inception_name, calcu...
function fid (line 84) | def fid(generator, batch_size, n_sample, truncation, inception_name, cal...
function get_dataset_inception_features (line 155) | def get_dataset_inception_features(loader, inception_name, size):
function compute_pairwise_distance (line 179) | def compute_pairwise_distance(data_x, data_y=None, metric="l2"):
function get_kth_value (line 188) | def get_kth_value(unsorted, k, axis=-1):
function compute_nearest_neighbour_distances (line 195) | def compute_nearest_neighbour_distances(input_features, nearest_k, metric):
function prdc (line 201) | def prdc(real_features, fake_features, nearest_k=10, metric="l2"):
function lerp (line 217) | def lerp(a, b, t):
function ppl (line 222) | def ppl(generator, batch_size, n_sample, space, crop, latent_dim, eps=1e...
FILE: validation/spectral_norm.py
class SpectralNorm (line 4) | class SpectralNorm(object):
method __init__ (line 5) | def __init__(self, name="weight", n_power_iterations=1, dim=0, eps=1e-...
method reshape_weight_to_matrix (line 16) | def reshape_weight_to_matrix(self, weight):
method compute_sigma (line 24) | def compute_sigma(self, module):
method remove (line 40) | def remove(self, module):
method __call__ (line 46) | def __call__(self, module, inputs):
method _solve_v_and_rescale (line 49) | def _solve_v_and_rescale(self, weight_mat, u, target_sigma):
method apply (line 54) | def apply(module, name, n_power_iterations, dim, eps, normalize=True):
function track_spectral_norm (line 76) | def track_spectral_norm(module, name="weight", n_power_iterations=1, eps...
function remove_spectral_norm (line 106) | def remove_spectral_norm(module, name="weight"):
Condensed preview — 86 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (599K chars).
[
{
"path": ".gitignore",
"chars": 1931,
"preview": "pretrained_models/\nwandb\nwandb/\n*.lmdb/\n*.pkl\ncheckpoints/\nmaua-stylegan/\n.vscode\noutput/\nworkspace/*\n!workspace\noutput/"
},
{
"path": "LICENSE/LICENSE-AUDIOREACTIVE",
"chars": 29018,
"preview": "Code for Audio-reactive Latent Interpolations with StyleGAN\nIncluding the folder audioreactive/, generate_audiovisual.py"
},
{
"path": "LICENSE/LICENSE-AUTOENCODER",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "LICENSE/LICENSE-CONTRASTIVE-LEARNER",
"chars": 1066,
"preview": "MIT License\n\nCopyright (c) 2020 Phil Wang\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n"
},
{
"path": "LICENSE/LICENSE-FID",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "LICENSE/LICENSE-LPIPS",
"chars": 1381,
"preview": "Copyright (c) 2018, Richard Zhang, Phillip Isola, Alexei A. Efros, Eli Shechtman, Oliver Wang\r\nAll rights reserved.\r\n\r\nR"
},
{
"path": "LICENSE/LICENSE-LUCIDRAINS",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "LICENSE/LICENSE-NVIDIA",
"chars": 4767,
"preview": "Copyright (c) 2019, NVIDIA Corporation. All rights reserved.\r\n\r\n\r\nNvidia Source Code License-NC\r\n\r\n====================="
},
{
"path": "LICENSE/LICENSE-ROSINALITY",
"chars": 1071,
"preview": "MIT License\n\nCopyright (c) 2019 Kim Seonghyeon\n\nPermission is hereby granted, free of charge, to any person obtaining a "
},
{
"path": "LICENSE/LICENSE-VGG",
"chars": 2472,
"preview": "Copyright (C) 2019 NVIDIA Corporation. Ting-Chun Wang, Ming-Yu Liu, Jun-Yan Zhu.\nBSD License. All rights reserved. \n\nRed"
},
{
"path": "README.md",
"chars": 10357,
"preview": "# maua-stylegan2\r\n\r\nThis is the repo for my experiments with StyleGAN2. There are many like it, but this one is mine.\r\n\r"
},
{
"path": "accelerate/accelerate_inception.py",
"chars": 6629,
"preview": "import os\nimport gc\nimport wandb\nimport argparse\nimport torch as th\nfrom tqdm import tqdm\nfrom torch.utils import data\ni"
},
{
"path": "accelerate/accelerate_logcosh.py",
"chars": 8976,
"preview": "import os\nimport gc\nimport wandb\nimport argparse\nimport validation\nimport torch as th\nfrom tqdm import tqdm\nfrom torch.u"
},
{
"path": "accelerate/accelerate_segnet.py",
"chars": 7535,
"preview": "import os\nimport gc\nimport wandb\nimport argparse\nimport torch as th\nfrom tqdm import tqdm\nfrom torch.utils import data\nf"
},
{
"path": "audioreactive/__init__.py",
"chars": 108,
"preview": "from .bend import *\nfrom .examples import *\nfrom .latent import *\nfrom .signal import *\nfrom .util import *\n"
},
{
"path": "audioreactive/bend.py",
"chars": 3617,
"preview": "import math\n\nimport kornia.augmentation as kA\nimport kornia.geometry.transform as kT\nimport torch as th\n\n# ============="
},
{
"path": "audioreactive/examples/__init__.py",
"chars": 16,
"preview": "from . import *\n"
},
{
"path": "audioreactive/examples/default.py",
"chars": 1462,
"preview": "import torch as th\n\nimport audioreactive as ar\n\n\ndef initialize(args):\n args.lo_onsets = ar.onsets(args.audio, args.s"
},
{
"path": "audioreactive/examples/kelp.py",
"chars": 5670,
"preview": "\"\"\"\nThis file shows an example of a loop based interpolation\nHere sections are identified with laplacian segmentation an"
},
{
"path": "audioreactive/examples/tauceti.py",
"chars": 7176,
"preview": "\"\"\"\nThis file shows an example of network bending\nThe latents and noise are similar to temper.py (although without spati"
},
{
"path": "audioreactive/examples/temper.py",
"chars": 3544,
"preview": "\"\"\"\nThis file shows an example of spatial control of the noise using a simple circular mask\nThe latents are a chromagram"
},
{
"path": "audioreactive/latent.py",
"chars": 10412,
"preview": "import gc\n\nimport numpy as np\nimport torch as th\nfrom scipy import interpolate\n\nfrom models.stylegan2 import Generator\nf"
},
{
"path": "audioreactive/signal.py",
"chars": 16062,
"preview": "import os\nimport warnings\nfrom pathlib import Path\n\nimport joblib\nimport librosa as rosa\nimport librosa.display\nimport m"
},
{
"path": "audioreactive/util.py",
"chars": 3122,
"preview": "import librosa as rosa\nimport librosa.display\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# ===================="
},
{
"path": "augment.py",
"chars": 10227,
"preview": "import math\r\n\r\nimport torch\r\nfrom torch.nn import functional as F\r\n\r\nfrom op import upfirdn2d\r\n\r\n\r\nSYM6 = (\r\n 0.01540"
},
{
"path": "contrastive_learner.py",
"chars": 7173,
"preview": "import copy\nimport random\nfrom functools import wraps\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F"
},
{
"path": "convert_weight.py",
"chars": 7388,
"preview": "import argparse\nimport math\nimport os\nimport pickle\nimport sys\n\nimport numpy as np\nimport torch\nfrom torchvision import "
},
{
"path": "dataset.py",
"chars": 1296,
"preview": "from io import BytesIO\n\nimport lmdb\nimport numpy as np\nfrom PIL import Image\nfrom PIL import Image\nfrom torch.utils.data"
},
{
"path": "distributed.py",
"chars": 2654,
"preview": "import pickle\n\nimport torch\nfrom torch import distributed as dist\n\n\ndef get_rank():\n if not dist.is_available():\n "
},
{
"path": "generate.py",
"chars": 1607,
"preview": "import argparse\nimport torch\nfrom torchvision import utils\nfrom models.stylegan2 import Generator\nfrom tqdm import tqdm\n"
},
{
"path": "generate_audiovisual.py",
"chars": 11170,
"preview": "import argparse\nimport gc\nimport os\nimport random\nimport time\nimport traceback\nimport uuid\nimport warnings\n\nimport libro"
},
{
"path": "generate_video.py",
"chars": 22053,
"preview": "import argparse\nimport uuid\n\nimport numpy as np\nimport torch as th\nimport torch.multiprocessing as mp\nimport torch.nn.fu"
},
{
"path": "gpu_profile.py",
"chars": 4057,
"preview": "import datetime\nimport linecache\nimport os\n\nos.environ[\"CUDA_LAUNCH_BLOCKING\"] = \"1\"\n\nfrom py3nvml import py3nvml\nimport"
},
{
"path": "gpumon.py",
"chars": 3232,
"preview": "import argparse\nimport os\nimport signal\nimport subprocess\nimport time\nfrom queue import Empty, Queue\nfrom threading impo"
},
{
"path": "lightning.py",
"chars": 15351,
"preview": "import os\nimport gc\nimport math\nimport wandb\nimport random\nimport argparse\nimport validation\nimport torch as th\nimport t"
},
{
"path": "lookahead_minimax.py",
"chars": 8586,
"preview": "from collections import defaultdict\n\nimport torch\nfrom torch.optim.optimizer import Optimizer\n\n\nclass LookaheadMinimax(O"
},
{
"path": "lucidrains.py",
"chars": 41492,
"preview": "import json, time, pickle, argparse\nfrom math import floor, log2, sqrt\nfrom random import random\nfrom shutil import rmtr"
},
{
"path": "models/autoencoder.py",
"chars": 25180,
"preview": "import os\nimport sys\nfrom copy import copy\n\nimport torch as th\nimport torch.nn.functional as F\n\nsys.path.append(os.path."
},
{
"path": "models/stylegan1.py",
"chars": 22251,
"preview": "# from https://github.com/lernapparat/lernapparat/blob/master/style_gan/pyth_style_gan.ipynb\n\nimport gc\nfrom collections"
},
{
"path": "models/stylegan2.py",
"chars": 21693,
"preview": "import math\nimport os\nimport random\nimport sys\n\nimport torch as th\nfrom torch import nn\nfrom torch.nn import functional "
},
{
"path": "op/__init__.py",
"chars": 89,
"preview": "from .fused_act import FusedLeakyReLU, fused_leaky_relu\nfrom .upfirdn2d import upfirdn2d\n"
},
{
"path": "op/fused_act.py",
"chars": 2787,
"preview": "import os\r\n\r\nimport torch\r\nfrom torch import nn\r\nfrom torch.nn import functional as F\r\nfrom torch.autograd import Functi"
},
{
"path": "op/fused_bias_act.cpp",
"chars": 846,
"preview": "#include <torch/extension.h>\r\n\r\n\r\ntorch::Tensor fused_bias_act_op(const torch::Tensor& input, const torch::Tensor& bias,"
},
{
"path": "op/fused_bias_act_kernel.cu",
"chars": 2875,
"preview": "// Copyright (c) 2019, NVIDIA Corporation. All rights reserved.\r\n//\r\n// This work is made available under the Nvidia Sou"
},
{
"path": "op/upfirdn2d.cpp",
"chars": 988,
"preview": "#include <torch/extension.h>\r\n\r\n\r\ntorch::Tensor upfirdn2d_op(const torch::Tensor& input, const torch::Tensor& kernel,\r\n "
},
{
"path": "op/upfirdn2d.py",
"chars": 5872,
"preview": "import os\r\n\r\nimport torch\r\nfrom torch.nn import functional as F\r\nfrom torch.autograd import Function\r\nfrom torch.utils.c"
},
{
"path": "op/upfirdn2d_kernel.cu",
"chars": 12079,
"preview": "// Copyright (c) 2019, NVIDIA Corporation. All rights reserved.\r\n//\r\n// This work is made available under the Nvidia Sou"
},
{
"path": "prepare_data.py",
"chars": 2638,
"preview": "import argparse\nfrom io import BytesIO\nimport multiprocessing\nfrom functools import partial\n\nfrom PIL import Image\n\nimpo"
},
{
"path": "prepare_vae_codes.py",
"chars": 2469,
"preview": "import argparse\nimport numpy as np\nimport multiprocessing\nfrom functools import partial\n\nimport lmdb\nfrom tqdm import tq"
},
{
"path": "projector.py",
"chars": 5800,
"preview": "import argparse\r\nimport math\r\nimport os\r\n\r\nimport torch\r\nfrom torch import optim\r\nfrom torch.nn import functional as F\r\n"
},
{
"path": "render.py",
"chars": 7532,
"preview": "import queue\nfrom threading import Thread\n\nimport ffmpeg\nimport numpy as np\nimport PIL.Image\nimport torch as th\nfrom tqd"
},
{
"path": "requirements.txt",
"chars": 89,
"preview": "torch\ntorchvision\nnumpy\nlibrosa\ncython\nmadmom\ntqdm\nkornia\nmatplotlib\nffmpeg-python\njoblib"
},
{
"path": "select_latents.py",
"chars": 15873,
"preview": "import gc, math\nimport argparse\nimport tkinter as tk\nimport numpy as np\nfrom PIL import Image, ImageTk\nimport torch as t"
},
{
"path": "train.py",
"chars": 24851,
"preview": "import argparse\nimport gc\nimport math\nimport os\nimport random\nimport sys\nimport time\n\nimport numpy as np\nimport torch as"
},
{
"path": "train_profile.py",
"chars": 29441,
"preview": "import argparse\nimport gc\nimport math\nimport os\nimport random\nimport sys\nimport time\n\nimport numpy as np\nimport torch as"
},
{
"path": "validation/__init__.py",
"chars": 124,
"preview": "from .metrics import vae_fid, fid, get_dataset_inception_features, ppl, prdc\nfrom .spectral_norm import track_spectral_n"
},
{
"path": "validation/calc_fid.py",
"chars": 3167,
"preview": "import argparse\nimport pickle\n\nimport torch\nfrom torch import nn\nimport numpy as np\nfrom scipy import linalg\nfrom tqdm i"
},
{
"path": "validation/calc_inception.py",
"chars": 3845,
"preview": "import argparse\nimport pickle\nimport os\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom tor"
},
{
"path": "validation/calc_ppl.py",
"chars": 2992,
"preview": "import argparse\r\n\r\nimport torch\r\nfrom torch.nn import functional as F\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\n\r\nimpo"
},
{
"path": "validation/inception.py",
"chars": 11318,
"preview": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import models\n\ntry:\n from torchvi"
},
{
"path": "validation/lpips/__init__.py",
"chars": 1585,
"preview": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport num"
},
{
"path": "validation/lpips/base_model.py",
"chars": 1501,
"preview": "import os\nimport torch\n\n\nclass BaseModel:\n def __init__(self):\n pass\n\n def name(self):\n return \"Base"
},
{
"path": "validation/lpips/dist_model.py",
"chars": 11871,
"preview": "import numpy as np\nimport torch\nimport os\nfrom collections import OrderedDict\nfrom torch.autograd import Variable\nfrom ."
},
{
"path": "validation/lpips/networks_basic.py",
"chars": 7820,
"preview": "import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom . import pretrained_networks as pn\n\nfrom . i"
},
{
"path": "validation/lpips/pretrained_networks.py",
"chars": 6530,
"preview": "from collections import namedtuple\nimport torch\nfrom torchvision import models as tv\n\n\nclass squeezenet(torch.nn.Module)"
},
{
"path": "validation/lpips/util.py",
"chars": 4445,
"preview": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport num"
},
{
"path": "validation/metrics.py",
"chars": 9434,
"preview": "import os\nimport pickle\nimport random\n\nfrom sklearn.metrics import pairwise_distances\nfrom tqdm import tqdm\nimport torch"
},
{
"path": "validation/spectral_norm.py",
"chars": 4989,
"preview": "import torch\n\n\nclass SpectralNorm(object):\n def __init__(self, name=\"weight\", n_power_iterations=1, dim=0, eps=1e-12)"
},
{
"path": "workspace/naamloos_metadata.json",
"chars": 23,
"preview": "{\"total_frames\": 4986}\n"
},
{
"path": "workspace/naamloos_params.json",
"chars": 698,
"preview": "{\"intro_num_beats\": 64, \"intro_loop_smoothing\": 30, \"intro_loop_factor\": 0.4, \"intro_loop_len\": 12, \"drop_num_beats\": 32"
}
]
// ... and 16 more files (download for full content)
About this extraction
This page contains the full source code of the JCBrouwer/maua-stylegan2 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 86 files (560.8 KB), approximately 144.5k tokens, and a symbol index with 689 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.