├── .data ├── clvp_tok.json └── mel_norms.pth ├── .gitignore ├── CITATION.cff ├── LICENSE ├── README.md ├── requirements.txt ├── setup.cfg ├── setup.py ├── tts-scores.py └── tts_scores ├── clvp.py ├── intelligibility.py ├── tokenizer.py ├── transformers.py └── utils.py /.data/clvp_tok.json: -------------------------------------------------------------------------------- 1 | {"version":"1.0","truncation":null,"padding":null,"added_tokens":[{"id":0,"special":true,"content":"[STOP]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false},{"id":1,"special":true,"content":"[UNK]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false},{"id":2,"special":true,"content":"[SPACE]","single_word":false,"lstrip":false,"rstrip":false,"normalized":false}],"normalizer":null,"pre_tokenizer":{"type":"Whitespace"},"post_processor":null,"decoder":null,"model":{"type":"BPE","dropout":null,"unk_token":"[UNK]","continuing_subword_prefix":null,"end_of_word_suffix":null,"fuse_unk":false,"vocab":{"[STOP]":0,"[UNK]":1,"[SPACE]":2,"!":3,"'":4,"(":5,")":6,",":7,"-":8,".":9,"/":10,":":11,";":12,"?":13,"a":14,"b":15,"c":16,"d":17,"e":18,"f":19,"g":20,"h":21,"i":22,"j":23,"k":24,"l":25,"m":26,"n":27,"o":28,"p":29,"q":30,"r":31,"s":32,"t":33,"u":34,"v":35,"w":36,"x":37,"y":38,"z":39,"th":40,"in":41,"the":42,"an":43,"er":44,"ou":45,"re":46,"on":47,"at":48,"ed":49,"en":50,"to":51,"ing":52,"and":53,"is":54,"as":55,"al":56,"or":57,"of":58,"ar":59,"it":60,"es":61,"he":62,"st":63,"le":64,"om":65,"se":66,"be":67,"ad":68,"ow":69,"ly":70,"ch":71,"wh":72,"that":73,"you":74,"li":75,"ve":76,"ac":77,"ti":78,"ld":79,"me":80,"was":81,"gh":82,"id":83,"ll":84,"wi":85,"ent":86,"for":87,"ay":88,"ro":89,"ver":90,"ic":91,"her":92,"ke":93,"his":94,"no":95,"ut":96,"un":97,"ir":98,"lo":99,"we":100,"ri":101,"ha":102,"with":103,"ght":104,"out":105,"im":106,"ion":107,"all":108,"ab":109,"one":110,"ne":111,"ge":112,"ould":113,"ter":114,"mo":115,"had":116,"ce":117,"she":118,"go":119,"sh":120,"ur":121,"am":122,"so":123,"pe":124,"my":125,"de":126,"are":127,"but":128,"ome":129,"fr":130,"ther":131,"fe":132,"su":133,"do":134,"con":135,"te":136,"ain":137,"ere":138,"po":139,"if":140,"they":141,"us":142,"ag":143,"tr":144,"now":145,"oun":146,"this":147,"have":148,"not":149,"sa":150,"il":151,"up":152,"thing":153,"from":154,"ap":155,"him":156,"ack":157,"ation":158,"ant":159,"our":160,"op":161,"like":162,"ust":163,"ess":164,"bo":165,"ok":166,"ul":167,"ind":168,"ex":169,"com":170,"some":171,"there":172,"ers":173,"co":174,"res":175,"man":176,"ard":177,"pl":178,"wor":179,"way":180,"tion":181,"fo":182,"ca":183,"were":184,"by":185,"ate":186,"pro":187,"ted":188,"ound":189,"own":190,"would":191,"ts":192,"what":193,"qu":194,"ally":195,"ight":196,"ck":197,"gr":198,"when":199,"ven":200,"can":201,"ough":202,"ine":203,"end":204,"per":205,"ous":206,"od":207,"ide":208,"know":209,"ty":210,"very":211,"si":212,"ak":213,"who":214,"about":215,"ill":216,"them":217,"est":218,"red":219,"ye":220,"could":221,"ong":222,"your":223,"their":224,"em":225,"just":226,"other":227,"into":228,"any":229,"whi":230,"um":231,"tw":232,"ast":233,"der":234,"did":235,"ie":236,"been":237,"ace":238,"ink":239,"ity":240,"back":241,"ting":242,"br":243,"more":244,"ake":245,"pp":246,"then":247,"sp":248,"el":249,"use":250,"bl":251,"said":252,"over":253,"get":254},"merges":["t h","i n","th e","a n","e r","o u","r e","o n","a t","e d","e n","t o","in g","an d","i s","a s","a l","o r","o f","a r","i t","e s","h e","s t","l e","o m","s e","b e","a d","o w","l y","c h","w h","th at","y ou","l i","v e","a c","t i","l d","m e","w as","g h","i d","l l","w i","en t","f or","a y","r o","v er","i c","h er","k e","h is","n o","u t","u n","i r","l o","w e","r i","h a","wi th","gh t","ou t","i m","i on","al l","a b","on e","n e","g e","ou ld","t er","m o","h ad","c e","s he","g o","s h","u r","a m","s o","p e","m y","d e","a re","b ut","om e","f r","the r","f e","s u","d o","c on","t e","a in","er e","p o","i f","the y","u s","a g","t r","n ow","ou n","th is","ha ve","no t","s a","i l","u p","th ing","fr om","a p","h im","ac k","at ion","an t","ou r","o p","li ke","u st","es s","b o","o k","u l","in d","e x","c om","s ome","the re","er s","c o","re s","m an","ar d","p l","w or","w ay","ti on","f o","c a","w ere","b y","at e","p ro","t ed","oun d","ow n","w ould","t s","wh at","q u","al ly","i ght","c k","g r","wh en","v en","c an","ou gh","in e","en d","p er","ou s","o d","id e","k now","t y","ver y","s i","a k","wh o","ab out","i ll","the m","es t","re d","y e","c ould","on g","you r","the ir","e m","j ust","o ther","in to","an y","wh i","u m","t w","as t","d er","d id","i e","be en","ac e","in k","it y","b ack","t ing","b r","mo re","a ke","p p","the n","s p","e l","u se","b l","sa id","o ver","ge t"]}} -------------------------------------------------------------------------------- /.data/mel_norms.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/neonbjb/tts-scores/b2b44ddeaa03732bf6e6d5e15afa4dac08f19a9a/.data/mel_norms.pth -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | dist/* 3 | tts_scores.egg-info/* -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | cff-version: 1.2.0 2 | message: "If you use this software, please cite it as below." 3 | authors: 4 | - family-names: "Betker" 5 | given-names: "James" 6 | orcid: "https://orcid.org/my-orcid?orcid=0000-0003-3259-4862" 7 | title: "TTS Scores" 8 | version: 1.0.0 9 | date-released: 2022-04-01 10 | url: "https://github.com/neonbjb/tts-scores" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TTS Scores - Better evaluation metrics for text to speech models 2 | 3 | TTS quality is a difficult thing to measure. Distance-based metrics are poor measurements because they only measure 4 | similarity to the test set, not the realism of the generated speech. For this reason, most TTS papers rely on Mean 5 | Opinion Scores to report model quality. Computing MOS involves humans in the loop, meaning it is costly and time 6 | consuming. More importantly, it cannot be used while training to evaluate the real-time performance of a model while 7 | training. 8 | 9 | The field of image generation has settled on the usage of the Frechet Inception Distance and Inception Score metrics 10 | to measure live performance. They are quite successful. I think we should take a page out of their book. But, we can 11 | modernize this a little: 12 | 13 | ## Installation 14 | 15 | tts-scores is available on pypi: 16 | ```shell 17 | pip install tts-scores 18 | ``` 19 | 20 | ## Contrastive Language-Voice Pretrained model (CLVP) 21 | 22 | To this end, I trained a CLIP-like architecture with a twist: instead of measuring the similarity of text and images, 23 | it measures the similarity of text and voice clips. I call this model CLVP. I believe such a model is an exceptional 24 | candidate for synthesizing a quality metric for Text->Voice models, much in the way that the Inception model is used for 25 | FID and IS scores. 26 | 27 | This repo contains the source code for CLVP and scripts that allow you to use it. I have built two metrics: 28 | 29 | ### CLVP Score 30 | 31 | The CLVP score measures the distance predicted by CVLP between text and an audio clip where that text is spoken. A lower 32 | score is better. It can be obtained by: 33 | 34 | ```python 35 | from tts_scores.clvp import CLVPMetric 36 | cv_metric = CLVPMetric(device='cuda') 37 | score = cv_metric.compute_clvp('', 'D:\\tmp\\tortoise-tts-eval\\real') 38 | ``` 39 | 40 | *Note: the format of the TSV file is described in a later section* 41 | 42 | ### CLVP Frechet Distance 43 | 44 | Similar to FID, this metric compares the distribution of real spoken text with whatever your TTS model generatets. 45 | It is particularly useful if you have a bunch of spoken text that you want to compare against but do not have the 46 | transcriptions for that text. For example, this is a good fit for measuring the performance of vocoders. 47 | 48 | It works by computing the frechet distance of the outputs of the last layer of the CLVP model when fed data from 49 | both distributions. Similar to FID, a lower score is better. It can be obtained by: 50 | 51 | ```python 52 | from tts_scores.clvp import CLVPMetric 53 | cv_metric = CLVPMetric(device='cuda') 54 | score = cv_metric.compute_fd(', '') 55 | ``` 56 | 57 | ### TSV format 58 | 59 | The TSV input is a tab-separated-value file. Each line must contain a transcript followed by a tab, followed by 60 | a filename. It can be optionally followed by more tab separated values, only the first two are important: 61 | 62 | ``` 63 | <|tab|><|tab|>.... 64 | <|tab|><|tab|>.... 65 | ... 66 | <|tab|><|tab|>.... 67 | ``` 68 | 69 | ## wav2vec2 Intelligibility Score 70 | 71 | One rather obvious way to compute the performance of a TTS system that I have not seen before is to leverage an ASR 72 | system. If the goal is to produce intelligible speech - why not use a speech recognition system to measure that 73 | intelligibility. 74 | 75 | The intelligibility score packaged in this repo does exactly that. It takes in a list of generated and real audio files 76 | and their transcriptions, and feeds everything through a pre-trained wav2vec2 model. The raw losses are returned. The 77 | score is the difference between the wav2vec2 losses for the fake/generated samples and the real samples. 78 | 79 | While CLVP scores take things like voice quality, voice diversity and prosody into account, the intelligibility score 80 | only considers whether or not the speech your TTS model generates maps coherently to the text you put into it. For some 81 | use cases, this will be the most important score. For others, all of the scores are important. 82 | 83 | ```python 84 | from tts_scores.intelligibility import IntelligibilityMetric 85 | is_metric = IntelligibilityMetric(device='cuda') 86 | score = is_metric.compute_intelligibility('', '') 87 | ``` 88 | 89 | ## Scores from common models 90 | 91 | A metric is only good if there are benchmarks which can be used as points of comparison. To this end, I computed 92 | all of the scores in this repo on two high-performance TTS models: 93 | 94 | 1. Tacotron2+waveglow from [NVIDIA's repo](https://github.com/NVIDIA/tacotron2) 95 | 2. FastSpeech2+hifigan from [ming024's repo](https://github.com/ming024/FastSpeech2) 96 | 97 | See the scores below: 98 | 99 | # Citations 100 | 101 | Please cite this repo if you use it in your repo: 102 | 103 | ``` 104 | @software{TTS-scores, 105 | author = {Betker, J ames}, 106 | month = {4}, 107 | title = {{TTS-scores}}, 108 | url = {https://github.com/neonbjb/tts-scores}, 109 | version = {1.0.0}, 110 | year = {2022} 111 | } 112 | ``` 113 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch 2 | einops 3 | transformers 4 | tokenizers 5 | scipy 6 | pytorch_fid 7 | tqdm 8 | inflect 9 | unidecode 10 | requests -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r", encoding="utf-8") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="tts-scores", 8 | packages=["tts_scores"], 9 | version="1.0.0", 10 | author="James", 11 | author_email="james@adamant.ai", 12 | description="A library for computing performance metrics for text-to-speech systems", 13 | long_description=long_description, 14 | long_description_content_type="text/markdown", 15 | url="https://github.com/neonbjb/tts-scores", 16 | project_urls={}, 17 | install_requires=[ 18 | 'tqdm', 19 | 'scipy', 20 | 'torch>=1.8', 21 | 'torchaudio>0.9', 22 | 'transformers', 23 | 'tokenizers', 24 | 'requests', 25 | 'ffmpeg', 26 | 'unidecode', 27 | 'inflect', 28 | 'pytorch_fid', 29 | 'einops' 30 | ], 31 | classifiers=[ 32 | "Programming Language :: Python :: 3", 33 | "License :: OSI Approved :: Apache Software License", 34 | "Operating System :: OS Independent", 35 | ], 36 | download_url = 'https://github.com/neonbjb/tts-scores/archive/refs/tags/1.0.0.tar.gz', 37 | python_requires=">=3.6", 38 | ) -------------------------------------------------------------------------------- /tts-scores.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from tts_scores.clvp import CLVPMetric 4 | from tts_scores.intelligibility import IntelligibilityMetric 5 | 6 | if __name__ == '__main__': 7 | os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" # Bleh. 8 | 9 | cv_metric = CLVPMetric(device='cuda') 10 | is_metric = IntelligibilityMetric(device='cuda') 11 | basedir = 'D:\\tmp\\tortoise-tts-eval\\' 12 | realdir = 'D:\\tmp\\tortoise-tts-eval\\real' 13 | for sd in os.listdir(basedir): 14 | metric_dir = os.path.join(basedir, sd) 15 | if not os.path.exists(os.path.join(metric_dir, 'transcript.tsv')): 16 | continue 17 | fd = cv_metric.compute_fd(metric_dir, realdir, verbose=False) 18 | clvp = cv_metric.compute_clvp(os.path.join(metric_dir, 'transcript.tsv'), realdir, verbose=False) 19 | ism = is_metric.compute_intelligibility(os.path.join(metric_dir, 'transcript.tsv'), realdir, verbose=False) 20 | print(f"{metric_dir}: FD: {fd}; CLVP: {clvp}; IS: {ism}") 21 | -------------------------------------------------------------------------------- /tts_scores/clvp.py: -------------------------------------------------------------------------------- 1 | import math 2 | import os.path 3 | import pathlib 4 | from random import random 5 | 6 | import numpy as np 7 | import torch 8 | import torch.nn as nn 9 | import torch.nn.functional as F 10 | from pytorch_fid.fid_score import calculate_frechet_distance 11 | from torch import einsum, distributed 12 | from torch.distributed import get_world_size 13 | from torch.utils.checkpoint import checkpoint 14 | from tqdm import tqdm 15 | 16 | from tts_scores.transformers import ContinuousTransformerWrapper, Encoder 17 | from tts_scores.tokenizer import text_to_sequence, VoiceBpeTokenizer 18 | from tts_scores.utils import load_audio, to_mel, load_tsv 19 | 20 | 21 | class GroupNorm32(nn.GroupNorm): 22 | def forward(self, x): 23 | return super().forward(x.float()).type(x.dtype) 24 | 25 | 26 | def conv_nd(dims, *args, **kwargs): 27 | """ 28 | Create a 1D, 2D, or 3D convolution module. 29 | """ 30 | if dims == 1: 31 | return nn.Conv1d(*args, **kwargs) 32 | elif dims == 2: 33 | return nn.Conv2d(*args, **kwargs) 34 | elif dims == 3: 35 | return nn.Conv3d(*args, **kwargs) 36 | raise ValueError(f"unsupported dimensions: {dims}") 37 | 38 | 39 | def normalization(channels): 40 | """ 41 | Make a standard normalization layer. 42 | 43 | :param channels: number of input channels. 44 | :return: an nn.Module for normalization. 45 | """ 46 | groups = 32 47 | if channels <= 16: 48 | groups = 8 49 | elif channels <= 64: 50 | groups = 16 51 | while channels % groups != 0: 52 | groups = int(groups / 2) 53 | assert groups > 2 54 | return GroupNorm32(groups, channels) 55 | 56 | 57 | def zero_module(module): 58 | """ 59 | Zero out the parameters of a module and return it. 60 | """ 61 | for p in module.parameters(): 62 | p.detach().zero_() 63 | return module 64 | 65 | 66 | class AttentionBlock(nn.Module): 67 | """ 68 | An attention block that allows spatial positions to attend to each other. 69 | 70 | Originally ported from here, but adapted to the N-d case. 71 | https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. 72 | """ 73 | 74 | def __init__( 75 | self, 76 | channels, 77 | num_heads=1, 78 | num_head_channels=-1, 79 | do_checkpoint=True, 80 | ): 81 | super().__init__() 82 | self.channels = channels 83 | self.do_checkpoint = do_checkpoint 84 | if num_head_channels == -1: 85 | self.num_heads = num_heads 86 | else: 87 | assert ( 88 | channels % num_head_channels == 0 89 | ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" 90 | self.num_heads = channels // num_head_channels 91 | self.norm = normalization(channels) 92 | self.qkv = conv_nd(1, channels, channels * 3, 1) 93 | self.attention = QKVAttentionLegacy(self.num_heads) 94 | 95 | self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) 96 | 97 | def forward(self, x, mask=None): 98 | if self.do_checkpoint: 99 | if mask is not None: 100 | return checkpoint(self._forward, x, mask) 101 | else: 102 | return checkpoint(self._forward, x) 103 | else: 104 | return self._forward(x, mask) 105 | 106 | def _forward(self, x, mask=None): 107 | b, c, *spatial = x.shape 108 | x = x.reshape(b, c, -1) 109 | qkv = self.qkv(self.norm(x)) 110 | h = self.attention(qkv, mask) 111 | h = self.proj_out(h) 112 | return (x + h).reshape(b, c, *spatial) 113 | 114 | 115 | class QKVAttentionLegacy(nn.Module): 116 | """ 117 | A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping 118 | """ 119 | 120 | def __init__(self, n_heads): 121 | super().__init__() 122 | self.n_heads = n_heads 123 | 124 | def forward(self, qkv, mask=None): 125 | """ 126 | Apply QKV attention. 127 | 128 | :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. 129 | :return: an [N x (H * C) x T] tensor after attention. 130 | """ 131 | bs, width, length = qkv.shape 132 | assert width % (3 * self.n_heads) == 0 133 | ch = width // (3 * self.n_heads) 134 | q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) 135 | scale = 1 / math.sqrt(math.sqrt(ch)) 136 | weight = torch.einsum( 137 | "bct,bcs->bts", q * scale, k * scale 138 | ) # More stable with f16 than dividing afterwards 139 | weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) 140 | if mask is not None: 141 | # The proper way to do this is to mask before the softmax using -inf, but that doesn't work properly on CPUs. 142 | mask = mask.repeat(self.n_heads, 1).unsqueeze(1) 143 | weight = weight * mask 144 | a = torch.einsum("bts,bcs->bct", weight, v) 145 | 146 | return a.reshape(bs, -1, length) 147 | 148 | 149 | def exists(val): 150 | return val is not None 151 | 152 | 153 | def masked_mean(t, mask): 154 | t = t.masked_fill(~mask, 0.) 155 | return t.sum(dim = 1) / mask.sum(dim = 1) 156 | 157 | 158 | class CollapsingTransformer(nn.Module): 159 | def __init__(self, model_dim, output_dims, heads, dropout, depth, mask_percentage=0, **encoder_kwargs): 160 | super().__init__() 161 | self.transformer = ContinuousTransformerWrapper( 162 | max_seq_len=-1, 163 | use_pos_emb=False, 164 | attn_layers=Encoder( 165 | dim=model_dim, 166 | depth=depth, 167 | heads=heads, 168 | ff_dropout=dropout, 169 | ff_mult=1, 170 | attn_dropout=dropout, 171 | use_rmsnorm=True, 172 | ff_glu=True, 173 | rotary_pos_emb=True, 174 | **encoder_kwargs, 175 | )) 176 | self.pre_combiner = nn.Sequential(nn.Conv1d(model_dim, output_dims, 1), 177 | AttentionBlock(output_dims, num_heads=heads, do_checkpoint=False), 178 | nn.Conv1d(output_dims, output_dims, 1)) 179 | self.mask_percentage = mask_percentage 180 | 181 | def forward(self, x, **transformer_kwargs): 182 | h = self.transformer(x, **transformer_kwargs) 183 | h = h.permute(0,2,1) 184 | h = checkpoint(self.pre_combiner, h).permute(0,2,1) 185 | if self.training: 186 | mask = torch.rand_like(h.float()) > self.mask_percentage 187 | else: 188 | mask = torch.ones_like(h.float()).bool() 189 | return masked_mean(h, mask) 190 | 191 | 192 | class ConvFormatEmbedding(nn.Module): 193 | def __init__(self, *args, **kwargs): 194 | super().__init__() 195 | self.emb = nn.Embedding(*args, **kwargs) 196 | 197 | def forward(self, x): 198 | y = self.emb(x) 199 | return y.permute(0,2,1) 200 | 201 | 202 | class CLVP(nn.Module): 203 | """ 204 | Contrastic Language-Voice Pretraining model for generating embedding that can be used to associate text and 205 | speech clips. 206 | """ 207 | 208 | def __init__( 209 | self, 210 | model_dim=512, 211 | transformer_heads=8, 212 | dropout=.1, 213 | num_text_tokens=256, 214 | text_enc_depth=6, 215 | text_mask_percentage=0, 216 | conditioning_enc_depth=4, 217 | mel_channels=80, 218 | mel_codes=None, 219 | speech_enc_depth=6, 220 | speech_mask_percentage=0, 221 | latent_multiplier=4, 222 | is_distributed=False, 223 | ): 224 | super().__init__() 225 | latent_dim = latent_multiplier*model_dim 226 | self.temperature = nn.Parameter(torch.tensor(1.)) 227 | 228 | self.cond_emb = nn.Sequential(nn.Conv1d(mel_channels, model_dim//2, kernel_size=5, stride=2, padding=2), 229 | nn.Conv1d(model_dim//2, model_dim, kernel_size=3, stride=2, padding=1)) 230 | self.conditioning_transformer = CollapsingTransformer(model_dim, model_dim*2, transformer_heads, dropout, conditioning_enc_depth, 0) 231 | 232 | self.text_emb = nn.Embedding(num_text_tokens, model_dim) 233 | self.text_transformer = CollapsingTransformer(model_dim, latent_dim, transformer_heads, dropout, text_enc_depth, text_mask_percentage, use_rms_scaleshift_norm=True) 234 | self.to_text_latent = nn.Linear(latent_dim, latent_dim, bias=False) 235 | 236 | self.distributed = is_distributed 237 | 238 | if mel_codes is None: 239 | self.speech_emb = nn.Conv1d(mel_channels, model_dim, kernel_size=5, padding=2) 240 | else: 241 | self.speech_emb = ConvFormatEmbedding(mel_codes, model_dim) 242 | self.speech_transformer = CollapsingTransformer(model_dim, latent_dim, transformer_heads, dropout, speech_enc_depth, speech_mask_percentage) 243 | self.to_speech_latent = nn.Linear(latent_dim, latent_dim, bias=False) 244 | 245 | def get_grad_norm_parameter_groups(self): 246 | return { 247 | 'conditioning': list(self.conditioning_transformer.parameters()), 248 | 'text': list(self.text_transformer.parameters()), 249 | 'speech': list(self.speech_transformer.parameters()), 250 | } 251 | 252 | def forward( 253 | self, 254 | text, 255 | mel_input, 256 | mel_cond, 257 | return_loss=False 258 | ): 259 | device = text.device 260 | 261 | text_emb = self.text_emb(text) 262 | speech_emb = self.speech_emb(mel_input).permute(0,2,1) 263 | 264 | unused_params = [] 265 | cond_emb = self.cond_emb(mel_cond).permute(0,2,1) 266 | enc_cond = self.conditioning_transformer(cond_emb) 267 | enc_text = self.text_transformer(text_emb, norm_scale_shift_inp=enc_cond) 268 | enc_speech = self.speech_transformer(speech_emb) 269 | 270 | text_latents = self.to_text_latent(enc_text) 271 | speech_latents = self.to_speech_latent(enc_speech) 272 | 273 | text_latents, speech_latents = map(lambda t: F.normalize(t, p=2, dim=-1), (text_latents, speech_latents)) 274 | temp = self.temperature.exp() 275 | 276 | if not return_loss: 277 | sim = einsum('n d, n d -> n', text_latents, speech_latents) * temp 278 | return sim 279 | 280 | sim = einsum('i d, j d -> i j', text_latents, speech_latents) * temp 281 | labels = torch.arange(text_latents.shape[0], device=device) 282 | loss = (F.cross_entropy(sim, labels) + F.cross_entropy(sim.t(), labels)) / 2 283 | 284 | # Involve probabilistic or possibly unused parameters in loss so we don't get DDP errors. 285 | extraneous_addition = 0 286 | for p in unused_params: 287 | extraneous_addition = extraneous_addition + p.mean() 288 | loss = loss + extraneous_addition * 0 289 | return loss 290 | 291 | def get_speech_projection(self, mel): 292 | speech_emb = self.speech_emb(mel).permute(0,2,1) 293 | enc_speech = self.speech_transformer(speech_emb) 294 | speech_latents = self.to_speech_latent(enc_speech) 295 | return speech_latents 296 | 297 | 298 | class CLVPMetric: 299 | def __init__(self, device='cpu', pretrained_path='.data/clvp.pth'): 300 | self.device = device 301 | self.model = CLVP(model_dim=512, transformer_heads=8, dropout=0, num_text_tokens=256, text_enc_depth=8, 302 | text_mask_percentage=0, conditioning_enc_depth=4, speech_enc_depth=8, 303 | speech_mask_percentage=0, latent_multiplier=2).eval().to(device) 304 | sd = torch.load(pretrained_path, map_location=device) 305 | self.model.load_state_dict(sd) 306 | self.tokenizer = VoiceBpeTokenizer() 307 | 308 | def compute_frechet_distance(self, proj1, proj2): 309 | # I really REALLY FUCKING HATE that this is going to numpy. I do it because the `pytorch_fid` repo does it and 310 | # I want to retain parity (and torch.cov doesn't operate the same). Why does "pytorch_fid" operate in numpy land. WHY? 311 | proj1 = proj1.cpu().numpy() 312 | proj2 = proj2.cpu().numpy() 313 | mu1 = np.mean(proj1, axis=0) 314 | mu2 = np.mean(proj2, axis=0) 315 | sigma1 = np.cov(proj1, rowvar=False) 316 | sigma2 = np.cov(proj2, rowvar=False) 317 | return torch.tensor(calculate_frechet_distance(mu1, sigma1, mu2, sigma2)) 318 | 319 | def get_projection_for_files(self, files, verbose=True): 320 | with torch.no_grad(): 321 | projections = [] 322 | for file in tqdm(files, disable=not verbose): 323 | # Batching these could make this process faster, but they are being sequentially loaded anyways so whatever. 324 | audio = load_audio(str(file), 22050).to(self.device)[:1] # Only take the first channel (if multiple are present) 325 | mel = to_mel(audio).unsqueeze(0) 326 | projections.append(self.model.get_speech_projection(mel).cpu()) 327 | return projections 328 | 329 | def compute_fd(self, gen_path, real_path, verbose=True): 330 | gen_files = pathlib.Path(gen_path).rglob('*.wav') 331 | gen_projections = torch.cat(self.get_projection_for_files(gen_files, verbose), dim=0) 332 | real_files = pathlib.Path(real_path).rglob('*.wav') 333 | real_projections = torch.cat(self.get_projection_for_files(real_files, verbose), dim=0) 334 | return self.compute_frechet_distance(gen_projections, real_projections) 335 | 336 | def compute_clvp(self, tsv, real_dir, verbose=True): 337 | with torch.no_grad(): 338 | paths_and_text = load_tsv(tsv) 339 | ces = [] 340 | for path, text in tqdm(paths_and_text, disable=not verbose): 341 | audio = load_audio(str(path), 22050).to(self.device)[:1] # Only take the first channel (if multiple are present) 342 | mel = to_mel(audio).unsqueeze(0) 343 | real_path = os.path.join(real_dir, os.path.basename(str(path))) 344 | cond_audio = load_audio(real_path, 22050).to(self.device)[:1] 345 | cond_mel = to_mel(cond_audio).unsqueeze(0) 346 | text_codes = torch.tensor(self.tokenizer.encode(text), device=self.device).unsqueeze(0) 347 | ces.append(self.model(text_codes, mel, cond_mel, False)) 348 | return torch.stack(ces).mean() 349 | 350 | 351 | if __name__ == '__main__': 352 | clvp = CLVP() 353 | clvp(torch.randint(0,256,(2,120)), 354 | torch.randn(2,80,100), 355 | torch.randn(2,80,95), 356 | return_loss=True) 357 | nonloss = clvp(torch.randint(0,256,(2,120)), 358 | torch.randn(2,80,100), 359 | torch.randn(2,80,95), 360 | return_loss=False) 361 | clvp.get_speech_projection(torch.randn(2,80,95)) 362 | clvp = CLVP(mel_codes=8192) 363 | clvp(torch.randint(0,256,(2,120)), 364 | torch.randint(0,8192,(2,150)), 365 | torch.randn(2,80,95), 366 | return_loss=True) 367 | print(nonloss.shape) -------------------------------------------------------------------------------- /tts_scores/intelligibility.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | 3 | import torch 4 | from tqdm import tqdm 5 | from transformers import Wav2Vec2ForCTC 6 | 7 | from tts_scores.tokenizer import text_to_sequence 8 | from tts_scores.utils import load_tsv, load_audio 9 | 10 | 11 | class IntelligibilityMetric: 12 | """ 13 | Defines the logic for computing an "intelligibility" score. The intelligibility score measures how well the text 14 | being spoken can be understood by an ASR model. 15 | 16 | It is computed from the CTC losses for a wav2vec model between a true audio sample and its transcription and a 17 | fake audio sample and the same transcription. 18 | """ 19 | def __init__(self, device='cpu'): 20 | self.device = device 21 | self.model = Wav2Vec2ForCTC.from_pretrained("jbetker/wav2vec2-large-robust-ft-libritts-voxpopuli").to(device).eval() 22 | 23 | def fetch_ctc_loss(self, sample, text_codes): 24 | with torch.no_grad(): 25 | norm_s = (sample - sample.mean()) / torch.sqrt(sample.var() + 1e-7) 26 | norm_s = norm_s.squeeze(1) 27 | return self.model(input_values=norm_s, labels=text_codes).loss 28 | 29 | def compute_intelligibility(self, tsv_file, real_base_dir=None, verbose=True): 30 | """ 31 | Computes the intelligibility score and returns it. 32 | :param tsv_file: A path to a Tab-Separated-Value file that follows this format: 33 | {transcription}\t{relative path to TTS audio file}\n 34 | :param real_base_dir: A folder containing real spoken audio files, with the same basenames as the TTS-generated 35 | audio files from the tsv_file above. If None, one-sided intelligibility will be computed, 36 | which does not take into account natural intelligibility losses from the ground truth data. 37 | :param verbose: When true, a TQDM bar showing metric computation status will be shown. 38 | :return: The mean intelligibility score for the provided data. 39 | """ 40 | paths_and_text = load_tsv(tsv_file) 41 | ils = [] 42 | for path, text in tqdm(paths_and_text, disable=not verbose): 43 | text_codes = torch.tensor(text_to_sequence(text), device=self.device) 44 | audio = load_audio(str(path), 16000).to(self.device)[:1] 45 | il = self.fetch_ctc_loss(audio, text_codes) 46 | if real_base_dir is not None: 47 | real_path = os.path.join(real_base_dir, os.path.basename(path)) 48 | assert os.path.exists(real_path), real_path 49 | real_audio = load_audio(str(real_path), 16000).to(self.device)[:1] 50 | il = il - self.fetch_ctc_loss(real_audio, text_codes) 51 | if torch.isnan(il) or torch.isinf(il): 52 | continue 53 | ils.append(il) 54 | return torch.stack(ils).mean() 55 | -------------------------------------------------------------------------------- /tts_scores/tokenizer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Character-level tokenizer derived from the nvidia-tacotron2 implementation: 3 | https://github.com/NVIDIA/tacotron2 4 | """ 5 | 6 | import re 7 | 8 | import inflect 9 | # Regular expression matching whitespace: 10 | import torch 11 | from tokenizers import Tokenizer 12 | from unidecode import unidecode 13 | 14 | _pad = '_' 15 | _punctuation = '!\'(),.:;? ' 16 | _special = '-' 17 | _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' 18 | 19 | # Export all symbols: 20 | symbols = [_pad] + list(_special) + list(_punctuation) + list(_letters) 21 | 22 | 23 | _whitespace_re = re.compile(r'\s+') 24 | _curly_re = re.compile(r'(.*?)\{(.+?)\}(.*)') 25 | 26 | 27 | # List of (regular expression, replacement) pairs for abbreviations: 28 | _abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [ 29 | ('mrs', 'misess'), 30 | ('mr', 'mister'), 31 | ('dr', 'doctor'), 32 | ('st', 'saint'), 33 | ('co', 'company'), 34 | ('jr', 'junior'), 35 | ('maj', 'major'), 36 | ('gen', 'general'), 37 | ('drs', 'doctors'), 38 | ('rev', 'reverend'), 39 | ('lt', 'lieutenant'), 40 | ('hon', 'honorable'), 41 | ('sgt', 'sergeant'), 42 | ('capt', 'captain'), 43 | ('esq', 'esquire'), 44 | ('ltd', 'limited'), 45 | ('col', 'colonel'), 46 | ('ft', 'fort'), 47 | ]] 48 | 49 | _symbol_to_id = {s: i for i, s in enumerate(symbols)} 50 | 51 | def expand_abbreviations(text): 52 | for regex, replacement in _abbreviations: 53 | text = re.sub(regex, replacement, text) 54 | return text 55 | 56 | 57 | _inflect = inflect.engine() 58 | _comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])') 59 | _decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)') 60 | _pounds_re = re.compile(r'£([0-9\,]*[0-9]+)') 61 | _dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)') 62 | _ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)') 63 | _number_re = re.compile(r'[0-9]+') 64 | 65 | 66 | def _remove_commas(m): 67 | return m.group(1).replace(',', '') 68 | 69 | 70 | def _expand_decimal_point(m): 71 | return m.group(1).replace('.', ' point ') 72 | 73 | 74 | def _expand_dollars(m): 75 | match = m.group(1) 76 | parts = match.split('.') 77 | if len(parts) > 2: 78 | return match + ' dollars' # Unexpected format 79 | dollars = int(parts[0]) if parts[0] else 0 80 | cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0 81 | if dollars and cents: 82 | dollar_unit = 'dollar' if dollars == 1 else 'dollars' 83 | cent_unit = 'cent' if cents == 1 else 'cents' 84 | return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit) 85 | elif dollars: 86 | dollar_unit = 'dollar' if dollars == 1 else 'dollars' 87 | return '%s %s' % (dollars, dollar_unit) 88 | elif cents: 89 | cent_unit = 'cent' if cents == 1 else 'cents' 90 | return '%s %s' % (cents, cent_unit) 91 | else: 92 | return 'zero dollars' 93 | 94 | 95 | def _expand_ordinal(m): 96 | return _inflect.number_to_words(m.group(0)) 97 | 98 | 99 | def _expand_number(m): 100 | num = int(m.group(0)) 101 | if num > 1000 and num < 3000: 102 | if num == 2000: 103 | return 'two thousand' 104 | elif num > 2000 and num < 2010: 105 | return 'two thousand ' + _inflect.number_to_words(num % 100) 106 | elif num % 100 == 0: 107 | return _inflect.number_to_words(num // 100) + ' hundred' 108 | else: 109 | return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ') 110 | else: 111 | return _inflect.number_to_words(num, andword='') 112 | 113 | 114 | def normalize_numbers(text): 115 | text = re.sub(_comma_number_re, _remove_commas, text) 116 | text = re.sub(_pounds_re, r'\1 pounds', text) 117 | text = re.sub(_dollars_re, _expand_dollars, text) 118 | text = re.sub(_decimal_number_re, _expand_decimal_point, text) 119 | text = re.sub(_ordinal_re, _expand_ordinal, text) 120 | text = re.sub(_number_re, _expand_number, text) 121 | return text 122 | 123 | 124 | def expand_numbers(text): 125 | return normalize_numbers(text) 126 | 127 | 128 | def lowercase(text): 129 | return text.lower() 130 | 131 | 132 | def collapse_whitespace(text): 133 | return re.sub(_whitespace_re, ' ', text) 134 | 135 | 136 | def convert_to_ascii(text): 137 | return unidecode(text) 138 | 139 | 140 | def basic_cleaners(text): 141 | '''Basic pipeline that lowercases and collapses whitespace without transliteration.''' 142 | text = lowercase(text) 143 | text = collapse_whitespace(text) 144 | return text 145 | 146 | 147 | def transliteration_cleaners(text): 148 | '''Pipeline for non-English text that transliterates to ASCII.''' 149 | text = convert_to_ascii(text) 150 | text = lowercase(text) 151 | text = collapse_whitespace(text) 152 | return text 153 | 154 | 155 | def english_cleaners(text): 156 | '''Pipeline for English text, including number and abbreviation expansion.''' 157 | text = convert_to_ascii(text) 158 | text = lowercase(text) 159 | text = expand_numbers(text) 160 | text = expand_abbreviations(text) 161 | text = collapse_whitespace(text) 162 | text = text.replace('"', '') 163 | return text 164 | 165 | 166 | def _symbols_to_sequence(symbols): 167 | return [_symbol_to_id[s] for s in symbols if _should_keep_symbol(s)] 168 | 169 | 170 | def _arpabet_to_sequence(text): 171 | return _symbols_to_sequence(['@' + s for s in text.split()]) 172 | 173 | 174 | def _should_keep_symbol(s): 175 | return s in _symbol_to_id and s != '_' and s != '~' 176 | 177 | 178 | def text_to_sequence(text, cleaner_names=['english_cleaners']): 179 | '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text. 180 | 181 | The text can optionally have ARPAbet sequences enclosed in curly braces embedded 182 | in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street." 183 | 184 | Args: 185 | text: string to convert to a sequence 186 | cleaner_names: names of the cleaner functions to run the text through 187 | 188 | Returns: 189 | List of integers corresponding to the symbols in the text 190 | ''' 191 | sequence = [] 192 | 193 | # Check for curly braces and treat their contents as ARPAbet: 194 | while len(text): 195 | m = _curly_re.match(text) 196 | if not m: 197 | sequence += _symbols_to_sequence(english_cleaners(text)) 198 | break 199 | sequence += _symbols_to_sequence(english_cleaners(m.group(1))) 200 | sequence += _arpabet_to_sequence(m.group(2)) 201 | text = m.group(3) 202 | 203 | return sequence 204 | 205 | 206 | def remove_extraneous_punctuation(word): 207 | replacement_punctuation = { 208 | '{': '(', '}': ')', 209 | '[': '(', ']': ')', 210 | '`': '\'', '—': '-', 211 | '—': '-', '`': '\'', 212 | 'ʼ': '\'' 213 | } 214 | replace = re.compile("|".join([re.escape(k) for k in sorted(replacement_punctuation, key=len, reverse=True)]), flags=re.DOTALL) 215 | word = replace.sub(lambda x: replacement_punctuation[x.group(0)], word) 216 | 217 | # TODO: some of these are spoken ('@', '%', '+', etc). Integrate them into the cleaners. 218 | extraneous = re.compile(r'^[@#%_=\$\^&\*\+\\]$') 219 | word = extraneous.sub('', word) 220 | return word 221 | 222 | 223 | class VoiceBpeTokenizer: 224 | def __init__(self): 225 | self.tokenizer = Tokenizer.from_file('.data/clvp_tok.json') 226 | 227 | def preprocess_text(self, txt): 228 | txt = english_cleaners(txt) 229 | txt = remove_extraneous_punctuation(txt) 230 | return txt 231 | 232 | def encode(self, txt): 233 | txt = self.preprocess_text(txt) 234 | txt = txt.replace(' ', '[SPACE]') 235 | return self.tokenizer.encode(txt).ids 236 | 237 | def decode(self, seq): 238 | if isinstance(seq, torch.Tensor): 239 | seq = seq.cpu().numpy() 240 | txt = self.tokenizer.decode(seq, skip_special_tokens=False).replace(' ', '') 241 | txt = txt.replace('[SPACE]', ' ') 242 | txt = txt.replace('[STOP]', '') 243 | txt = txt.replace('[UNK]', '') 244 | 245 | return txt -------------------------------------------------------------------------------- /tts_scores/transformers.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import math 3 | import torch 4 | from torch import nn, einsum 5 | import torch.nn.functional as F 6 | from functools import partial 7 | from inspect import isfunction 8 | from collections import namedtuple 9 | 10 | from einops import rearrange, repeat, reduce 11 | from einops.layers.torch import Rearrange 12 | 13 | from entmax import entmax15 14 | from torch.utils.checkpoint import checkpoint 15 | 16 | from x_transformers.autoregressive_wrapper import AutoregressiveWrapper 17 | 18 | DEFAULT_DIM_HEAD = 64 19 | 20 | Intermediates = namedtuple('Intermediates', [ 21 | 'pre_softmax_attn', 22 | 'post_softmax_attn' 23 | ]) 24 | 25 | LayerIntermediates = namedtuple('Intermediates', [ 26 | 'hiddens', 27 | 'attn_intermediates', 28 | 'past_key_values', 29 | ]) 30 | 31 | 32 | # helpers 33 | 34 | def exists(val): 35 | return val is not None 36 | 37 | 38 | def default(val, d): 39 | if exists(val): 40 | return val 41 | return d() if isfunction(d) else d 42 | 43 | 44 | def cast_tuple(val, depth): 45 | return val if isinstance(val, tuple) else (val,) * depth 46 | 47 | 48 | class always(): 49 | def __init__(self, val): 50 | self.val = val 51 | 52 | def __call__(self, *args, **kwargs): 53 | return self.val 54 | 55 | 56 | class not_equals(): 57 | def __init__(self, val): 58 | self.val = val 59 | 60 | def __call__(self, x, *args, **kwargs): 61 | return x != self.val 62 | 63 | 64 | class equals(): 65 | def __init__(self, val): 66 | self.val = val 67 | 68 | def __call__(self, x, *args, **kwargs): 69 | return x == self.val 70 | 71 | 72 | def max_neg_value(tensor): 73 | return -torch.finfo(tensor.dtype).max 74 | 75 | 76 | def l2norm(t): 77 | return F.normalize(t, p=2, dim=-1) 78 | 79 | 80 | # init helpers 81 | 82 | def init_zero_(layer): 83 | nn.init.constant_(layer.weight, 0.) 84 | if exists(layer.bias): 85 | nn.init.constant_(layer.bias, 0.) 86 | 87 | 88 | # keyword argument helpers 89 | 90 | def pick_and_pop(keys, d): 91 | values = list(map(lambda key: d.pop(key), keys)) 92 | return dict(zip(keys, values)) 93 | 94 | 95 | def group_dict_by_key(cond, d): 96 | return_val = [dict(), dict()] 97 | for key in d.keys(): 98 | match = bool(cond(key)) 99 | ind = int(not match) 100 | return_val[ind][key] = d[key] 101 | return (*return_val,) 102 | 103 | 104 | def string_begins_with(prefix, str): 105 | return str.startswith(prefix) 106 | 107 | 108 | def group_by_key_prefix(prefix, d): 109 | return group_dict_by_key(partial(string_begins_with, prefix), d) 110 | 111 | 112 | def groupby_prefix_and_trim(prefix, d): 113 | kwargs_with_prefix, kwargs = group_dict_by_key(partial(string_begins_with, prefix), d) 114 | kwargs_without_prefix = dict(map(lambda x: (x[0][len(prefix):], x[1]), tuple(kwargs_with_prefix.items()))) 115 | return kwargs_without_prefix, kwargs 116 | 117 | 118 | # activations 119 | 120 | class ReluSquared(nn.Module): 121 | def forward(self, x): 122 | return F.relu(x) ** 2 123 | 124 | 125 | # positional embeddings 126 | 127 | class AbsolutePositionalEmbedding(nn.Module): 128 | def __init__(self, dim, max_seq_len): 129 | super().__init__() 130 | self.scale = dim ** -0.5 131 | self.emb = nn.Embedding(max_seq_len, dim) 132 | 133 | def forward(self, x): 134 | n = torch.arange(x.shape[1], device=x.device) 135 | pos_emb = self.emb(n) 136 | pos_emb = rearrange(pos_emb, 'n d -> () n d') 137 | return pos_emb * self.scale 138 | 139 | 140 | class FixedPositionalEmbedding(nn.Module): 141 | def __init__(self, dim): 142 | super().__init__() 143 | inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim)) 144 | self.register_buffer('inv_freq', inv_freq) 145 | 146 | def forward(self, x, seq_dim=1, offset=0): 147 | t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq) + offset 148 | sinusoid_inp = torch.einsum('i , j -> i j', t, self.inv_freq) 149 | emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1) 150 | return rearrange(emb, 'n d -> () n d') 151 | 152 | 153 | class RelativePositionBias(nn.Module): 154 | def __init__(self, scale, causal=False, num_buckets=32, max_distance=128, heads=8): 155 | super().__init__() 156 | self.scale = scale 157 | self.causal = causal 158 | self.num_buckets = num_buckets 159 | self.max_distance = max_distance 160 | self.relative_attention_bias = nn.Embedding(num_buckets, heads) 161 | 162 | @staticmethod 163 | def _relative_position_bucket(relative_position, causal=True, num_buckets=32, max_distance=128): 164 | ret = 0 165 | n = -relative_position 166 | if not causal: 167 | num_buckets //= 2 168 | ret += (n < 0).long() * num_buckets 169 | n = torch.abs(n) 170 | else: 171 | n = torch.max(n, torch.zeros_like(n)) 172 | 173 | max_exact = num_buckets // 2 174 | is_small = n < max_exact 175 | 176 | val_if_large = max_exact + ( 177 | torch.log(n.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact) 178 | ).long() 179 | val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1)) 180 | 181 | ret += torch.where(is_small, n, val_if_large) 182 | return ret 183 | 184 | def forward(self, qk_dots): 185 | i, j, device = *qk_dots.shape[-2:], qk_dots.device 186 | q_pos = torch.arange(i, dtype=torch.long, device=device) 187 | k_pos = torch.arange(j, dtype=torch.long, device=device) 188 | rel_pos = k_pos[None, :] - q_pos[:, None] 189 | rp_bucket = self._relative_position_bucket(rel_pos, causal=self.causal, num_buckets=self.num_buckets, 190 | max_distance=self.max_distance) 191 | values = self.relative_attention_bias(rp_bucket) 192 | bias = rearrange(values, 'i j h -> () h i j') 193 | return qk_dots + (bias * self.scale) 194 | 195 | 196 | class AlibiPositionalBias(nn.Module): 197 | def __init__(self, heads, **kwargs): 198 | super().__init__() 199 | self.heads = heads 200 | slopes = torch.Tensor(self._get_slopes(heads)) 201 | slopes = rearrange(slopes, 'h -> () h () ()') 202 | self.register_buffer('slopes', slopes, persistent=False) 203 | self.register_buffer('bias', None, persistent=False) 204 | 205 | @staticmethod 206 | def _get_slopes(heads): 207 | def get_slopes_power_of_2(n): 208 | start = (2 ** (-2 ** -(math.log2(n) - 3))) 209 | ratio = start 210 | return [start * ratio ** i for i in range(n)] 211 | 212 | if math.log2(heads).is_integer(): 213 | return get_slopes_power_of_2(heads) 214 | 215 | closest_power_of_2 = 2 ** math.floor(math.log2(heads)) 216 | return get_slopes_power_of_2(closest_power_of_2) + get_slopes_power_of_2(2 * closest_power_of_2)[0::2][ 217 | :heads - closest_power_of_2] 218 | 219 | def forward(self, qk_dots): 220 | h, i, j, device = *qk_dots.shape[-3:], qk_dots.device 221 | 222 | if exists(self.bias) and self.bias.shape[-1] >= j: 223 | return qk_dots + self.bias[..., :j] 224 | 225 | bias = torch.arange(j, device=device) 226 | bias = rearrange(bias, 'j -> () () () j') 227 | bias = bias * self.slopes 228 | 229 | num_heads_unalibied = h - bias.shape[1] 230 | bias = F.pad(bias, (0, 0, 0, 0, 0, num_heads_unalibied)) 231 | 232 | self.register_buffer('bias', bias, persistent=False) 233 | return qk_dots + self.bias 234 | 235 | 236 | class LearnedAlibiPositionalBias(AlibiPositionalBias): 237 | def __init__(self, heads, bidirectional=False): 238 | super().__init__(heads) 239 | los_slopes = torch.log(self.slopes) 240 | self.learned_logslopes = nn.Parameter(los_slopes) 241 | 242 | self.bidirectional = bidirectional 243 | if self.bidirectional: 244 | self.learned_logslopes_future = nn.Parameter(los_slopes) 245 | 246 | def forward(self, qk_dots): 247 | h, i, j, device = *qk_dots.shape[-3:], qk_dots.device 248 | 249 | def get_slopes(param): 250 | return F.pad(param.exp(), (0, 0, 0, 0, 0, h - param.shape[1])) 251 | 252 | if exists(self.bias) and self.bias.shape[-1] >= j: 253 | bias = self.bias[..., :i, :j] 254 | else: 255 | i_arange = torch.arange(i, device=device) 256 | j_arange = torch.arange(j, device=device) 257 | bias = rearrange(j_arange, 'j -> 1 1 1 j') - rearrange(i_arange, 'i -> 1 1 i 1') 258 | self.register_buffer('bias', bias, persistent=False) 259 | 260 | if self.bidirectional: 261 | past_slopes = get_slopes(self.learned_logslopes) 262 | future_slopes = get_slopes(self.learned_logslopes_future) 263 | bias = torch.tril(bias * past_slopes) + torch.triu(bias * future_slopes) 264 | else: 265 | slopes = get_slopes(self.learned_logslopes) 266 | bias = bias * slopes 267 | 268 | return qk_dots + bias 269 | 270 | 271 | class RotaryEmbedding(nn.Module): 272 | def __init__(self, dim): 273 | super().__init__() 274 | inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim)) 275 | self.register_buffer('inv_freq', inv_freq) 276 | 277 | def forward(self, max_seq_len, device): 278 | t = torch.arange(max_seq_len, device=device).type_as(self.inv_freq) 279 | freqs = torch.einsum('i , j -> i j', t, self.inv_freq) 280 | emb = torch.cat((freqs, freqs), dim=-1) 281 | return rearrange(emb, 'n d -> () () n d') 282 | 283 | 284 | def rotate_half(x): 285 | x = rearrange(x, '... (j d) -> ... j d', j=2) 286 | x1, x2 = x.unbind(dim=-2) 287 | return torch.cat((-x2, x1), dim=-1) 288 | 289 | 290 | def apply_rotary_pos_emb(t, freqs): 291 | seq_len = t.shape[-2] 292 | freqs = freqs[:, :, -seq_len:] 293 | return (t * freqs.cos()) + (rotate_half(t) * freqs.sin()) 294 | 295 | 296 | # norms 297 | 298 | class Scale(nn.Module): 299 | def __init__(self, value, fn): 300 | super().__init__() 301 | self.value = value 302 | self.fn = fn 303 | 304 | def forward(self, x, **kwargs): 305 | out = self.fn(x, **kwargs) 306 | scale_fn = lambda t: t * self.value 307 | 308 | if not isinstance(out, tuple): 309 | return scale_fn(out) 310 | 311 | return (scale_fn(out[0]), *out[1:]) 312 | 313 | 314 | class Rezero(nn.Module): 315 | def __init__(self, fn): 316 | super().__init__() 317 | self.fn = fn 318 | self.g = nn.Parameter(torch.zeros(1)) 319 | 320 | def forward(self, x, **kwargs): 321 | out = self.fn(x, **kwargs) 322 | rezero_fn = lambda t: t * self.g 323 | 324 | if not isinstance(out, tuple): 325 | return rezero_fn(out) 326 | 327 | return (rezero_fn(out[0]), *out[1:]) 328 | 329 | 330 | class ScaleNorm(nn.Module): 331 | def __init__(self, dim, eps=1e-5): 332 | super().__init__() 333 | self.scale = dim ** -0.5 334 | self.eps = eps 335 | self.g = nn.Parameter(torch.ones(1)) 336 | 337 | def forward(self, x): 338 | norm = torch.norm(x, dim=-1, keepdim=True) * self.scale 339 | return x / norm.clamp(min=self.eps) * self.g 340 | 341 | 342 | class RMSNorm(nn.Module): 343 | def __init__(self, dim, eps=1e-8): 344 | super().__init__() 345 | self.scale = dim ** -0.5 346 | self.eps = eps 347 | self.g = nn.Parameter(torch.ones(dim)) 348 | 349 | def forward(self, x): 350 | norm = torch.norm(x, dim=-1, keepdim=True) * self.scale 351 | return x / norm.clamp(min=self.eps) * self.g 352 | 353 | 354 | class RMSScaleShiftNorm(nn.Module): 355 | def __init__(self, dim, eps=1e-8): 356 | super().__init__() 357 | self.scale = dim ** -0.5 358 | self.eps = eps 359 | self.g = nn.Parameter(torch.ones(dim)) 360 | self.scale_shift_process = nn.Linear(dim * 2, dim * 2) 361 | 362 | def forward(self, x, norm_scale_shift_inp): 363 | norm = torch.norm(x, dim=-1, keepdim=True) * self.scale 364 | norm = x / norm.clamp(min=self.eps) * self.g 365 | 366 | ss_emb = self.scale_shift_process(norm_scale_shift_inp) 367 | scale, shift = torch.chunk(ss_emb, 2, dim=1) 368 | h = norm * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) 369 | return h 370 | 371 | 372 | # residual and residual gates 373 | 374 | class Residual(nn.Module): 375 | def __init__(self, dim, scale_residual=False): 376 | super().__init__() 377 | self.residual_scale = nn.Parameter(torch.ones(dim)) if scale_residual else None 378 | 379 | def forward(self, x, residual): 380 | if exists(self.residual_scale): 381 | residual = residual * self.residual_scale 382 | 383 | return x + residual 384 | 385 | 386 | class GRUGating(nn.Module): 387 | def __init__(self, dim, scale_residual=False): 388 | super().__init__() 389 | self.gru = nn.GRUCell(dim, dim) 390 | self.residual_scale = nn.Parameter(torch.ones(dim)) if scale_residual else None 391 | 392 | def forward(self, x, residual): 393 | if exists(self.residual_scale): 394 | residual = residual * self.residual_scale 395 | 396 | gated_output = self.gru( 397 | rearrange(x, 'b n d -> (b n) d'), 398 | rearrange(residual, 'b n d -> (b n) d') 399 | ) 400 | 401 | return gated_output.reshape_as(x) 402 | 403 | 404 | # token shifting 405 | 406 | def shift(t, amount, mask=None): 407 | if amount == 0: 408 | return t 409 | 410 | if exists(mask): 411 | t = t.masked_fill(~mask[..., None], 0.) 412 | 413 | return F.pad(t, (0, 0, amount, -amount), value=0.) 414 | 415 | 416 | class ShiftTokens(nn.Module): 417 | def __init__(self, shifts, fn): 418 | super().__init__() 419 | self.fn = fn 420 | self.shifts = tuple(shifts) 421 | 422 | def forward(self, x, **kwargs): 423 | mask = kwargs.get('mask', None) 424 | shifts = self.shifts 425 | segments = len(shifts) 426 | feats_per_shift = x.shape[-1] // segments 427 | splitted = x.split(feats_per_shift, dim=-1) 428 | segments_to_shift, rest = splitted[:segments], splitted[segments:] 429 | segments_to_shift = list(map(lambda args: shift(*args, mask=mask), zip(segments_to_shift, shifts))) 430 | x = torch.cat((*segments_to_shift, *rest), dim=-1) 431 | return self.fn(x, **kwargs) 432 | 433 | 434 | # feedforward 435 | 436 | class GLU(nn.Module): 437 | def __init__(self, dim_in, dim_out, activation): 438 | super().__init__() 439 | self.act = activation 440 | self.proj = nn.Linear(dim_in, dim_out * 2) 441 | 442 | def forward(self, x): 443 | x, gate = self.proj(x).chunk(2, dim=-1) 444 | return x * self.act(gate) 445 | 446 | 447 | class FeedForward(nn.Module): 448 | def __init__( 449 | self, 450 | dim, 451 | dim_out=None, 452 | mult=4, 453 | glu=False, 454 | relu_squared=False, 455 | post_act_ln=False, 456 | dropout=0., 457 | zero_init_output=False 458 | ): 459 | super().__init__() 460 | inner_dim = int(dim * mult) 461 | dim_out = default(dim_out, dim) 462 | activation = ReluSquared() if relu_squared else nn.GELU() 463 | 464 | project_in = nn.Sequential( 465 | nn.Linear(dim, inner_dim), 466 | activation 467 | ) if not glu else GLU(dim, inner_dim, activation) 468 | 469 | self.net = nn.Sequential( 470 | project_in, 471 | nn.LayerNorm(inner_dim) if post_act_ln else nn.Identity(), 472 | nn.Dropout(dropout), 473 | nn.Linear(inner_dim, dim_out) 474 | ) 475 | 476 | # init last linear layer to 0 477 | if zero_init_output: 478 | init_zero_(self.net[-1]) 479 | 480 | def forward(self, x): 481 | return self.net(x) 482 | 483 | 484 | # attention. 485 | 486 | class Attention(nn.Module): 487 | def __init__( 488 | self, 489 | dim, 490 | dim_head=DEFAULT_DIM_HEAD, 491 | heads=8, 492 | causal=False, 493 | talking_heads=False, 494 | head_scale=False, 495 | collab_heads=False, 496 | collab_compression=.3, 497 | sparse_topk=None, 498 | use_entmax15=False, 499 | num_mem_kv=0, 500 | dropout=0., 501 | on_attn=False, 502 | gate_values=False, 503 | zero_init_output=False, 504 | max_attend_past=None, 505 | qk_norm=False, 506 | scale_init_value=None, 507 | rel_pos_bias=False, 508 | rel_pos_num_buckets=32, 509 | rel_pos_max_distance=128, 510 | ): 511 | super().__init__() 512 | self.scale = dim_head ** -0.5 513 | 514 | self.heads = heads 515 | self.causal = causal 516 | self.max_attend_past = max_attend_past 517 | 518 | qk_dim = v_dim = dim_head * heads 519 | 520 | # collaborative heads 521 | self.collab_heads = collab_heads 522 | if self.collab_heads: 523 | qk_dim = int(collab_compression * qk_dim) 524 | self.collab_mixing = nn.Parameter(torch.randn(heads, qk_dim)) 525 | 526 | self.to_q = nn.Linear(dim, qk_dim, bias=False) 527 | self.to_k = nn.Linear(dim, qk_dim, bias=False) 528 | self.to_v = nn.Linear(dim, v_dim, bias=False) 529 | 530 | self.dropout = nn.Dropout(dropout) 531 | 532 | # add GLU gating for aggregated values, from alphafold2 533 | self.to_v_gate = None 534 | if gate_values: 535 | self.to_v_gate = nn.Linear(dim, v_dim) 536 | nn.init.constant_(self.to_v_gate.weight, 0) 537 | nn.init.constant_(self.to_v_gate.bias, 1) 538 | 539 | # cosine sim attention 540 | self.qk_norm = qk_norm 541 | if qk_norm: 542 | scale_init_value = default(scale_init_value, 543 | -3) # if not provided, initialize as though it were sequence length of 1024 544 | self.scale = nn.Parameter(torch.ones(1, heads, 1, 1) * scale_init_value) 545 | 546 | # talking heads 547 | self.talking_heads = talking_heads 548 | if talking_heads: 549 | self.pre_softmax_proj = nn.Parameter(torch.randn(heads, heads)) 550 | self.post_softmax_proj = nn.Parameter(torch.randn(heads, heads)) 551 | 552 | # head scaling 553 | self.head_scale = head_scale 554 | if head_scale: 555 | self.head_scale_params = nn.Parameter(torch.ones(1, heads, 1, 1)) 556 | 557 | # explicit topk sparse attention 558 | self.sparse_topk = sparse_topk 559 | 560 | # entmax 561 | self.attn_fn = entmax15 if use_entmax15 else F.softmax 562 | 563 | # add memory key / values 564 | self.num_mem_kv = num_mem_kv 565 | if num_mem_kv > 0: 566 | self.mem_k = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head)) 567 | self.mem_v = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head)) 568 | 569 | # attention on attention 570 | self.attn_on_attn = on_attn 571 | self.to_out = nn.Sequential(nn.Linear(v_dim, dim * 2), nn.GLU()) if on_attn else nn.Linear(v_dim, dim) 572 | 573 | self.rel_pos_bias = rel_pos_bias 574 | if rel_pos_bias: 575 | assert rel_pos_num_buckets <= rel_pos_max_distance, 'number of relative position buckets must be less than the relative position max distance' 576 | self.rel_pos = RelativePositionBias(scale=dim_head ** 0.5, causal=causal, heads=heads, 577 | num_buckets=rel_pos_num_buckets, max_distance=rel_pos_max_distance) 578 | 579 | # init output projection 0 580 | if zero_init_output: 581 | init_zero_(self.to_out) 582 | 583 | def forward( 584 | self, 585 | x, 586 | context=None, 587 | mask=None, 588 | context_mask=None, 589 | attn_mask=None, 590 | sinusoidal_emb=None, 591 | rotary_pos_emb=None, 592 | prev_attn=None, 593 | mem=None, 594 | layer_past=None, 595 | ): 596 | b, n, _, h, talking_heads, collab_heads, head_scale, scale, device, has_context = *x.shape, self.heads, self.talking_heads, self.collab_heads, self.head_scale, self.scale, x.device, exists( 597 | context) 598 | kv_input = default(context, x) 599 | 600 | q_input = x 601 | k_input = kv_input 602 | v_input = kv_input 603 | 604 | if exists(mem): 605 | k_input = torch.cat((mem, k_input), dim=-2) 606 | v_input = torch.cat((mem, v_input), dim=-2) 607 | 608 | if exists(sinusoidal_emb): 609 | # in shortformer, the query would start at a position offset depending on the past cached memory 610 | offset = k_input.shape[-2] - q_input.shape[-2] 611 | q_input = q_input + sinusoidal_emb(q_input, offset=offset) 612 | k_input = k_input + sinusoidal_emb(k_input) 613 | 614 | q = self.to_q(q_input) 615 | k = self.to_k(k_input) 616 | v = self.to_v(v_input) 617 | 618 | if not collab_heads: 619 | q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=h), (q, k, v)) 620 | else: 621 | q = einsum('b i d, h d -> b h i d', q, self.collab_mixing) 622 | k = rearrange(k, 'b n d -> b () n d') 623 | v = rearrange(v, 'b n (h d) -> b h n d', h=h) 624 | 625 | if layer_past is not None: 626 | past_key, past_value = layer_past 627 | k = torch.cat([past_key, k], dim=-2) 628 | v = torch.cat([past_value, v], dim=-2) 629 | k_cache = k 630 | v_cache = v 631 | 632 | if exists(rotary_pos_emb) and not has_context: 633 | l = rotary_pos_emb.shape[-1] 634 | (ql, qr), (kl, kr), (vl, vr) = map(lambda t: (t[..., :l], t[..., l:]), (q, k, v)) 635 | ql, kl, vl = map(lambda t: apply_rotary_pos_emb(t, rotary_pos_emb), (ql, kl, vl)) 636 | q, k, v = map(lambda t: torch.cat(t, dim=-1), ((ql, qr), (kl, kr), (vl, vr))) 637 | 638 | input_mask = None 639 | if any(map(exists, (mask, context_mask))): 640 | q_mask = default(mask, lambda: torch.ones((b, n), device=device).bool()) 641 | k_mask = q_mask if not exists(context) else context_mask 642 | k_mask = default(k_mask, lambda: torch.ones((b, k.shape[-2]), device=device).bool()) 643 | q_mask = rearrange(q_mask, 'b i -> b () i ()') 644 | k_mask = rearrange(k_mask, 'b j -> b () () j') 645 | input_mask = q_mask * k_mask 646 | 647 | if self.num_mem_kv > 0: 648 | mem_k, mem_v = map(lambda t: repeat(t, 'h n d -> b h n d', b=b), (self.mem_k, self.mem_v)) 649 | k = torch.cat((mem_k, k), dim=-2) 650 | v = torch.cat((mem_v, v), dim=-2) 651 | if exists(input_mask): 652 | input_mask = F.pad(input_mask, (self.num_mem_kv, 0), value=True) 653 | 654 | if collab_heads: 655 | k = k.expand(-1, h, -1, -1) 656 | 657 | if self.qk_norm: 658 | q, k = map(l2norm, (q, k)) 659 | scale = 1 / (self.scale.exp().clamp(min=1e-2)) 660 | 661 | dots = einsum('b h i d, b h j d -> b h i j', q, k) * scale 662 | mask_value = max_neg_value(dots) 663 | 664 | if exists(prev_attn): 665 | dots = dots + prev_attn 666 | 667 | pre_softmax_attn = dots.clone() 668 | 669 | if talking_heads: 670 | dots = einsum('b h i j, h k -> b k i j', dots, self.pre_softmax_proj).contiguous() 671 | 672 | if self.rel_pos_bias: 673 | dots = self.rel_pos(dots) 674 | 675 | if exists(input_mask): 676 | dots.masked_fill_(~input_mask, mask_value) 677 | del input_mask 678 | 679 | if exists(attn_mask): 680 | assert 2 <= attn_mask.ndim <= 4, 'attention mask must have greater than 2 dimensions but less than or equal to 4' 681 | if attn_mask.ndim == 2: 682 | attn_mask = rearrange(attn_mask, 'i j -> () () i j') 683 | elif attn_mask.ndim == 3: 684 | attn_mask = rearrange(attn_mask, 'h i j -> () h i j') 685 | dots.masked_fill_(~attn_mask, mask_value) 686 | 687 | if exists(self.max_attend_past): 688 | i, j = dots.shape[-2:] 689 | range_q = torch.arange(j - i, j, device=device) 690 | range_k = torch.arange(j, device=device) 691 | dist = rearrange(range_q, 'i -> () () i ()') - rearrange(range_k, 'j -> () () () j') 692 | mask = dist > self.max_attend_past 693 | dots.masked_fill_(mask, mask_value) 694 | del mask 695 | 696 | if self.causal: 697 | i, j = dots.shape[-2:] 698 | r = torch.arange(i, device=device) 699 | mask = rearrange(r, 'i -> () () i ()') < rearrange(r, 'j -> () () () j') 700 | mask = F.pad(mask, (j - i, 0), value=False) 701 | dots.masked_fill_(mask, mask_value) 702 | del mask 703 | 704 | if exists(self.sparse_topk) and self.sparse_topk < dots.shape[-1]: 705 | top, _ = dots.topk(self.sparse_topk, dim=-1) 706 | vk = top[..., -1].unsqueeze(-1).expand_as(dots) 707 | mask = dots < vk 708 | dots.masked_fill_(mask, mask_value) 709 | del mask 710 | 711 | attn = self.attn_fn(dots, dim=-1) 712 | post_softmax_attn = attn.clone() 713 | 714 | attn = self.dropout(attn) 715 | 716 | if talking_heads: 717 | attn = einsum('b h i j, h k -> b k i j', attn, self.post_softmax_proj).contiguous() 718 | 719 | out = einsum('b h i j, b h j d -> b h i d', attn, v) 720 | 721 | if head_scale: 722 | out = out * self.head_scale_params 723 | 724 | out = rearrange(out, 'b h n d -> b n (h d)') 725 | 726 | if exists(self.to_v_gate): 727 | gates = self.to_v_gate(x) 728 | out = out * gates.sigmoid() 729 | 730 | intermediates = Intermediates( 731 | pre_softmax_attn=pre_softmax_attn, 732 | post_softmax_attn=post_softmax_attn 733 | ) 734 | 735 | return self.to_out(out), intermediates, k_cache, v_cache 736 | 737 | 738 | class AttentionLayers(nn.Module): 739 | def __init__( 740 | self, 741 | dim, 742 | depth, 743 | heads=8, 744 | causal=False, 745 | cross_attend=False, 746 | only_cross=False, 747 | use_scalenorm=False, 748 | use_rms_scaleshift_norm=False, 749 | use_rmsnorm=False, 750 | use_rezero=False, 751 | alibi_pos_bias=False, 752 | alibi_num_heads=None, 753 | alibi_learned=False, 754 | position_infused_attn=False, 755 | rotary_pos_emb=False, 756 | rotary_emb_dim=None, 757 | custom_layers=None, 758 | sandwich_coef=None, 759 | par_ratio=None, 760 | residual_attn=False, 761 | cross_residual_attn=False, 762 | macaron=False, 763 | pre_norm=True, 764 | gate_residual=False, 765 | scale_residual=False, 766 | shift_tokens=0, 767 | sandwich_norm=False, 768 | use_qk_norm_attn=False, 769 | qk_norm_attn_seq_len=None, 770 | zero_init_branch_output=False, 771 | **kwargs 772 | ): 773 | super().__init__() 774 | ff_kwargs, kwargs = groupby_prefix_and_trim('ff_', kwargs) 775 | attn_kwargs, _ = groupby_prefix_and_trim('attn_', kwargs) 776 | 777 | dim_head = attn_kwargs.get('dim_head', DEFAULT_DIM_HEAD) 778 | 779 | self.dim = dim 780 | self.depth = depth 781 | self.layers = nn.ModuleList([]) 782 | self.causal = causal 783 | 784 | rel_pos_bias = 'rel_pos_bias' in attn_kwargs 785 | self.has_pos_emb = position_infused_attn or rel_pos_bias or rotary_pos_emb 786 | self.pia_pos_emb = FixedPositionalEmbedding(dim) if position_infused_attn else None 787 | 788 | rotary_emb_dim = max(default(rotary_emb_dim, dim_head // 2), 32) 789 | self.rotary_pos_emb = RotaryEmbedding(rotary_emb_dim) if rotary_pos_emb else None 790 | 791 | assert not ( 792 | alibi_pos_bias and rel_pos_bias), 'you can only choose Alibi positional bias or T5 relative positional bias, not both' 793 | 794 | if alibi_pos_bias: 795 | alibi_num_heads = default(alibi_num_heads, heads) 796 | assert alibi_num_heads <= heads, 'number of ALiBi heads must be less than the total number of heads' 797 | alibi_pos_klass = LearnedAlibiPositionalBias if alibi_learned or not causal else AlibiPositionalBias 798 | self.rel_pos = alibi_pos_klass(heads=alibi_num_heads, bidirectional=not causal) 799 | else: 800 | self.rel_pos = None 801 | 802 | assert not (not pre_norm and sandwich_norm), 'sandwich norm cannot be used when not using prenorm' 803 | self.pre_norm = pre_norm 804 | self.sandwich_norm = sandwich_norm 805 | 806 | self.residual_attn = residual_attn 807 | self.cross_residual_attn = cross_residual_attn 808 | self.cross_attend = cross_attend 809 | 810 | norm_class = ScaleNorm if use_scalenorm else nn.LayerNorm 811 | norm_class = RMSNorm if use_rmsnorm else norm_class 812 | norm_class = RMSScaleShiftNorm if use_rms_scaleshift_norm else norm_class 813 | norm_fn = partial(norm_class, dim) 814 | 815 | norm_fn = nn.Identity if use_rezero else norm_fn 816 | branch_fn = Rezero if use_rezero else None 817 | 818 | if cross_attend and not only_cross: 819 | default_block = ('a', 'c', 'f') 820 | elif cross_attend and only_cross: 821 | default_block = ('c', 'f') 822 | else: 823 | default_block = ('a', 'f') 824 | 825 | if macaron: 826 | default_block = ('f',) + default_block 827 | 828 | # qk normalization 829 | 830 | if use_qk_norm_attn: 831 | attn_scale_init_value = -math.log(math.log2(qk_norm_attn_seq_len ** 2 - qk_norm_attn_seq_len)) if exists( 832 | qk_norm_attn_seq_len) else None 833 | attn_kwargs = {**attn_kwargs, 'qk_norm': True, 'scale_init_value': attn_scale_init_value} 834 | 835 | # zero init 836 | 837 | if zero_init_branch_output: 838 | attn_kwargs = {**attn_kwargs, 'zero_init_output': True} 839 | ff_kwargs = {**ff_kwargs, 'zero_init_output': True} 840 | 841 | # calculate layer block order 842 | 843 | if exists(custom_layers): 844 | layer_types = custom_layers 845 | elif exists(par_ratio): 846 | par_depth = depth * len(default_block) 847 | assert 1 < par_ratio <= par_depth, 'par ratio out of range' 848 | default_block = tuple(filter(not_equals('f'), default_block)) 849 | par_attn = par_depth // par_ratio 850 | depth_cut = par_depth * 2 // 3 # 2 / 3 attention layer cutoff suggested by PAR paper 851 | par_width = (depth_cut + depth_cut // par_attn) // par_attn 852 | assert len(default_block) <= par_width, 'default block is too large for par_ratio' 853 | par_block = default_block + ('f',) * (par_width - len(default_block)) 854 | par_head = par_block * par_attn 855 | layer_types = par_head + ('f',) * (par_depth - len(par_head)) 856 | elif exists(sandwich_coef): 857 | assert sandwich_coef > 0 and sandwich_coef <= depth, 'sandwich coefficient should be less than the depth' 858 | layer_types = ('a',) * sandwich_coef + default_block * (depth - sandwich_coef) + ('f',) * sandwich_coef 859 | else: 860 | layer_types = default_block * depth 861 | 862 | self.layer_types = layer_types 863 | self.num_attn_layers = len(list(filter(equals('a'), layer_types))) 864 | 865 | # calculate token shifting 866 | 867 | shift_tokens = cast_tuple(shift_tokens, len(layer_types)) 868 | 869 | # iterate and construct layers 870 | 871 | for ind, (layer_type, layer_shift_tokens) in enumerate(zip(self.layer_types, shift_tokens)): 872 | is_last_layer = ind == (len(self.layer_types) - 1) 873 | 874 | if layer_type == 'a': 875 | layer = Attention(dim, heads=heads, causal=causal, **attn_kwargs) 876 | elif layer_type == 'c': 877 | layer = Attention(dim, heads=heads, **attn_kwargs) 878 | elif layer_type == 'f': 879 | layer = FeedForward(dim, **ff_kwargs) 880 | layer = layer if not macaron else Scale(0.5, layer) 881 | else: 882 | raise Exception(f'invalid layer type {layer_type}') 883 | 884 | if layer_shift_tokens > 0: 885 | shift_range_upper = layer_shift_tokens + 1 886 | shift_range_lower = -layer_shift_tokens if not causal else 0 887 | layer = ShiftTokens(range(shift_range_lower, shift_range_upper), layer) 888 | 889 | if exists(branch_fn): 890 | layer = branch_fn(layer) 891 | 892 | residual_fn = GRUGating if gate_residual else Residual 893 | residual = residual_fn(dim, scale_residual=scale_residual) 894 | 895 | layer_uses_qk_norm = use_qk_norm_attn and layer_type in ('a', 'c') 896 | 897 | pre_branch_norm = norm_fn() if pre_norm and not layer_uses_qk_norm else None 898 | post_branch_norm = norm_fn() if sandwich_norm or layer_uses_qk_norm else None 899 | post_main_norm = norm_fn() if not pre_norm and not is_last_layer else None 900 | 901 | norms = nn.ModuleList([ 902 | pre_branch_norm, 903 | post_branch_norm, 904 | post_main_norm 905 | ]) 906 | 907 | self.layers.append(nn.ModuleList([ 908 | norms, 909 | layer, 910 | residual 911 | ])) 912 | 913 | def forward( 914 | self, 915 | x, 916 | context=None, 917 | full_context=None, # for passing a list of hidden states from an encoder 918 | mask=None, 919 | context_mask=None, 920 | attn_mask=None, 921 | mems=None, 922 | return_hiddens=False, 923 | norm_scale_shift_inp=None, 924 | past_key_values=None, 925 | expected_seq_len=None, 926 | ): 927 | 928 | assert not (self.cross_attend ^ (exists(context) or exists( 929 | full_context))), 'context must be passed in if cross_attend is set to True' 930 | assert context is None or full_context is None, 'only one of full_context or context can be provided' 931 | 932 | hiddens = [] 933 | intermediates = [] 934 | prev_attn = None 935 | prev_cross_attn = None 936 | 937 | mems = mems.copy() if exists(mems) else [None] * self.num_attn_layers 938 | norm_args = {} 939 | if exists(norm_scale_shift_inp): 940 | norm_args['norm_scale_shift_inp'] = norm_scale_shift_inp 941 | 942 | rotary_pos_emb = None 943 | if exists(self.rotary_pos_emb): 944 | if not self.training and self.causal: 945 | assert expected_seq_len is not None, "To decode a transformer with rotary embeddings, you must specify an `expected_seq_len`" 946 | elif expected_seq_len is None: 947 | expected_seq_len = 0 948 | seq_len = x.shape[1] 949 | if past_key_values is not None: 950 | seq_len += past_key_values[0][0].shape[-2] 951 | max_rotary_emb_length = max(list(map(lambda m: (m.shape[1] if exists(m) else 0) + seq_len, mems)) + [expected_seq_len]) 952 | rotary_pos_emb = self.rotary_pos_emb(max_rotary_emb_length, x.device) 953 | 954 | present_key_values = [] 955 | cross_attn_count = 0 956 | for ind, (layer_type, (norm, block, residual_fn)) in enumerate(zip(self.layer_types, self.layers)): 957 | if layer_type == 'a': 958 | layer_mem = mems.pop(0) if mems else None 959 | 960 | residual = x 961 | 962 | pre_branch_norm, post_branch_norm, post_main_norm = norm 963 | 964 | if exists(pre_branch_norm): 965 | x = pre_branch_norm(x, **norm_args) 966 | 967 | if layer_type == 'a' or layer_type == 'c': 968 | if past_key_values is not None: 969 | layer_kv = past_key_values.pop(0) 970 | layer_past = tuple(s.to(x.device) for s in layer_kv) 971 | else: 972 | layer_past = None 973 | 974 | if layer_type == 'a': 975 | out, inter, k, v = checkpoint(block, x, None, mask, None, attn_mask, self.pia_pos_emb, rotary_pos_emb, 976 | prev_attn, layer_mem, layer_past) 977 | elif layer_type == 'c': 978 | if exists(full_context): 979 | out, inter, k, v = checkpoint(block, x, full_context[cross_attn_count], mask, context_mask, None, None, 980 | None, prev_attn, None, layer_past) 981 | else: 982 | out, inter, k, v = checkpoint(block, x, context, mask, context_mask, None, None, None, prev_attn, None, layer_past) 983 | elif layer_type == 'f': 984 | out = checkpoint(block, x) 985 | 986 | if layer_type == 'a' or layer_type == 'c' and present_key_values is not None: 987 | present_key_values.append((k.detach(), v.detach())) 988 | 989 | if exists(post_branch_norm): 990 | out = post_branch_norm(out, **norm_args) 991 | 992 | x = residual_fn(out, residual) 993 | 994 | if layer_type in ('a', 'c'): 995 | intermediates.append(inter) 996 | 997 | if layer_type == 'a' and self.residual_attn: 998 | prev_attn = inter.pre_softmax_attn 999 | elif layer_type == 'c' and self.cross_residual_attn: 1000 | prev_cross_attn = inter.pre_softmax_attn 1001 | 1002 | if exists(post_main_norm): 1003 | x = post_main_norm(x, **norm_args) 1004 | 1005 | if layer_type == 'c': 1006 | cross_attn_count += 1 1007 | 1008 | if layer_type == 'f': 1009 | hiddens.append(x) 1010 | 1011 | if return_hiddens: 1012 | intermediates = LayerIntermediates( 1013 | hiddens=hiddens, 1014 | attn_intermediates=intermediates, 1015 | past_key_values=present_key_values 1016 | ) 1017 | 1018 | return x, intermediates 1019 | 1020 | return x 1021 | 1022 | 1023 | class Encoder(AttentionLayers): 1024 | def __init__(self, **kwargs): 1025 | assert 'causal' not in kwargs, 'cannot set causality on encoder' 1026 | super().__init__(causal=False, **kwargs) 1027 | 1028 | 1029 | class Decoder(AttentionLayers): 1030 | def __init__(self, **kwargs): 1031 | assert 'causal' not in kwargs, 'cannot set causality on decoder' 1032 | super().__init__(causal=True, **kwargs) 1033 | 1034 | 1035 | class CrossAttender(AttentionLayers): 1036 | def __init__(self, **kwargs): 1037 | super().__init__(cross_attend=True, only_cross=True, **kwargs) 1038 | 1039 | 1040 | class ViTransformerWrapper(nn.Module): 1041 | def __init__( 1042 | self, 1043 | *, 1044 | image_size, 1045 | patch_size, 1046 | attn_layers, 1047 | num_classes=None, 1048 | dropout=0., 1049 | emb_dropout=0. 1050 | ): 1051 | super().__init__() 1052 | assert isinstance(attn_layers, Encoder), 'attention layers must be an Encoder' 1053 | assert image_size % patch_size == 0, 'image dimensions must be divisible by the patch size' 1054 | dim = attn_layers.dim 1055 | num_patches = (image_size // patch_size) ** 2 1056 | patch_dim = 3 * patch_size ** 2 1057 | 1058 | self.patch_size = patch_size 1059 | 1060 | self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim)) 1061 | self.patch_to_embedding = nn.Linear(patch_dim, dim) 1062 | self.cls_token = nn.Parameter(torch.randn(1, 1, dim)) 1063 | self.dropout = nn.Dropout(emb_dropout) 1064 | 1065 | self.attn_layers = attn_layers 1066 | self.norm = nn.LayerNorm(dim) 1067 | self.mlp_head = FeedForward(dim, dim_out=num_classes, dropout=dropout) if exists(num_classes) else None 1068 | 1069 | def forward( 1070 | self, 1071 | img, 1072 | return_embeddings=False 1073 | ): 1074 | p = self.patch_size 1075 | 1076 | x = rearrange(img, 'b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1=p, p2=p) 1077 | x = self.patch_to_embedding(x) 1078 | b, n, _ = x.shape 1079 | 1080 | cls_tokens = repeat(self.cls_token, '() n d -> b n d', b=b) 1081 | x = torch.cat((cls_tokens, x), dim=1) 1082 | x = x + self.pos_embedding[:, :(n + 1)] 1083 | x = self.dropout(x) 1084 | 1085 | x = self.attn_layers(x) 1086 | x = self.norm(x) 1087 | 1088 | if not exists(self.mlp_head) or return_embeddings: 1089 | return x 1090 | 1091 | return self.mlp_head(x[:, 0]) 1092 | 1093 | 1094 | class TransformerWrapper(nn.Module): 1095 | def __init__( 1096 | self, 1097 | *, 1098 | num_tokens, 1099 | max_seq_len, 1100 | attn_layers, 1101 | emb_dim=None, 1102 | max_mem_len=0., 1103 | shift_mem_down=0, 1104 | emb_dropout=0., 1105 | num_memory_tokens=None, 1106 | tie_embedding=False, 1107 | use_pos_emb=True 1108 | ): 1109 | super().__init__() 1110 | assert isinstance(attn_layers, AttentionLayers), 'attention layers must be one of Encoder or Decoder' 1111 | 1112 | dim = attn_layers.dim 1113 | emb_dim = default(emb_dim, dim) 1114 | 1115 | self.max_seq_len = max_seq_len 1116 | self.max_mem_len = max_mem_len 1117 | self.shift_mem_down = shift_mem_down 1118 | 1119 | self.token_emb = nn.Embedding(num_tokens, emb_dim) 1120 | self.pos_emb = AbsolutePositionalEmbedding(emb_dim, max_seq_len) if ( 1121 | use_pos_emb and not attn_layers.has_pos_emb) else always(0) 1122 | self.emb_dropout = nn.Dropout(emb_dropout) 1123 | 1124 | self.project_emb = nn.Linear(emb_dim, dim) if emb_dim != dim else nn.Identity() 1125 | self.attn_layers = attn_layers 1126 | self.norm = nn.LayerNorm(dim) 1127 | 1128 | self.init_() 1129 | 1130 | self.to_logits = nn.Linear(dim, num_tokens) if not tie_embedding else lambda t: t @ self.token_emb.weight.t() 1131 | 1132 | # memory tokens (like [cls]) from Memory Transformers paper 1133 | num_memory_tokens = default(num_memory_tokens, 0) 1134 | self.num_memory_tokens = num_memory_tokens 1135 | if num_memory_tokens > 0: 1136 | self.memory_tokens = nn.Parameter(torch.randn(num_memory_tokens, dim)) 1137 | 1138 | def init_(self): 1139 | nn.init.kaiming_normal_(self.token_emb.weight) 1140 | 1141 | def forward( 1142 | self, 1143 | x, 1144 | return_embeddings=False, 1145 | mask=None, 1146 | return_hiddens=False, 1147 | return_attn=False, 1148 | mems=None, 1149 | use_cache=False, 1150 | **kwargs 1151 | ): 1152 | b, n, device, num_mem = *x.shape, x.device, self.num_memory_tokens 1153 | x = self.token_emb(x) 1154 | x = x + self.pos_emb(x) 1155 | x = self.emb_dropout(x) 1156 | 1157 | x = self.project_emb(x) 1158 | 1159 | if num_mem > 0: 1160 | mem = repeat(self.memory_tokens, 'n d -> b n d', b=b) 1161 | x = torch.cat((mem, x), dim=1) 1162 | 1163 | # auto-handle masking after appending memory tokens 1164 | if exists(mask): 1165 | mask = F.pad(mask, (num_mem, 0), value=True) 1166 | 1167 | if self.shift_mem_down and exists(mems): 1168 | mems_l, mems_r = mems[:self.shift_mem_down], mems[self.shift_mem_down:] 1169 | mems = [*mems_r, *mems_l] 1170 | 1171 | x, intermediates = self.attn_layers(x, mask=mask, mems=mems, return_hiddens=True, **kwargs) 1172 | x = self.norm(x) 1173 | 1174 | mem, x = x[:, :num_mem], x[:, num_mem:] 1175 | 1176 | out = self.to_logits(x) if not return_embeddings else x 1177 | 1178 | if return_hiddens: 1179 | hiddens = intermediates.hiddens 1180 | return out, hiddens 1181 | 1182 | res = [out] 1183 | if return_attn: 1184 | attn_maps = list(map(lambda t: t.post_softmax_attn, intermediates.attn_intermediates)) 1185 | res.append(attn_maps) 1186 | if use_cache: 1187 | res.append(intermediates.past_key_values) 1188 | 1189 | if len(res) > 1: 1190 | return tuple(res) 1191 | return res[0] 1192 | 1193 | 1194 | class ContinuousTransformerWrapper(nn.Module): 1195 | def __init__( 1196 | self, 1197 | *, 1198 | max_seq_len, 1199 | attn_layers, 1200 | dim_in=None, 1201 | dim_out=None, 1202 | emb_dim=None, 1203 | emb_dropout=0., 1204 | use_pos_emb=True 1205 | ): 1206 | super().__init__() 1207 | assert isinstance(attn_layers, AttentionLayers), 'attention layers must be one of Encoder or Decoder' 1208 | 1209 | dim = attn_layers.dim 1210 | 1211 | self.max_seq_len = max_seq_len 1212 | 1213 | self.pos_emb = AbsolutePositionalEmbedding(dim, max_seq_len) if ( 1214 | use_pos_emb and not attn_layers.has_pos_emb) else always(0) 1215 | self.emb_dropout = nn.Dropout(emb_dropout) 1216 | 1217 | self.project_in = nn.Linear(dim_in, dim) if exists(dim_in) else nn.Identity() 1218 | 1219 | self.attn_layers = attn_layers 1220 | self.norm = nn.LayerNorm(dim) 1221 | 1222 | self.project_out = nn.Linear(dim, dim_out) if exists(dim_out) else nn.Identity() 1223 | 1224 | def forward( 1225 | self, 1226 | x, 1227 | return_embeddings=False, 1228 | mask=None, 1229 | return_attn=False, 1230 | mems=None, 1231 | use_cache=False, 1232 | **kwargs 1233 | ): 1234 | b, n, _, device = *x.shape, x.device 1235 | 1236 | x = self.project_in(x) 1237 | x = x + self.pos_emb(x) 1238 | x = self.emb_dropout(x) 1239 | 1240 | x, intermediates = self.attn_layers(x, mask=mask, mems=mems, return_hiddens=True, **kwargs) 1241 | x = self.norm(x) 1242 | 1243 | out = self.project_out(x) if not return_embeddings else x 1244 | 1245 | res = [out] 1246 | if return_attn: 1247 | attn_maps = list(map(lambda t: t.post_softmax_attn, intermediates.attn_intermediates)) 1248 | res.append(attn_maps) 1249 | if use_cache: 1250 | res.append(intermediates.past_key_values) 1251 | 1252 | if len(res) > 1: 1253 | return tuple(res) 1254 | return res[0] 1255 | 1256 | 1257 | class XTransformer(nn.Module): 1258 | def __init__( 1259 | self, 1260 | *, 1261 | dim, 1262 | tie_token_emb=False, 1263 | **kwargs 1264 | ): 1265 | super().__init__() 1266 | enc_kwargs, kwargs = groupby_prefix_and_trim('enc_', kwargs) 1267 | dec_kwargs, kwargs = groupby_prefix_and_trim('dec_', kwargs) 1268 | 1269 | assert 'dim' not in enc_kwargs and 'dim' not in dec_kwargs, 'dimension of either encoder or decoder must be set with `dim` keyword' 1270 | enc_transformer_kwargs = pick_and_pop(['num_tokens', 'max_seq_len'], enc_kwargs) 1271 | enc_transformer_kwargs['emb_dropout'] = enc_kwargs.pop('emb_dropout', 0) 1272 | enc_transformer_kwargs['num_memory_tokens'] = enc_kwargs.pop('num_memory_tokens', None) 1273 | enc_transformer_kwargs['use_pos_emb'] = enc_kwargs.pop('use_pos_emb', True) 1274 | 1275 | dec_transformer_kwargs = pick_and_pop(['num_tokens', 'max_seq_len'], dec_kwargs) 1276 | dec_transformer_kwargs['emb_dropout'] = dec_kwargs.pop('emb_dropout', 0) 1277 | dec_transformer_kwargs['use_pos_emb'] = dec_kwargs.pop('use_pos_emb', True) 1278 | 1279 | self.encoder = TransformerWrapper( 1280 | **enc_transformer_kwargs, 1281 | attn_layers=Encoder(dim=dim, **enc_kwargs) 1282 | ) 1283 | 1284 | self.decoder = TransformerWrapper( 1285 | **dec_transformer_kwargs, 1286 | attn_layers=Decoder(dim=dim, cross_attend=True, **dec_kwargs) 1287 | ) 1288 | 1289 | if tie_token_emb: 1290 | self.decoder.token_emb = self.encoder.token_emb 1291 | 1292 | self.decoder = AutoregressiveWrapper(self.decoder) 1293 | 1294 | @torch.no_grad() 1295 | def generate(self, seq_in, seq_out_start, seq_len, src_mask=None, src_attn_mask=None, **kwargs): 1296 | encodings = self.encoder(seq_in, mask=src_mask, attn_mask=src_attn_mask, return_embeddings=True) 1297 | return self.decoder.generate(seq_out_start, seq_len, context=encodings, context_mask=src_mask, **kwargs) 1298 | 1299 | def forward(self, src, tgt, src_mask=None, tgt_mask=None, src_attn_mask=None): 1300 | enc = self.encoder(src, mask=src_mask, attn_mask=src_attn_mask, return_embeddings=True) 1301 | out = self.decoder(tgt, context=enc, mask=tgt_mask, context_mask=src_mask) 1302 | return out 1303 | -------------------------------------------------------------------------------- /tts_scores/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import torch 4 | import torchaudio 5 | from torch import nn 6 | import numpy as np 7 | from scipy.io.wavfile import read 8 | 9 | 10 | def load_wav_to_torch(full_path): 11 | sampling_rate, data = read(full_path) 12 | if data.dtype == np.int32: 13 | norm_fix = 2 ** 31 14 | elif data.dtype == np.int16: 15 | norm_fix = 2 ** 15 16 | elif data.dtype == np.float16 or data.dtype == np.float32: 17 | norm_fix = 1. 18 | else: 19 | raise NotImplemented(f"Provided data dtype not supported: {data.dtype}") 20 | return (torch.FloatTensor(data.astype(np.float32)) / norm_fix, sampling_rate) 21 | 22 | 23 | def load_audio(audiopath, sampling_rate): 24 | if audiopath[-4:] == '.wav': 25 | audio, lsr = load_wav_to_torch(audiopath) 26 | else: 27 | raise RuntimeError 28 | 29 | # Remove any channel data. 30 | if len(audio.shape) > 1: 31 | if audio.shape[0] < 5: 32 | audio = audio[0] 33 | else: 34 | assert audio.shape[1] < 5 35 | audio = audio[:, 0] 36 | 37 | if lsr != sampling_rate: 38 | audio = torchaudio.functional.resample(audio, lsr, sampling_rate) 39 | 40 | # Check some assumptions about audio range. This should be automatically fixed in load_wav_to_torch, but might not be in some edge cases, where we should squawk. 41 | # '2' is arbitrarily chosen since it seems like audio will often "overdrive" the [-1,1] bounds. 42 | if torch.any(audio > 2) or not torch.any(audio < 0): 43 | print(f"Error with {audiopath}. Max={audio.max()} min={audio.min()}") 44 | audio.clip_(-1, 1) 45 | 46 | return audio.unsqueeze(0) 47 | 48 | 49 | def load_tsv(filename): 50 | with open(filename, encoding='utf-8') as f: 51 | filepaths_and_text = [] 52 | base = os.path.dirname(filename) 53 | for line in f: 54 | components = line.strip().split('\t') 55 | filepaths_and_text.append([os.path.join(base, f'{components[1]}'), components[0]]) 56 | return filepaths_and_text 57 | 58 | 59 | class TorchMelSpectrogram(nn.Module): 60 | def __init__(self, filter_length=1024, hop_length=256, win_length=1024, n_mel_channels=80, mel_fmin=0, mel_fmax=8000, 61 | sampling_rate=22050, normalize=False, mel_norm_file='.data/mel_norms.pth'): 62 | super().__init__() 63 | # These are the default tacotron values for the MEL spectrogram. 64 | self.filter_length = filter_length 65 | self.hop_length = hop_length 66 | self.win_length = win_length 67 | self.n_mel_channels = n_mel_channels 68 | self.mel_fmin = mel_fmin 69 | self.mel_fmax = mel_fmax 70 | self.sampling_rate = sampling_rate 71 | self.mel_stft = torchaudio.transforms.MelSpectrogram(n_fft=self.filter_length, hop_length=self.hop_length, 72 | win_length=self.win_length, power=2, normalized=normalize, 73 | sample_rate=self.sampling_rate, f_min=self.mel_fmin, 74 | f_max=self.mel_fmax, n_mels=self.n_mel_channels, 75 | norm="slaney") 76 | self.mel_norm_file = mel_norm_file 77 | if self.mel_norm_file is not None: 78 | self.mel_norms = torch.load(self.mel_norm_file) 79 | else: 80 | self.mel_norms = None 81 | 82 | def forward(self, inp): 83 | if len(inp.shape) == 3: # Automatically squeeze out the channels dimension if it is present (assuming mono-audio) 84 | inp = inp.squeeze(1) 85 | assert len(inp.shape) == 2 86 | self.mel_stft = self.mel_stft.to(inp.device) 87 | mel = self.mel_stft(inp) 88 | # Perform dynamic range compression 89 | mel = torch.log(torch.clamp(mel, min=1e-5)) 90 | if self.mel_norms is not None: 91 | self.mel_norms = self.mel_norms.to(mel.device) 92 | mel = mel / self.mel_norms.unsqueeze(0).unsqueeze(-1) 93 | return mel 94 | 95 | 96 | def to_mel(wav): 97 | return TorchMelSpectrogram()(wav.unsqueeze(0)).squeeze(0) --------------------------------------------------------------------------------