├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── architecture.png ├── music2latent.png ├── music2latent ├── __init__.py ├── audio.py ├── hparams.py ├── hparams_inference.py ├── inference.py ├── models.py ├── requirements.txt └── utils.py ├── setup.py └── tutorial.ipynb /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pt filter=lfs diff=lfs merge=lfs -text 2 | final_models/*.pt filter=lfs diff=lfs merge=lfs -text -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | *.pt 163 | music2latent/models/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution-NonCommercial 4.0 International 2 | 3 | Creative Commons Corporation ("Creative Commons") is not a law firm and 4 | does not provide legal services or legal advice. Distribution of 5 | Creative Commons public licenses does not create a lawyer-client or 6 | other relationship. Creative Commons makes its licenses and related 7 | information available on an "as-is" basis. Creative Commons gives no 8 | warranties regarding its licenses, any material licensed under their 9 | terms and conditions, or any related information. Creative Commons 10 | disclaims all liability for damages resulting from their use to the 11 | fullest extent possible. 12 | 13 | Using Creative Commons Public Licenses 14 | 15 | Creative Commons public licenses provide a standard set of terms and 16 | conditions that creators and other rights holders may use to share 17 | original works of authorship and other material subject to copyright and 18 | certain other rights specified in the public license below. The 19 | following considerations are for informational purposes only, are not 20 | exhaustive, and do not form part of our licenses. 21 | 22 | - Considerations for licensors: Our public licenses are intended for 23 | use by those authorized to give the public permission to use 24 | material in ways otherwise restricted by copyright and certain other 25 | rights. Our licenses are irrevocable. Licensors should read and 26 | understand the terms and conditions of the license they choose 27 | before applying it. Licensors should also secure all rights 28 | necessary before applying our licenses so that the public can reuse 29 | the material as expected. Licensors should clearly mark any material 30 | not subject to the license. This includes other CC-licensed 31 | material, or material used under an exception or limitation to 32 | copyright. More considerations for licensors : 33 | wiki.creativecommons.org/Considerations_for_licensors 34 | 35 | - Considerations for the public: By using one of our public licenses, 36 | a licensor grants the public permission to use the licensed material 37 | under specified terms and conditions. If the licensor's permission 38 | is not necessary for any reason–for example, because of any 39 | applicable exception or limitation to copyright–then that use is not 40 | regulated by the license. Our licenses grant only permissions under 41 | copyright and certain other rights that a licensor has authority to 42 | grant. Use of the licensed material may still be restricted for 43 | other reasons, including because others have copyright or other 44 | rights in the material. A licensor may make special requests, such 45 | as asking that all changes be marked or described. Although not 46 | required by our licenses, you are encouraged to respect those 47 | requests where reasonable. More considerations for the public : 48 | wiki.creativecommons.org/Considerations_for_licensees 49 | 50 | Creative Commons Attribution-NonCommercial 4.0 International Public 51 | License 52 | 53 | By exercising the Licensed Rights (defined below), You accept and agree 54 | to be bound by the terms and conditions of this Creative Commons 55 | Attribution-NonCommercial 4.0 International Public License ("Public 56 | License"). To the extent this Public License may be interpreted as a 57 | contract, You are granted the Licensed Rights in consideration of Your 58 | acceptance of these terms and conditions, and the Licensor grants You 59 | such rights in consideration of benefits the Licensor receives from 60 | making the Licensed Material available under these terms and conditions. 61 | 62 | - Section 1 – Definitions. 63 | 64 | - a. Adapted Material means material subject to Copyright and 65 | Similar Rights that is derived from or based upon the Licensed 66 | Material and in which the Licensed Material is translated, 67 | altered, arranged, transformed, or otherwise modified in a 68 | manner requiring permission under the Copyright and Similar 69 | Rights held by the Licensor. For purposes of this Public 70 | License, where the Licensed Material is a musical work, 71 | performance, or sound recording, Adapted Material is always 72 | produced where the Licensed Material is synched in timed 73 | relation with a moving image. 74 | - b. Adapter's License means the license You apply to Your 75 | Copyright and Similar Rights in Your contributions to Adapted 76 | Material in accordance with the terms and conditions of this 77 | Public License. 78 | - c. Copyright and Similar Rights means copyright and/or similar 79 | rights closely related to copyright including, without 80 | limitation, performance, broadcast, sound recording, and Sui 81 | Generis Database Rights, without regard to how the rights are 82 | labeled or categorized. For purposes of this Public License, the 83 | rights specified in Section 2(b)(1)-(2) are not Copyright and 84 | Similar Rights. 85 | - d. Effective Technological Measures means those measures that, 86 | in the absence of proper authority, may not be circumvented 87 | under laws fulfilling obligations under Article 11 of the WIPO 88 | Copyright Treaty adopted on December 20, 1996, and/or similar 89 | international agreements. 90 | - e. Exceptions and Limitations means fair use, fair dealing, 91 | and/or any other exception or limitation to Copyright and 92 | Similar Rights that applies to Your use of the Licensed 93 | Material. 94 | - f. Licensed Material means the artistic or literary work, 95 | database, or other material to which the Licensor applied this 96 | Public License. 97 | - g. Licensed Rights means the rights granted to You subject to 98 | the terms and conditions of this Public License, which are 99 | limited to all Copyright and Similar Rights that apply to Your 100 | use of the Licensed Material and that the Licensor has authority 101 | to license. 102 | - h. Licensor means the individual(s) or entity(ies) granting 103 | rights under this Public License. 104 | - i. NonCommercial means not primarily intended for or directed 105 | towards commercial advantage or monetary compensation. For 106 | purposes of this Public License, the exchange of the Licensed 107 | Material for other material subject to Copyright and Similar 108 | Rights by digital file-sharing or similar means is NonCommercial 109 | provided there is no payment of monetary compensation in 110 | connection with the exchange. 111 | - j. Share means to provide material to the public by any means or 112 | process that requires permission under the Licensed Rights, such 113 | as reproduction, public display, public performance, 114 | distribution, dissemination, communication, or importation, and 115 | to make material available to the public including in ways that 116 | members of the public may access the material from a place and 117 | at a time individually chosen by them. 118 | - k. Sui Generis Database Rights means rights other than copyright 119 | resulting from Directive 96/9/EC of the European Parliament and 120 | of the Council of 11 March 1996 on the legal protection of 121 | databases, as amended and/or succeeded, as well as other 122 | essentially equivalent rights anywhere in the world. 123 | - l. You means the individual or entity exercising the Licensed 124 | Rights under this Public License. Your has a corresponding 125 | meaning. 126 | 127 | - Section 2 – Scope. 128 | 129 | - a. License grant. 130 | - 1. Subject to the terms and conditions of this Public 131 | License, the Licensor hereby grants You a worldwide, 132 | royalty-free, non-sublicensable, non-exclusive, irrevocable 133 | license to exercise the Licensed Rights in the Licensed 134 | Material to: 135 | - A. reproduce and Share the Licensed Material, in whole 136 | or in part, for NonCommercial purposes only; and 137 | - B. produce, reproduce, and Share Adapted Material for 138 | NonCommercial purposes only. 139 | - 2. Exceptions and Limitations. For the avoidance of doubt, 140 | where Exceptions and Limitations apply to Your use, this 141 | Public License does not apply, and You do not need to comply 142 | with its terms and conditions. 143 | - 3. Term. The term of this Public License is specified in 144 | Section 6(a). 145 | - 4. Media and formats; technical modifications allowed. The 146 | Licensor authorizes You to exercise the Licensed Rights in 147 | all media and formats whether now known or hereafter 148 | created, and to make technical modifications necessary to do 149 | so. The Licensor waives and/or agrees not to assert any 150 | right or authority to forbid You from making technical 151 | modifications necessary to exercise the Licensed Rights, 152 | including technical modifications necessary to circumvent 153 | Effective Technological Measures. For purposes of this 154 | Public License, simply making modifications authorized by 155 | this Section 2(a)(4) never produces Adapted Material. 156 | - 5. Downstream recipients. 157 | - A. Offer from the Licensor – Licensed Material. Every 158 | recipient of the Licensed Material automatically 159 | receives an offer from the Licensor to exercise the 160 | Licensed Rights under the terms and conditions of this 161 | Public License. 162 | - B. No downstream restrictions. You may not offer or 163 | impose any additional or different terms or conditions 164 | on, or apply any Effective Technological Measures to, 165 | the Licensed Material if doing so restricts exercise of 166 | the Licensed Rights by any recipient of the Licensed 167 | Material. 168 | - 6. No endorsement. Nothing in this Public License 169 | constitutes or may be construed as permission to assert or 170 | imply that You are, or that Your use of the Licensed 171 | Material is, connected with, or sponsored, endorsed, or 172 | granted official status by, the Licensor or others 173 | designated to receive attribution as provided in Section 174 | 3(a)(1)(A)(i). 175 | - b. Other rights. 176 | - 1. Moral rights, such as the right of integrity, are not 177 | licensed under this Public License, nor are publicity, 178 | privacy, and/or other similar personality rights; however, 179 | to the extent possible, the Licensor waives and/or agrees 180 | not to assert any such rights held by the Licensor to the 181 | limited extent necessary to allow You to exercise the 182 | Licensed Rights, but not otherwise. 183 | - 2. Patent and trademark rights are not licensed under this 184 | Public License. 185 | - 3. To the extent possible, the Licensor waives any right to 186 | collect royalties from You for the exercise of the Licensed 187 | Rights, whether directly or through a collecting society 188 | under any voluntary or waivable statutory or compulsory 189 | licensing scheme. In all other cases the Licensor expressly 190 | reserves any right to collect such royalties, including when 191 | the Licensed Material is used other than for NonCommercial 192 | purposes. 193 | 194 | - Section 3 – License Conditions. 195 | 196 | Your exercise of the Licensed Rights is expressly made subject to 197 | the following conditions. 198 | 199 | - a. Attribution. 200 | - 1. If You Share the Licensed Material (including in modified 201 | form), You must: 202 | - A. retain the following if it is supplied by the 203 | Licensor with the Licensed Material: 204 | - i. identification of the creator(s) of the Licensed 205 | Material and any others designated to receive 206 | attribution, in any reasonable manner requested by 207 | the Licensor (including by pseudonym if designated); 208 | - ii. a copyright notice; 209 | - iii. a notice that refers to this Public License; 210 | - iv. a notice that refers to the disclaimer of 211 | warranties; 212 | - v. a URI or hyperlink to the Licensed Material to 213 | the extent reasonably practicable; 214 | - B. indicate if You modified the Licensed Material and 215 | retain an indication of any previous modifications; and 216 | - C. indicate the Licensed Material is licensed under this 217 | Public License, and include the text of, or the URI or 218 | hyperlink to, this Public License. 219 | - 2. You may satisfy the conditions in Section 3(a)(1) in any 220 | reasonable manner based on the medium, means, and context in 221 | which You Share the Licensed Material. For example, it may 222 | be reasonable to satisfy the conditions by providing a URI 223 | or hyperlink to a resource that includes the required 224 | information. 225 | - 3. If requested by the Licensor, You must remove any of the 226 | information required by Section 3(a)(1)(A) to the extent 227 | reasonably practicable. 228 | - 4. If You Share Adapted Material You produce, the Adapter's 229 | License You apply must not prevent recipients of the Adapted 230 | Material from complying with this Public License. 231 | 232 | - Section 4 – Sui Generis Database Rights. 233 | 234 | Where the Licensed Rights include Sui Generis Database Rights that 235 | apply to Your use of the Licensed Material: 236 | 237 | - a. for the avoidance of doubt, Section 2(a)(1) grants You the 238 | right to extract, reuse, reproduce, and Share all or a 239 | substantial portion of the contents of the database for 240 | NonCommercial purposes only; 241 | - b. if You include all or a substantial portion of the database 242 | contents in a database in which You have Sui Generis Database 243 | Rights, then the database in which You have Sui Generis Database 244 | Rights (but not its individual contents) is Adapted Material; 245 | and 246 | - c. You must comply with the conditions in Section 3(a) if You 247 | Share all or a substantial portion of the contents of the 248 | database. 249 | 250 | For the avoidance of doubt, this Section 4 supplements and does not 251 | replace Your obligations under this Public License where the 252 | Licensed Rights include other Copyright and Similar Rights. 253 | 254 | - Section 5 – Disclaimer of Warranties and Limitation of Liability. 255 | 256 | - a. Unless otherwise separately undertaken by the Licensor, to 257 | the extent possible, the Licensor offers the Licensed Material 258 | as-is and as-available, and makes no representations or 259 | warranties of any kind concerning the Licensed Material, whether 260 | express, implied, statutory, or other. This includes, without 261 | limitation, warranties of title, merchantability, fitness for a 262 | particular purpose, non-infringement, absence of latent or other 263 | defects, accuracy, or the presence or absence of errors, whether 264 | or not known or discoverable. Where disclaimers of warranties 265 | are not allowed in full or in part, this disclaimer may not 266 | apply to You. 267 | - b. To the extent possible, in no event will the Licensor be 268 | liable to You on any legal theory (including, without 269 | limitation, negligence) or otherwise for any direct, special, 270 | indirect, incidental, consequential, punitive, exemplary, or 271 | other losses, costs, expenses, or damages arising out of this 272 | Public License or use of the Licensed Material, even if the 273 | Licensor has been advised of the possibility of such losses, 274 | costs, expenses, or damages. Where a limitation of liability is 275 | not allowed in full or in part, this limitation may not apply to 276 | You. 277 | - c. The disclaimer of warranties and limitation of liability 278 | provided above shall be interpreted in a manner that, to the 279 | extent possible, most closely approximates an absolute 280 | disclaimer and waiver of all liability. 281 | 282 | - Section 6 – Term and Termination. 283 | 284 | - a. This Public License applies for the term of the Copyright and 285 | Similar Rights licensed here. However, if You fail to comply 286 | with this Public License, then Your rights under this Public 287 | License terminate automatically. 288 | - b. Where Your right to use the Licensed Material has terminated 289 | under Section 6(a), it reinstates: 290 | 291 | - 1. automatically as of the date the violation is cured, 292 | provided it is cured within 30 days of Your discovery of the 293 | violation; or 294 | - 2. upon express reinstatement by the Licensor. 295 | 296 | For the avoidance of doubt, this Section 6(b) does not affect 297 | any right the Licensor may have to seek remedies for Your 298 | violations of this Public License. 299 | 300 | - c. For the avoidance of doubt, the Licensor may also offer the 301 | Licensed Material under separate terms or conditions or stop 302 | distributing the Licensed Material at any time; however, doing 303 | so will not terminate this Public License. 304 | - d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 305 | License. 306 | 307 | - Section 7 – Other Terms and Conditions. 308 | 309 | - a. The Licensor shall not be bound by any additional or 310 | different terms or conditions communicated by You unless 311 | expressly agreed. 312 | - b. Any arrangements, understandings, or agreements regarding the 313 | Licensed Material not stated herein are separate from and 314 | independent of the terms and conditions of this Public License. 315 | 316 | - Section 8 – Interpretation. 317 | 318 | - a. For the avoidance of doubt, this Public License does not, and 319 | shall not be interpreted to, reduce, limit, restrict, or impose 320 | conditions on any use of the Licensed Material that could 321 | lawfully be made without permission under this Public License. 322 | - b. To the extent possible, if any provision of this Public 323 | License is deemed unenforceable, it shall be automatically 324 | reformed to the minimum extent necessary to make it enforceable. 325 | If the provision cannot be reformed, it shall be severed from 326 | this Public License without affecting the enforceability of the 327 | remaining terms and conditions. 328 | - c. No term or condition of this Public License will be waived 329 | and no failure to comply consented to unless expressly agreed to 330 | by the Licensor. 331 | - d. Nothing in this Public License constitutes or may be 332 | interpreted as a limitation upon, or waiver of, any privileges 333 | and immunities that apply to the Licensor or You, including from 334 | the legal processes of any jurisdiction or authority. 335 | 336 | Creative Commons is not a party to its public licenses. Notwithstanding, 337 | Creative Commons may elect to apply one of its public licenses to 338 | material it publishes and in those instances will be considered the 339 | "Licensor." The text of the Creative Commons public licenses is 340 | dedicated to the public domain under the CC0 Public Domain Dedication. 341 | Except for the limited purpose of indicating that material is shared 342 | under a Creative Commons public license or as otherwise permitted by the 343 | Creative Commons policies published at creativecommons.org/policies, 344 | Creative Commons does not authorize the use of the trademark "Creative 345 | Commons" or any other trademark or logo of Creative Commons without its 346 | prior written consent including, without limitation, in connection with 347 | any unauthorized modifications to any of its public licenses or any 348 | other arrangements, understandings, or agreements concerning use of 349 | licensed material. For the avoidance of doubt, this paragraph does not 350 | form part of the public licenses. 351 | 352 | Creative Commons may be contacted at creativecommons.org. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Music2Latent 2 | Encode and decode audio samples to/from compressed representations! Useful for efficient generative modelling applications and for other downstream tasks. 3 | 4 | ![music2latent](music2latent.png) 5 | 6 | Read the ISMIR 2024 paper [here](https://arxiv.org/abs/2408.06500). 7 | Listen to audio samples [here](https://sonycslparis.github.io/music2latent-companion/). 8 | 9 | Under the hood, __Music2Latent__ uses a __Consistency Autoencoder__ model to efficiently encode and decode audio samples. 10 | 11 | 44.1 kHz audio is encoded into a sequence of __~10 Hz__, and each of the latents has 64 channels. 12 | 48 kHz audio can also be encoded, which results in a sequence of ~12 Hz. 13 | A generative model can then be trained on these embeddings, or they can be used for other downstream tasks. 14 | 15 | Music2Latent was trained on __music__ and on __speech__. Refer to the [paper](https://arxiv.org/abs/2408.06500) for more details. 16 | 17 | 18 | ## Installation 19 | 20 | ```bash 21 | pip install music2latent 22 | ``` 23 | The model weights will be downloaded automatically the first time the code is run. 24 | 25 | 26 | ## How to use 27 | To encode and decode audio samples to/from latent embeddings: 28 | ```bash 29 | audio_path = librosa.example('trumpet') 30 | wv, sr = librosa.load(audio_path, sr=44100) 31 | 32 | from music2latent import EncoderDecoder 33 | encdec = EncoderDecoder() 34 | 35 | latent = encdec.encode(wv) 36 | # latent has shape (batch_size/audio_channels, dim (64), sequence_length) 37 | 38 | wv_rec = encdec.decode(latent) 39 | ``` 40 | To extract encoder features to use in downstream tasks: 41 | ```bash 42 | features = encoder.encode(wv, extract_features=True) 43 | ``` 44 | These features are extracted before the encoder bottleneck, and thus have more channels (contain more information) than the latents used for reconstruction. It will not be possible to directly decode these features back to audio. 45 | 46 | music2latent supports more advanced usage, including GPU memory management controls. Please refer to __tutorial.ipynb__. 47 | 48 | 49 | ## License 50 | This library is released under the CC BY-NC 4.0 license. Please refer to the LICENSE file for more details. 51 | 52 | 53 | 54 | This work was conducted by [Marco Pasini](https://twitter.com/marco_ppasini) during his PhD at Queen Mary University of London, in partnership with Sony Computer Science Laboratories Paris. 55 | This work was supervised by Stefan Lattner and George Fazekas. -------------------------------------------------------------------------------- /architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SonyCSLParis/music2latent/f6df26e6777977807b40a98d32a96105cc8e0e0a/architecture.png -------------------------------------------------------------------------------- /music2latent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SonyCSLParis/music2latent/f6df26e6777977807b40a98d32a96105cc8e0e0a/music2latent.png -------------------------------------------------------------------------------- /music2latent/__init__.py: -------------------------------------------------------------------------------- 1 | from .inference import EncoderDecoder -------------------------------------------------------------------------------- /music2latent/audio.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | import numpy as np 4 | 5 | from .hparams import * 6 | 7 | 8 | def wv2spec(wv, hop_size=256, fac=4): 9 | X = stft(wv, hop_size=hop_size, fac=fac, device=wv.device) 10 | X = power2db(torch.abs(X)**2) 11 | X = normalize(X) 12 | return X 13 | 14 | def spec2wv(S,P, hop_size=256, fac=4): 15 | S = denormalize(S) 16 | S = torch.sqrt(db2power(S)) 17 | P = P * np.pi 18 | SP = torch.complex(S * torch.cos(P), S * torch.sin(P)) 19 | return istft(SP, fac=fac, hop_size=hop_size, device=SP.device) 20 | 21 | def denormalize_realimag(x): 22 | x = x/beta_rescale 23 | return torch.sign(x)*(x.abs()**(1./alpha_rescale)) 24 | 25 | def normalize_complex(x): 26 | return beta_rescale*(x.abs()**alpha_rescale).to(torch.complex64)*torch.exp(1j*torch.angle(x).to(torch.complex64)) 27 | 28 | def denormalize_complex(x): 29 | x = x/beta_rescale 30 | return (x.abs()**(1./alpha_rescale)).to(torch.complex64)*torch.exp(1j*torch.angle(x).to(torch.complex64)) 31 | 32 | def wv2complex(wv, hop_size=256, fac=4): 33 | X = stft(wv, hop_size=hop_size, fac=fac, device=wv.device) 34 | return X[:,:hop_size*2,:] 35 | 36 | def wv2realimag(wv, hop_size=256, fac=4): 37 | X = wv2complex(wv, hop_size, fac) 38 | X = normalize_complex(X) 39 | return torch.stack((torch.real(X),torch.imag(X)), -3) 40 | 41 | def realimag2wv(x, hop_size=256, fac=4): 42 | x = torch.nn.functional.pad(x, (0,0,0,1)) 43 | real,imag = torch.chunk(x, 2, -3) 44 | X = torch.complex(real.squeeze(-3),imag.squeeze(-3)) 45 | X = denormalize_complex(X) 46 | return istft(X, fac=fac, hop_size=hop_size, device=X.device).clamp(-1.,1.) 47 | 48 | def to_representation_encoder(x): 49 | return wv2realimag(x, hop) 50 | 51 | def to_representation(x): 52 | return wv2realimag(x, hop) 53 | 54 | def to_waveform(x): 55 | return realimag2wv(x, hop) 56 | 57 | def overlap_and_add(signal, frame_step): 58 | 59 | outer_dimensions = signal.shape[:-2] 60 | outer_rank = torch.numel(torch.tensor(outer_dimensions)) 61 | 62 | def full_shape(inner_shape): 63 | s = torch.cat([torch.tensor(outer_dimensions), torch.tensor(inner_shape)], 0) 64 | s = list(s) 65 | s = [int(el) for el in s] 66 | return s 67 | 68 | frame_length = signal.shape[-1] 69 | frames = signal.shape[-2] 70 | 71 | # Compute output length. 72 | output_length = frame_length + frame_step * (frames - 1) 73 | 74 | # Compute the number of segments, per frame. 75 | segments = -(-frame_length // frame_step) # Divide and round up. 76 | 77 | signal = torch.nn.functional.pad(signal, (0, segments * frame_step - frame_length, 0, segments)) 78 | 79 | shape = full_shape([frames + segments, segments, frame_step]) 80 | signal = torch.reshape(signal, shape) 81 | 82 | perm = torch.cat([torch.arange(0, outer_rank), torch.tensor([el+outer_rank for el in [1, 0, 2]])], 0) 83 | perm = list(perm) 84 | perm = [int(el) for el in perm] 85 | signal = torch.permute(signal, perm) 86 | 87 | shape = full_shape([(frames + segments) * segments, frame_step]) 88 | signal = torch.reshape(signal, shape) 89 | 90 | signal = signal[..., :(frames + segments - 1) * segments, :] 91 | 92 | shape = full_shape([segments, (frames + segments - 1), frame_step]) 93 | signal = torch.reshape(signal, shape) 94 | 95 | signal = signal.sum(-3) 96 | 97 | # Flatten the array. 98 | shape = full_shape([(frames + segments - 1) * frame_step]) 99 | signal = torch.reshape(signal, shape) 100 | 101 | # Truncate to final length. 102 | signal = signal[..., :output_length] 103 | 104 | return signal 105 | 106 | def inverse_stft_window(frame_length, frame_step, forward_window): 107 | denom = forward_window**2 108 | overlaps = -(-frame_length // frame_step) 109 | denom = F.pad(denom, (0, overlaps * frame_step - frame_length)) 110 | denom = torch.reshape(denom, [overlaps, frame_step]) 111 | denom = torch.sum(denom, 0, keepdim=True) 112 | denom = torch.tile(denom, [overlaps, 1]) 113 | denom = torch.reshape(denom, [overlaps * frame_step]) 114 | return forward_window / denom[:frame_length] 115 | 116 | def istft(SP, fac=4, hop_size=256, device='cuda'): 117 | x = torch.fft.irfft(SP, dim=-2) 118 | window = torch.hann_window(fac*hop_size).to(device) 119 | window = inverse_stft_window(fac*hop_size, hop_size, window) 120 | x = x*window.unsqueeze(-1) 121 | return overlap_and_add(x.permute(0,2,1), hop_size) 122 | 123 | def frame(signal, frame_length, frame_step, pad_end=False, pad_value=0, axis=-1): 124 | """ 125 | equivalent of tf.signal.frame 126 | """ 127 | signal_length = signal.shape[axis] 128 | if pad_end: 129 | frames_overlap = frame_length - frame_step 130 | rest_samples = np.abs(signal_length - frames_overlap) % np.abs(frame_length - frames_overlap) 131 | pad_size = int(frame_length - rest_samples) 132 | if pad_size != 0: 133 | pad_axis = [0] * signal.ndim 134 | pad_axis[axis] = pad_size 135 | signal = F.pad(signal, pad_axis, "constant", pad_value) 136 | frames = signal.unfold(axis, frame_length, frame_step) 137 | return frames 138 | 139 | def stft(wv, fac=4, hop_size=256, device='cuda'): 140 | window = torch.hann_window(fac*hop_size).to(device) 141 | framed_signals = frame(wv, fac*hop_size, hop_size) 142 | framed_signals = framed_signals*window 143 | return torch.fft.rfft(framed_signals, n=None, dim=- 1, norm=None).permute(0,2,1) 144 | 145 | def normalize(S, mu_rescale=-25., sigma_rescale=75.): 146 | return (S - mu_rescale) / sigma_rescale 147 | 148 | def denormalize(S, mu_rescale=-25., sigma_rescale=75.): 149 | return (S * sigma_rescale) + mu_rescale 150 | 151 | def db2power(S_db, ref=1.0): 152 | return ref * torch.pow(10.0, 0.1 * S_db) 153 | 154 | def power2db(power, ref_value=1.0, amin=1e-10): 155 | log_spec = 10.0 * torch.log10(torch.maximum(torch.tensor(amin), power)) 156 | log_spec -= 10.0 * torch.log10(torch.maximum(torch.tensor(amin), torch.tensor(ref_value))) 157 | return log_spec -------------------------------------------------------------------------------- /music2latent/hparams.py: -------------------------------------------------------------------------------- 1 | # GENERAL 2 | mixed_precision = True # use mixed precision 3 | seed = 42 # seed for Pytorch 4 | 5 | # DATA 6 | data_channels = 2 # channels of input data 7 | data_length = 64 # sequence length of input data 8 | data_length_test = 1024//4 # sequence length of data used for testing 9 | sample_rate = 44100 # sampling rate of input/output audio 10 | 11 | hop = 128*4 # hop size of transformation 12 | 13 | alpha_rescale = 0.65 14 | beta_rescale = 0.34 15 | sigma_data = 0.5 16 | 17 | 18 | 19 | # MODEL 20 | base_channels = 64 # base channel number for architecture 21 | layers_list = [2,2,2,2,2] # number of blocks per each resolution level 22 | multipliers_list = [1,2,4,4,4] # base channels multipliers for each resolution level 23 | attention_list = [0,0,1,1,1] # for each resolution, 0 if no attention is performed, 1 if attention is performed 24 | freq_downsample_list = [1,0,0,0] # for each resolution, 0 if frequency 4x downsampling, 1 if standard frequency 2x and time 2x downsampling 25 | 26 | layers_list_encoder = [1,1,1,1,1] # number of blocks per each resolution level 27 | attention_list_encoder = [0,0,1,1,1] # for each resolution, 0 if no attention is performed, 1 if attention is performed 28 | bottleneck_base_channels = 512 # base channels to use for block before/after bottleneck 29 | num_bottleneck_layers = 4 # number of blocks to use before/after bottleneck 30 | frequency_scaling = True 31 | 32 | heads = 4 # number of attention heads 33 | cond_channels = 256 # dimension of time embedding 34 | use_fourier = False # if True, use random Fourier embedding, if False, use Positional 35 | fourier_scale = 0.2 # scale parameter for gaussian fourier layer (original is 0.02, but to me it appears too small) 36 | normalization = True # use group normalization 37 | dropout_rate = 0. # dropout rate 38 | min_res_dropout = 16 # dropout is applied on equal or smaller feature map resolutions 39 | init_as_zero = True # initialize convolution kernels before skip connections with zeros 40 | 41 | bottleneck_channels = 32*2 # channels of encoder bottleneck 42 | 43 | pre_normalize_2d_to_1d = True # pre-normalize 2D to 1D connection in encoder 44 | pre_normalize_downsampling_encoder = True # pre-normalize downsampling layers in encoder 45 | 46 | sigma_min = 0.002 # minimum sigma 47 | sigma_max = 80. # maximum sigma 48 | rho = 7. # rho parameter for sigma schedule -------------------------------------------------------------------------------- /music2latent/hparams_inference.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | filepath = os.path.abspath(__file__) 4 | lib_root = os.path.dirname(filepath) 5 | 6 | load_path_inference_default = os.path.join(lib_root, 'models/music2latent.pt') 7 | 8 | max_batch_size_encode = 1 # maximum inference batch size for encoding: tune it depending on the available GPU memory 9 | max_waveform_length_encode = 44100*60 # maximum length of waveforms in the batch for encoding: tune it depending on the available GPU memory 10 | max_batch_size_decode = 1 # maximum inference batch size for decoding: tune it depending on the available GPU memory 11 | max_waveform_length_decode = 44100*60 # maximum length of waveforms in the batch for decoding: tune it depending on the available GPU memory 12 | 13 | 14 | sigma_rescale = 0.06 # rescale sigma for inference -------------------------------------------------------------------------------- /music2latent/inference.py: -------------------------------------------------------------------------------- 1 | import soundfile as sf 2 | import torch 3 | import numpy as np 4 | 5 | from .hparams import * 6 | from .hparams_inference import * 7 | from .utils import * 8 | from .models import * 9 | from .audio import * 10 | 11 | 12 | class EncoderDecoder: 13 | def __init__(self, load_path_inference=None, device=None): 14 | download_model() 15 | if device is None: 16 | self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 17 | else: 18 | self.device = device 19 | self.load_path_inference = load_path_inference 20 | if load_path_inference is None: 21 | self.load_path_inference = load_path_inference_default 22 | self.get_models() 23 | 24 | def get_models(self): 25 | gen = UNet().to(self.device) 26 | checkpoint = torch.load(self.load_path_inference, map_location=self.device) 27 | gen.load_state_dict(checkpoint['gen_state_dict'], strict=False) 28 | self.gen = gen 29 | 30 | def encode(self, path_or_audio, max_waveform_length=None, max_batch_size=None, extract_features=False): 31 | ''' 32 | path_or_audio: path of audio sample to encode or numpy array of waveform to encode 33 | max_waveform_length: maximum length of waveforms in the batch for encoding: tune it depending on the available GPU memory 34 | max_batch_size: maximum inference batch size for encoding: tune it depending on the available GPU memory 35 | 36 | WARNING! if input is numpy array of stereo waveform, it must have shape [waveform_samples, audio_channels] 37 | 38 | Returns latents with shape [audio_channels, dim, length] 39 | ''' 40 | if max_waveform_length is None: 41 | max_waveform_length = max_waveform_length_encode 42 | if max_batch_size is None: 43 | max_batch_size = max_batch_size_encode 44 | return encode_audio_inference(path_or_audio, self, max_waveform_length, max_batch_size, device=self.device, extract_features=extract_features) 45 | 46 | def decode(self, latent, denoising_steps=1, max_waveform_length=None, max_batch_size=None): 47 | ''' 48 | latent: numpy array of latents to decode with shape [audio_channels, dim, length] 49 | denoising_steps: number of denoising steps to use for decoding 50 | max_waveform_length: maximum length of waveforms in the batch for decoding: tune it depending on the available GPU memory 51 | max_batch_size: maximum inference batch size for decoding: tune it depending on the available GPU memory 52 | 53 | Returns numpy array of decoded waveform with shape [waveform_samples, audio_channels] 54 | ''' 55 | if max_waveform_length is None: 56 | max_waveform_length = max_waveform_length_decode 57 | if max_batch_size is None: 58 | max_batch_size = max_batch_size_decode 59 | return decode_latent_inference(latent, self, max_waveform_length, max_batch_size, diffusion_steps=denoising_steps, device=self.device) 60 | 61 | 62 | 63 | 64 | 65 | 66 | # decode samples with consistency model to real/imag STFT spectrograms 67 | # Parameters: 68 | # model: trained consistency model 69 | # latents: latent representation with shape [audio_channels/batch_size, dim, length] 70 | # diffusion_steps: number of steps 71 | # Returns: 72 | # decoded_spectrograms with shape [audio_channels/batch_size, data_channels, hop*2, length*downscaling_factor] 73 | def decode_to_representation(model, latents, diffusion_steps=1, device='cuda'): 74 | num_samples = latents.shape[0] 75 | downscaling_factor = 2**freq_downsample_list.count(0) 76 | sample_length = int(latents.shape[-1]*downscaling_factor) 77 | initial_noise = torch.randn((num_samples, data_channels, hop*2, sample_length)).to(device)*sigma_max 78 | decoded_spectrograms = reverse_diffusion(model, initial_noise, diffusion_steps, latents=latents) 79 | return decoded_spectrograms 80 | 81 | 82 | 83 | 84 | # Encode audio sample for inference 85 | # Parameters: 86 | # audio_path: path of audio sample 87 | # model: trained consistency model 88 | # device: device to run the model on 89 | # Returns: 90 | # latent: compressed latent representation with shape [audio_channels, dim, latent_length] 91 | @torch.no_grad() 92 | def encode_audio_inference(audio_path, trainer, max_waveform_length_encode, max_batch_size_encode, device='cuda', extract_features=False): 93 | trainer.gen = trainer.gen.to(device) 94 | trainer.gen.eval() 95 | downscaling_factor = 2**freq_downsample_list.count(0) 96 | if is_path(audio_path): 97 | audio, sr = sf.read(audio_path, dtype='float32', always_2d=True) 98 | audio = np.transpose(audio, [1,0]) 99 | else: 100 | audio = audio_path 101 | sr = None 102 | if len(audio.shape)==1: 103 | # check if audio is numpy array, then use np.expand_dims, if it is a pytorch tensor, then use torch.unsqueeze 104 | if isinstance(audio, np.ndarray): 105 | audio = np.expand_dims(audio, 0) 106 | else: 107 | audio = torch.unsqueeze(audio, 0) 108 | audio_channels = audio.shape[0] 109 | if isinstance(audio, np.ndarray): 110 | audio = torch.from_numpy(audio).to(device) 111 | else: 112 | # check if audio tensor is on cpu. if it is, move it to the device 113 | if audio.device.type=='cpu': 114 | audio = audio.to(device) 115 | 116 | # EXPERIMENTAL: crop audio to be divisible by downscaling_factor 117 | cropped_length = ((((audio.shape[-1]-3*hop)//hop)//downscaling_factor)*hop*downscaling_factor)+3*hop 118 | audio = audio[:,:cropped_length] 119 | 120 | repr_encoder = to_representation_encoder(audio) 121 | sample_length = repr_encoder.shape[-1] 122 | max_sample_length = (int(max_waveform_length_encode/hop)//downscaling_factor)*downscaling_factor 123 | 124 | # if repr_encoder is longer than max_sample_length, chunk it into max_sample_length chunks, the last chunk will be zero-padded, then concatenate the chunks into the batch dimension (before encoding them) 125 | pad_size = 0 126 | if sample_length > max_sample_length: 127 | # pad repr_encoder with copies of the sample to be divisible by max_sample_length 128 | pad_size = max_sample_length - (sample_length % max_sample_length) 129 | # repeat repr_encoder such that repr_encoder.shape[-1] is higher than pad_size, then crop it such that repr_encoder.shape[-1]=pad_size 130 | repr_encoder_pad = torch.cat([repr_encoder for _ in range(1+(pad_size//repr_encoder.shape[-1]))], dim=-1)[:,:,:,:pad_size] 131 | repr_encoder = torch.cat([repr_encoder, repr_encoder_pad], dim=-1) 132 | repr_encoder = torch.split(repr_encoder, max_sample_length, dim=-1) 133 | repr_encoder = torch.cat(repr_encoder, dim=0) 134 | # encode repr_encoder using a maximum batch size (dimension 0) of max_batch_size_inference, if repr_encoder is longer than max_batch_size_inference, chunk it into max_batch_size_inference chunks, the last chunk will maybe have less samples in the batch, then encode the chunks and concatenate the results into the batch dimension 135 | max_batch_size = max_batch_size_encode 136 | if repr_encoder.shape[0] > max_batch_size: 137 | repr_encoder_ls = torch.split(repr_encoder, max_batch_size, dim=0) 138 | latent_ls = [] 139 | for i in range(len(repr_encoder_ls)): 140 | with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=mixed_precision): # disable float16 for encoding (can cause nans) 141 | latent = trainer.gen.encoder(repr_encoder_ls[i], extract_features=extract_features) 142 | latent_ls.append(latent) 143 | latent = torch.cat(latent_ls, dim=0) 144 | else: 145 | with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=mixed_precision): # disable float16 for encoding (can cause nans) 146 | latent = trainer.gen.encoder(repr_encoder, extract_features=extract_features) 147 | # split samples 148 | if latent.shape[0]>1: 149 | latent_ls = torch.split(latent, audio_channels, 0) 150 | latent = torch.cat(latent_ls, -1) 151 | latent = latent[:,:,:latent.shape[-1]-(pad_size//downscaling_factor)] 152 | if extract_features: 153 | return latent 154 | else: 155 | return latent/sigma_rescale 156 | 157 | 158 | 159 | # Decode latent representation for inference, use the same framework as in encode_audio_inference, but in reverse order for decoding 160 | # Parameters: 161 | # latent: compressed latent representation with shape [audio_channels, dim, length] 162 | # model: trained consistency model 163 | # diffusion_steps: number of diffusion steps to use for decoding 164 | # device: device to run the model on 165 | # Returns: 166 | # audio: numpy array of decoded waveform with shape [waveform_samples, audio_channels] 167 | @torch.no_grad() 168 | def decode_latent_inference(latent, trainer, max_waveform_length_decode, max_batch_size_decode, diffusion_steps=1, device='cuda'): 169 | trainer.gen = trainer.gen.to(device) 170 | trainer.gen.eval() 171 | downscaling_factor = 2**freq_downsample_list.count(0) 172 | latent = latent*sigma_rescale 173 | # check if latent is numpy array, then convert to tensor 174 | if isinstance(latent, np.ndarray): 175 | latent = torch.from_numpy(latent) 176 | # check if latent tensor is on cpu. if it is, move it to the device 177 | if latent.device.type=='cpu': 178 | latent = latent.to(device) 179 | # if latent has only 2 dimensions, add a third dimension as axis 0 180 | if len(latent.shape)==2: 181 | latent = torch.unsqueeze(latent, 0) 182 | audio_channels = latent.shape[0] 183 | latent_length = latent.shape[-1] 184 | max_latent_length = int(max_waveform_length_decode/hop)//downscaling_factor 185 | 186 | # if latent is longer than max_latent_length, chunk it into max_latent_length chunks, the last chunk will be zero-padded, then concatenate the chunks into the batch dimension (before decoding them) 187 | pad_size = 0 188 | if latent_length > max_latent_length: 189 | # pad latent with copies of itself to be divisible by max_latent_length 190 | pad_size = max_latent_length - (latent_length % max_latent_length) 191 | # repeat latent such that latent.shape[-1] is higher than pad_size, then crop it such that latent.shape[-1]=pad_size 192 | latent_pad = torch.cat([latent for _ in range(1+(pad_size//latent.shape[-1]))], dim=-1)[:,:,:pad_size] 193 | latent = torch.cat([latent, latent_pad], dim=-1) 194 | latent = torch.split(latent, max_latent_length, dim=-1) 195 | latent = torch.cat(latent, dim=0) 196 | # decode latent using a maximum batch size (dimension 0) of max_batch_size_inference, if latent is longer than max_batch_size_inference, chunk it into max_batch_size_inference chunks, the last chunk will maybe have less samples in the batch, then decode the chunks and concatenate the results into the batch dimension 197 | max_batch_size = max_batch_size_decode 198 | if latent.shape[0] > max_batch_size: 199 | latent_ls = torch.split(latent, max_batch_size, dim=0) 200 | repr_ls = [] 201 | for i in range(len(latent_ls)): 202 | repr = decode_to_representation(trainer.gen, latent_ls[i], diffusion_steps=diffusion_steps, device=device) 203 | repr_ls.append(repr) 204 | repr = torch.cat(repr_ls, dim=0) 205 | else: 206 | repr = decode_to_representation(trainer.gen, latent, diffusion_steps=diffusion_steps, device=device) 207 | # split samples 208 | if repr.shape[0]>1: 209 | repr_ls = torch.split(repr, audio_channels, 0) 210 | repr = torch.cat(repr_ls, -1) 211 | repr = repr[:,:,:,:repr.shape[-1]-(pad_size*downscaling_factor)] 212 | return to_waveform(repr) -------------------------------------------------------------------------------- /music2latent/models.py: -------------------------------------------------------------------------------- 1 | from .utils import * 2 | from .audio import * 3 | 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | 8 | 9 | def zero_init(module): 10 | if init_as_zero: 11 | for p in module.parameters(): 12 | p.detach().zero_() 13 | return module 14 | 15 | def upsample_1d(x): 16 | return F.interpolate(x, scale_factor=2, mode="nearest") 17 | 18 | def downsample_1d(x): 19 | return F.avg_pool1d(x, kernel_size=2, stride=2) 20 | 21 | def upsample_2d(x): 22 | return F.interpolate(x, scale_factor=2, mode="nearest") 23 | 24 | def downsample_2d(x): 25 | return F.avg_pool2d(x, kernel_size=2, stride=2) 26 | 27 | 28 | class LayerNorm(nn.Module): 29 | def __init__(self, dim): 30 | super(LayerNorm, self).__init__() 31 | self.ln = torch.nn.LayerNorm(dim) 32 | 33 | def forward(self, input): 34 | x = input.permute(0,2,3,1) 35 | x = self.ln(x) 36 | x = x.permute(0,3,1,2) 37 | return x 38 | 39 | class FreqGain(nn.Module): 40 | def __init__(self, freq_dim): 41 | super(FreqGain, self).__init__() 42 | self.scale = nn.Parameter(torch.ones((1,1,freq_dim,1))) 43 | 44 | def forward(self, input): 45 | return input*self.scale 46 | 47 | 48 | class UpsampleConv(nn.Module): 49 | def __init__(self, in_channels, out_channels=None, use_2d=False, normalize=False): 50 | super(UpsampleConv, self).__init__() 51 | self.normalize = normalize 52 | 53 | self.use_2d = use_2d 54 | 55 | if out_channels is None: 56 | out_channels = in_channels 57 | 58 | if normalize: 59 | self.norm = nn.GroupNorm(min(in_channels//4, 32), in_channels) 60 | 61 | if use_2d: 62 | self.c = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding='same') 63 | else: 64 | self.c = nn.Conv1d(in_channels, out_channels, kernel_size=3, stride=1, padding='same') 65 | 66 | def forward(self, x): 67 | 68 | if self.normalize: 69 | x = self.norm(x) 70 | 71 | if self.use_2d: 72 | x = upsample_2d(x) 73 | else: 74 | x = upsample_1d(x) 75 | x = self.c(x) 76 | 77 | return x 78 | 79 | class DownsampleConv(nn.Module): 80 | def __init__(self, in_channels, out_channels=None, use_2d=False, normalize=False): 81 | super(DownsampleConv, self).__init__() 82 | self.normalize = normalize 83 | 84 | if out_channels is None: 85 | out_channels = in_channels 86 | 87 | if normalize: 88 | self.norm = nn.GroupNorm(min(in_channels//4, 32), in_channels) 89 | 90 | if use_2d: 91 | self.c = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=2, padding=1) 92 | else: 93 | self.c = nn.Conv1d(in_channels, out_channels, kernel_size=3, stride=2, padding=1) 94 | 95 | def forward(self, x): 96 | 97 | if self.normalize: 98 | x = self.norm(x) 99 | x = self.c(x) 100 | 101 | return x 102 | 103 | class UpsampleFreqConv(nn.Module): 104 | def __init__(self, in_channels, out_channels=None, normalize=False): 105 | super(UpsampleFreqConv, self).__init__() 106 | self.normalize = normalize 107 | 108 | if out_channels is None: 109 | out_channels = in_channels 110 | 111 | if normalize: 112 | self.norm = nn.GroupNorm(min(in_channels//4, 32), in_channels) 113 | 114 | self.c = nn.Conv2d(in_channels, out_channels, kernel_size=(5,1), stride=1, padding='same') 115 | 116 | def forward(self, x): 117 | if self.normalize: 118 | x = self.norm(x) 119 | x = F.interpolate(x, scale_factor=(4,1), mode="nearest") 120 | x = self.c(x) 121 | return x 122 | 123 | class DownsampleFreqConv(nn.Module): 124 | def __init__(self, in_channels, out_channels=None, normalize=False): 125 | super(DownsampleFreqConv, self).__init__() 126 | self.normalize = normalize 127 | 128 | if out_channels is None: 129 | out_channels = in_channels 130 | 131 | if normalize: 132 | self.norm = nn.GroupNorm(min(in_channels//4, 32), in_channels) 133 | 134 | self.c = nn.Conv2d(in_channels, out_channels, kernel_size=(5,1), stride=(4,1), padding=(2,0)) 135 | 136 | def forward(self, x): 137 | if self.normalize: 138 | x = self.norm(x) 139 | x = self.c(x) 140 | return x 141 | 142 | class MultiheadAttention(nn.MultiheadAttention): 143 | def _reset_parameters(self): 144 | super()._reset_parameters() 145 | self.out_proj = zero_init(self.out_proj) 146 | 147 | class Attention(nn.Module): 148 | def __init__(self, dim, heads=4, normalize=True, use_2d=False): 149 | super(Attention, self).__init__() 150 | 151 | self.normalize = normalize 152 | self.use_2d = use_2d 153 | 154 | self.mha = MultiheadAttention(embed_dim=dim, num_heads=heads, dropout=0.0, add_zero_attn=False, batch_first=True) 155 | if normalize: 156 | self.norm = nn.GroupNorm(min(dim//4, 32), dim) 157 | 158 | def forward(self, x): 159 | 160 | inp = x 161 | 162 | if self.normalize: 163 | x = self.norm(x) 164 | 165 | if self.use_2d: 166 | x = x.permute(0,3,2,1) # shape: [bs,len,freq,channels] 167 | bs,len,freq,channels = x.shape[0],x.shape[1],x.shape[2],x.shape[3] 168 | x = x.reshape(bs*len,freq,channels) # shape: [bs*len,freq,channels] 169 | else: 170 | x = x.permute(0,2,1) # shape: [bs,len,channels] 171 | 172 | x = self.mha(x, x, x, need_weights=False)[0] 173 | 174 | if self.use_2d: 175 | x = x.reshape(bs,len,freq,channels).permute(0,3,2,1) 176 | else: 177 | x = x.permute(0,2,1) 178 | x = x+inp 179 | 180 | return x 181 | 182 | 183 | 184 | class ResBlock(nn.Module): 185 | def __init__(self, in_channels, out_channels, cond_channels=None, kernel_size=3, downsample=False, upsample=False, normalize=True, leaky=False, attention=False, heads=4, use_2d=False, normalize_residual=False): 186 | super(ResBlock, self).__init__() 187 | self.normalize = normalize 188 | self.attention = attention 189 | self.upsample = upsample 190 | self.downsample = downsample 191 | self.leaky = leaky 192 | self.kernel_size = kernel_size 193 | self.normalize_residual = normalize_residual 194 | self.use_2d = use_2d 195 | if use_2d: 196 | Conv = nn.Conv2d 197 | else: 198 | Conv = nn.Conv1d 199 | self.conv1 = Conv(in_channels, out_channels, kernel_size=kernel_size, stride=1, padding='same') 200 | self.conv2 = zero_init(Conv(out_channels, out_channels, kernel_size=kernel_size, stride=1, padding='same')) 201 | if in_channels!=out_channels: 202 | self.res_conv = Conv(in_channels, out_channels, kernel_size=1, stride=1, padding=0) 203 | else: 204 | self.res_conv = nn.Identity() 205 | if normalize: 206 | self.norm1 = nn.GroupNorm(min(in_channels//4, 32), in_channels) 207 | self.norm2 = nn.GroupNorm(min(out_channels//4, 32), out_channels) 208 | if leaky: 209 | self.activation = nn.LeakyReLU(negative_slope=0.2) 210 | else: 211 | self.activation = nn.SiLU() 212 | if cond_channels is not None: 213 | self.proj_emb = zero_init(nn.Linear(cond_channels, out_channels)) 214 | self.dropout = nn.Dropout(dropout_rate) 215 | if attention: 216 | self.att = Attention(out_channels, heads, use_2d=use_2d) 217 | 218 | 219 | def forward(self, x, time_emb=None): 220 | if not self.normalize_residual: 221 | y = x.clone() 222 | if self.normalize: 223 | x = self.norm1(x) 224 | if self.normalize_residual: 225 | y = x.clone() 226 | x = self.activation(x) 227 | if self.downsample: 228 | if self.use_2d: 229 | x = downsample_2d(x) 230 | y = downsample_2d(y) 231 | else: 232 | x = downsample_1d(x) 233 | y = downsample_1d(y) 234 | if self.upsample: 235 | if self.use_2d: 236 | x = upsample_2d(x) 237 | y = upsample_2d(y) 238 | else: 239 | x = upsample_1d(x) 240 | y = upsample_1d(y) 241 | x = self.conv1(x) 242 | if time_emb is not None: 243 | if self.use_2d: 244 | x = x+self.proj_emb(time_emb)[:,:,None,None] 245 | else: 246 | x = x+self.proj_emb(time_emb)[:,:,None] 247 | if self.normalize: 248 | x = self.norm2(x) 249 | x = self.activation(x) 250 | if x.shape[-1]<=min_res_dropout: 251 | x = self.dropout(x) 252 | x = self.conv2(x) 253 | y = self.res_conv(y) 254 | x = x+y 255 | if self.attention: 256 | x = self.att(x) 257 | return x 258 | 259 | 260 | # adapted from https://github.com/yang-song/score_sde_pytorch/blob/main/models/layerspp.py 261 | class GaussianFourierProjection(torch.nn.Module): 262 | """Gaussian Fourier embeddings for noise levels.""" 263 | 264 | def __init__(self, embedding_size=128, scale=0.02): 265 | super().__init__() 266 | self.W = torch.nn.Parameter(torch.randn(embedding_size//2) * scale, requires_grad=False) 267 | 268 | def forward(self, x): 269 | x_proj = x[:, None] * self.W[None, :] * 2. * np.pi 270 | return torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1) 271 | 272 | 273 | class PositionalEmbedding(torch.nn.Module): 274 | def __init__(self, embedding_size=128, max_positions=10000): 275 | super().__init__() 276 | self.embedding_size = embedding_size 277 | self.max_positions = max_positions 278 | 279 | def forward(self, x): 280 | freqs = torch.arange(start=0, end=self.embedding_size//2, dtype=torch.float32, device=x.device) 281 | freqs = freqs / (self.embedding_size // 2 - 1) 282 | freqs = (1 / self.max_positions) ** freqs 283 | x = x.ger(freqs.to(x.dtype)) 284 | x = torch.cat([torch.sin(x), torch.cos(x)], dim=-1) 285 | return x 286 | 287 | class Encoder(nn.Module): 288 | def __init__(self): 289 | super(Encoder, self).__init__() 290 | 291 | layers_list = layers_list_encoder 292 | attention_list = attention_list_encoder 293 | self.layers_list = layers_list 294 | self.multipliers_list = multipliers_list 295 | input_channels = base_channels*multipliers_list[0] 296 | Conv = nn.Conv2d 297 | self.gain = FreqGain(freq_dim=hop*2) 298 | 299 | channels = data_channels 300 | self.conv_inp = Conv(channels, input_channels, kernel_size=3, stride=1, padding=1) 301 | 302 | self.freq_dim = (hop*2)//(4**freq_downsample_list.count(1)) 303 | self.freq_dim = self.freq_dim//(2**freq_downsample_list.count(0)) 304 | 305 | # DOWNSAMPLING 306 | down_layers = [] 307 | for i, (num_layers,multiplier) in enumerate(zip(layers_list,multipliers_list)): 308 | output_channels = base_channels*multiplier 309 | for num in range(num_layers): 310 | down_layers.append(ResBlock(input_channels, output_channels, normalize=normalization, attention=attention_list[i]==1, heads=heads, use_2d=True)) 311 | input_channels = output_channels 312 | if i!=(len(layers_list)-1): 313 | if freq_downsample_list[i]==1: 314 | down_layers.append(DownsampleFreqConv(input_channels, normalize=pre_normalize_downsampling_encoder)) 315 | else: 316 | down_layers.append(DownsampleConv(input_channels, use_2d=True, normalize=pre_normalize_downsampling_encoder)) 317 | 318 | if pre_normalize_2d_to_1d: 319 | self.prenorm_1d_to_2d = nn.GroupNorm(min(input_channels//4, 32), input_channels) 320 | 321 | bottleneck_layers = [] 322 | output_channels = bottleneck_base_channels 323 | bottleneck_layers.append(nn.Conv1d(input_channels*self.freq_dim, output_channels, kernel_size=1, stride=1, padding='same')) 324 | for i in range(num_bottleneck_layers): 325 | bottleneck_layers.append(ResBlock(output_channels, output_channels, normalize=normalization, use_2d=False)) 326 | self.bottleneck_layers = nn.ModuleList(bottleneck_layers) 327 | 328 | self.norm_out = nn.GroupNorm(min(output_channels//4, 32), output_channels) 329 | self.activation_out = nn.SiLU() 330 | self.conv_out = nn.Conv1d(output_channels, bottleneck_channels, kernel_size=1, stride=1, padding='same') 331 | self.activation_bottleneck = nn.Tanh() 332 | 333 | self.down_layers = nn.ModuleList(down_layers) 334 | 335 | 336 | def forward(self, x, extract_features=False): 337 | 338 | x = self.conv_inp(x) 339 | if frequency_scaling: 340 | x = self.gain(x) 341 | 342 | # DOWNSAMPLING 343 | k = 0 344 | for i,num_layers in enumerate(self.layers_list): 345 | for num in range(num_layers): 346 | x = self.down_layers[k](x) 347 | k = k+1 348 | if i!=(len(self.layers_list)-1): 349 | x = self.down_layers[k](x) 350 | k = k+1 351 | 352 | if pre_normalize_2d_to_1d: 353 | x = self.prenorm_1d_to_2d(x) 354 | 355 | x = x.reshape(x.size(0), x.size(1) * x.size(2), x.size(3)) 356 | if extract_features: 357 | return x 358 | 359 | for layer in self.bottleneck_layers: 360 | x = layer(x) 361 | 362 | x = self.norm_out(x) 363 | x = self.activation_out(x) 364 | x = self.conv_out(x) 365 | x = self.activation_bottleneck(x) 366 | 367 | return x 368 | 369 | 370 | class Decoder(nn.Module): 371 | def __init__(self): 372 | super(Decoder, self).__init__() 373 | 374 | layers_list = layers_list_encoder 375 | attention_list = attention_list_encoder 376 | self.layers_list = layers_list_encoder 377 | self.multipliers_list = multipliers_list 378 | input_channels = base_channels*multipliers_list[-1] 379 | 380 | output_channels = bottleneck_base_channels 381 | self.conv_inp = nn.Conv1d(bottleneck_channels, output_channels, kernel_size=1, stride=1, padding='same') 382 | 383 | self.freq_dim = (hop*2)//(4**freq_downsample_list.count(1)) 384 | self.freq_dim = self.freq_dim//(2**freq_downsample_list.count(0)) 385 | 386 | bottleneck_layers = [] 387 | for i in range(num_bottleneck_layers): 388 | bottleneck_layers.append(ResBlock(output_channels, output_channels, cond_channels, normalize=normalization, use_2d=False)) 389 | 390 | self.conv_out_bottleneck = nn.Conv1d(output_channels, input_channels*self.freq_dim, kernel_size=1, stride=1, padding='same') 391 | self.bottleneck_layers = nn.ModuleList(bottleneck_layers) 392 | 393 | # UPSAMPLING 394 | multipliers_list_upsampling = list(reversed(multipliers_list))[1:]+list(reversed(multipliers_list))[:1] 395 | freq_upsample_list = list(reversed(freq_downsample_list)) 396 | up_layers = [] 397 | for i, (num_layers,multiplier) in enumerate(zip(reversed(layers_list),multipliers_list_upsampling)): 398 | for num in range(num_layers): 399 | up_layers.append(ResBlock(input_channels, input_channels, normalize=normalization, attention=list(reversed(attention_list))[i]==1, heads=heads, use_2d=True)) 400 | if i!=(len(layers_list)-1): 401 | output_channels = base_channels*multiplier 402 | if freq_upsample_list[i]==1: 403 | up_layers.append(UpsampleFreqConv(input_channels, output_channels)) 404 | else: 405 | up_layers.append(UpsampleConv(input_channels, output_channels, use_2d=True)) 406 | input_channels = output_channels 407 | 408 | self.up_layers = nn.ModuleList(up_layers) 409 | 410 | 411 | def forward(self, x): 412 | 413 | x = self.conv_inp(x) 414 | 415 | for layer in self.bottleneck_layers: 416 | x = layer(x) 417 | x = self.conv_out_bottleneck(x) 418 | 419 | x_ls = torch.chunk(x.unsqueeze(-2), self.freq_dim, -3) 420 | x = torch.cat(x_ls, -2) 421 | 422 | # UPSAMPLING 423 | k = 0 424 | pyramid_list = [] 425 | for i,num_layers in enumerate(reversed(self.layers_list)): 426 | for num in range(num_layers): 427 | x = self.up_layers[k](x) 428 | k = k+1 429 | pyramid_list.append(x) 430 | if i!=(len(self.layers_list)-1): 431 | x = self.up_layers[k](x) 432 | k = k+1 433 | 434 | pyramid_list = pyramid_list[::-1] 435 | 436 | return pyramid_list 437 | 438 | 439 | class UNet(nn.Module): 440 | def __init__(self): 441 | super(UNet, self).__init__() 442 | 443 | self.layers_list = layers_list 444 | self.multipliers_list = multipliers_list 445 | input_channels = base_channels*multipliers_list[0] 446 | Conv = nn.Conv2d 447 | 448 | self.encoder = Encoder() 449 | self.decoder = Decoder() 450 | 451 | if use_fourier: 452 | self.emb = GaussianFourierProjection(embedding_size=cond_channels, scale=fourier_scale) 453 | else: 454 | self.emb = PositionalEmbedding(embedding_size=cond_channels) 455 | 456 | self.emb_proj = nn.Sequential(nn.Linear(cond_channels, cond_channels), nn.SiLU(), nn.Linear(cond_channels, cond_channels), nn.SiLU()) 457 | 458 | self.scale_inp = nn.Sequential(nn.Linear(cond_channels, cond_channels), nn.SiLU(), nn.Linear(cond_channels, cond_channels), nn.SiLU(), zero_init(nn.Linear(cond_channels, hop*2))) 459 | self.scale_out = nn.Sequential(nn.Linear(cond_channels, cond_channels), nn.SiLU(), nn.Linear(cond_channels, cond_channels), nn.SiLU(), zero_init(nn.Linear(cond_channels, hop*2))) 460 | 461 | self.conv_inp = Conv(data_channels, input_channels, kernel_size=3, stride=1, padding=1) 462 | 463 | # DOWNSAMPLING 464 | down_layers = [] 465 | for i, (num_layers,multiplier) in enumerate(zip(layers_list,multipliers_list)): 466 | output_channels = base_channels*multiplier 467 | for num in range(num_layers): 468 | down_layers.append(Conv(output_channels, output_channels, kernel_size=1, stride=1, padding=0)) 469 | down_layers.append(ResBlock(output_channels, output_channels, cond_channels, normalize=normalization, attention=attention_list[i]==1, heads=heads, use_2d=True)) 470 | input_channels = output_channels 471 | if i!=(len(layers_list)-1): 472 | output_channels = base_channels*multipliers_list[i+1] 473 | if freq_downsample_list[i]==1: 474 | down_layers.append(DownsampleFreqConv(input_channels, output_channels)) 475 | else: 476 | down_layers.append(DownsampleConv(input_channels, output_channels, use_2d=True)) 477 | 478 | # UPSAMPLING 479 | multipliers_list_upsampling = list(reversed(multipliers_list))[1:]+list(reversed(multipliers_list))[:1] 480 | freq_upsample_list = list(reversed(freq_downsample_list)) 481 | up_layers = [] 482 | for i, (num_layers,multiplier) in enumerate(zip(reversed(layers_list),multipliers_list_upsampling)): 483 | for num in range(num_layers): 484 | up_layers.append(Conv(input_channels, input_channels, kernel_size=1, stride=1, padding=0)) 485 | up_layers.append(ResBlock(input_channels, input_channels, cond_channels, normalize=normalization, attention=list(reversed(attention_list))[i]==1, heads=heads, use_2d=True)) 486 | if i!=(len(layers_list)-1): 487 | output_channels = base_channels*multiplier 488 | if freq_upsample_list[i]==1: 489 | up_layers.append(UpsampleFreqConv(input_channels, output_channels)) 490 | else: 491 | up_layers.append(UpsampleConv(input_channels, output_channels, use_2d=True)) 492 | input_channels = output_channels 493 | 494 | self.conv_decoded = Conv(input_channels, input_channels, kernel_size=1, stride=1, padding=0) 495 | self.norm_out = nn.GroupNorm(min(input_channels//4, 32), input_channels) 496 | self.activation_out = nn.SiLU() 497 | self.conv_out = zero_init(Conv(input_channels, data_channels, kernel_size=3, stride=1, padding=1)) 498 | 499 | self.down_layers = nn.ModuleList(down_layers) 500 | self.up_layers = nn.ModuleList(up_layers) 501 | 502 | 503 | def forward(self, latents, x, sigma=None, pyramid_latents=None): 504 | 505 | if sigma is None: 506 | sigma = sigma_max 507 | 508 | inp = x 509 | 510 | # CONDITIONING 511 | sigma = torch.ones((x.shape[0],), dtype=torch.float32).to(x.device)*sigma 512 | sigma_log = torch.log(sigma)/4. 513 | emb_sigma_log = self.emb(sigma_log) 514 | time_emb = self.emb_proj(emb_sigma_log) 515 | 516 | scale_w_inp = self.scale_inp(emb_sigma_log).reshape(x.shape[0],1,-1,1) 517 | scale_w_out = self.scale_out(emb_sigma_log).reshape(x.shape[0],1,-1,1) 518 | 519 | c_skip, c_out, c_in = get_c(sigma) 520 | 521 | x = c_in*x 522 | 523 | if latents.shape == x.shape: 524 | latents = self.encoder(latents) 525 | 526 | if pyramid_latents is None: 527 | pyramid_latents = self.decoder(latents) 528 | 529 | x = self.conv_inp(x) 530 | if frequency_scaling: 531 | x = (1.+scale_w_inp)*x 532 | 533 | skip_list = [] 534 | 535 | # DOWNSAMPLING 536 | k = 0 537 | r = 0 538 | for i,num_layers in enumerate(self.layers_list): 539 | for num in range(num_layers): 540 | d = self.down_layers[k](pyramid_latents[i]) 541 | k = k+1 542 | x = (x+d)/np.sqrt(2.) 543 | x = self.down_layers[k](x, time_emb) 544 | skip_list.append(x) 545 | k = k+1 546 | if i!=(len(self.layers_list)-1): 547 | x = self.down_layers[k](x) 548 | k = k+1 549 | 550 | # UPSAMPLING 551 | k = 0 552 | for i,num_layers in enumerate(reversed(self.layers_list)): 553 | for num in range(num_layers): 554 | d = self.up_layers[k](pyramid_latents[-i-1]) 555 | k = k+1 556 | x = (x+skip_list.pop()+d)/np.sqrt(3.) 557 | x = self.up_layers[k](x, time_emb) 558 | k = k+1 559 | if i!=(len(self.layers_list)-1): 560 | x = self.up_layers[k](x) 561 | k = k+1 562 | 563 | d = self.conv_decoded(pyramid_latents[0]) 564 | x = (x+d)/np.sqrt(2.) 565 | 566 | x = self.norm_out(x) 567 | x = self.activation_out(x) 568 | if frequency_scaling: 569 | x = (1.+scale_w_out)*x 570 | x = self.conv_out(x) 571 | 572 | out = c_skip*inp + c_out*x 573 | 574 | return out -------------------------------------------------------------------------------- /music2latent/requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | soundfile 3 | huggingface_hub 4 | torch>=2.0.1 -------------------------------------------------------------------------------- /music2latent/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | from os import path as ospath 3 | from huggingface_hub import hf_hub_download 4 | import torch 5 | 6 | from .hparams import * 7 | 8 | # Get scaling coefficients c_skip, c_out, c_in based on noise sigma 9 | # These are used to scale the input and output of the consistency model, while satisfying the boundary condition for consistency models 10 | # Parameters: 11 | # sigma: noise level 12 | # Returns: 13 | # c_skip, c_out, c_in: scaling coefficients 14 | def get_c(sigma): 15 | sigma_correct = sigma_min 16 | c_skip = (sigma_data**2.)/(((sigma-sigma_correct)**2.) + (sigma_data**2.)) 17 | c_out = (sigma_data*(sigma-sigma_correct))/(((sigma_data**2.) + (sigma**2.))**0.5) 18 | c_in = 1./(((sigma**2.)+(sigma_data**2.))**0.5) 19 | return c_skip.reshape(-1,1,1,1), c_out.reshape(-1,1,1,1), c_in.reshape(-1,1,1,1) 20 | 21 | # Get noise level sigma_i based on index i and number of discretization steps k 22 | # Parameters: 23 | # i: index 24 | # k: number of discretization steps 25 | # Returns: 26 | # sigma_i: noise level corresponding to index i 27 | def get_sigma(i, k): 28 | return (sigma_min**(1./rho) + ((i-1)/(k-1))*(sigma_max**(1./rho)-sigma_min**(1./rho)))**rho 29 | 30 | # Get noise level sigma for a continuous index i in [0, 1] 31 | # Follows parameterization in https://openreview.net/pdf?id=FmqFfMTNnv 32 | # Parameters: 33 | # i: continuous index in [0, 1] 34 | # Returns: 35 | # sigma: corresponding noise level 36 | def get_sigma_continuous(i): 37 | return (sigma_min**(1./rho) + i*(sigma_max**(1./rho)-sigma_min**(1./rho)))**rho 38 | 39 | 40 | # Add Gaussian noise to input x based on given noise and sigma 41 | # Parameters: 42 | # x: input tensor 43 | # noise: tensor containing Gaussian noise 44 | # sigma: noise level 45 | # Returns: 46 | # x_noisy: x with noise added 47 | def add_noise(x, noise, sigma): 48 | return x + sigma.reshape(-1,1,1,1)*noise 49 | 50 | 51 | # Reverse the probability flow ODE by one step 52 | # Parameters: 53 | # x: input 54 | # noise: Gaussian noise 55 | # sigma: noise level 56 | # Returns: 57 | # x: x after reversing ODE by one step 58 | def reverse_step(x, noise, sigma): 59 | return x + ((sigma**2 - sigma_min**2)**0.5)*noise 60 | 61 | 62 | # Denoise samples at a given noise level 63 | # Parameters: 64 | # model: consistency model 65 | # noisy_samples: input noisy samples 66 | # sigma: noise level 67 | # Returns: 68 | # pred_noises: predicted noise 69 | # pred_samples: denoised samples 70 | def denoise(model, noisy_samples, sigma, latents=None): 71 | # Denoise samples 72 | with torch.no_grad(): 73 | with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=mixed_precision): 74 | if latents is not None: 75 | pred_samples = model(latents, noisy_samples, sigma) 76 | else: 77 | pred_samples = model(noisy_samples, sigma) 78 | # Sample noise 79 | pred_noises = torch.randn_like(pred_samples) 80 | return pred_noises, pred_samples 81 | 82 | # Reverse the diffusion process to generate samples 83 | # Parameters: 84 | # model: trained consistency model 85 | # initial_noise: initial noise to start from 86 | # diffusion_steps: number of steps to reverse 87 | # Returns: 88 | # final_samples: generated samples 89 | def reverse_diffusion(model, initial_noise, diffusion_steps, latents=None): 90 | next_noisy_samples = initial_noise 91 | # Reverse process step-by-step 92 | for k in range(diffusion_steps): 93 | 94 | # Get sigma values 95 | sigma = get_sigma(diffusion_steps+1-k, diffusion_steps+1) 96 | next_sigma = get_sigma(diffusion_steps-k, diffusion_steps+1) 97 | 98 | # Denoise 99 | noisy_samples = next_noisy_samples 100 | pred_noises, pred_samples = denoise(model, noisy_samples, sigma, latents) 101 | 102 | # Step to next (lower) noise level 103 | next_noisy_samples = reverse_step(pred_samples, pred_noises, next_sigma) 104 | 105 | return pred_samples.detach().cpu() 106 | 107 | 108 | def is_path(variable): 109 | return isinstance(variable, str) and os.path.exists(variable) 110 | 111 | 112 | 113 | def download_model(): 114 | filepath = os.path.abspath(__file__) 115 | lib_root = os.path.dirname(filepath) 116 | 117 | if not ospath.exists(lib_root + "/models/music2latent.pt"): 118 | print("Downloading model...") 119 | os.makedirs(lib_root + "/models", exist_ok=True) 120 | _ = hf_hub_download(repo_id="SonyCSLParis/music2latent", filename="music2latent.pt", cache_dir=lib_root + "/models", local_dir=lib_root + "/models") 121 | print("Model was downloaded successfully!") -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name='music2latent', 5 | version='0.1.6', 6 | packages=find_packages(), 7 | description='Encode and decode audio samples to/from compressed representations!', 8 | author='Sony Computer Science Laboratories Paris', 9 | author_email='music@csl.sony.fr', 10 | long_description=open('README.md').read(), 11 | long_description_content_type='text/markdown', 12 | install_requires=[ 13 | 'numpy', 14 | 'soundfile', 15 | 'huggingface_hub', 16 | 'torch', 17 | ], 18 | license='CC BY-NC 4.0', 19 | url='https://github.com/SonyCSLParis/music2latent', 20 | keywords='audio speech music compression generative-model autoencoder diffusion consistency', 21 | ) -------------------------------------------------------------------------------- /tutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# music2latent" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "# basic imports\n", 17 | "import numpy as np\n", 18 | "import IPython\n", 19 | "import librosa" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "Initialize the EncoderDecoder model." 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": null, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "from music2latent import EncoderDecoder\n", 36 | "\n", 37 | "encdec = EncoderDecoder()" 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "metadata": {}, 43 | "source": [ 44 | "Let's load an audio file for this tutorial:" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "audio_path = librosa.example('trumpet')\n", 54 | "\n", 55 | "wv, sr = librosa.load(audio_path, sr=44100)\n", 56 | "\n", 57 | "IPython.display.display(IPython.display.Audio(wv, rate=sr))" 58 | ] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "# Encode" 65 | ] 66 | }, 67 | { 68 | "cell_type": "markdown", 69 | "metadata": {}, 70 | "source": [ 71 | "To encode an audio sample into latents, you need to provide the waveform as input, with shape [audio_channels, waveform_samples] or simply [waveform_samples,]:" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "wv, sr = librosa.load(audio_path, sr=44100)\n", 81 | "print(f'waveform samples: {wv.shape}')\n", 82 | "\n", 83 | "latent = encdec.encode(wv)\n", 84 | "print(f'Shape of latents: {latent.shape}')" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": {}, 90 | "source": [ 91 | "You can also process a batch of waveforms. Just use a numpy array with shape [batch_size, waveform_samples] as input:" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "metadata": {}, 98 | "outputs": [], 99 | "source": [ 100 | "wv, sr = librosa.load(audio_path, sr=44100)\n", 101 | "\n", 102 | "# create a batch of waveforms\n", 103 | "wv_batched = np.stack([wv]*3, axis=0)\n", 104 | "print(f'batch of waveforms shape: {wv_batched.shape}')\n", 105 | "\n", 106 | "latent_batched = encdec.encode(wv_batched)\n", 107 | "print(f'Shape of batched latents: {latent_batched.shape}')" 108 | ] 109 | }, 110 | { 111 | "cell_type": "markdown", 112 | "metadata": {}, 113 | "source": [ 114 | "# Decode" 115 | ] 116 | }, 117 | { 118 | "cell_type": "markdown", 119 | "metadata": {}, 120 | "source": [ 121 | "To decode latent embeddings back to waveform, be sure to have latents with shape [batch_size/audio_channels, latent_dim, latent_length]:" 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": null, 127 | "metadata": {}, 128 | "outputs": [], 129 | "source": [ 130 | "wv_rec = encdec.decode(latent)\n", 131 | "print(f'Shape of decoded waveform: {wv_rec.shape}')\n", 132 | "\n", 133 | "print(wv.shape, wv_rec.shape)\n", 134 | "\n", 135 | "print('Original')\n", 136 | "IPython.display.display(IPython.display.Audio(wv, rate=sr))\n", 137 | "print('Reconstructed')\n", 138 | "IPython.display.display(IPython.display.Audio(wv_rec.squeeze().cpu().numpy(), rate=sr))" 139 | ] 140 | }, 141 | { 142 | "cell_type": "markdown", 143 | "metadata": {}, 144 | "source": [ 145 | "You can also specify how many denoising steps to perform (default is 1). However, we do not notice any improvements in audio quality by increasing the denoise_steps." 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": null, 151 | "metadata": {}, 152 | "outputs": [], 153 | "source": [ 154 | "wv_rec = encdec.decode(latent, denoising_steps=3)\n", 155 | "print(f'Shape of decoded waveform: {wv_rec.shape}')\n", 156 | "\n", 157 | "print('Original')\n", 158 | "IPython.display.display(IPython.display.Audio(wv, rate=sr))\n", 159 | "print('Reconstructed')\n", 160 | "IPython.display.display(IPython.display.Audio(wv_rec.squeeze().cpu().numpy(), rate=sr))" 161 | ] 162 | }, 163 | { 164 | "cell_type": "markdown", 165 | "metadata": {}, 166 | "source": [ 167 | "# Keeping GPU memory under control" 168 | ] 169 | }, 170 | { 171 | "cell_type": "markdown", 172 | "metadata": {}, 173 | "source": [ 174 | "The autoencoder model needs plenty of memory to encode and decode samples.\n", 175 | "We offer a way to keep the memory usage under control.\n", 176 | "\n", 177 | "You can specify both the __max_batch_size__ and __max_waveform_length__ to use for encoding or decoding samples.\n", 178 | "\n", 179 | "If not specified, the default values are the ones in hparams_inference.py (__max_batch_size__=1, __max_waveform_length__=44100*10)\n", 180 | "\n", 181 | "If the waveform sample to encode or to reconstruct is longer than __max_waveform_length__, the spectrogram representation will be split into multiple samples, processed sequentially, and then concatenated back together." 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": null, 187 | "metadata": {}, 188 | "outputs": [], 189 | "source": [ 190 | "wv, sr = librosa.load(audio_path, sr=44100)\n", 191 | "print(f'waveform samples: {wv.shape}')\n", 192 | "\n", 193 | "# split spectrogram into 1 second chunks, process each chunk separately, concatenate the results\n", 194 | "# much lower memory usage\n", 195 | "latent = encdec.encode(wv, max_waveform_length=44100*1)\n", 196 | "print(f'Shape of latents: {latent.shape}')\n", 197 | "\n", 198 | "wv_rec = encdec.decode(latent, max_waveform_length=44100*1)\n", 199 | "print(f'Shape of decoded waveform: {wv_rec.shape}')\n", 200 | "\n", 201 | "print('Original')\n", 202 | "IPython.display.display(IPython.display.Audio(wv, rate=sr))\n", 203 | "print('Reconstructed')\n", 204 | "IPython.display.display(IPython.display.Audio(wv_rec.squeeze().cpu().numpy(), rate=sr))" 205 | ] 206 | }, 207 | { 208 | "cell_type": "markdown", 209 | "metadata": {}, 210 | "source": [ 211 | "If you need to encode/decode batches of samples in parallel you can increase the __max_batch_size__ argument until you reach your maximum memory budget:" 212 | ] 213 | }, 214 | { 215 | "cell_type": "code", 216 | "execution_count": null, 217 | "metadata": {}, 218 | "outputs": [], 219 | "source": [ 220 | "wv, sr = librosa.load(audio_path, sr=44100)\n", 221 | "\n", 222 | "# create a batch of waveforms\n", 223 | "wv_batched = np.stack([wv]*3, axis=0)\n", 224 | "print(f'batch of waveforms shape: {wv_batched.shape}')\n", 225 | "\n", 226 | "latent_batched = encdec.encode(wv_batched, max_batch_size=3)\n", 227 | "print(f'Shape of batched latents: {latent_batched.shape}')\n", 228 | "\n", 229 | "wv_rec = encdec.decode(latent, max_batch_size=3)\n", 230 | "print(f'Shape of decoded waveform: {wv_rec.shape}')\n", 231 | "\n", 232 | "print('Original')\n", 233 | "IPython.display.display(IPython.display.Audio(wv, rate=sr))\n", 234 | "print('Reconstructed')\n", 235 | "IPython.display.display(IPython.display.Audio(wv_rec[0].squeeze().cpu().numpy(), rate=sr))" 236 | ] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "metadata": {}, 241 | "source": [ 242 | "# Keep in Mind:" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": {}, 248 | "source": [ 249 | "When using the latents for generation tasks using diffusion-type models, make sure to properly normalize the latents according to the chosen diffusion framework. The latents extracted with this library are rescaled to have unit standard deviation for a reference music dataset, but ensure that the latents are properly normalized for your specific use case." 250 | ] 251 | } 252 | ], 253 | "metadata": { 254 | "kernelspec": { 255 | "display_name": "onestep", 256 | "language": "python", 257 | "name": "python3" 258 | }, 259 | "language_info": { 260 | "codemirror_mode": { 261 | "name": "ipython", 262 | "version": 3 263 | }, 264 | "file_extension": ".py", 265 | "mimetype": "text/x-python", 266 | "name": "python", 267 | "nbconvert_exporter": "python", 268 | "pygments_lexer": "ipython3", 269 | "version": "3.9.18" 270 | } 271 | }, 272 | "nbformat": 4, 273 | "nbformat_minor": 2 274 | } 275 | --------------------------------------------------------------------------------