├── nextformer ├── convnext_time_freq.py ├── utils.py ├── feedforward.py ├── conformer.py ├── convolution.py └── attention.py ├── .gitignore ├── README.md └── LICENSE /nextformer/convnext_time_freq.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Nguyen Van Anh Tuan 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /nextformer/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Nguyen Van Anh Tuan 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | class Transpose(nn.Module): 17 | """ Wrapper class of torch.transpose() for Sequential module. """ 18 | 19 | def __init__(self, shape: tuple): 20 | super(Transpose, self).__init__() 21 | self.shape = shape 22 | 23 | def forward(self, x: Tensor) -> Tensor: 24 | return x.transpose(*self.shape) 25 | -------------------------------------------------------------------------------- /nextformer/feedforward.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Nguyen Van Anh Tuan 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | class FeedForwardModule(nn.Module): 17 | """ 18 | Conformer Feed Forward Module follow pre-norm residual units and apply layer normalization within the residual unit 19 | and on the input before the first linear layer. This module also apply Swish activation and dropout, which helps 20 | regularizing the network. 21 | Args: 22 | encoder_dim (int): Dimension of conformer encoder 23 | expansion_factor (int): Expansion factor of feed forward module. 24 | dropout_p (float): Ratio of dropout 25 | Inputs: inputs 26 | - **inputs** (batch, time, dim): Tensor contains input sequences 27 | Outputs: outputs 28 | - **outputs** (batch, time, dim): Tensor produces by feed forward module. 29 | """ 30 | 31 | def __init__( 32 | self, encoder_dim: int = 512, expansion_factor: int = 4, dropout_p: float = 0.1, 33 | ) -> None: 34 | super(FeedForwardModule, self).__init__() 35 | self.sequential = nn.Sequential( 36 | nn.LayerNorm(encoder_dim), 37 | nn.Linear(encoder_dim, encoder_dim * expansion_factor, bias=True), 38 | nn.SiLU(), 39 | nn.Dropout(p=dropout_p), 40 | nn.Linear(encoder_dim * expansion_factor, encoder_dim, bias=True), 41 | nn.Dropout(p=dropout_p), 42 | ) 43 | 44 | def forward(self, inputs: Tensor) -> Tensor: 45 | return self.sequential(inputs) 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | experiment/ 2 | experiment/* 3 | data/sample 4 | data/sample/* 5 | data/data_list/debug_list.csv 6 | data/data_list/sample_list.csv 7 | *.bin 8 | *.zip 9 | *.idea 10 | docs/training 11 | docs/training/* 12 | __pycache__/ 13 | venv/* 14 | *.pyc 15 | .idea 16 | .ipynb_checkpoints 17 | # Byte-compiled / optimized / DLL files 18 | __pycache__/ 19 | *.py[cod] 20 | *$py.class 21 | 22 | # C extensions 23 | *.so 24 | 25 | # Distribution / packaging 26 | .Python 27 | build/ 28 | develop-eggs/ 29 | dist/ 30 | downloads/ 31 | eggs/ 32 | .eggs/ 33 | lib/ 34 | lib64/ 35 | parts/ 36 | sdist/ 37 | var/ 38 | wheels/ 39 | pip-wheel-metadata/ 40 | share/python-wheels/ 41 | *.egg-info/ 42 | .installed.cfg 43 | *.egg 44 | MANIFEST 45 | 46 | # PyInstaller 47 | # Usually these files are written by a python script from a template 48 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 49 | *.manifest 50 | *.spec 51 | 52 | # Installer logs 53 | pip-log.txt 54 | pip-delete-this-directory.txt 55 | 56 | # Unit test / coverage reports 57 | htmlcov/ 58 | .tox/ 59 | .nox/ 60 | .coverage 61 | .coverage.* 62 | .cache 63 | nosetests.xml 64 | coverage.xml 65 | *.cover 66 | *.py,cover 67 | .hypothesis/ 68 | .pytest_cache/ 69 | 70 | # Translations 71 | *.mo 72 | *.pot 73 | 74 | # Django stuff: 75 | *.log 76 | local_settings.py 77 | db.sqlite3 78 | db.sqlite3-journal 79 | 80 | # Flask stuff: 81 | instance/ 82 | .webassets-cache 83 | 84 | # Scrapy stuff: 85 | .scrapy 86 | 87 | # Sphinx documentation 88 | docs/_build/ 89 | 90 | # PyBuilder 91 | target/ 92 | 93 | # Jupyter Notebook 94 | .ipynb_checkpoints 95 | 96 | # IPython 97 | profile_default/ 98 | ipython_config.py 99 | 100 | # pyenv 101 | .python-version 102 | 103 | # pipenv 104 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 105 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 106 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 107 | # install all needed dependencies. 108 | #Pipfile.lock 109 | 110 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 111 | __pypackages__/ 112 | 113 | # Celery stuff 114 | celerybeat-schedule 115 | celerybeat.pid 116 | 117 | # SageMath parsed files 118 | *.sage.py 119 | 120 | # Environments 121 | .env 122 | .venv 123 | env/ 124 | venv/ 125 | ENV/ 126 | env.bak/ 127 | venv.bak/ 128 | 129 | # Spyder project settings 130 | .spyderproject 131 | .spyproject 132 | 133 | # Rope project settings 134 | .ropeproject 135 | 136 | # mkdocs documentation 137 | /site 138 | 139 | # mypy 140 | .mypy_cache/ 141 | .dmypy.json 142 | dmypy.json 143 | 144 | # Pyre type checker 145 | .pyre/ 146 | -------------------------------------------------------------------------------- /nextformer/conformer.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Nguyen Van Anh Tuan 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from .attention import MultiHeadedSelfAttentionModule 16 | from .convolution import ConvolutionModule 17 | from .feedforward import FeedForwardModule 18 | 19 | 20 | class ConformerBlock(nn.Module): 21 | """ 22 | Conformer block contains two Feed Forward modules sandwiching the Multi-Headed Self-Attention module 23 | and the Convolution module. This sandwich structure is inspired by Macaron-Net, which proposes replacing 24 | the original feed-forward layer in the Transformer block into two half-step feed-forward layers, 25 | one before the attention layer and one after. 26 | Args: 27 | encoder_dim (int, optional): Dimension of conformer encoder 28 | num_attention_heads (int, optional): Number of attention heads 29 | feed_forward_expansion_factor (int, optional): Expansion factor of feed forward module 30 | conv_expansion_factor (int, optional): Expansion factor of conformer convolution module 31 | feed_forward_dropout_p (float, optional): Probability of feed forward module dropout 32 | attention_dropout_p (float, optional): Probability of attention module dropout 33 | conv_dropout_p (float, optional): Probability of conformer convolution module dropout 34 | conv_kernel_size (int or tuple, optional): Size of the convolving kernel 35 | half_step_residual (bool): Flag indication whether to use half step residual or not 36 | Inputs: inputs 37 | - **inputs** (batch, time, dim): Tensor containing input vector 38 | Returns: outputs 39 | - **outputs** (batch, time, dim): Tensor produces by conformer block. 40 | """ 41 | 42 | def __init__( 43 | self, 44 | encoder_dim: int = 512, 45 | num_attention_heads: int = 8, 46 | feed_forward_expansion_factor: int = 4, 47 | conv_expansion_factor: int = 2, 48 | feed_forward_dropout_p: float = 0.1, 49 | attention_dropout_p: float = 0.1, 50 | conv_dropout_p: float = 0.1, 51 | conv_kernel_size: int = 31, 52 | half_step_residual: bool = True, 53 | ): 54 | super(ConformerBlock, self).__init__() 55 | if half_step_residual: 56 | self.feed_forward_residual_factor = 0.5 57 | else: 58 | self.feed_forward_residual_factor = 1 59 | 60 | self.ffn_1 = FeedForwardModule( 61 | encoder_dim=encoder_dim, 62 | expansion_factor=feed_forward_expansion_factor, 63 | dropout_p=feed_forward_dropout_p, 64 | ) 65 | self.ffn_2 = FeedForwardModule( 66 | encoder_dim=encoder_dim, 67 | expansion_factor=feed_forward_expansion_factor, 68 | dropout_p=feed_forward_dropout_p, 69 | ) 70 | self.conv = ConformerConvModule( 71 | in_channels=encoder_dim, 72 | kernel_size=conv_kernel_size, 73 | expansion_factor=conv_expansion_factor, 74 | dropout_p=conv_dropout_p, 75 | ) 76 | self.mhsa = MultiHeadedSelfAttentionModule( 77 | d_model=encoder_dim, 78 | num_heads=num_attention_heads, 79 | dropout_p=attention_dropout_p, 80 | ) 81 | self.post_layernorm = nn.LayerNorm(encoder_dim) 82 | 83 | def forward(self, inputs: Tensor) -> Tensor: 84 | x = 0.5 * self.ffn_1(inputs) + x 85 | x = self.mhsa(x) + x 86 | x = self.conv(x) + x 87 | x = 0.5 * self.ffn_2(x) + x 88 | x = self.post_layernorm(x) 89 | return x 90 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 | **PyTorch implementation of Nextformer: A ConvNeXt Augmented Conformer For End-To-End Speech Recognition.** 6 | 7 |
8 | 9 | --- 10 | 11 |

12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 27 | 28 | 29 | Conformer models have achieved state-of-the-art (SOTA) results in end-to-end speech recognition. However Conformer mainly focuses on temporal modeling while pays less attention on time-frequency property of speech feature. Authors has augment Conformer with ConvNeXt and propose Nextformer structure, they stacks of ConvNeXt block to replace the commonly used subsampling module in Conformer for utilizing the information contained in timefrequency speech feature. Besides, they insert an additional downsampling module in middle of Conformer layers to make Nextformer model more efficient and accurate. 30 | 31 | 32 | 33 | This repository contains only model code. 34 | 35 | ## Installation 36 | This project recommends Python 3.7 or higher. 37 | We recommend creating a new virtual environment for this project (using virtual env or conda). 38 | 39 | ### Prerequisites 40 | 42 | 43 | ### Install from source 44 | 50 | 51 | ## Usage 52 | 53 | 83 | 84 | ## Troubleshoots and Contributing 85 | 86 | If you have any questions, bug reports, and feature requests, please [open an issue](https://github.com/tuanio/nextformer/issues) on github or 87 | contacts nvatuan3@gmail.com please. 88 | 89 | I appreciate any kind of feedback or contribution. Feel free to proceed with small issues like bug fixes, documentation improvement. For major contributions and new features, please discuss with the collaborators in corresponding issues. 90 | 91 | ## Code Style 92 | 93 | I follow [Black](https://black.readthedocs.io/en/stable/) for code style. Especially the style of docstrings is important to generate documentation. 94 | 95 | ## Reference 96 | 97 | - [Nextformer: A ConvNeXt Augmented Conformer For End-To-End Speech Recognition](https://arxiv.org/abs/2206.14747) 98 | - [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) 99 | - [Conformer: Convolution-augmented Transformer for Speech Recognition](https://arxiv.org/pdf/2005.08100.pdf) 100 | - [sooftware/conformer](https://github.com/sooftware/conformer) 101 | - [facebookresearch/ConvNeXt](https://github.com/facebookresearch/ConvNeXt) 102 | 103 | ## Author 104 | 105 | - Nguyen Van Anh Tuan [@tuanio](https://github.com/tuanio) 106 | - Contacts: nvatuan3@gmail.com 107 | -------------------------------------------------------------------------------- /nextformer/convolution.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Nguyen Van Anh Tuan 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from .utils import Transpose 17 | 18 | 19 | class DepthwiseConv1d(nn.Module): 20 | """ 21 | When groups == in_channels and out_channels == K * in_channels, where K is a positive integer, 22 | this operation is termed in literature as depthwise convolution. 23 | Args: 24 | in_channels (int): Number of channels in the input 25 | out_channels (int): Number of channels produced by the convolution 26 | kernel_size (int or tuple): Size of the convolving kernel 27 | stride (int, optional): Stride of the convolution. Default: 1 28 | padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0 29 | bias (bool, optional): If True, adds a learnable bias to the output. Default: True 30 | Inputs: inputs 31 | - **inputs** (batch, in_channels, time): Tensor containing input vector 32 | Returns: outputs 33 | - **outputs** (batch, out_channels, time): Tensor produces by depthwise 1-D convolution. 34 | """ 35 | 36 | def __init__( 37 | self, 38 | in_channels: int, 39 | out_channels: int, 40 | kernel_size: int, 41 | stride: int = 1, 42 | padding: int = 0, 43 | bias: bool = False, 44 | ) -> None: 45 | super(DepthwiseConv1d, self).__init__() 46 | assert ( 47 | out_channels % in_channels == 0 48 | ), "out_channels should be constant multiple of in_channels" 49 | self.conv = nn.Conv1d( 50 | in_channels=in_channels, 51 | out_channels=out_channels, 52 | kernel_size=kernel_size, 53 | groups=in_channels, 54 | stride=stride, 55 | padding=padding, 56 | bias=bias, 57 | ) 58 | 59 | def forward(self, inputs: Tensor) -> Tensor: 60 | return self.conv(inputs) 61 | 62 | 63 | class PointwiseConv1d(nn.Module): 64 | """ 65 | When kernel size == 1 conv1d, this operation is termed in literature as pointwise convolution. 66 | This operation often used to match dimensions. 67 | Args: 68 | in_channels (int): Number of channels in the input 69 | out_channels (int): Number of channels produced by the convolution 70 | stride (int, optional): Stride of the convolution. Default: 1 71 | padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0 72 | bias (bool, optional): If True, adds a learnable bias to the output. Default: True 73 | Inputs: inputs 74 | - **inputs** (batch, in_channels, time): Tensor containing input vector 75 | Returns: outputs 76 | - **outputs** (batch, out_channels, time): Tensor produces by pointwise 1-D convolution. 77 | """ 78 | 79 | def __init__( 80 | self, 81 | in_channels: int, 82 | out_channels: int, 83 | stride: int = 1, 84 | padding: int = 0, 85 | bias: bool = True, 86 | ) -> None: 87 | super(PointwiseConv1d, self).__init__() 88 | self.conv = nn.Conv1d( 89 | in_channels=in_channels, 90 | out_channels=out_channels, 91 | kernel_size=1, 92 | stride=stride, 93 | padding=padding, 94 | bias=bias, 95 | ) 96 | 97 | def forward(self, inputs: Tensor) -> Tensor: 98 | return self.conv(inputs) 99 | 100 | 101 | class ConvolutionModule(nn.Module): 102 | """ 103 | Conformer convolution module starts with a pointwise convolution and a gated linear unit (GLU). 104 | This is followed by a single 1-D depthwise convolution layer. Batchnorm is deployed just after the convolution 105 | to aid training deep models. 106 | Args: 107 | in_channels (int): Number of channels in the input 108 | kernel_size (int or tuple, optional): Size of the convolving kernel Default: 31 109 | dropout_p (float, optional): probability of dropout 110 | Inputs: inputs 111 | inputs (batch, time, dim): Tensor contains input sequences 112 | Outputs: outputs 113 | outputs (batch, time, dim): Tensor produces by conformer convolution module. 114 | """ 115 | 116 | def __init__( 117 | self, 118 | in_channels: int, 119 | kernel_size: int = 31, 120 | expansion_factor: int = 2, 121 | dropout_p: float = 0.1, 122 | ) -> None: 123 | super(ConformerConvModule, self).__init__() 124 | assert ( 125 | kernel_size - 1 126 | ) % 2 == 0, "kernel_size should be a odd number for 'SAME' padding" 127 | assert expansion_factor == 2, "Currently, Only Supports expansion_factor 2" 128 | 129 | self.sequential = nn.Sequential( 130 | nn.LayerNorm(in_channels), 131 | Transpose(shape=(1, 2)), 132 | PointwiseConv1d( 133 | in_channels, 134 | in_channels * expansion_factor, 135 | stride=1, 136 | padding=0, 137 | bias=True, 138 | ), 139 | nn.GLU(dim=1), 140 | DepthwiseConv1d( 141 | in_channels, 142 | in_channels, 143 | kernel_size, 144 | stride=1, 145 | padding=(kernel_size - 1) // 2, 146 | ), 147 | nn.BatchNorm1d(in_channels), 148 | nn.SiLU(), 149 | PointwiseConv1d(in_channels, in_channels, stride=1, padding=0, bias=True), 150 | nn.Dropout(p=dropout_p), 151 | ) 152 | 153 | def forward(self, inputs: Tensor) -> Tensor: 154 | return self.sequential(inputs).transpose(1, 2) 155 | -------------------------------------------------------------------------------- /nextformer/attention.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Nguyen Van Anh Tuan 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import math 16 | import torch 17 | import torch.nn as nn 18 | from torch import Tensor 19 | 20 | 21 | class PositionalEncoding(nn.Module): 22 | """ 23 | Positional Encoding proposed in "Attention Is All You Need". 24 | Since transformer contains no recurrence and no convolution, in order for the model to make 25 | use of the order of the sequence, we must add some positional information. 26 | "Attention Is All You Need" use sine and cosine functions of different frequencies: 27 | PE_(pos, 2i) = sin(pos / power(10000, 2i / d_model)) 28 | PE_(pos, 2i+1) = cos(pos / power(10000, 2i / d_model)) 29 | """ 30 | 31 | def __init__(self, d_model: int = 512, max_len: int = 10000) -> None: 32 | super(PositionalEncoding, self).__init__() 33 | pe = torch.zeros(max_len, d_model, requires_grad=False) 34 | position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) 35 | div_term = torch.exp( 36 | torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model) 37 | ) 38 | pe[:, 0::2] = torch.sin(position * div_term) 39 | pe[:, 1::2] = torch.cos(position * div_term) 40 | pe = pe.unsqueeze(0) 41 | self.register_buffer("pe", pe) 42 | 43 | def forward(self, length: int) -> Tensor: 44 | return self.pe[:, :length] 45 | 46 | 47 | class RelativeMultiHeadAttention(nn.Module): 48 | """ 49 | Multi-head attention with relative positional encoding. 50 | This concept was proposed in the "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context" 51 | Args: 52 | d_model (int): The dimension of model 53 | num_heads (int): The number of attention heads. 54 | dropout_p (float): probability of dropout 55 | Inputs: query, key, value, pos_embedding, mask 56 | - **query** (batch, time, dim): Tensor containing query vector 57 | - **key** (batch, time, dim): Tensor containing key vector 58 | - **value** (batch, time, dim): Tensor containing value vector 59 | - **pos_embedding** (batch, time, dim): Positional embedding tensor 60 | - **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked 61 | Returns: 62 | - **outputs**: Tensor produces by relative multi head attention module. 63 | """ 64 | 65 | def __init__( 66 | self, d_model: int = 512, num_heads: int = 16, dropout_p: float = 0.1, 67 | ): 68 | super(RelativeMultiHeadAttention, self).__init__() 69 | assert d_model % num_heads == 0, "d_model % num_heads should be zero." 70 | self.d_model = d_model 71 | self.d_head = int(d_model / num_heads) 72 | self.num_heads = num_heads 73 | self.sqrt_dim = math.sqrt(d_model) 74 | 75 | self.query_proj = Linear(d_model, d_model) 76 | self.key_proj = Linear(d_model, d_model) 77 | self.value_proj = Linear(d_model, d_model) 78 | self.pos_proj = Linear(d_model, d_model, bias=False) 79 | 80 | self.dropout = nn.Dropout(p=dropout_p) 81 | self.u_bias = nn.Parameter(torch.Tensor(self.num_heads, self.d_head)) 82 | self.v_bias = nn.Parameter(torch.Tensor(self.num_heads, self.d_head)) 83 | torch.nn.init.xavier_uniform_(self.u_bias) 84 | torch.nn.init.xavier_uniform_(self.v_bias) 85 | 86 | self.out_proj = Linear(d_model, d_model) 87 | 88 | def forward( 89 | self, 90 | query: Tensor, 91 | key: Tensor, 92 | value: Tensor, 93 | pos_embedding: Tensor, 94 | mask: Optional[Tensor] = None, 95 | ) -> Tensor: 96 | batch_size = value.size(0) 97 | 98 | query = self.query_proj(query).view(batch_size, -1, self.num_heads, self.d_head) 99 | key = ( 100 | self.key_proj(key) 101 | .view(batch_size, -1, self.num_heads, self.d_head) 102 | .permute(0, 2, 1, 3) 103 | ) 104 | value = ( 105 | self.value_proj(value) 106 | .view(batch_size, -1, self.num_heads, self.d_head) 107 | .permute(0, 2, 1, 3) 108 | ) 109 | pos_embedding = self.pos_proj(pos_embedding).view( 110 | batch_size, -1, self.num_heads, self.d_head 111 | ) 112 | 113 | content_score = torch.matmul( 114 | (query + self.u_bias).transpose(1, 2), key.transpose(2, 3) 115 | ) 116 | pos_score = torch.matmul( 117 | (query + self.v_bias).transpose(1, 2), pos_embedding.permute(0, 2, 3, 1) 118 | ) 119 | pos_score = self._relative_shift(pos_score) 120 | 121 | score = (content_score + pos_score) / self.sqrt_dim 122 | 123 | if mask is not None: 124 | mask = mask.unsqueeze(1) 125 | score.masked_fill_(mask, -1e9) 126 | 127 | attn = F.softmax(score, -1) 128 | attn = self.dropout(attn) 129 | 130 | context = torch.matmul(attn, value).transpose(1, 2) 131 | context = context.contiguous().view(batch_size, -1, self.d_model) 132 | 133 | return self.out_proj(context) 134 | 135 | def _relative_shift(self, pos_score: Tensor) -> Tensor: 136 | batch_size, num_heads, seq_length1, seq_length2 = pos_score.size() 137 | zeros = pos_score.new_zeros(batch_size, num_heads, seq_length1, 1) 138 | padded_pos_score = torch.cat([zeros, pos_score], dim=-1) 139 | 140 | padded_pos_score = padded_pos_score.view( 141 | batch_size, num_heads, seq_length2 + 1, seq_length1 142 | ) 143 | pos_score = padded_pos_score[:, :, 1:].view_as(pos_score) 144 | 145 | return pos_score 146 | 147 | 148 | class MultiHeadedSelfAttentionModule(nn.Module): 149 | """ 150 | Conformer employ multi-headed self-attention (MHSA) while integrating an important technique from Transformer-XL, 151 | the relative sinusoidal positional encoding scheme. The relative positional encoding allows the self-attention 152 | module to generalize better on different input length and the resulting encoder is more robust to the variance of 153 | the utterance length. Conformer use prenorm residual units with dropout which helps training 154 | and regularizing deeper models. 155 | Args: 156 | d_model (int): The dimension of model 157 | num_heads (int): The number of attention heads. 158 | dropout_p (float): probability of dropout 159 | Inputs: inputs, mask 160 | - **inputs** (batch, time, dim): Tensor containing input vector 161 | - **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked 162 | Returns: 163 | - **outputs** (batch, time, dim): Tensor produces by relative multi headed self attention module. 164 | """ 165 | 166 | def __init__(self, d_model: int, num_heads: int, dropout_p: float = 0.1): 167 | super(MultiHeadedSelfAttentionModule, self).__init__() 168 | self.positional_encoding = PositionalEncoding(d_model) 169 | self.layer_norm = nn.LayerNorm(d_model) 170 | self.attention = RelativeMultiHeadAttention(d_model, num_heads, dropout_p) 171 | self.dropout = nn.Dropout(p=dropout_p) 172 | 173 | def forward(self, inputs: Tensor, mask: Optional[Tensor] = None): 174 | batch_size, seq_length, _ = inputs.size() 175 | pos_embedding = self.positional_encoding(seq_length) 176 | pos_embedding = pos_embedding.repeat(batch_size, 1, 1) 177 | 178 | inputs = self.layer_norm(inputs) 179 | outputs = self.attention( 180 | inputs, inputs, inputs, pos_embedding=pos_embedding, mask=mask 181 | ) 182 | 183 | return self.dropout(outputs) 184 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------