├── .gitignore
├── LICENSE
├── README.md
├── conformer
├── __init__.py
├── activation.py
├── attention.py
├── convolution.py
├── embedding.py
├── encoder.py
├── feed_forward.py
├── model.py
└── modules.py
├── docs
├── .DS_Store
├── Makefile
├── Model.html
├── Modules.html
├── Submodules.html
├── _sources
│ ├── Model.rst.txt
│ ├── Modules.rst.txt
│ ├── Submodules.rst.txt
│ └── index.rst.txt
├── _static
│ ├── basic.css
│ ├── css
│ │ ├── badge_only.css
│ │ ├── fonts
│ │ │ ├── Roboto-Slab-Bold.woff
│ │ │ ├── Roboto-Slab-Bold.woff2
│ │ │ ├── Roboto-Slab-Regular.woff
│ │ │ ├── Roboto-Slab-Regular.woff2
│ │ │ ├── fontawesome-webfont.eot
│ │ │ ├── fontawesome-webfont.svg
│ │ │ ├── fontawesome-webfont.ttf
│ │ │ ├── fontawesome-webfont.woff
│ │ │ ├── fontawesome-webfont.woff2
│ │ │ ├── lato-bold-italic.woff
│ │ │ ├── lato-bold-italic.woff2
│ │ │ ├── lato-bold.woff
│ │ │ ├── lato-bold.woff2
│ │ │ ├── lato-normal-italic.woff
│ │ │ ├── lato-normal-italic.woff2
│ │ │ ├── lato-normal.woff
│ │ │ └── lato-normal.woff2
│ │ └── theme.css
│ ├── doctools.js
│ ├── documentation_options.js
│ ├── file.png
│ ├── jquery-3.5.1.js
│ ├── jquery.js
│ ├── js
│ │ ├── badge_only.js
│ │ ├── html5shiv-printshiv.min.js
│ │ ├── html5shiv.min.js
│ │ └── theme.js
│ ├── language_data.js
│ ├── minus.png
│ ├── plus.png
│ ├── pygments.css
│ ├── searchtools.js
│ ├── underscore-1.3.1.js
│ └── underscore.js
├── genindex.html
├── index.html
├── make.bat
├── objects.inv
├── search.html
├── searchindex.js
└── source
│ ├── Model.rst
│ ├── Modules.rst
│ ├── Submodules.rst
│ ├── conf.py
│ └── index.rst
└── setup.py
/.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 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | **PyTorch implementation of Conformer: Convolution-augmented Transformer for Speech Recognition.**
7 |
8 |
9 |
10 |
11 | ***
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 | Transformer models are good at capturing content-based global interactions, while CNNs exploit local features effectively. Conformer combine convolution neural networks and transformers to model both local and global dependencies of an audio sequence in a parameter-efficient way. Conformer significantly outperforms the previous Transformer and CNN based models achieving state-of-the-art accuracies.
29 |
30 |
31 |
32 | This repository contains only model code, but you can train with conformer at [openspeech](https://github.com/openspeech-team/openspeech)
33 |
34 | ## Installation
35 | This project recommends Python 3.7 or higher.
36 | We recommend creating a new virtual environment for this project (using virtual env or conda).
37 |
38 | ### Prerequisites
39 | * Numpy: `pip install numpy` (Refer [here](https://github.com/numpy/numpy) for problem installing Numpy).
40 | * Pytorch: Refer to [PyTorch website](http://pytorch.org/) to install the version w.r.t. your environment.
41 |
42 | ### Install from source
43 | Currently we only support installation from source code using setuptools. Checkout the source code and run the
44 | following commands:
45 |
46 | ```
47 | pip install -e .
48 | ```
49 |
50 | ## Usage
51 |
52 | ```python
53 | import torch
54 | import torch.nn as nn
55 | from conformer import Conformer
56 |
57 | batch_size, sequence_length, dim = 3, 12345, 80
58 |
59 | cuda = torch.cuda.is_available()
60 | device = torch.device('cuda' if cuda else 'cpu')
61 |
62 | criterion = nn.CTCLoss().to(device)
63 |
64 | inputs = torch.rand(batch_size, sequence_length, dim).to(device)
65 | input_lengths = torch.LongTensor([12345, 12300, 12000])
66 | targets = torch.LongTensor([[1, 3, 3, 3, 3, 3, 4, 5, 6, 2],
67 | [1, 3, 3, 3, 3, 3, 4, 5, 2, 0],
68 | [1, 3, 3, 3, 3, 3, 4, 2, 0, 0]]).to(device)
69 | target_lengths = torch.LongTensor([9, 8, 7])
70 |
71 | model = Conformer(num_classes=10,
72 | input_dim=dim,
73 | encoder_dim=32,
74 | num_encoder_layers=3).to(device)
75 |
76 | # Forward propagate
77 | outputs, output_lengths = model(inputs, input_lengths)
78 |
79 | # Calculate CTC Loss
80 | loss = criterion(outputs.transpose(0, 1), targets, output_lengths, target_lengths)
81 | ```
82 |
83 | ## Troubleshoots and Contributing
84 | If you have any questions, bug reports, and feature requests, please [open an issue](https://github.com/sooftware/conformer/issues) on github or
85 | contacts sh951011@gmail.com please.
86 |
87 | 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.
88 |
89 | ## Code Style
90 | I follow [PEP-8](https://www.python.org/dev/peps/pep-0008/) for code style. Especially the style of docstrings is important to generate documentation.
91 |
92 | ## Reference
93 | - [Conformer: Convolution-augmented Transformer for Speech Recognition](https://arxiv.org/pdf/2005.08100.pdf)
94 | - [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860)
95 | - [kimiyoung/transformer-xl](https://github.com/kimiyoung/transformer-xl)
96 | - [espnet/espnet](https://github.com/espnet/espnet)
97 |
98 | ## Author
99 |
100 | * Soohwan Kim [@sooftware](https://github.com/sooftware)
101 | * Contacts: sh951011@gmail.com
102 |
--------------------------------------------------------------------------------
/conformer/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021, Soohwan Kim. All rights reserved.
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 .model import Conformer
16 |
--------------------------------------------------------------------------------
/conformer/activation.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021, Soohwan Kim. All rights reserved.
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 torch.nn as nn
16 | from torch import Tensor
17 |
18 |
19 | class Swish(nn.Module):
20 | """
21 | Swish is a smooth, non-monotonic function that consistently matches or outperforms ReLU on deep networks applied
22 | to a variety of challenging domains such as Image classification and Machine translation.
23 | """
24 | def __init__(self):
25 | super(Swish, self).__init__()
26 |
27 | def forward(self, inputs: Tensor) -> Tensor:
28 | return inputs * inputs.sigmoid()
29 |
30 |
31 | class GLU(nn.Module):
32 | """
33 | The gating mechanism is called Gated Linear Units (GLU), which was first introduced for natural language processing
34 | in the paper “Language Modeling with Gated Convolutional Networks”
35 | """
36 | def __init__(self, dim: int) -> None:
37 | super(GLU, self).__init__()
38 | self.dim = dim
39 |
40 | def forward(self, inputs: Tensor) -> Tensor:
41 | outputs, gate = inputs.chunk(2, dim=self.dim)
42 | return outputs * gate.sigmoid()
43 |
--------------------------------------------------------------------------------
/conformer/attention.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021, Soohwan Kim. All rights reserved.
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 | import torch.nn.functional as F
19 | from torch import Tensor
20 | from typing import Optional
21 |
22 | from .embedding import RelPositionalEncoding
23 | from .modules import Linear
24 |
25 |
26 | class RelativeMultiHeadAttention(nn.Module):
27 | """
28 | Multi-head attention with relative positional encoding.
29 | This concept was proposed in the "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context"
30 |
31 | Args:
32 | d_model (int): The dimension of model
33 | num_heads (int): The number of attention heads.
34 | dropout_p (float): probability of dropout
35 |
36 | Inputs: query, key, value, pos_embedding, mask
37 | - **query** (batch, time, dim): Tensor containing query vector
38 | - **key** (batch, time, dim): Tensor containing key vector
39 | - **value** (batch, time, dim): Tensor containing value vector
40 | - **pos_embedding** (batch, time, dim): Positional embedding tensor
41 | - **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked
42 |
43 | Returns:
44 | - **outputs**: Tensor produces by relative multi head attention module.
45 | """
46 | def __init__(
47 | self,
48 | d_model: int = 512,
49 | num_heads: int = 16,
50 | dropout_p: float = 0.1,
51 | ):
52 | super(RelativeMultiHeadAttention, self).__init__()
53 | assert d_model % num_heads == 0, "d_model % num_heads should be zero."
54 | self.d_model = d_model
55 | self.d_head = int(d_model / num_heads)
56 | self.num_heads = num_heads
57 | self.sqrt_dim = math.sqrt(self.d_head)
58 |
59 | self.query_proj = Linear(d_model, d_model)
60 | self.key_proj = Linear(d_model, d_model)
61 | self.value_proj = Linear(d_model, d_model)
62 | self.pos_proj = Linear(d_model, d_model, bias=False)
63 |
64 | self.dropout = nn.Dropout(p=dropout_p)
65 | self.u_bias = nn.Parameter(torch.Tensor(self.num_heads, self.d_head))
66 | self.v_bias = nn.Parameter(torch.Tensor(self.num_heads, self.d_head))
67 | torch.nn.init.xavier_uniform_(self.u_bias)
68 | torch.nn.init.xavier_uniform_(self.v_bias)
69 |
70 | self.out_proj = Linear(d_model, d_model)
71 |
72 | def forward(
73 | self,
74 | query: Tensor,
75 | key: Tensor,
76 | value: Tensor,
77 | pos_embedding: Tensor,
78 | mask: Optional[Tensor] = None,
79 | ) -> Tensor:
80 | batch_size = value.size(0)
81 |
82 | query = self.query_proj(query).view(batch_size, -1, self.num_heads, self.d_head)
83 | key = self.key_proj(key).view(batch_size, -1, self.num_heads, self.d_head).permute(0, 2, 1, 3)
84 | value = self.value_proj(value).view(batch_size, -1, self.num_heads, self.d_head).permute(0, 2, 1, 3)
85 | pos_embedding = self.pos_proj(pos_embedding).view(batch_size, -1, self.num_heads, self.d_head)
86 |
87 | content_score = torch.matmul((query + self.u_bias).transpose(1, 2), key.transpose(2, 3))
88 | pos_score = torch.matmul((query + self.v_bias).transpose(1, 2), pos_embedding.permute(0, 2, 3, 1))
89 | pos_score = self._relative_shift(pos_score)
90 |
91 | score = (content_score + pos_score) / self.sqrt_dim
92 |
93 | if mask is not None:
94 | mask = mask.unsqueeze(1)
95 | score.masked_fill_(mask, -1e9)
96 |
97 | attn = F.softmax(score, -1)
98 | attn = self.dropout(attn)
99 |
100 | context = torch.matmul(attn, value).transpose(1, 2)
101 | context = context.contiguous().view(batch_size, -1, self.d_model)
102 |
103 | return self.out_proj(context)
104 |
105 | def _relative_shift(self, pos_score: Tensor) -> Tensor:
106 | batch_size, num_heads, seq_length1, seq_length2 = pos_score.size()
107 | zeros = pos_score.new_zeros(batch_size, num_heads, seq_length1, 1)
108 | padded_pos_score = torch.cat([zeros, pos_score], dim=-1)
109 |
110 | padded_pos_score = padded_pos_score.view(batch_size, num_heads, seq_length2 + 1, seq_length1)
111 | pos_score = padded_pos_score[:, :, 1:].view_as(pos_score)[:, :, :, : seq_length2 // 2 + 1]
112 |
113 | return pos_score
114 |
115 |
116 | class MultiHeadedSelfAttentionModule(nn.Module):
117 | """
118 | Conformer employ multi-headed self-attention (MHSA) while integrating an important technique from Transformer-XL,
119 | the relative sinusoidal positional encoding scheme. The relative positional encoding allows the self-attention
120 | module to generalize better on different input length and the resulting encoder is more robust to the variance of
121 | the utterance length. Conformer use prenorm residual units with dropout which helps training
122 | and regularizing deeper models.
123 |
124 | Args:
125 | d_model (int): The dimension of model
126 | num_heads (int): The number of attention heads.
127 | dropout_p (float): probability of dropout
128 |
129 | Inputs: inputs, mask
130 | - **inputs** (batch, time, dim): Tensor containing input vector
131 | - **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked
132 |
133 | Returns:
134 | - **outputs** (batch, time, dim): Tensor produces by relative multi headed self attention module.
135 | """
136 | def __init__(self, d_model: int, num_heads: int, dropout_p: float = 0.1):
137 | super(MultiHeadedSelfAttentionModule, self).__init__()
138 | self.positional_encoding = RelPositionalEncoding(d_model)
139 | self.layer_norm = nn.LayerNorm(d_model)
140 | self.attention = RelativeMultiHeadAttention(d_model, num_heads, dropout_p)
141 | self.dropout = nn.Dropout(p=dropout_p)
142 |
143 | def forward(self, inputs: Tensor, mask: Optional[Tensor] = None):
144 | batch_size = inputs.size(0)
145 | pos_embedding = self.positional_encoding(inputs)
146 | pos_embedding = pos_embedding.repeat(batch_size, 1, 1)
147 |
148 | inputs = self.layer_norm(inputs)
149 | outputs = self.attention(inputs, inputs, inputs, pos_embedding=pos_embedding, mask=mask)
150 |
151 | return self.dropout(outputs)
152 |
--------------------------------------------------------------------------------
/conformer/convolution.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021, Soohwan Kim. All rights reserved.
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 torch
16 | import torch.nn as nn
17 | from torch import Tensor
18 | from typing import Tuple
19 |
20 | from .activation import Swish, GLU
21 | from .modules import Transpose
22 |
23 |
24 | class DepthwiseConv1d(nn.Module):
25 | """
26 | When groups == in_channels and out_channels == K * in_channels, where K is a positive integer,
27 | this operation is termed in literature as depthwise convolution.
28 |
29 | Args:
30 | in_channels (int): Number of channels in the input
31 | out_channels (int): Number of channels produced by the convolution
32 | kernel_size (int or tuple): Size of the convolving kernel
33 | stride (int, optional): Stride of the convolution. Default: 1
34 | padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0
35 | bias (bool, optional): If True, adds a learnable bias to the output. Default: True
36 |
37 | Inputs: inputs
38 | - **inputs** (batch, in_channels, time): Tensor containing input vector
39 |
40 | Returns: outputs
41 | - **outputs** (batch, out_channels, time): Tensor produces by depthwise 1-D convolution.
42 | """
43 | def __init__(
44 | self,
45 | in_channels: int,
46 | out_channels: int,
47 | kernel_size: int,
48 | stride: int = 1,
49 | padding: int = 0,
50 | bias: bool = False,
51 | ) -> None:
52 | super(DepthwiseConv1d, self).__init__()
53 | assert out_channels % in_channels == 0, "out_channels should be constant multiple of in_channels"
54 | self.conv = nn.Conv1d(
55 | in_channels=in_channels,
56 | out_channels=out_channels,
57 | kernel_size=kernel_size,
58 | groups=in_channels,
59 | stride=stride,
60 | padding=padding,
61 | bias=bias,
62 | )
63 |
64 | def forward(self, inputs: Tensor) -> Tensor:
65 | return self.conv(inputs)
66 |
67 |
68 | class PointwiseConv1d(nn.Module):
69 | """
70 | When kernel size == 1 conv1d, this operation is termed in literature as pointwise convolution.
71 | This operation often used to match dimensions.
72 |
73 | Args:
74 | in_channels (int): Number of channels in the input
75 | out_channels (int): Number of channels produced by the convolution
76 | stride (int, optional): Stride of the convolution. Default: 1
77 | padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0
78 | bias (bool, optional): If True, adds a learnable bias to the output. Default: True
79 |
80 | Inputs: inputs
81 | - **inputs** (batch, in_channels, time): Tensor containing input vector
82 |
83 | Returns: outputs
84 | - **outputs** (batch, out_channels, time): Tensor produces by pointwise 1-D convolution.
85 | """
86 | def __init__(
87 | self,
88 | in_channels: int,
89 | out_channels: int,
90 | stride: int = 1,
91 | padding: int = 0,
92 | bias: bool = True,
93 | ) -> None:
94 | super(PointwiseConv1d, self).__init__()
95 | self.conv = nn.Conv1d(
96 | in_channels=in_channels,
97 | out_channels=out_channels,
98 | kernel_size=1,
99 | stride=stride,
100 | padding=padding,
101 | bias=bias,
102 | )
103 |
104 | def forward(self, inputs: Tensor) -> Tensor:
105 | return self.conv(inputs)
106 |
107 |
108 | class ConformerConvModule(nn.Module):
109 | """
110 | Conformer convolution module starts with a pointwise convolution and a gated linear unit (GLU).
111 | This is followed by a single 1-D depthwise convolution layer. Batchnorm is deployed just after the convolution
112 | to aid training deep models.
113 |
114 | Args:
115 | in_channels (int): Number of channels in the input
116 | kernel_size (int or tuple, optional): Size of the convolving kernel Default: 31
117 | dropout_p (float, optional): probability of dropout
118 |
119 | Inputs: inputs
120 | inputs (batch, time, dim): Tensor contains input sequences
121 |
122 | Outputs: outputs
123 | outputs (batch, time, dim): Tensor produces by conformer convolution module.
124 | """
125 | def __init__(
126 | self,
127 | in_channels: int,
128 | kernel_size: int = 31,
129 | expansion_factor: int = 2,
130 | dropout_p: float = 0.1,
131 | ) -> None:
132 | super(ConformerConvModule, self).__init__()
133 | assert (kernel_size - 1) % 2 == 0, "kernel_size should be a odd number for 'SAME' padding"
134 | assert expansion_factor == 2, "Currently, Only Supports expansion_factor 2"
135 |
136 | self.sequential = nn.Sequential(
137 | nn.LayerNorm(in_channels),
138 | Transpose(shape=(1, 2)),
139 | PointwiseConv1d(in_channels, in_channels * expansion_factor, stride=1, padding=0, bias=True),
140 | GLU(dim=1),
141 | DepthwiseConv1d(in_channels, in_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2),
142 | nn.BatchNorm1d(in_channels),
143 | Swish(),
144 | PointwiseConv1d(in_channels, in_channels, stride=1, padding=0, bias=True),
145 | nn.Dropout(p=dropout_p),
146 | )
147 |
148 | def forward(self, inputs: Tensor) -> Tensor:
149 | return self.sequential(inputs).transpose(1, 2)
150 |
151 |
152 | class Conv2dSubampling(nn.Module):
153 | """
154 | Convolutional 2D subsampling (to 1/4 length)
155 |
156 | Args:
157 | in_channels (int): Number of channels in the input image
158 | out_channels (int): Number of channels produced by the convolution
159 |
160 | Inputs: inputs
161 | - **inputs** (batch, time, dim): Tensor containing sequence of inputs
162 |
163 | Returns: outputs, output_lengths
164 | - **outputs** (batch, time, dim): Tensor produced by the convolution
165 | - **output_lengths** (batch): list of sequence output lengths
166 | """
167 | def __init__(self, in_channels: int, out_channels: int) -> None:
168 | super(Conv2dSubampling, self).__init__()
169 | self.sequential = nn.Sequential(
170 | nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=2),
171 | nn.ReLU(),
172 | nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=2),
173 | nn.ReLU(),
174 | )
175 |
176 | def forward(self, inputs: Tensor, input_lengths: Tensor) -> Tuple[Tensor, Tensor]:
177 | outputs = self.sequential(inputs.unsqueeze(1))
178 | batch_size, channels, subsampled_lengths, sumsampled_dim = outputs.size()
179 |
180 | outputs = outputs.permute(0, 2, 1, 3)
181 | outputs = outputs.contiguous().view(batch_size, subsampled_lengths, channels * sumsampled_dim)
182 |
183 | output_lengths = input_lengths >> 2
184 | output_lengths -= 1
185 |
186 | return outputs, output_lengths
187 |
--------------------------------------------------------------------------------
/conformer/embedding.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021, Soohwan Kim. All rights reserved.
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 RelPositionalEncoding(nn.Module):
22 | """
23 | Relative positional encoding module.
24 | Args:
25 | d_model: Embedding dimension.
26 | max_len: Maximum input length.
27 | """
28 |
29 | def __init__(self, d_model: int = 512, max_len: int = 5000) -> None:
30 | super(RelPositionalEncoding, self).__init__()
31 | self.d_model = d_model
32 | self.pe = None
33 | self.extend_pe(torch.tensor(0.0).expand(1, max_len))
34 |
35 | def extend_pe(self, x: Tensor) -> None:
36 | if self.pe is not None:
37 | if self.pe.size(1) >= x.size(1) * 2 - 1:
38 | if self.pe.dtype != x.dtype or self.pe.device != x.device:
39 | self.pe = self.pe.to(dtype=x.dtype, device=x.device)
40 | return
41 |
42 | pe_positive = torch.zeros(x.size(1), self.d_model)
43 | pe_negative = torch.zeros(x.size(1), self.d_model)
44 | position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
45 | div_term = torch.exp(
46 | torch.arange(0, self.d_model, 2, dtype=torch.float32) * -(math.log(10000.0) / self.d_model)
47 | )
48 | pe_positive[:, 0::2] = torch.sin(position * div_term)
49 | pe_positive[:, 1::2] = torch.cos(position * div_term)
50 | pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
51 | pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
52 |
53 | pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
54 | pe_negative = pe_negative[1:].unsqueeze(0)
55 | pe = torch.cat([pe_positive, pe_negative], dim=1)
56 | self.pe = pe.to(device=x.device, dtype=x.dtype)
57 |
58 | def forward(self, x: Tensor) -> Tensor:
59 | """
60 | Args:
61 | x : Input tensor B X T X C
62 | Returns:
63 | torch.Tensor: Encoded tensor B X T X C
64 | """
65 | self.extend_pe(x)
66 | pos_emb = self.pe[
67 | :,
68 | self.pe.size(1) // 2 - x.size(1) + 1 : self.pe.size(1) // 2 + x.size(1),
69 | ]
70 | return pos_emb
71 |
--------------------------------------------------------------------------------
/conformer/encoder.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021, Soohwan Kim. All rights reserved.
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 torch
16 | import torch.nn as nn
17 | from torch import Tensor
18 | from typing import Tuple
19 |
20 | from .feed_forward import FeedForwardModule
21 | from .attention import MultiHeadedSelfAttentionModule
22 | from .convolution import (
23 | ConformerConvModule,
24 | Conv2dSubampling,
25 | )
26 | from .modules import (
27 | ResidualConnectionModule,
28 | Linear,
29 | )
30 |
31 |
32 | class ConformerBlock(nn.Module):
33 | """
34 | Conformer block contains two Feed Forward modules sandwiching the Multi-Headed Self-Attention module
35 | and the Convolution module. This sandwich structure is inspired by Macaron-Net, which proposes replacing
36 | the original feed-forward layer in the Transformer block into two half-step feed-forward layers,
37 | one before the attention layer and one after.
38 |
39 | Args:
40 | encoder_dim (int, optional): Dimension of conformer encoder
41 | num_attention_heads (int, optional): Number of attention heads
42 | feed_forward_expansion_factor (int, optional): Expansion factor of feed forward module
43 | conv_expansion_factor (int, optional): Expansion factor of conformer convolution module
44 | feed_forward_dropout_p (float, optional): Probability of feed forward module dropout
45 | attention_dropout_p (float, optional): Probability of attention module dropout
46 | conv_dropout_p (float, optional): Probability of conformer convolution module dropout
47 | conv_kernel_size (int or tuple, optional): Size of the convolving kernel
48 | half_step_residual (bool): Flag indication whether to use half step residual or not
49 |
50 | Inputs: inputs
51 | - **inputs** (batch, time, dim): Tensor containing input vector
52 |
53 | Returns: outputs
54 | - **outputs** (batch, time, dim): Tensor produces by conformer block.
55 | """
56 | def __init__(
57 | self,
58 | encoder_dim: int = 512,
59 | num_attention_heads: int = 8,
60 | feed_forward_expansion_factor: int = 4,
61 | conv_expansion_factor: int = 2,
62 | feed_forward_dropout_p: float = 0.1,
63 | attention_dropout_p: float = 0.1,
64 | conv_dropout_p: float = 0.1,
65 | conv_kernel_size: int = 31,
66 | half_step_residual: bool = True,
67 | ):
68 | super(ConformerBlock, self).__init__()
69 | if half_step_residual:
70 | self.feed_forward_residual_factor = 0.5
71 | else:
72 | self.feed_forward_residual_factor = 1
73 |
74 | self.sequential = nn.Sequential(
75 | ResidualConnectionModule(
76 | module=FeedForwardModule(
77 | encoder_dim=encoder_dim,
78 | expansion_factor=feed_forward_expansion_factor,
79 | dropout_p=feed_forward_dropout_p,
80 | ),
81 | module_factor=self.feed_forward_residual_factor,
82 | ),
83 | ResidualConnectionModule(
84 | module=MultiHeadedSelfAttentionModule(
85 | d_model=encoder_dim,
86 | num_heads=num_attention_heads,
87 | dropout_p=attention_dropout_p,
88 | ),
89 | ),
90 | ResidualConnectionModule(
91 | module=ConformerConvModule(
92 | in_channels=encoder_dim,
93 | kernel_size=conv_kernel_size,
94 | expansion_factor=conv_expansion_factor,
95 | dropout_p=conv_dropout_p,
96 | ),
97 | ),
98 | ResidualConnectionModule(
99 | module=FeedForwardModule(
100 | encoder_dim=encoder_dim,
101 | expansion_factor=feed_forward_expansion_factor,
102 | dropout_p=feed_forward_dropout_p,
103 | ),
104 | module_factor=self.feed_forward_residual_factor,
105 | ),
106 | nn.LayerNorm(encoder_dim),
107 | )
108 |
109 | def forward(self, inputs: Tensor) -> Tensor:
110 | return self.sequential(inputs)
111 |
112 |
113 | class ConformerEncoder(nn.Module):
114 | """
115 | Conformer encoder first processes the input with a convolution subsampling layer and then
116 | with a number of conformer blocks.
117 |
118 | Args:
119 | input_dim (int, optional): Dimension of input vector
120 | encoder_dim (int, optional): Dimension of conformer encoder
121 | num_layers (int, optional): Number of conformer blocks
122 | num_attention_heads (int, optional): Number of attention heads
123 | feed_forward_expansion_factor (int, optional): Expansion factor of feed forward module
124 | conv_expansion_factor (int, optional): Expansion factor of conformer convolution module
125 | feed_forward_dropout_p (float, optional): Probability of feed forward module dropout
126 | attention_dropout_p (float, optional): Probability of attention module dropout
127 | conv_dropout_p (float, optional): Probability of conformer convolution module dropout
128 | conv_kernel_size (int or tuple, optional): Size of the convolving kernel
129 | half_step_residual (bool): Flag indication whether to use half step residual or not
130 |
131 | Inputs: inputs, input_lengths
132 | - **inputs** (batch, time, dim): Tensor containing input vector
133 | - **input_lengths** (batch): list of sequence input lengths
134 |
135 | Returns: outputs, output_lengths
136 | - **outputs** (batch, out_channels, time): Tensor produces by conformer encoder.
137 | - **output_lengths** (batch): list of sequence output lengths
138 | """
139 | def __init__(
140 | self,
141 | input_dim: int = 80,
142 | encoder_dim: int = 512,
143 | num_layers: int = 17,
144 | num_attention_heads: int = 8,
145 | feed_forward_expansion_factor: int = 4,
146 | conv_expansion_factor: int = 2,
147 | input_dropout_p: float = 0.1,
148 | feed_forward_dropout_p: float = 0.1,
149 | attention_dropout_p: float = 0.1,
150 | conv_dropout_p: float = 0.1,
151 | conv_kernel_size: int = 31,
152 | half_step_residual: bool = True,
153 | ):
154 | super(ConformerEncoder, self).__init__()
155 | self.conv_subsample = Conv2dSubampling(in_channels=1, out_channels=encoder_dim)
156 | self.input_projection = nn.Sequential(
157 | Linear(encoder_dim * (((input_dim - 1) // 2 - 1) // 2), encoder_dim),
158 | nn.Dropout(p=input_dropout_p),
159 | )
160 | self.layers = nn.ModuleList([ConformerBlock(
161 | encoder_dim=encoder_dim,
162 | num_attention_heads=num_attention_heads,
163 | feed_forward_expansion_factor=feed_forward_expansion_factor,
164 | conv_expansion_factor=conv_expansion_factor,
165 | feed_forward_dropout_p=feed_forward_dropout_p,
166 | attention_dropout_p=attention_dropout_p,
167 | conv_dropout_p=conv_dropout_p,
168 | conv_kernel_size=conv_kernel_size,
169 | half_step_residual=half_step_residual,
170 | ) for _ in range(num_layers)])
171 |
172 | def count_parameters(self) -> int:
173 | """ Count parameters of encoder """
174 | return sum([p.numel() for p in self.parameters()])
175 |
176 | def update_dropout(self, dropout_p: float) -> None:
177 | """ Update dropout probability of encoder """
178 | for name, child in self.named_children():
179 | if isinstance(child, nn.Dropout):
180 | child.p = dropout_p
181 |
182 | def forward(self, inputs: Tensor, input_lengths: Tensor) -> Tuple[Tensor, Tensor]:
183 | """
184 | Forward propagate a `inputs` for encoder training.
185 |
186 | Args:
187 | inputs (torch.FloatTensor): A input sequence passed to encoder. Typically for inputs this will be a padded
188 | `FloatTensor` of size ``(batch, seq_length, dimension)``.
189 | input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``
190 |
191 | Returns:
192 | (Tensor, Tensor)
193 |
194 | * outputs (torch.FloatTensor): A output sequence of encoder. `FloatTensor` of size
195 | ``(batch, seq_length, dimension)``
196 | * output_lengths (torch.LongTensor): The length of output tensor. ``(batch)``
197 | """
198 | outputs, output_lengths = self.conv_subsample(inputs, input_lengths)
199 | outputs = self.input_projection(outputs)
200 |
201 | for layer in self.layers:
202 | outputs = layer(outputs)
203 |
204 | return outputs, output_lengths
205 |
--------------------------------------------------------------------------------
/conformer/feed_forward.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021, Soohwan Kim. All rights reserved.
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 torch
16 | import torch.nn as nn
17 | from torch import Tensor
18 |
19 | from .activation import Swish
20 | from .modules import Linear
21 |
22 |
23 | class FeedForwardModule(nn.Module):
24 | """
25 | Conformer Feed Forward Module follow pre-norm residual units and apply layer normalization within the residual unit
26 | and on the input before the first linear layer. This module also apply Swish activation and dropout, which helps
27 | regularizing the network.
28 |
29 | Args:
30 | encoder_dim (int): Dimension of conformer encoder
31 | expansion_factor (int): Expansion factor of feed forward module.
32 | dropout_p (float): Ratio of dropout
33 |
34 | Inputs: inputs
35 | - **inputs** (batch, time, dim): Tensor contains input sequences
36 |
37 | Outputs: outputs
38 | - **outputs** (batch, time, dim): Tensor produces by feed forward module.
39 | """
40 | def __init__(
41 | self,
42 | encoder_dim: int = 512,
43 | expansion_factor: int = 4,
44 | dropout_p: float = 0.1,
45 | ) -> None:
46 | super(FeedForwardModule, self).__init__()
47 | self.sequential = nn.Sequential(
48 | nn.LayerNorm(encoder_dim),
49 | Linear(encoder_dim, encoder_dim * expansion_factor, bias=True),
50 | Swish(),
51 | nn.Dropout(p=dropout_p),
52 | Linear(encoder_dim * expansion_factor, encoder_dim, bias=True),
53 | nn.Dropout(p=dropout_p),
54 | )
55 |
56 | def forward(self, inputs: Tensor) -> Tensor:
57 | return self.sequential(inputs)
58 |
--------------------------------------------------------------------------------
/conformer/model.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021, Soohwan Kim. All rights reserved.
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 torch
16 | import torch.nn as nn
17 | from torch import Tensor
18 | from typing import Tuple
19 |
20 | from .encoder import ConformerEncoder
21 | from .modules import Linear
22 |
23 |
24 | class Conformer(nn.Module):
25 | """
26 | Conformer: Convolution-augmented Transformer for Speech Recognition
27 | The paper used a one-lstm Transducer decoder, currently still only implemented
28 | the conformer encoder shown in the paper.
29 |
30 | Args:
31 | num_classes (int): Number of classification classes
32 | input_dim (int, optional): Dimension of input vector
33 | encoder_dim (int, optional): Dimension of conformer encoder
34 | num_encoder_layers (int, optional): Number of conformer blocks
35 | num_attention_heads (int, optional): Number of attention heads
36 | feed_forward_expansion_factor (int, optional): Expansion factor of feed forward module
37 | conv_expansion_factor (int, optional): Expansion factor of conformer convolution module
38 | feed_forward_dropout_p (float, optional): Probability of feed forward module dropout
39 | attention_dropout_p (float, optional): Probability of attention module dropout
40 | conv_dropout_p (float, optional): Probability of conformer convolution module dropout
41 | conv_kernel_size (int or tuple, optional): Size of the convolving kernel
42 | half_step_residual (bool): Flag indication whether to use half step residual or not
43 |
44 | Inputs: inputs, input_lengths
45 | - **inputs** (batch, time, dim): Tensor containing input vector
46 | - **input_lengths** (batch): list of sequence input lengths
47 |
48 | Returns: outputs, output_lengths
49 | - **outputs** (batch, out_channels, time): Tensor produces by conformer.
50 | - **output_lengths** (batch): list of sequence output lengths
51 | """
52 | def __init__(
53 | self,
54 | num_classes: int,
55 | input_dim: int = 80,
56 | encoder_dim: int = 512,
57 | num_encoder_layers: int = 17,
58 | num_attention_heads: int = 8,
59 | feed_forward_expansion_factor: int = 4,
60 | conv_expansion_factor: int = 2,
61 | input_dropout_p: float = 0.1,
62 | feed_forward_dropout_p: float = 0.1,
63 | attention_dropout_p: float = 0.1,
64 | conv_dropout_p: float = 0.1,
65 | conv_kernel_size: int = 31,
66 | half_step_residual: bool = True,
67 | ) -> None:
68 | super(Conformer, self).__init__()
69 | self.encoder = ConformerEncoder(
70 | input_dim=input_dim,
71 | encoder_dim=encoder_dim,
72 | num_layers=num_encoder_layers,
73 | num_attention_heads=num_attention_heads,
74 | feed_forward_expansion_factor=feed_forward_expansion_factor,
75 | conv_expansion_factor=conv_expansion_factor,
76 | input_dropout_p=input_dropout_p,
77 | feed_forward_dropout_p=feed_forward_dropout_p,
78 | attention_dropout_p=attention_dropout_p,
79 | conv_dropout_p=conv_dropout_p,
80 | conv_kernel_size=conv_kernel_size,
81 | half_step_residual=half_step_residual,
82 | )
83 | self.fc = Linear(encoder_dim, num_classes, bias=False)
84 |
85 | def count_parameters(self) -> int:
86 | """ Count parameters of encoder """
87 | return self.encoder.count_parameters()
88 |
89 | def update_dropout(self, dropout_p) -> None:
90 | """ Update dropout probability of model """
91 | self.encoder.update_dropout(dropout_p)
92 |
93 | def forward(self, inputs: Tensor, input_lengths: Tensor) -> Tuple[Tensor, Tensor]:
94 | """
95 | Forward propagate a `inputs` and `targets` pair for training.
96 |
97 | Args:
98 | inputs (torch.FloatTensor): A input sequence passed to encoder. Typically for inputs this will be a padded
99 | `FloatTensor` of size ``(batch, seq_length, dimension)``.
100 | input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``
101 |
102 | Returns:
103 | * predictions (torch.FloatTensor): Result of model predictions.
104 | """
105 | encoder_outputs, encoder_output_lengths = self.encoder(inputs, input_lengths)
106 | outputs = self.fc(encoder_outputs)
107 | outputs = nn.functional.log_softmax(outputs, dim=-1)
108 | return outputs, encoder_output_lengths
109 |
--------------------------------------------------------------------------------
/conformer/modules.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2021, Soohwan Kim. All rights reserved.
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 torch
16 | import torch.nn as nn
17 | import torch.nn.init as init
18 | from torch import Tensor
19 |
20 |
21 | class ResidualConnectionModule(nn.Module):
22 | """
23 | Residual Connection Module.
24 | outputs = (module(inputs) x module_factor + inputs x input_factor)
25 | """
26 | def __init__(self, module: nn.Module, module_factor: float = 1.0, input_factor: float = 1.0):
27 | super(ResidualConnectionModule, self).__init__()
28 | self.module = module
29 | self.module_factor = module_factor
30 | self.input_factor = input_factor
31 |
32 | def forward(self, inputs: Tensor) -> Tensor:
33 | return (self.module(inputs) * self.module_factor) + (inputs * self.input_factor)
34 |
35 |
36 | class Linear(nn.Module):
37 | """
38 | Wrapper class of torch.nn.Linear
39 | Weight initialize by xavier initialization and bias initialize to zeros.
40 | """
41 | def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None:
42 | super(Linear, self).__init__()
43 | self.linear = nn.Linear(in_features, out_features, bias=bias)
44 | init.xavier_uniform_(self.linear.weight)
45 | if bias:
46 | init.zeros_(self.linear.bias)
47 |
48 | def forward(self, x: Tensor) -> Tensor:
49 | return self.linear(x)
50 |
51 |
52 | class View(nn.Module):
53 | """ Wrapper class of torch.view() for Sequential module. """
54 | def __init__(self, shape: tuple, contiguous: bool = False):
55 | super(View, self).__init__()
56 | self.shape = shape
57 | self.contiguous = contiguous
58 |
59 | def forward(self, x: Tensor) -> Tensor:
60 | if self.contiguous:
61 | x = x.contiguous()
62 |
63 | return x.view(*self.shape)
64 |
65 |
66 | class Transpose(nn.Module):
67 | """ Wrapper class of torch.transpose() for Sequential module. """
68 | def __init__(self, shape: tuple):
69 | super(Transpose, self).__init__()
70 | self.shape = shape
71 |
72 | def forward(self, x: Tensor) -> Tensor:
73 | return x.transpose(*self.shape)
74 |
--------------------------------------------------------------------------------
/docs/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sooftware/conformer/b4e7d44944214db6e5912f92ff43d5ea1919eaa2/docs/.DS_Store
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line, and also
5 | # from the environment for the first two.
6 | SPHINXOPTS ?=
7 | SPHINXBUILD ?= sphinx-build
8 | SOURCEDIR = source
9 | BUILDDIR = build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
21 |
--------------------------------------------------------------------------------
/docs/Model.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |