├── .gitignore ├── LICENSE ├── README.md ├── asv-subtools_license ├── attention.py ├── config.yaml ├── dataset.py ├── model.py ├── path.sh ├── run.sh ├── siamese-triplet_license └── train.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2020, Yamagishi Laboratory, National Institute of Informatics 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | 3. Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Attention_Backend_for_ASV 2 | Attention Backend for Automatic Speaker Verification with Multiple Enrollment Utterances 3 | 4 | It contains the official implementation of the paper [Attention Back-end for Automatic Speaker Verification with Multiple Enrollment Utterances](https://arxiv.org/abs/2104.01541) 5 | 6 | ## Authors 7 | 8 | - Chang Zeng 9 | - Xin Wang 10 | - Erica Cooper 11 | - [Junichi Yamagishi](https://nii-yamagishilab.github.io/) 12 | 13 | ## Requirements 14 | 15 | 1. Kaldi. And set kaldi path in `path.sh` and `run.sh` according to the instruction in these files. 16 | 2. Pytorch >= 1.0.0 17 | 3. Numpy 18 | 19 | ## Data 20 | 21 | You can download the data from this [link](https://dubox.com/s/1m8n3h7zP4lr1UA64aFYPfQ). (People from China mainland may need a VPN to download the data) 22 | 23 | Password: e2de. 24 | 25 | It contains x-vectors extracted by the script of cnceleb example in Kaldi (train_xv, enroll_xv, eval_xv) 26 | 27 | - x-vectors are extracted from the [CN-Celeb database](http://www.openslr.org/82/) owned by the Tsinghua University. 28 | 29 | - x-vectors are distributed under the CC BY-SA license. 30 | 31 | ## Usage 32 | 33 | 1. Install all requirements. 34 | 35 | - Pytorch and Numpy for training 36 | 37 | - Kaldi for evaluation (EER and minDCF computation) 38 | 39 | 2. Create a directory for exp. 40 | 41 | ``` 42 | mkdir attention_backend_exp 43 | ``` 44 | 45 | 3. Download the data (x-vectors) from above link and put it in `attention_backend_exp` directory. 46 | 47 | 4. Clone this repo 48 | 49 | ``` 50 | cd attention_backend_exp 51 | git clone https://github.com/nii-yamagishilab/Attention_Backend_for_ASV.git 52 | ``` 53 | 54 | 5. Run the following command for training and scoring 55 | 56 | ``` 57 | python3 train.py 58 | ``` 59 | 60 | This script will generate exp log directory in `exp` for each training process. The directory is named by the time when you run this code. You can also resume training process by set the model path in exp log directory in `config.yaml` file. 61 | 62 | 6. EER and minDCF compuation 63 | 64 | ``` 65 | ./run.sh exp_log_directory 66 | ``` 67 | 68 | ## Results 69 | 70 | ![image-20210411134608804](https://i.loli.net/2021/04/11/hmEyBCFvSIbJ4Ro.png) 71 | 72 | **Note**: This code only for X-Vectors extracted from TDNN. 73 | 74 | ## To do 75 | 76 | - [ ] TD-ASV (RedDots) 77 | 78 | - [ ] Change score method from cosine similarity to PLDA-like score 79 | 80 | - [ ] Breakdown results per domain (genre) in CN-Celeb 81 | 82 | ## Acknowlegment 83 | 84 | This study is supported by JST CREST Grants (JPMJCR18A6, JPMJCR20D3), MEXT KAKENHI Grants (16H06302, 18H04120, 18H04112, 18KT0051), Japan, and Google AI for Japan program. 85 | 86 | 87 | This project used some code snippets from following repo: 88 | 89 | - `dataset.py` implemented `BalancedBatchSampler` class from [siamese-triplet](https://github.com/adambielski/siamese-triplet). The corresponding license file is `siamese-triplet_license`. 90 | - `attention.py` implemented `AttentionAlphaComponent` class from [asv-subtools](https://github.com/Snowdar/asv-subtools). The corresponding license file is `asv-subtools_license`. 91 | 92 | ## Citation 93 | 94 | ``` 95 | @inproceedings{zeng2022attention, 96 | title={Attention back-end for automatic speaker verification with multiple enrollment utterances}, 97 | author={Zeng, Chang and Wang, Xin and Cooper, Erica and Miao, Xiaoxiao and Yamagishi, Junichi}, 98 | booktitle={ICASSP 2022-2022 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)}, 99 | pages={6717--6721}, 100 | year={2022}, 101 | organization={IEEE} 102 | } 103 | ``` 104 | 105 | ## License 106 | 107 | BSD 3-Clause License 108 | 109 | Copyright (c) 2020, Yamagishi Laboratory, National Institute of Informatics All rights reserved. 110 | 111 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 112 | 113 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 114 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 115 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 116 | 117 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 118 | -------------------------------------------------------------------------------- /asv-subtools_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 | -------------------------------------------------------------------------------- /attention.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | from torch import Tensor 6 | import numpy as np 7 | from typing import Optional, Tuple 8 | 9 | class TdnnAffine(torch.nn.Module): 10 | """ An implemented tdnn affine component by conv1d 11 | y = splice(w * x, context) + b 12 | @input_dim: number of dims of frame <=> inputs channels of conv 13 | @output_dim: number of layer nodes <=> outputs channels of conv 14 | @context: a list of context 15 | e.g. [-2,0,2] 16 | If context is [0], then the TdnnAffine is equal to linear layer. 17 | """ 18 | def __init__(self, input_dim, output_dim, context=[0], bias=True, pad=True, stride=1, groups=1, norm_w=False, norm_f=False): 19 | super(TdnnAffine, self).__init__() 20 | assert input_dim % groups == 0 21 | # Check to make sure the context sorted and has no duplicated values 22 | for index in range(0, len(context) - 1): 23 | if(context[index] >= context[index + 1]): 24 | raise ValueError("Context tuple {} is invalid, such as the order.".format(context)) 25 | 26 | self.input_dim = input_dim 27 | self.output_dim = output_dim 28 | self.context = context 29 | self.bool_bias = bias 30 | self.pad = pad 31 | self.groups = groups 32 | 33 | self.norm_w = norm_w 34 | self.norm_f = norm_f 35 | 36 | # It is used to subsample frames with this factor 37 | self.stride = stride 38 | 39 | self.left_context = context[0] if context[0] < 0 else 0 40 | self.right_context = context[-1] if context[-1] > 0 else 0 41 | 42 | self.tot_context = self.right_context - self.left_context + 1 43 | 44 | # Do not support sphereConv now. 45 | if self.tot_context > 1 and self.norm_f: 46 | self.norm_f = False 47 | print("Warning: do not support sphereConv now and set norm_f=False.") 48 | 49 | kernel_size = (self.tot_context,) 50 | 51 | self.weight = torch.nn.Parameter(torch.randn(output_dim, input_dim//groups, *kernel_size)) 52 | 53 | if self.bool_bias: 54 | self.bias = torch.nn.Parameter(torch.randn(output_dim)) 55 | else: 56 | self.register_parameter('bias', None) 57 | 58 | # init weight and bias. It is important 59 | self.init_weight() 60 | 61 | # Save GPU memory for no skiping case 62 | if len(context) != self.tot_context: 63 | # Used to skip some frames index according to context 64 | self.mask = torch.tensor([[[ 1 if index in context else 0 \ 65 | for index in range(self.left_context, self.right_context + 1) ]]]) 66 | else: 67 | self.mask = None 68 | 69 | ## Deprecated: the broadcast method could be used to save GPU memory, 70 | # self.mask = torch.randn(output_dim, input_dim, 0) 71 | # for index in range(self.left_context, self.right_context + 1): 72 | # if index in context: 73 | # fixed_value = torch.ones(output_dim, input_dim, 1) 74 | # else: 75 | # fixed_value = torch.zeros(output_dim, input_dim, 1) 76 | 77 | # self.mask=torch.cat((self.mask, fixed_value), dim = 2) 78 | 79 | # Save GPU memory of thi case. 80 | 81 | self.selected_device = False 82 | 83 | def init_weight(self): 84 | # Note, var should be small to avoid slow-shrinking 85 | torch.nn.init.normal_(self.weight, 0., 0.01) 86 | 87 | if self.bias is not None: 88 | torch.nn.init.constant_(self.bias, 0.) 89 | 90 | 91 | def forward(self, inputs): 92 | """ 93 | @inputs: a 3-dimensional tensor (a batch), including [samples-index, frames-dim-index, frames-index] 94 | """ 95 | assert len(inputs.shape) == 3 96 | assert inputs.shape[1] == self.input_dim 97 | 98 | # Do not use conv1d.padding for self.left_context + self.right_context != 0 case. 99 | if self.pad: 100 | inputs = F.pad(inputs, (-self.left_context, self.right_context), mode="constant", value=0) 101 | 102 | assert inputs.shape[2] >= self.tot_context 103 | 104 | if not self.selected_device and self.mask is not None: 105 | # To save the CPU -> GPU moving time 106 | # Another simple case, for a temporary tensor, jus specify the device when creating it. 107 | # such as, this_tensor = torch.tensor([1.0], device=inputs.device) 108 | self.mask = to_device(self, self.mask) 109 | self.selected_device = True 110 | 111 | filters = self.weight * self.mask if self.mask is not None else self.weight 112 | 113 | if self.norm_w: 114 | filters = F.normalize(filters, dim=1) 115 | 116 | if self.norm_f: 117 | inputs = F.normalize(inputs, dim=1) 118 | 119 | outputs = F.conv1d(inputs, filters, self.bias, stride=self.stride, padding=0, dilation=1, groups=self.groups) 120 | 121 | return outputs 122 | 123 | def extra_repr(self): 124 | return '{input_dim}, {output_dim}, context={context}, bias={bool_bias}, stride={stride}, ' \ 125 | 'pad={pad}, groups={groups}, norm_w={norm_w}, norm_f={norm_f}'.format(**self.__dict__) 126 | 127 | @classmethod 128 | def thop_count(self, m, x, y): 129 | x = x[0] 130 | 131 | kernel_ops = torch.zeros(m.weight.size()[2:]).numel() # Kw x Kh 132 | bias_ops = 1 if m.bias is not None else 0 133 | 134 | # N x Cout x H x W x (Cin x Kw x Kh + bias) 135 | total_ops = y.nelement() * (m.input_dim * kernel_ops + bias_ops) 136 | 137 | m.total_ops += torch.DoubleTensor([int(total_ops)]) 138 | 139 | # Attention-based 140 | class AttentionAlphaComponent(torch.nn.Module): 141 | """Compute the alpha with attention module. 142 | alpha = softmax(v'·f(w·x + b) + k) or softmax(v'·x + k) 143 | where f is relu here and bias could be lost. 144 | Support: 145 | 1. Single or Multi-head attention 146 | 2. One affine or two affine 147 | 3. Share weight (last affine = vector) or un-shared weight (last affine = matrix) 148 | 4. Self-attention or time context attention (supported by context parameter of TdnnAffine) 149 | 5. Different temperatures for different heads. 150 | """ 151 | def __init__(self, input_dim, num_head=1, split_input=True, share=True, affine_layers=2, 152 | hidden_size=64, context=[0], bias=True, temperature=False, fixed=True): 153 | super(AttentionAlphaComponent, self).__init__() 154 | assert num_head >= 1 155 | # Multi-head case. 156 | if num_head > 1: 157 | if split_input: 158 | # Make sure fatures/planes with input_dim dims could be splited to num_head parts. 159 | assert input_dim % num_head == 0 160 | if temperature: 161 | if fixed: 162 | t_list = [] 163 | for i in range(num_head): 164 | t_list.append([[max(1, (i // 2) * 5)]]) 165 | # shape [1, num_head, 1, 1] 166 | self.register_buffer('t', torch.tensor([t_list])) 167 | else: 168 | # Different heads have different temperature. 169 | # Use 1 + self.t**2 in forward to make sure temperature >= 1. 170 | self.t = torch.nn.Parameter(torch.zeros(1, num_head, 1, 1)) 171 | 172 | self.input_dim = input_dim 173 | self.num_head = num_head 174 | self.split_input = split_input 175 | self.share = share 176 | self.temperature = temperature 177 | self.fixed = fixed 178 | 179 | if share: 180 | # weight: [input_dim, 1] or [input_dim, hidden_size] -> [hidden_size, 1] 181 | final_dim = 1 182 | elif split_input: 183 | # weight: [input_dim, input_dim // num_head] or [input_dim, hidden_size] -> [hidden_size, input_dim // num_head] 184 | final_dim = input_dim // num_head 185 | else: 186 | # weight: [input_dim, input_dim] or [input_dim, hidden_size] -> [hidden_size, input_dim] 187 | final_dim = input_dim 188 | 189 | first_groups = 1 190 | last_groups = 1 191 | 192 | if affine_layers == 1: 193 | last_affine_input_dim = input_dim 194 | # (x, 1) for global case and (x, h) for split case. 195 | if num_head > 1 and split_input: 196 | last_groups = num_head 197 | self.relu_affine = False 198 | elif affine_layers == 2: 199 | last_affine_input_dim = hidden_size * num_head 200 | if num_head > 1: 201 | # (1, h) for global case and (h, h) for split case. 202 | last_groups = num_head 203 | if split_input: 204 | first_groups = num_head 205 | # Add a relu-affine with affine_layers=2. 206 | self.relu_affine = True 207 | self.first_affine = TdnnAffine(input_dim, last_affine_input_dim, context=context, bias=bias, groups=first_groups) 208 | # self.first_affine = torch.nn.Linear(input_dim, last_affine_input_dim) 209 | self.relu = torch.nn.ReLU(inplace=True) 210 | else: 211 | raise ValueError("Expected 1 or 2 affine layers, but got {}.",format(affine_layers)) 212 | 213 | self.last_affine = TdnnAffine(last_affine_input_dim, final_dim * num_head, context=context, bias=bias, groups=last_groups) 214 | # self.last_affine = torch.nn.Linear(last_affine_input_dim, final_dim * num_head) 215 | # Dim=2 means to apply softmax in different frames-index (batch is a 3-dim tensor in this case). 216 | self.softmax = torch.nn.Softmax(dim=2) 217 | 218 | def forward(self, inputs): 219 | """ 220 | @inputs: a 3-dimensional tensor (a batch), including [samples-index, frames-dim-index, frames-index] 221 | """ 222 | assert len(inputs.shape) == 3 223 | assert inputs.shape[1] == self.input_dim 224 | 225 | if self.temperature: 226 | batch_size = inputs.shape[0] 227 | chunk_size = inputs.shape[2] 228 | 229 | x = inputs 230 | if self.relu_affine: 231 | x = self.relu(self.first_affine(x)) 232 | if self.num_head > 1 and self.temperature: 233 | if self.fixed: 234 | t = self.t 235 | else: 236 | t = 1 + self.t**2 237 | x = self.last_affine(x).reshape(batch_size, self.num_head, -1, chunk_size) / t 238 | return self.softmax(x.reshape(batch_size, -1, chunk_size)) 239 | else: 240 | return self.softmax(self.last_affine(x)) 241 | -------------------------------------------------------------------------------- /config.yaml: -------------------------------------------------------------------------------- 1 | dataset: 2 | train_path: ../data/train 3 | enroll_path: ../data/enroll_mean 4 | eval_path: ../data/eval 5 | n_spks: 16 6 | n_utts: 5 7 | 8 | model: 9 | d_model: 512 10 | head: 2 11 | pooling: mha 12 | 13 | lr: 0.01 14 | resume: None 15 | epochs: 40 16 | milestones: [20, 32] 17 | -------------------------------------------------------------------------------- /dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | 4 | from torch.utils.data import Dataset, DataLoader, BatchSampler 5 | import numpy as np 6 | import torch 7 | 8 | class EmbeddingTrainDataset(Dataset): 9 | def __init__(self, opts): 10 | path = opts['train_path'] 11 | self.dataset = [] 12 | self.count = 0 13 | self.labels = [] 14 | spk_idx = 0 15 | for speaker in os.listdir(path): 16 | speaker_path = os.path.join(path, speaker) 17 | embeddings = os.listdir(speaker_path) 18 | if len(embeddings) > 30: 19 | for embedding in embeddings: 20 | self.dataset.append(os.path.join(speaker_path, embedding)) 21 | self.labels.append(spk_idx) 22 | spk_idx += 1 23 | 24 | def __len__(self): 25 | return len(self.dataset) * 5 # form more trials 26 | 27 | def __getitem__(self, idx): 28 | embedding_path = self.dataset[idx] 29 | sid = self.labels[idx] 30 | embedding = np.load(embedding_path) 31 | return embedding, sid 32 | 33 | class EmbeddingEnrollDataset(Dataset): 34 | def __init__(self, opts): 35 | path = opts['enroll_path'] 36 | self.dataset = [] 37 | self.count = 0 38 | self.labels = [] 39 | spk_idx = 0 40 | for speaker in os.listdir(path): 41 | speaker_path = os.path.join(path, speaker) 42 | self.dataset.append(speaker_path) 43 | 44 | def __len__(self): 45 | return len(self.dataset) 46 | 47 | def __getitem__(self, idx): 48 | speaker_path = self.dataset[idx] 49 | embeddings = os.listdir(speaker_path) 50 | all_embeddings = [] 51 | for embedding in embeddings: 52 | embedding_path = os.path.join(speaker_path, embedding) 53 | embedding = np.load(embedding_path) 54 | all_embeddings.append(embedding.reshape(-1)) 55 | embedding = torch.from_numpy(np.array(all_embeddings)) 56 | return embedding.unsqueeze(0), os.path.basename(speaker_path) 57 | 58 | def __call__(self): 59 | idx = 0 60 | while idx < len(self.dataset): 61 | embedding, spk = self.__getitem__(idx) 62 | yield embedding, spk 63 | idx += 1 64 | 65 | class BalancedBatchSampler(BatchSampler): 66 | """ 67 | BatchSampler - from a MNIST-like dataset, samples n_classes and within these classes samples n_samples. 68 | Returns batches of size n_classes * n_samples 69 | """ 70 | 71 | def __init__(self, labels, all_speech, n_classes, n_samples): 72 | self.labels = np.array(labels) 73 | self.labels_set = list(set(self.labels)) 74 | self.label_to_indices = {label: np.where(self.labels == label)[0] 75 | for label in self.labels_set} 76 | for l in self.labels_set: 77 | np.random.shuffle(self.label_to_indices[l]) 78 | self.used_label_indices_count = {label: 0 for label in self.labels_set} 79 | self.count = 0 80 | self.n_classes = n_classes 81 | self.n_samples = n_samples 82 | self.n_dataset = all_speech 83 | self.batch_size = self.n_samples * self.n_classes 84 | 85 | def __iter__(self): 86 | self.count = 0 87 | while self.count + self.batch_size < self.n_dataset: 88 | classes = np.random.choice(self.labels_set, self.n_classes, replace=False) 89 | indices = [] 90 | for class_ in classes: 91 | indices.extend(self.label_to_indices[class_][ 92 | self.used_label_indices_count[class_]:self.used_label_indices_count[ 93 | class_] + self.n_samples]) 94 | self.used_label_indices_count[class_] += self.n_samples 95 | if self.used_label_indices_count[class_] + self.n_samples > len(self.label_to_indices[class_]): 96 | np.random.shuffle(self.label_to_indices[class_]) 97 | self.used_label_indices_count[class_] = 0 98 | yield indices 99 | self.count += self.n_classes * self.n_samples 100 | 101 | def __len__(self): 102 | return self.n_dataset // self.batch_size 103 | -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | from attention import AttentionAlphaComponent 6 | import copy 7 | import math 8 | 9 | def mean(x, dim = 0): 10 | return torch.mean(x, dim = dim) 11 | 12 | class AttentionAggregation(nn.Module): 13 | def __init__(self, opts): 14 | super(AttentionAggregation, self).__init__() 15 | self.head = opts['head'] 16 | self.d_model = opts['d_model'] 17 | self.pooling = opts['pooling'] 18 | self.attention_transformation = nn.MultiheadAttention(self.d_model, self.head) 19 | if self.pooling == 'mean': 20 | self.aggregation = mean 21 | elif self.pooling == 'mha': 22 | self.aggregation = AttentionAlphaComponent(self.d_model, self.head) 23 | self.logistic = nn.Linear(1, 1) 24 | self.sigmoid = nn.Sigmoid() 25 | 26 | def merge(self, x): 27 | ''' 28 | params: 29 | x: (N, M, D), N speakers, M utterances per speaker, D dimension 30 | ''' 31 | assert len(x.size()) == 3 32 | n_spks, n_utts, dimension = x.size() 33 | x = x.repeat(1, n_utts, 1) 34 | mask = torch.logical_not(torch.eye(n_utts)).repeat(n_spks, 1).view(-1).to(x.device) 35 | masked_x = x.view(-1, self.d_model)[mask].contiguous().view(n_spks * n_utts, -1, self.d_model) 36 | masked_x = masked_x.transpose(0, 1).contiguous() # n_utts - 1, n_spks * n_utts, dimension 37 | x, _ = self.attention_transformation(masked_x, masked_x, masked_x, None) # n_utts - 1, n_spks * n_utts, dimension 38 | x = x + masked_x 39 | if self.pooling == 'mean': 40 | aggregation = mean(x) # (n_spks * (n_utts - 1), dimension), n_spks * (n_utts - 1) 41 | else: 42 | x = x.permute(1, 2, 0) # n_spks * n_utts, dimension, n_utts - 1 43 | alpha = self.aggregation(x) 44 | aggregation = x.view(n_spks * n_utts, self.head, self.d_model // self.head, -1).matmul(alpha.unsqueeze(-1)).view(n_spks * n_utts, self.d_model) 45 | return aggregation 46 | 47 | def forward(self, x): 48 | ''' 49 | params: 50 | x: (N, M, D), N speakers, M utterances per speaker, D dimension 51 | ''' 52 | n_spks, n_utts, dimension = x.size() 53 | aggregation = self.merge(x) # obtain n_spks * n_utts centers 54 | x = x.view(-1, self.d_model) 55 | cosine_score_matrix = F.normalize(x).matmul(F.normalize(aggregation).T) 56 | mask = torch.eye(n_utts, dtype = torch.bool).repeat(n_spks, n_spks).to(x.device) # mask 57 | ground_truth_matrix = torch.eye(mask.size(0)).to(x.device) 58 | scores = cosine_score_matrix.view(-1)[mask.view(-1)].view(-1, 1) 59 | ground_truth = ground_truth_matrix.view(-1)[mask.view(-1)].view(-1, 1) 60 | scores = self.logistic(scores) 61 | scores = self.sigmoid(scores) 62 | return scores, ground_truth 63 | 64 | def center(self, x): 65 | x = x.transpose(0, 1).contiguous() # n_utts, 1, dimension 66 | output, _ = self.attention_transformation(x, x, x, None) 67 | x += output # n_utts, 1, dimension 68 | if self.pooling == 'mean': 69 | aggregation = mean(x) # (n_spks * (n_utts - 1), dimension), n_spks * (n_utts - 1) 70 | else: 71 | x = x.permute(1, 2, 0) # 1, dimension, n_utts 72 | alpha = self.aggregation(x) 73 | aggregation = x.view(x.size(0), self.head, self.d_model // self.head, -1).matmul(alpha.unsqueeze(-1)).view(x.size(0), self.d_model) 74 | return F.normalize(aggregation) 75 | 76 | def test(self, center, evaluation): 77 | cosine_score = F.cosine_similarity(evaluation, center) 78 | score = self.logistic(cosine_score.view(-1, 1)) 79 | return cosine_score 80 | -------------------------------------------------------------------------------- /path.sh: -------------------------------------------------------------------------------- 1 | export KALDI_ROOT= # set your kaldi root here 2 | export PATH=$PWD/utils/:$KALDI_ROOT/tools/openfst/bin:$KALDI_ROOT/tools/sph2pipe_v2.5:$PWD:$PATH 3 | [ ! -f $KALDI_ROOT/tools/config/common_path.sh ] && echo >&2 "The standard file $KALDI_ROOT/tools/config/common_path.sh is not present -> Exit!" && exit 1 4 | . $KALDI_ROOT/tools/config/common_path.sh 5 | export LC_ALL=C 6 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Copyright 2017 Johns Hopkins University (Author: Daniel Povey) 3 | # 2017 Johns Hopkins University (Author: Daniel Garcia-Romero) 4 | # 2018 Ewald Enzinger 5 | # 2020 Tsinghua University (Author: Ruiqi Liu and Lantian Li) 6 | # Apache 2.0. 7 | # 8 | # This is an x-vector-based recipe for CN-Celeb database. 9 | # The recipe uses augmented CN-Celeb1/dev and CN-Celeb2 for training. 10 | # See README.txt for more info on data required. The results are reported 11 | # in terms of EER and minDCF, and are inline in the comments below. 12 | 13 | root=/home/fbmao/fengsong/kaldi/egs/cnceleb/v1 14 | 15 | . /home/fbmao/fengsong/kaldi/egs/cnceleb/v1/cmd.sh 16 | # . /home/fbmao/fengsong/kaldi/egs/cnceleb/v1/path.sh 17 | . path.sh 18 | set -e 19 | mfccdir=/groups1/gcc50479/kaldi/egs/cnceleb/v2/mfcc 20 | vaddir=/groups1/gcc50479/kaldi/egs/cnceleb/v2/mfcc 21 | 22 | cnceleb1_root=/groups1/gcc50479/cnceleb/CN-Celeb 23 | cnceleb2_root=/groups1/gcc50479/cnceleb/CN-Celeb2 24 | eval_trials_core=$root/data/eval_test/trials/trials.lst 25 | musan_root=/groups1/gcc50479/spk/data/musan 26 | nnet_dir=$root/exp 27 | 28 | stage=11 29 | 30 | if [ $stage -le 0 ]; then 31 | # This script creates data/cnceleb1_train and data/eval_{enroll,test}. 32 | # Our evaluation set is the eval portion of CN-Celeb1. 33 | # local/make_cnceleb1.sh $cnceleb1_root data 34 | 35 | # This script creates data/cnceleb2_train of CN-Celeb2. 36 | # local/make_cnceleb2.sh $cnceleb2_root data/cnceleb2_train 37 | 38 | # We'll train on all of CN-Celeb2, plus the training portion of CN-Celeb1. 39 | # This should give 2,800 speakers and 640,744 utterances. 40 | utils/combine_data.sh data/train data/cnceleb1_train data/cnceleb2_train 41 | fi 42 | 43 | if [ $stage -le 1 ]; then 44 | # Make MFCCs and compute the energy-based VAD for each dataset 45 | for name in train eval_enroll eval_test; do 46 | steps/make_mfcc.sh --write-utt2num-frames true --mfcc-config conf/mfcc.conf --nj 40 --cmd "$train_cmd" \ 47 | data/${name} exp/make_mfcc $mfccdir 48 | utils/fix_data_dir.sh data/${name} 49 | sid/compute_vad_decision.sh --nj 40 --cmd "$train_cmd" \ 50 | data/${name} exp/make_vad $vaddir 51 | utils/fix_data_dir.sh data/${name} 52 | done 53 | fi 54 | 55 | # In this section, we augment the CN-Celeb1/dev and CN-Celeb2 data with reverberation, 56 | # noise, music, and babble, and combine it with the clean data. 57 | if [ $stage -le 2 ]; then 58 | frame_shift=0.01 59 | awk -v frame_shift=$frame_shift '{print $1, $2*frame_shift;}' data/train/utt2num_frames > data/train/reco2dur 60 | 61 | if [ ! -d "RIRS_NOISES" ]; then 62 | # Download the package that includes the real RIRs, simulated RIRs, isotropic noises and point-source noises 63 | wget --no-check-certificate http://www.openslr.org/resources/28/rirs_noises.zip 64 | unzip rirs_noises.zip 65 | fi 66 | 67 | # Make a version with reverberated speech 68 | rvb_opts=() 69 | rvb_opts+=(--rir-set-parameters "0.5, RIRS_NOISES/simulated_rirs/smallroom/rir_list") 70 | rvb_opts+=(--rir-set-parameters "0.5, RIRS_NOISES/simulated_rirs/mediumroom/rir_list") 71 | 72 | # Make a reverberated version of the CN-Celeb list. Note that we don't add any 73 | # additive noise here. 74 | steps/data/reverberate_data_dir.py \ 75 | "${rvb_opts[@]}" \ 76 | --speech-rvb-probability 1 \ 77 | --pointsource-noise-addition-probability 0 \ 78 | --isotropic-noise-addition-probability 0 \ 79 | --num-replications 1 \ 80 | --source-sampling-rate 16000 \ 81 | data/train data/train_reverb 82 | cp data/train/vad.scp data/train_reverb/ 83 | utils/copy_data_dir.sh --utt-suffix "-reverb" data/train_reverb data/train_reverb.new 84 | rm -rf data/train_reverb 85 | mv data/train_reverb.new data/train_reverb 86 | 87 | # Prepare the MUSAN corpus, which consists of music, speech, and noise 88 | # suitable for augmentation. 89 | steps/data/make_musan.sh --sampling-rate 16000 $musan_root data 90 | 91 | # Get the duration of the MUSAN recordings. This will be used by the 92 | # script augment_data_dir.py. 93 | for name in speech noise music; do 94 | utils/data/get_utt2dur.sh data/musan_${name} 95 | mv data/musan_${name}/utt2dur data/musan_${name}/reco2dur 96 | done 97 | 98 | # Augment with musan_noise 99 | steps/data/augment_data_dir.py --utt-suffix "noise" --fg-interval 1 --fg-snrs "15:10:5:0" --fg-noise-dir "data/musan_noise" data/train data/train_noise 100 | # Augment with musan_music 101 | steps/data/augment_data_dir.py --utt-suffix "music" --bg-snrs "15:10:8:5" --num-bg-noises "1" --bg-noise-dir "data/musan_music" data/train data/train_music 102 | # Augment with musan_speech 103 | steps/data/augment_data_dir.py --utt-suffix "babble" --bg-snrs "20:17:15:13" --num-bg-noises "3:4:5:6:7" --bg-noise-dir "data/musan_speech" data/train data/train_babble 104 | 105 | # Combine reverb, noise, music, and babble into one directory. 106 | utils/combine_data.sh data/train_aug data/train_reverb data/train_noise data/train_music data/train_babble 107 | fi 108 | 109 | if [ $stage -le 3 ]; then 110 | # Take a random subset of the augmentations 111 | # utils/subset_data_dir.sh data/train_aug 600000 data/train_aug_600k 112 | cp -rf data/train_aug data/train_aug_600k 113 | utils/fix_data_dir.sh data/train_aug_600k 114 | 115 | # Make MFCCs for the augmented data. Note that we do not compute a new 116 | # vad.scp file here. Instead, we use the vad.scp from the clean version of 117 | # the list. 118 | steps/make_mfcc.sh --mfcc-config conf/mfcc.conf --nj 40 --cmd "$train_cmd" \ 119 | data/train_aug_600k exp/make_mfcc $mfccdir 120 | 121 | # Combine the clean and augmented CN-Celeb list. This is now roughly 122 | # double the size of the original clean list. 123 | utils/combine_data.sh data/train_combined data/train_aug_600k data/train 124 | fi 125 | 126 | # Now we prepare the features to generate examples for xvector training. 127 | if [ $stage -le 4 ]; then 128 | # This script applies CMVN and removes nonspeech frames. Note that this is somewhat 129 | # wasteful, as it roughly doubles the amount of training data on disk. After 130 | # creating training examples, this can be removed. 131 | # cp -rf data/train data/train_combined 132 | local/nnet3/xvector/prepare_feats_for_egs.sh --nj 40 --cmd "$train_cmd" \ 133 | data/train_combined data/train_combined_no_sil exp/train_combined_no_sil 134 | utils/fix_data_dir.sh data/train_combined_no_sil 135 | fi 136 | 137 | if [ $stage -le 5 ]; then 138 | # Now, we need to remove features that are too short after removing silence 139 | # frames. We want atleast 5s (500 frames) per utterance. 140 | min_len=400 141 | mv data/train_combined_no_sil/utt2num_frames data/train_combined_no_sil/utt2num_frames.bak 142 | awk -v min_len=${min_len} '$2 > min_len {print $1, $2}' data/train_combined_no_sil/utt2num_frames.bak > data/train_combined_no_sil/utt2num_frames 143 | utils/filter_scp.pl data/train_combined_no_sil/utt2num_frames data/train_combined_no_sil/utt2spk > data/train_combined_no_sil/utt2spk.new 144 | mv data/train_combined_no_sil/utt2spk.new data/train_combined_no_sil/utt2spk 145 | utils/fix_data_dir.sh data/train_combined_no_sil 146 | 147 | # We also want several utterances per speaker. Now we'll throw out speakers 148 | # with fewer than 8 utterances. 149 | min_num_utts=8 150 | awk '{print $1, NF-1}' data/train_combined_no_sil/spk2utt > data/train_combined_no_sil/spk2num 151 | awk -v min_num_utts=${min_num_utts} '$2 >= min_num_utts {print $1, $2}' data/train_combined_no_sil/spk2num | utils/filter_scp.pl - data/train_combined_no_sil/spk2utt > data/train_combined_no_sil/spk2utt.new 152 | mv data/train_combined_no_sil/spk2utt.new data/train_combined_no_sil/spk2utt 153 | utils/spk2utt_to_utt2spk.pl data/train_combined_no_sil/spk2utt > data/train_combined_no_sil/utt2spk 154 | 155 | utils/filter_scp.pl data/train_combined_no_sil/utt2spk data/train_combined_no_sil/utt2num_frames > data/train_combined_no_sil/utt2num_frames.new 156 | mv data/train_combined_no_sil/utt2num_frames.new data/train_combined_no_sil/utt2num_frames 157 | 158 | # Now we're ready to create training examples. 159 | utils/fix_data_dir.sh data/train_combined_no_sil 160 | fi 161 | 162 | # Stages 6 through 8 are handled in run_xvector.sh 163 | # local/nnet3/xvector/run_xvector.sh --stage $stage --train-stage -1 \ 164 | # --data data/train_combined_no_sil --nnet-dir $nnet_dir \ 165 | # --egs-dir $nnet_dir/egs 166 | 167 | if [ $stage -le 9 ]; then 168 | # Now we will extract x-vectors used for centering, LDA, and PLDA training. 169 | # Note that data/train_combined has well over 1 million utterances, 170 | # which is far more than is needed to train the generative PLDA model. 171 | # In addition, many of the utterances are very short, which causes a 172 | # mismatch with our evaluation conditions. In the next command, we 173 | # create a data directory that contains the longest 100,000 recordings, 174 | # which we will use to train the backend. 175 | utils/subset_data_dir.sh \ 176 | --utt-list <(sort -n -k 2 data/train_combined_no_sil/utt2num_frames | tail -n 100000) \ 177 | data/train_combined data/train_combined_100k 178 | 179 | # These x-vectors will be used for mean-subtraction, LDA, and PLDA training. 180 | sid/nnet3/xvector/extract_xvectors.sh --cmd "$train_cmd --men 4G" --nj 80 \ 181 | $nnet_dir data/train_combined_100k \ 182 | $nnet_dir/xvectors_train_combined_100k 183 | 184 | # Extract x-vector for eval sets. 185 | for name in eval_enroll eval_test; do 186 | sid/nnet3/xvector/extract_xvectors.sh --cmd "$train_cmd --men 4G" --nj 40 \ 187 | $nnet_dir data/$name \ 188 | $nnet_dir/xvectors_$name 189 | done 190 | fi 191 | 192 | if [ $stage -le 10 ]; then 193 | # Compute the mean.vec used for centering. 194 | $train_cmd $nnet_dir/xvectors_train_combined_100k/log/compute_mean.log \ 195 | ivector-mean scp:$nnet_dir/xvectors_train_combined_100k/xvector.scp \ 196 | $nnet_dir/xvectors_train_combined_100k/mean.vec || exit 1; 197 | 198 | # Use LDA to decrease the dimensionality prior to PLDA. 199 | lda_dim=150 200 | $train_cmd $nnet_dir/xvectors_train_combined_100k/log/lda.log \ 201 | ivector-compute-lda --total-covariance-factor=0.0 --dim=$lda_dim \ 202 | "ark:ivector-subtract-global-mean scp:$nnet_dir/xvectors_train_combined_100k/xvector.scp ark:- |" \ 203 | ark:data/train_combined_100k/utt2spk $nnet_dir/xvectors_train_combined_100k/transform.mat || exit 1; 204 | 205 | # Train the PLDA model. 206 | $train_cmd $nnet_dir/xvectors_train_combined_100k/log/plda.log \ 207 | ivector-compute-plda ark:data/train_combined_100k/spk2utt \ 208 | "ark:ivector-subtract-global-mean scp:$nnet_dir/xvectors_train_combined_100k/xvector.scp ark:- | transform-vec $nnet_dir/xvectors_train_combined_100k/transform.mat ark:- ark:- | ivector-normalize-length ark:- ark:- |" \ 209 | $nnet_dir/xvectors_train_combined_100k/plda || exit 1; 210 | fi 211 | 212 | if [ $stage -le 11 ]; then 213 | # Compute PLDA scores for CN-Celeb eval core trials 214 | # $train_cmd $nnet_dir/scores/log/cnceleb_eval_scoring.log \ 215 | # ivector-plda-scoring --normalize-length=true \ 216 | # --num-utts=ark:$nnet_dir/xvectors_eval_enroll/num_utts.ark \ 217 | # "ivector-copy-plda --smoothing=0.0 $nnet_dir/xvectors_train_combined_100k/plda - |" \ 218 | # "ark:ivector-mean ark:data/eval_enroll/spk2utt scp:$nnet_dir/xvectors_eval_enroll/xvector.scp ark:- | ivector-subtract-global-mean $nnet_dir/xvectors_train_combined_100k/mean.vec ark:- ark:- | transform-vec $nnet_dir/xvectors_train_combined_100k/transform.mat ark:- ark:- | ivector-normalize-length ark:- ark:- |" \ 219 | # "ark:ivector-subtract-global-mean $nnet_dir/xvectors_train_combined_100k/mean.vec scp:$nnet_dir/xvectors_eval_test/xvector.scp ark:- | transform-vec $nnet_dir/xvectors_train_combined_100k/transform.mat ark:- ark:- | ivector-normalize-length ark:- ark:- |" \ 220 | # "cat '$eval_trials_core' | cut -d\ --fields=1,2 |" $nnet_dir/scores/cnceleb_eval_scores || exit 1; 221 | 222 | # CN-Celeb Eval Core: 223 | # EER: 12.39% 224 | # minDCF(p-target=0.01): 0.6011 225 | # minDCF(p-target=0.001): 0.7353 226 | # sort -n -t ' ' -k 2 exp/Thu_Mar_11_12:53:57_2021/backend_scores.txt | cut -d' ' -f3 | cut -d'[' -f2 | cut -d']' -f1 > temp 227 | # cut -d' ' -f1,2 $root/exp/scores/iv_eval_scores | paste -d' ' - temp > $root/exp/scores/cnceleb_eval_scores 228 | # sort -n -t ' ' -k 2 exp/Thu_Mar_11_12:53:57_2021/backend_scores.txt | cut -d' ' -f3 | cut -d'[' -f2 | cut -d']' -f1 > temp 229 | cut -d' ' -f3 exp/$1/backend_scores.txt > temp 230 | n=`wc -l temp | cut -d' ' -f1` 231 | echo "$n" 232 | cut -d' ' -f1,2 $root/exp/scores/iv_eval_scores | head -${n} | paste -d' ' - temp > $root/exp/scores/cnceleb_eval_scores 233 | head -${n} $eval_trials_core > trials 234 | eval_trials_core=trials 235 | echo -e "\nCN-Celeb Eval Core:"; 236 | eer=$(paste $eval_trials_core $nnet_dir/scores/cnceleb_eval_scores | awk '{print $6, $3}' | compute-eer - 2>/dev/null) 237 | mindcf1=`$root/sid/compute_min_dcf.py --p-target 0.01 $nnet_dir/scores/cnceleb_eval_scores $eval_trials_core 2>/dev/null` 238 | mindcf2=`$root/sid/compute_min_dcf.py --p-target 0.001 $nnet_dir/scores/cnceleb_eval_scores $eval_trials_core 2>/dev/null` 239 | echo "EER: $eer%" 240 | echo "minDCF(p-target=0.01): $mindcf1" 241 | echo "minDCF(p-target=0.001): $mindcf2" 242 | fi 243 | -------------------------------------------------------------------------------- /siamese-triplet_license: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2019, Adam Bielski 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | 3. Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import os 2 | import math 3 | import random 4 | import time 5 | import logging 6 | import warnings 7 | logging.basicConfig(level = logging.INFO, filename = 'dev.log', filemode = 'w', format = "%(asctime)s [%(filename)s:%(lineno)d - %(levelname)s ] %(message)s") 8 | warnings.filterwarnings('ignore') 9 | 10 | import numpy as np 11 | import yaml 12 | import torch 13 | import torch.nn.functional as F 14 | import torch.nn as nn 15 | import torch.optim as optim 16 | from torch.utils.data import DataLoader 17 | from tqdm import tqdm 18 | from sklearn.metrics.pairwise import cosine_similarity 19 | 20 | import dataset 21 | import model 22 | 23 | random.seed(20) 24 | np.random.seed(20) 25 | torch.manual_seed(20) 26 | 27 | class Trainer(object): 28 | def __init__(self, path): 29 | f = open(path) 30 | opts = yaml.load(f, Loader = yaml.CLoader) 31 | f.close() 32 | 33 | self.opts = opts 34 | 35 | if os.path.exists(self.opts['resume']): 36 | self.log_time = self.opts['resume'].split('/')[1] 37 | else: 38 | self.log_time = time.asctime(time.localtime(time.time())).replace(' ', '_') 39 | 40 | # self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') 41 | self.device = torch.device('cpu') 42 | 43 | self.trainset = dataset.EmbeddingTrainDataset(opts['dataset']) 44 | self.enrollset = dataset.EmbeddingEnrollDataset(opts['dataset']) 45 | self.n_spks = opts['n_spks'] 46 | self.n_utts = opts['n_utts'] 47 | milestones = opts['milestones'] 48 | batch_sampler = dataset.BalancedBatchSampler(self.trainset.labels, len(self.trainset), opts['n_spks'], opts['n_utts']) 49 | self.train_loader = DataLoader(self.trainset, batch_sampler = batch_sampler, num_workers = 16, pin_memory = True) 50 | self.eval_path = opts['dataset']['eval_path'] 51 | 52 | self.backend = model.AttentionAggregation(self.opts['model']).to(self.device) 53 | 54 | self.optimizer = optim.SGD(self.backend.parameters(), opts['lr'], momentum = 0.9, weight_decay = 0.00001) 55 | self.lr_scheduler = optim.lr_scheduler.MultiStepLR(self.optimizer, milestones = milestones, gamma = 0.1) 56 | self.criterion = nn.BCELoss(reduction = 'sum') 57 | 58 | self.epochs = opts['epochs'] 59 | self.current_epoch = 0 60 | self.grad_clip_threshold = 20 61 | 62 | if os.path.exists(self.opts['resume']): 63 | self.load(self.opts['resume']) 64 | print("Load model from {}".format(self.log_time)) 65 | else: 66 | print("Start new training {}".format(self.log_time)) 67 | 68 | 69 | def train(self): 70 | os.makedirs('exp/{}'.format(self.log_time), exist_ok = True) 71 | start_epoch = self.current_epoch 72 | for epoch in range(start_epoch + 1, self.epochs + 1): 73 | self.current_epoch = epoch 74 | self.train_epoch() 75 | self.lr_scheduler.step() 76 | 77 | def train_epoch(self): 78 | self.backend.train() 79 | sum_loss, sum_samples = 0, 0 80 | progress_bar = tqdm(enumerate(self.train_loader)) 81 | for batch_idx, (data, labels) in progress_bar: 82 | data = data.to(self.device) # spks * utts, 1, dimension 83 | data = data.view(self.n_spks, self.n_utts, -1) 84 | 85 | self.optimizer.zero_grad() 86 | scores, labels = self.backend(data) 87 | loss = self.criterion(scores, labels) 88 | loss.backward() 89 | 90 | grad_norm = torch.nn.utils.clip_grad_norm_( 91 | self.backend.parameters(), self.grad_clip_threshold 92 | ) 93 | logging.info("grad norm={}".format(grad_norm)) 94 | 95 | if math.isnan(grad_norm): 96 | logging.warning("grad norm is nan. Do not update model.") 97 | else: 98 | self.optimizer.step() 99 | 100 | sum_samples += self.n_spks * self.n_utts * self.n_spks 101 | sum_loss += loss.item() 102 | progress_bar.set_description( 103 | 'Train Epoch: {:3d} [{:4d}/{:4d} ({:3.3f}%)] Loss: {:.16f}'.format( 104 | self.current_epoch, batch_idx + 1, len(self.train_loader), 105 | 100. * (batch_idx + 1) / len(self.train_loader), sum_loss / sum_samples 106 | ) 107 | ) 108 | self.save() 109 | 110 | def enroll(self): 111 | self.backend.eval() 112 | os.makedirs('./exp/{}/enroll'.format(self.log_time), exist_ok = True) 113 | with torch.no_grad(): 114 | for embeddings, spk in tqdm(self.enrollset()): 115 | center = self.backend.center(embeddings.to(self.device)) 116 | path = os.path.join('./exp/{}/enroll/'.format(self.log_time), spk) + '-enroll.npy' 117 | np.save(path, center.cpu().numpy()) 118 | 119 | def test(self): 120 | self.backend.eval() 121 | y_true = [] 122 | y_pred4w = [] 123 | y_pred = [] 124 | count = 0 125 | enroll_dir = './exp/{}/'.format(self.log_time) 126 | wf = open('./exp/{}/backend_scores.txt'.format(self.log_time), 'w') 127 | with torch.no_grad(): 128 | with open('../task.txt', 'r') as f: 129 | for line in tqdm(f): 130 | count += 1 131 | line = line.rstrip() 132 | true_score, utt1, utt2 = line.split(' ') 133 | y_true.append(eval(true_score)) 134 | s_utt1 = np.load(os.path.join(enroll_dir, utt1.replace('.wav', '.npy'))) 135 | s_utt2 = np.load(os.path.join(self.eval_path, utt2.replace('.wav', '.npy'))) 136 | score = self.backend.test(torch.from_numpy(s_utt1).to(self.device), torch.from_numpy(s_utt2).to(self.device)) 137 | line = utt1 + ' ' + utt2 + ' ' + str(score.item()) + '\n' 138 | wf.write(line) 139 | wf.close() 140 | 141 | def save(self, filename = None): 142 | if filename is None: 143 | torch.save({'epoch': self.current_epoch, 'state_dict': self.backend.state_dict(), 'criterion': self.criterion, 144 | 'lr_scheduler': self.lr_scheduler.state_dict(), 'optimizer': self.optimizer.state_dict()}, 145 | 'exp/{}/net_{}.pth'.format(self.log_time, self.current_epoch)) 146 | else: 147 | torch.save({'epoch': self.current_epoch, 'state_dict': self.backend.state_dict(), 'criterion': self.criterion, 148 | 'lr_scheduler': self.lr_scheduler.state_dict(), 'optimizer': self.optimizer.state_dict()}, 149 | 'exp/{}/{}'.format(self.log_time, filename)) 150 | 151 | def load(self, resume): 152 | map_location = 'cuda' if torch.cuda.is_available() else 'cpu' 153 | ckpt = torch.load(resume, map_location = map_location) 154 | self.backend.load_state_dict(ckpt['state_dict']) 155 | if 'criterion' in ckpt: 156 | self.criterion = ckpt['criterion'] 157 | if 'lr_scheduler' in ckpt: 158 | self.lr_scheduler.load_state_dict(ckpt['lr_scheduler']) 159 | self.optimizer.load_state_dict(ckpt['optimizer']) 160 | self.current_epoch = ckpt['epoch'] 161 | 162 | if __name__ == '__main__': 163 | trainer = Trainer('./config.yaml') 164 | trainer.train() 165 | trainer.enroll() 166 | trainer.test() 167 | --------------------------------------------------------------------------------