samuli commited on
Commit
3dd0f09
·
verified ·
1 Parent(s): 7ae47ac

Initial release

Browse files
.gitattributes CHANGED
@@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ architecture.png filter=lfs diff=lfs merge=lfs -text
37
+ examples/commonvoice_1.wav filter=lfs diff=lfs merge=lfs -text
38
+ examples/commonvoice_2.wav filter=lfs diff=lfs merge=lfs -text
39
+ examples/commonvoice_3.wav filter=lfs diff=lfs merge=lfs -text
40
+ examples/commonvoice_4.wav filter=lfs diff=lfs merge=lfs -text
41
+ examples/commonvoice_5.wav filter=lfs diff=lfs merge=lfs -text
42
+ examples/commonvoice_6.wav filter=lfs diff=lfs merge=lfs -text
43
+ examples/voxpopuli_1.wav filter=lfs diff=lfs merge=lfs -text
44
+ examples/voxpopuli_2.wav filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution-NonCommercial 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution-NonCommercial 4.0 International Public
58
+ License
59
+
60
+ By exercising the Licensed Rights (defined below), You accept and agree
61
+ to be bound by the terms and conditions of this Creative Commons
62
+ Attribution-NonCommercial 4.0 International Public License ("Public
63
+ License"). To the extent this Public License may be interpreted as a
64
+ contract, You are granted the Licensed Rights in consideration of Your
65
+ acceptance of these terms and conditions, and the Licensor grants You
66
+ such rights in consideration of benefits the Licensor receives from
67
+ making the Licensed Material available under these terms and
68
+ conditions.
69
+
70
+
71
+ Section 1 -- Definitions.
72
+
73
+ a. Adapted Material means material subject to Copyright and Similar
74
+ Rights that is derived from or based upon the Licensed Material
75
+ and in which the Licensed Material is translated, altered,
76
+ arranged, transformed, or otherwise modified in a manner requiring
77
+ permission under the Copyright and Similar Rights held by the
78
+ Licensor. For purposes of this Public License, where the Licensed
79
+ Material is a musical work, performance, or sound recording,
80
+ Adapted Material is always produced where the Licensed Material is
81
+ synched in timed relation with a moving image.
82
+
83
+ b. Adapter's License means the license You apply to Your Copyright
84
+ and Similar Rights in Your contributions to Adapted Material in
85
+ accordance with the terms and conditions of this Public License.
86
+
87
+ c. Copyright and Similar Rights means copyright and/or similar rights
88
+ closely related to copyright including, without limitation,
89
+ performance, broadcast, sound recording, and Sui Generis Database
90
+ Rights, without regard to how the rights are labeled or
91
+ categorized. For purposes of this Public License, the rights
92
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
93
+ Rights.
94
+ d. Effective Technological Measures means those measures that, in the
95
+ absence of proper authority, may not be circumvented under laws
96
+ fulfilling obligations under Article 11 of the WIPO Copyright
97
+ Treaty adopted on December 20, 1996, and/or similar international
98
+ agreements.
99
+
100
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
101
+ any other exception or limitation to Copyright and Similar Rights
102
+ that applies to Your use of the Licensed Material.
103
+
104
+ f. Licensed Material means the artistic or literary work, database,
105
+ or other material to which the Licensor applied this Public
106
+ License.
107
+
108
+ g. Licensed Rights means the rights granted to You subject to the
109
+ terms and conditions of this Public License, which are limited to
110
+ all Copyright and Similar Rights that apply to Your use of the
111
+ Licensed Material and that the Licensor has authority to license.
112
+
113
+ h. Licensor means the individual(s) or entity(ies) granting rights
114
+ under this Public License.
115
+
116
+ i. NonCommercial means not primarily intended for or directed towards
117
+ commercial advantage or monetary compensation. For purposes of
118
+ this Public License, the exchange of the Licensed Material for
119
+ other material subject to Copyright and Similar Rights by digital
120
+ file-sharing or similar means is NonCommercial provided there is
121
+ no payment of monetary compensation in connection with the
122
+ exchange.
123
+
124
+ j. Share means to provide material to the public by any means or
125
+ process that requires permission under the Licensed Rights, such
126
+ as reproduction, public display, public performance, distribution,
127
+ dissemination, communication, or importation, and to make material
128
+ available to the public including in ways that members of the
129
+ public may access the material from a place and at a time
130
+ individually chosen by them.
131
+
132
+ k. Sui Generis Database Rights means rights other than copyright
133
+ resulting from Directive 96/9/EC of the European Parliament and of
134
+ the Council of 11 March 1996 on the legal protection of databases,
135
+ as amended and/or succeeded, as well as other essentially
136
+ equivalent rights anywhere in the world.
137
+
138
+ l. You means the individual or entity exercising the Licensed Rights
139
+ under this Public License. Your has a corresponding meaning.
140
+
141
+
142
+ Section 2 -- Scope.
143
+
144
+ a. License grant.
145
+
146
+ 1. Subject to the terms and conditions of this Public License,
147
+ the Licensor hereby grants You a worldwide, royalty-free,
148
+ non-sublicensable, non-exclusive, irrevocable license to
149
+ exercise the Licensed Rights in the Licensed Material to:
150
+
151
+ a. reproduce and Share the Licensed Material, in whole or
152
+ in part, for NonCommercial purposes only; and
153
+
154
+ b. produce, reproduce, and Share Adapted Material for
155
+ NonCommercial purposes only.
156
+
157
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
158
+ Exceptions and Limitations apply to Your use, this Public
159
+ License does not apply, and You do not need to comply with
160
+ its terms and conditions.
161
+
162
+ 3. Term. The term of this Public License is specified in Section
163
+ 6(a).
164
+
165
+ 4. Media and formats; technical modifications allowed. The
166
+ Licensor authorizes You to exercise the Licensed Rights in
167
+ all media and formats whether now known or hereafter created,
168
+ and to make technical modifications necessary to do so. The
169
+ Licensor waives and/or agrees not to assert any right or
170
+ authority to forbid You from making technical modifications
171
+ necessary to exercise the Licensed Rights, including
172
+ technical modifications necessary to circumvent Effective
173
+ Technological Measures. For purposes of this Public License,
174
+ simply making modifications authorized by this Section 2(a)
175
+ (4) never produces Adapted Material.
176
+
177
+ 5. Downstream recipients.
178
+
179
+ a. Offer from the Licensor -- Licensed Material. Every
180
+ recipient of the Licensed Material automatically
181
+ receives an offer from the Licensor to exercise the
182
+ Licensed Rights under the terms and conditions of this
183
+ Public License.
184
+
185
+ b. No downstream restrictions. You may not offer or impose
186
+ any additional or different terms or conditions on, or
187
+ apply any Effective Technological Measures to, the
188
+ Licensed Material if doing so restricts exercise of the
189
+ Licensed Rights by any recipient of the Licensed
190
+ Material.
191
+
192
+ 6. No endorsement. Nothing in this Public License constitutes or
193
+ may be construed as permission to assert or imply that You
194
+ are, or that Your use of the Licensed Material is, connected
195
+ with, or sponsored, endorsed, or granted official status by,
196
+ the Licensor or others designated to receive attribution as
197
+ provided in Section 3(a)(1)(A)(i).
198
+
199
+ b. Other rights.
200
+
201
+ 1. Moral rights, such as the right of integrity, are not
202
+ licensed under this Public License, nor are publicity,
203
+ privacy, and/or other similar personality rights; however, to
204
+ the extent possible, the Licensor waives and/or agrees not to
205
+ assert any such rights held by the Licensor to the limited
206
+ extent necessary to allow You to exercise the Licensed
207
+ Rights, but not otherwise.
208
+
209
+ 2. Patent and trademark rights are not licensed under this
210
+ Public License.
211
+
212
+ 3. To the extent possible, the Licensor waives any right to
213
+ collect royalties from You for the exercise of the Licensed
214
+ Rights, whether directly or through a collecting society
215
+ under any voluntary or waivable statutory or compulsory
216
+ licensing scheme. In all other cases the Licensor expressly
217
+ reserves any right to collect such royalties, including when
218
+ the Licensed Material is used other than for NonCommercial
219
+ purposes.
220
+
221
+
222
+ Section 3 -- License Conditions.
223
+
224
+ Your exercise of the Licensed Rights is expressly made subject to the
225
+ following conditions.
226
+
227
+ a. Attribution.
228
+
229
+ 1. If You Share the Licensed Material (including in modified
230
+ form), You must:
231
+
232
+ a. retain the following if it is supplied by the Licensor
233
+ with the Licensed Material:
234
+
235
+ i. identification of the creator(s) of the Licensed
236
+ Material and any others designated to receive
237
+ attribution, in any reasonable manner requested by
238
+ the Licensor (including by pseudonym if
239
+ designated);
240
+
241
+ ii. a copyright notice;
242
+
243
+ iii. a notice that refers to this Public License;
244
+
245
+ iv. a notice that refers to the disclaimer of
246
+ warranties;
247
+
248
+ v. a URI or hyperlink to the Licensed Material to the
249
+ extent reasonably practicable;
250
+
251
+ b. indicate if You modified the Licensed Material and
252
+ retain an indication of any previous modifications; and
253
+
254
+ c. indicate the Licensed Material is licensed under this
255
+ Public License, and include the text of, or the URI or
256
+ hyperlink to, this Public License.
257
+
258
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
259
+ reasonable manner based on the medium, means, and context in
260
+ which You Share the Licensed Material. For example, it may be
261
+ reasonable to satisfy the conditions by providing a URI or
262
+ hyperlink to a resource that includes the required
263
+ information.
264
+
265
+ 3. If requested by the Licensor, You must remove any of the
266
+ information required by Section 3(a)(1)(A) to the extent
267
+ reasonably practicable.
268
+
269
+ 4. If You Share Adapted Material You produce, the Adapter's
270
+ License You apply must not prevent recipients of the Adapted
271
+ Material from complying with this Public License.
272
+
273
+
274
+ Section 4 -- Sui Generis Database Rights.
275
+
276
+ Where the Licensed Rights include Sui Generis Database Rights that
277
+ apply to Your use of the Licensed Material:
278
+
279
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
280
+ to extract, reuse, reproduce, and Share all or a substantial
281
+ portion of the contents of the database for NonCommercial purposes
282
+ only;
283
+
284
+ b. if You include all or a substantial portion of the database
285
+ contents in a database in which You have Sui Generis Database
286
+ Rights, then the database in which You have Sui Generis Database
287
+ Rights (but not its individual contents) is Adapted Material; and
288
+
289
+ c. You must comply with the conditions in Section 3(a) if You Share
290
+ all or a substantial portion of the contents of the database.
291
+
292
+ For the avoidance of doubt, this Section 4 supplements and does not
293
+ replace Your obligations under this Public License where the Licensed
294
+ Rights include other Copyright and Similar Rights.
295
+
296
+
297
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
298
+
299
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
300
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
301
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
302
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
303
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
304
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
305
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
306
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
307
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
308
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
309
+
310
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
311
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
312
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
313
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
314
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
315
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
316
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
317
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
318
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
319
+
320
+ c. The disclaimer of warranties and limitation of liability provided
321
+ above shall be interpreted in a manner that, to the extent
322
+ possible, most closely approximates an absolute disclaimer and
323
+ waiver of all liability.
324
+
325
+
326
+ Section 6 -- Term and Termination.
327
+
328
+ a. This Public License applies for the term of the Copyright and
329
+ Similar Rights licensed here. However, if You fail to comply with
330
+ this Public License, then Your rights under this Public License
331
+ terminate automatically.
332
+
333
+ b. Where Your right to use the Licensed Material has terminated under
334
+ Section 6(a), it reinstates:
335
+
336
+ 1. automatically as of the date the violation is cured, provided
337
+ it is cured within 30 days of Your discovery of the
338
+ violation; or
339
+
340
+ 2. upon express reinstatement by the Licensor.
341
+
342
+ For the avoidance of doubt, this Section 6(b) does not affect any
343
+ right the Licensor may have to seek remedies for Your violations
344
+ of this Public License.
345
+
346
+ c. For the avoidance of doubt, the Licensor may also offer the
347
+ Licensed Material under separate terms or conditions or stop
348
+ distributing the Licensed Material at any time; however, doing so
349
+ will not terminate this Public License.
350
+
351
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
352
+ License.
353
+
354
+
355
+ Section 7 -- Other Terms and Conditions.
356
+
357
+ a. The Licensor shall not be bound by any additional or different
358
+ terms or conditions communicated by You unless expressly agreed.
359
+
360
+ b. Any arrangements, understandings, or agreements regarding the
361
+ Licensed Material not stated herein are separate from and
362
+ independent of the terms and conditions of this Public License.
363
+
364
+
365
+ Section 8 -- Interpretation.
366
+
367
+ a. For the avoidance of doubt, this Public License does not, and
368
+ shall not be interpreted to, reduce, limit, restrict, or impose
369
+ conditions on any use of the Licensed Material that could lawfully
370
+ be made without permission under this Public License.
371
+
372
+ b. To the extent possible, if any provision of this Public License is
373
+ deemed unenforceable, it shall be automatically reformed to the
374
+ minimum extent necessary to make it enforceable. If the provision
375
+ cannot be reformed, it shall be severed from this Public License
376
+ without affecting the enforceability of the remaining terms and
377
+ conditions.
378
+
379
+ c. No term or condition of this Public License will be waived and no
380
+ failure to comply consented to unless expressly agreed to by the
381
+ Licensor.
382
+
383
+ d. Nothing in this Public License constitutes or may be interpreted
384
+ as a limitation upon, or waiver of, any privileges and immunities
385
+ that apply to the Licensor or You, including from the legal
386
+ processes of any jurisdiction or authority.
387
+
388
+ =======================================================================
389
+
390
+ Creative Commons is not a party to its public
391
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
392
+ its public licenses to material it publishes and in those instances
393
+ will be considered the “Licensor.” The text of the Creative Commons
394
+ public licenses is dedicated to the public domain under the CC0 Public
395
+ Domain Dedication. Except for the limited purpose of indicating that
396
+ material is shared under a Creative Commons public license or as
397
+ otherwise permitted by the Creative Commons policies published at
398
+ creativecommons.org/policies, Creative Commons does not authorize the
399
+ use of the trademark "Creative Commons" or any other trademark or logo
400
+ of Creative Commons without its prior written consent including,
401
+ without limitation, in connection with any unauthorized modifications
402
+ to any of its public licenses or any other arrangements,
403
+ understandings, or agreements concerning use of licensed material. For
404
+ the avoidance of doubt, this paragraph does not form part of the
405
+ public licenses.
406
+
407
+ Creative Commons may be contacted at creativecommons.org.
408
+
README.md ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - fi
4
+ license: cc-by-nc-4.0
5
+ library_name: pytorch
6
+ pipeline_tag: automatic-speech-recognition
7
+ tags:
8
+ - speech-recognition
9
+ - streaming
10
+ - transducer
11
+ - rnnt
12
+ - mingru
13
+ - finnish
14
+ model-index:
15
+ - name: mateli
16
+ results:
17
+ - task:
18
+ type: automatic-speech-recognition
19
+ dataset:
20
+ name: Common Voice 17.0 (fi, test)
21
+ type: mozilla-foundation/common_voice_17_0
22
+ config: fi
23
+ split: test
24
+ metrics:
25
+ - type: wer
26
+ value: 15.03
27
+ - type: cer
28
+ value: 3.08
29
+ - task:
30
+ type: automatic-speech-recognition
31
+ dataset:
32
+ name: FLEURS (fi, SIB-Fleurs subset)
33
+ type: google/fleurs
34
+ config: fi_fi
35
+ metrics:
36
+ - type: wer
37
+ value: 18.47
38
+ - type: cer
39
+ value: 7.49
40
+ - task:
41
+ type: automatic-speech-recognition
42
+ dataset:
43
+ name: VoxPopuli (fi, test)
44
+ type: facebook/voxpopuli
45
+ config: fi
46
+ split: test
47
+ metrics:
48
+ - type: wer
49
+ value: 17.44
50
+ - type: cer
51
+ value: 7.62
52
+ ---
53
+
54
+ # Mateli: streaming Finnish speech recognition
55
+
56
+ Mateli is a small streaming speech recognition model for Finnish (59.6 M parameters). Audio is processed in 320 ms chunks, each chunk sees only itself and the past, and the state carried between chunks has a fixed size. That makes it cheap enough to run live on a phone. This repository has the PyTorch weights and a single-file reference implementation. For streaming on phones and CPUs, use the ONNX export, [samuli/mateli-onnx](https://huggingface.co/samuli/mateli-onnx).
57
+
58
+ Mateli is not the most accurate Finnish recogniser. It makes mistakes on every kind of speech, and more of them on spontaneous conversation than on read or prepared speech. Its strengths are streaming output, low latency and a low cost to run.
59
+
60
+ Its output is lowercase words with word times, without punctuation. [samuli/mateli-punct](https://huggingface.co/samuli/mateli-punct) adds punctuation and capitals.
61
+
62
+ ## Examples
63
+
64
+ Eight clips from public test sets are in `examples/`, and `examples/references.tsv` lists their sources and reference transcripts. The outputs below are from `python mateli.py examples/<clip>.wav`.
65
+
66
+ Sentences written in colloquial Finnish (Common Voice), with [whisper-large-v3](https://huggingface.co/openai/whisper-large-v3) for comparison:
67
+
68
+ | clip | reference | whisper-large-v3 | Mateli |
69
+ |---|---|---|---|
70
+ | `commonvoice_4` | mä en oo ehtiny vielä katsoa. | Mä en ole ehtinyt vielä katsoa. | mä en oo ehtiny vielä katsoa |
71
+ | `commonvoice_5` | miten me voidaa olla varmoja et sä puhut totta? | Miten me voidaan olla varmoja, että sä puhut totta? | miten me voidaan olla varmoja et sä puhu totta |
72
+ | `commonvoice_6` | sano vaa aika ja paikka ni miä tuun mukkaa kuulin itseni sanovan. | Sano vaan aika ja paikka, niin minä tuun mukaan, kuulin itseni sanoa. | sano vaa aika ja paikka niin minä tuun mukkaa kuulin itseni sanovan |
73
+
74
+ Mateli writes the words in the form they were spoken (*oo ehtiny*, *et*, *vaa*, *mukkaa*), while Whisper turns them into standard written Finnish (*ole ehtinyt*, *että*, *vaan*, *mukaan*). Mateli also makes mistakes here. It writes *voidaan* for *voidaa*, *puhu* for *puhut* and *niin minä* for *ni miä*. Whisper was run with faster-whisper (int8 on CPU, beam 5, language set to Finnish).
75
+
76
+ Sentences in written Finnish (Common Voice and VoxPopuli):
77
+
78
+ | clip | reference | output |
79
+ |---|---|---|
80
+ | `commonvoice_1` | äänestin päätöslauselmaa vastaan koska siinä ei käsitellä riittävästi näitä seikkoja. | äänestin päätöslauselmaa vastaan koska siinä ei käsitellä riittävästi näitä seikkoja |
81
+ | `commonvoice_2` | ne koostuivat eritavoin asetelluista ympyröistä. | ne koostuivat eri tavoin asetelluissa ympyröistä |
82
+ | `commonvoice_3` | kaikki mikä tekisi tästä tuskasta edes hitusen siedettävämpää oli kiellettyä. | kaikki mikä tekis tästä tuskasta edes hitusen siedettävämpää oli kiellettyä |
83
+ | `voxpopuli_1` | arvoisa puhemies äänestin tämän mietinnön puolesta. vaikka komission tiedonannosta on kulunut jo yli kymmenen vuotta eivät kaikki matkustajat edelleenkään tiedä oikeuksistaan. | repo äänestin tämän mietinnön puolesta öö vaikka komission tiedonainnosta on kulunut jo yli kymmeneen vuotta eivät kaikki matkustajat edelleenkään tiedä oikeuksistaan |
84
+ | `voxpopuli_2` | boikotoiminen vaaleissa ja mielenosoitus ovat eri asioita mutta erittäin huolestuttavia ovat tiedot siitä että useampi kuin joka kymmenes äänestyspaikka ei voinut avata oviaan opposition saarron takia. | boiko toiminen vaaleissa ja mielenosoitus ovat eri asioita mutta erittäin huolestuttavia ovat tiedot siitä että useampi kuin joka kymmenen säänestyspaikka ei voinut avata oviaan opposition saannon takia |
85
+
86
+ Typical mistakes are wrong case endings (*asetelluissa*), split or misheard words (*boiko toiminen*, *säänestyspaikka*), an unclear start turned into a different word (*repo* for *arvoisa puhemies*), hesitation sounds written out (*öö*) and spoken forms kept as spoken (*tekis*).
87
+
88
+ Word times with `--words` (start and end in seconds):
89
+
90
+ ```
91
+ $ python mateli.py examples/commonvoice_2.wav --words
92
+ 1.60 1.64 ne
93
+ 1.76 2.40 koostuivat
94
+ 2.60 2.72 eri
95
+ 2.84 3.16 tavoin
96
+ 3.28 4.04 asetelluissa
97
+ 4.20 4.72 ympyröistä
98
+ ```
99
+
100
+ ## How to use
101
+
102
+ ```
103
+ pip install torch safetensors soundfile scipy
104
+ hf download samuli/mateli --local-dir mateli
105
+ python mateli/mateli.py mateli/examples/commonvoice_2.wav
106
+ ```
107
+
108
+ From Python (run next to the downloaded `mateli` directory):
109
+
110
+ ```python
111
+ import sys
112
+ sys.path.insert(0, "mateli")
113
+ from mateli import Mateli, load_audio
114
+
115
+ asr = Mateli.from_pretrained("mateli") # GPU if available, else CPU
116
+ result = asr.transcribe(load_audio("mateli/examples/commonvoice_3.wav"))
117
+ print(result.text)
118
+ for word in result.words[:3]:
119
+ print(word)
120
+ ```
121
+
122
+ ```
123
+ kaikki mikä tekis tästä tuskasta edes hitusen siedettävämpää oli kiellettyä
124
+ Word(text='kaikki', start=1.16, end=1.44)
125
+ Word(text='mikä', start=1.72, end=1.88)
126
+ Word(text='tekis', start=1.96, end=2.12)
127
+ ```
128
+
129
+ `transcribe()` takes float32 mono 16 kHz samples and runs the same 320 ms chunk loop that live streaming would, so its output equals streaming recognition of the same audio, and memory use stays flat on long recordings. The output is the same as the ONNX export's fp32 encoder.
130
+
131
+ ### Files
132
+
133
+ | file | what |
134
+ |---|---|
135
+ | `model.safetensors` | weights, fp32 (238 MB) |
136
+ | `config.json` | model settings and vocabulary |
137
+ | `mateli.py` | model definition, transcription, command line |
138
+
139
+ ## Model
140
+
141
+ ![Mateli architecture and streaming](architecture.png)
142
+
143
+ | | |
144
+ |---|---|
145
+ | parameters | 59.6 M |
146
+ | input | 16 kHz mono, 80-bin log-mel (25 ms window, 10 ms hop) |
147
+ | encoder | two stride-2 Conv2d (40 ms frames), 16 blocks of feed-forward / MinGRU / causal depthwise convolution / feed-forward, windowed self-attention after blocks 4, 7, 10 and 13 |
148
+ | attention window | the current 320 ms chunk + 64 earlier frames (2.56 s), no positional encoding |
149
+ | decoder | RNN-T: one-layer MinGRU prediction network, additive joiner, greedy search |
150
+ | output | 44 characters (blank, space, a-z, å, ä, ö, 0-9, `. ? !`) |
151
+ | latency | 320 ms chunks |
152
+ | compute | about 2 GMAC per second of audio |
153
+
154
+ [MinGRU](https://arxiv.org/abs/2410.01201) is a minimal gated recurrent unit whose gates do not depend on the previous state, so a whole chunk is computed in parallel with a log-space scan while streaming still carries a single state vector per layer. The model was trained with the RNN-T loss and an auxiliary CTC loss (the CTC head is not included).
155
+
156
+ ## Training data
157
+
158
+ About 2,600 hours of Finnish speech from various publicly available sources and different registers. Transcripts are either human produced or from larger Finnish speech recognition models. Most of the machine transcripts were produced with [GetmanY1/wav2vec2-xlarge-fi-150k-finetuned](https://huggingface.co/GetmanY1/wav2vec2-xlarge-fi-150k-finetuned).
159
+
160
+ The transcripts of conversational speech are deliberately verbatim. They write down what was said, in the form it was said (*mä*, *tekis*, *mahollisimman*), including hesitations like *öö*, instead of turning it into written language. Spoken Finnish differs a lot from written Finnish, and a verbatim transcript keeps that information. It stays faithful to the speaker, every spoken word gets its own time, and written forms can still be produced afterwards. Words that a cleaned-up transcript dropped or rewrote cannot be recovered. Read and prepared speech was transcribed in standard written form. The model learned both styles, so its output follows the speech. The cost is a higher word error rate against written-language references (see [Evaluation](#evaluation)).
161
+
162
+ ## Evaluation
163
+
164
+ Word and character error rates (%). References and outputs are lowercased, with punctuation removed and foreign diacritics removed (é becomes e).
165
+
166
+ | test set | clips | hours | words | WER | CER |
167
+ |---|---:|---:|---:|---:|---:|
168
+ | Common Voice 17.0, fi test (read sentences) | 1,763 | 2.50 | 11,135 | 15.03 | 3.08 |
169
+ | FLEURS fi, SIB-Fleurs subset (read sentences) | 175 | 0.64 | 2,766 | 18.47 | 7.49 |
170
+ | VoxPopuli fi test (parliamentary speeches) | 452 | 1.27 | 7,338 | 17.44 | 7.62 |
171
+
172
+ Part of every WER comes from spelling choices. Spoken forms (*mä*, *tekis*) and compound words written apart or together count as errors against a written-language reference.
173
+
174
+ ## Limitations
175
+
176
+ - No punctuation or capitals, and numbers are written as words. Use [samuli/mateli-punct](https://huggingface.co/samuli/mateli-punct) for punctuation and casing.
177
+ - Accuracy drops on spontaneous conversation, overlapping speakers, dialects, noise and rare names.
178
+ - Greedy decoding only, no language model.
179
+ - Finnish only.
180
+ - Behaviour on music, other languages and long non-speech passages has not been evaluated.
181
+
182
+ ## License
183
+
184
+ The model weights and the code in this repository are licensed under [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/). The example clips in `examples/` are CC0 (Common Voice and VoxPopuli).
architecture.png ADDED

Git LFS Details

  • SHA256: 260df6dac7e67bf01c814dc16ef6092a2d27b47c7911ad3622b6b8be8318b0fb
  • Pointer size: 131 Bytes
  • Size of remote file: 237 kB
config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "mateli-rnnt",
3
+ "sample_rate": 16000,
4
+ "n_mels": 80,
5
+ "d_model": 384,
6
+ "n_blocks": 16,
7
+ "conv_kernel": 15,
8
+ "ffn_expansion": 4,
9
+ "attn_after_blocks": [4, 7, 10, 13],
10
+ "attn_heads": 6,
11
+ "attn_left_context": 64,
12
+ "chunk_mel_frames": 32,
13
+ "frame_seconds": 0.04,
14
+ "pred_hidden": 384,
15
+ "joint_dim": 384,
16
+ "vocab": ["<blank>", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "å", "ä", "ö", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "?", "!"],
17
+ "blank_id": 0,
18
+ "space_id": 1,
19
+ "max_symbols_per_frame": 8
20
+ }
examples/commonvoice_1.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c6d67d2fe3d216f38da55485c6cb385aa91ca2f58070fefc0f1030d2c6cc159f
3
+ size 202796
examples/commonvoice_2.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33afa4226a5e70f322616e1fb8f91af43881ff5f9664c597c64999e0911dbb3b
3
+ size 193580
examples/commonvoice_3.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93496eaca60839a576bfd8ed4472f158b4980b9dbaab81d0a9b5c59bfdf1aa6a
3
+ size 203948
examples/commonvoice_4.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20345a545034417533fa5c15246f294865fb4afe3eb692ab74d512247070b315
3
+ size 114476
examples/commonvoice_5.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:735719b29eee996c2453a59275a9bb3e152fb77588bc980f1c68d122db4b3371
3
+ size 171692
examples/commonvoice_6.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:32adf4f3aef9cd037aef55a350c4fa3ec821e22c26db3d9a1679c0a2a701383c
3
+ size 218924
examples/references.tsv ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ file source clip licence reference
2
+ commonvoice_1.wav Common Voice 17.0, Finnish test split common_voice_fi_32490577.mp3 CC0-1.0 äänestin päätöslauselmaa vastaan koska siinä ei käsitellä riittävästi näitä seikkoja.
3
+ commonvoice_2.wav Common Voice 17.0, Finnish test split common_voice_fi_25005783.mp3 CC0-1.0 ne koostuivat eritavoin asetelluista ympyröistä.
4
+ commonvoice_3.wav Common Voice 17.0, Finnish test split common_voice_fi_25260168.mp3 CC0-1.0 kaikki mikä tekisi tästä tuskasta edes hitusen siedettävämpää oli kiellettyä.
5
+ commonvoice_4.wav Common Voice 17.0, Finnish test split common_voice_fi_23716223.mp3 CC0-1.0 mä en oo ehtiny vielä katsoa.
6
+ commonvoice_5.wav Common Voice 17.0, Finnish test split common_voice_fi_25132818.mp3 CC0-1.0 miten me voidaa olla varmoja et sä puhut totta?
7
+ commonvoice_6.wav Common Voice 17.0, Finnish test split common_voice_fi_25018016.mp3 CC0-1.0 sano vaa aika ja paikka ni miä tuun mukkaa kuulin itseni sanovan.
8
+ voxpopuli_1.wav VoxPopuli, Finnish transcribed test split fi_20121023-19:15:14_0.opus CC0-1.0 arvoisa puhemies äänestin tämän mietinnön puolesta. vaikka komission tiedonannosta on kulunut jo yli kymmenen vuotta eivät kaikki matkustajat edelleenkään tiedä oikeuksistaan.
9
+ voxpopuli_2.wav VoxPopuli, Finnish transcribed test split fi_20140206-15:12:12_3.opus CC0-1.0 boikotoiminen vaaleissa ja mielenosoitus ovat eri asioita mutta erittäin huolestuttavia ovat tiedot siitä että useampi kuin joka kymmenes äänestyspaikka ei voinut avata oviaan opposition saarron takia.
examples/voxpopuli_1.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09205953b9cc84e7a76a42f69bfebd8b15a4b10a0aa6b8d4a0195750dff05492
3
+ size 398764
examples/voxpopuli_2.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:44eca13281e0d8a3b1968f3db6aa0148fbcd91dcb6fe2fd00c8319b5f875c437
3
+ size 479338
mateli.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mateli: streaming Finnish speech recognition (MinGRU encoder + RNN-T), PyTorch reference.
2
+
3
+ python mateli.py speech.wav # text
4
+ python mateli.py speech.wav --words # one word per line with start/end times
5
+
6
+ from mateli import Mateli, load_audio
7
+ asr = Mateli.from_pretrained(".") # directory with config.json and model.safetensors
8
+ result = asr.transcribe(load_audio("speech.wav"))
9
+ print(result.text)
10
+
11
+ The encoder is chunk-causal: audio is processed in 320 ms chunks (32 log-mel frames -> 8 encoder
12
+ frames of 40 ms), each chunk sees only itself and the past, and the state carried between chunks
13
+ has a fixed size. transcribe() runs the same chunk loop a live stream would, so its output equals
14
+ streaming recognition of the same audio.
15
+
16
+ Model: log-mel (80 bins, 25 ms window, 10 ms hop) -> two stride-2 Conv2d -> 16 macaron blocks
17
+ (feed-forward / MinGRU / causal depthwise conv / feed-forward), with a windowed self-attention
18
+ sublayer after blocks 4, 7, 10 and 13 (keys = the current chunk + 64 previous frames) -> additive
19
+ joiner with a one-layer MinGRU prediction network over 44 characters. Greedy decoding.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import math
26
+ from dataclasses import dataclass
27
+ from pathlib import Path
28
+
29
+ import torch
30
+ import torch.nn as nn
31
+ import torch.nn.functional as F
32
+
33
+
34
+ # --------------------------------------------------------------------------- MinGRU
35
+ class MinGRU(nn.Module):
36
+ """minGRU (Feng et al. 2024, "Were RNNs All We Needed?") with a sigmoid highway.
37
+ h_t = (1 - z_t) * h_{t-1} + z_t * g(x_t), computed for a whole chunk with a log-space scan."""
38
+
39
+ def __init__(self, hidden: int):
40
+ super().__init__()
41
+ self.layers = nn.ModuleList([nn.Linear(hidden, 3 * hidden, bias=False)])
42
+
43
+ @staticmethod
44
+ def _log_g(x):
45
+ return torch.where(x >= 0, (F.relu(x) + 0.5).log(), -F.softplus(-x))
46
+
47
+ def forward(self, x, state):
48
+ """x [B, T, H], state [B, H] (>= 0) -> (output [B, T, H], new state [B, H])."""
49
+ hidden, gate, proj = self.layers[0](x).chunk(3, dim=-1)
50
+ log_coeffs = -F.softplus(gate)
51
+ log_values = -F.softplus(-gate) + self._log_g(hidden)
52
+ # the carried state enters the scan as an extra first step with coefficient 1
53
+ log_coeffs = torch.cat([torch.zeros_like(log_coeffs[:, :1]), log_coeffs], dim=1)
54
+ log_values = torch.cat([state.clamp_min(0).log().unsqueeze(1), log_values], dim=1)
55
+ a_star = log_coeffs.cumsum(dim=1)
56
+ h = (a_star + (log_values - a_star).logcumsumexp(dim=1)).exp()[:, 1:]
57
+ g = proj.sigmoid()
58
+ return g * h + (1.0 - g) * x, h[:, -1]
59
+
60
+ def step(self, x, state):
61
+ """One time step without the scan: x [B, H], state [B, H] -> (output, new state)."""
62
+ hidden, gate, proj = self.layers[0](x).chunk(3, dim=-1)
63
+ g_hidden = torch.where(hidden >= 0, hidden + 0.5, hidden.sigmoid())
64
+ h = torch.lerp(state, g_hidden, gate.sigmoid())
65
+ g = proj.sigmoid()
66
+ return g * h + (1.0 - g) * x, h
67
+
68
+
69
+ # --------------------------------------------------------------------------- encoder
70
+ class FeedForward(nn.Module):
71
+ def __init__(self, d: int, expansion: int):
72
+ super().__init__()
73
+ self.net = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, expansion * d), nn.SiLU(),
74
+ nn.Linear(expansion * d, d))
75
+
76
+ def forward(self, x):
77
+ return self.net(x)
78
+
79
+
80
+ class MinGRUMixer(nn.Module):
81
+ def __init__(self, d: int):
82
+ super().__init__()
83
+ self.norm = nn.LayerNorm(d)
84
+ self.gru = MinGRU(d)
85
+
86
+ def forward(self, x, state):
87
+ return self.gru(self.norm(x), state)
88
+
89
+
90
+ class ConvModule(nn.Module):
91
+ """Conformer convolution module with a causal depthwise convolution."""
92
+
93
+ def __init__(self, d: int, kernel: int):
94
+ super().__init__()
95
+ self.norm = nn.LayerNorm(d)
96
+ self.pw1 = nn.Conv1d(d, 2 * d, 1)
97
+ self.dw = nn.Conv1d(d, d, kernel, groups=d)
98
+ self.act_norm = nn.LayerNorm(d)
99
+ self.pw2 = nn.Conv1d(d, d, 1)
100
+
101
+ def forward(self, x, cache):
102
+ """x [B, T, D], cache [B, D, kernel-1] (the previous GLU outputs)."""
103
+ y = F.glu(self.pw1(self.norm(x).transpose(1, 2)), dim=1)
104
+ y = torch.cat([cache, y], dim=2)
105
+ new_cache = y[:, :, -cache.shape[2]:]
106
+ y = F.silu(self.act_norm(self.dw(y).transpose(1, 2)))
107
+ return self.pw2(y.transpose(1, 2)).transpose(1, 2), new_cache
108
+
109
+
110
+ class Block(nn.Module):
111
+ def __init__(self, d: int, kernel: int, expansion: int):
112
+ super().__init__()
113
+ self.ff1 = FeedForward(d, expansion)
114
+ self.mixer = MinGRUMixer(d)
115
+ self.conv = ConvModule(d, kernel)
116
+ self.ff2 = FeedForward(d, expansion)
117
+ self.norm = nn.LayerNorm(d)
118
+
119
+ def forward(self, x, state):
120
+ gru_h, conv_cache = state
121
+ x = x + 0.5 * self.ff1(x)
122
+ m, gru_h = self.mixer(x, gru_h)
123
+ x = x + m
124
+ c, conv_cache = self.conv(x, conv_cache)
125
+ x = x + c
126
+ x = x + 0.5 * self.ff2(x)
127
+ return self.norm(x), (gru_h, conv_cache)
128
+
129
+
130
+ class _Attn(nn.Module):
131
+ def __init__(self, d: int, heads: int):
132
+ super().__init__()
133
+ self.norm = nn.LayerNorm(d)
134
+ self.mha = nn.MultiheadAttention(d, heads, batch_first=True)
135
+
136
+
137
+ class WindowedAttention(nn.Module):
138
+ """Residual self-attention: the chunk's frames attend to the chunk and up to `left` cached
139
+ earlier inputs. No positional encoding (the causal convolutions provide position)."""
140
+
141
+ def __init__(self, d: int, heads: int, left: int):
142
+ super().__init__()
143
+ self.attn = _Attn(d, heads)
144
+ self.left = left
145
+
146
+ def forward(self, x, cache):
147
+ ctx = torch.cat([cache, x], dim=1)
148
+ q, kv = self.attn.norm(x), self.attn.norm(ctx)
149
+ y, _ = self.attn.mha(q, kv, kv, need_weights=False)
150
+ return x + y, ctx[:, -self.left:]
151
+
152
+
153
+ class Encoder(nn.Module):
154
+ def __init__(self, cfg: dict):
155
+ super().__init__()
156
+ d = cfg["d_model"]
157
+ self.blocks = nn.ModuleList([Block(d, cfg["conv_kernel"], cfg["ffn_expansion"])
158
+ for _ in range(cfg["n_blocks"])])
159
+ self.attn = nn.ModuleDict({str(p): WindowedAttention(d, cfg["attn_heads"], cfg["attn_left_context"])
160
+ for p in cfg["attn_after_blocks"]})
161
+
162
+ def initial_state(self, device):
163
+ d, k = self.blocks[0].norm.normalized_shape[0], self.blocks[0].conv.dw.kernel_size[0]
164
+ return {"blocks": [(torch.zeros(1, d, device=device), torch.zeros(1, d, k - 1, device=device))
165
+ for _ in self.blocks],
166
+ "attn": {p: torch.zeros(1, 0, d, device=device) for p in self.attn}}
167
+
168
+ def forward(self, x, state):
169
+ new_blocks, new_attn = [], {}
170
+ for i, blk in enumerate(self.blocks):
171
+ x, st = blk(x, state["blocks"][i])
172
+ new_blocks.append(st)
173
+ p = str(i + 1)
174
+ if p in self.attn:
175
+ x, new_attn[p] = self.attn[p](x, state["attn"][p])
176
+ return x, {"blocks": new_blocks, "attn": new_attn}
177
+
178
+
179
+ # --------------------------------------------------------------------------- front end
180
+ class LogMel(nn.Module):
181
+ def __init__(self, n_mels=80, n_fft=512, win=400, hop=160):
182
+ super().__init__()
183
+ self.n_fft, self.win, self.hop = n_fft, win, hop
184
+ self.register_buffer("fb", torch.zeros(n_mels, n_fft // 2 + 1)) # loaded from the checkpoint
185
+ self.register_buffer("window", torch.hann_window(win))
186
+
187
+ def forward(self, wav):
188
+ """[B, samples] -> [B, frames, n_mels], frames = 1 + samples // hop."""
189
+ spec = torch.stft(wav, self.n_fft, self.hop, win_length=self.win, window=self.window,
190
+ center=True, return_complex=True)
191
+ mel = torch.einsum("mf,bft->bmt", self.fb, spec.real ** 2 + spec.imag ** 2)
192
+ return torch.log(mel + 1e-6).transpose(1, 2)
193
+
194
+
195
+ class Subsampler(nn.Module):
196
+ """Two Conv2d (3x3, stride 2) over (time, mel) -> 40 ms frames."""
197
+
198
+ def __init__(self, n_mels: int, d: int):
199
+ super().__init__()
200
+ self.conv = nn.Sequential(nn.Conv2d(1, d, 3, stride=2, padding=1), nn.ReLU(),
201
+ nn.Conv2d(d, d, 3, stride=2, padding=1), nn.ReLU())
202
+ f_out = ((n_mels - 1) // 2 + 1 - 1) // 2 + 1
203
+ self.out = nn.Linear(d * f_out, d)
204
+
205
+ def forward(self, mel):
206
+ x = self.conv(mel.unsqueeze(1)) # [B, d, T/4, F/4]
207
+ b, c, t, f = x.shape
208
+ return self.out(x.transpose(1, 2).reshape(b, t, c * f))
209
+
210
+
211
+ class FrontEnd(nn.Module):
212
+ def __init__(self, n_mels: int, d: int):
213
+ super().__init__()
214
+ self.logmel = LogMel(n_mels)
215
+ self.subsample = Subsampler(n_mels, d)
216
+
217
+
218
+ # --------------------------------------------------------------------------- transducer
219
+ class PredictionNetwork(nn.Module):
220
+ def __init__(self, vocab_size: int, hidden: int):
221
+ super().__init__()
222
+ self.embed = nn.Embedding(vocab_size, hidden)
223
+ self.rnn = MinGRU(hidden)
224
+
225
+ def step(self, token: int, state):
226
+ return self.rnn.step(self.embed(torch.tensor([token], device=state.device)), state)
227
+
228
+
229
+ class Joiner(nn.Module):
230
+ def __init__(self, enc_dim: int, pred_dim: int, joint_dim: int, vocab_size: int):
231
+ super().__init__()
232
+ self.enc_proj = nn.Linear(enc_dim, joint_dim)
233
+ self.pred_proj = nn.Linear(pred_dim, joint_dim)
234
+ self.out = nn.Linear(joint_dim, vocab_size)
235
+
236
+
237
+ @dataclass(frozen=True)
238
+ class Word:
239
+ text: str
240
+ start: float # seconds, time of the first character's encoder frame
241
+ end: float # seconds, time of the last character's encoder frame
242
+
243
+
244
+ @dataclass
245
+ class Transcript:
246
+ words: list[Word]
247
+
248
+ @property
249
+ def text(self) -> str:
250
+ return " ".join(w.text for w in self.words)
251
+
252
+
253
+ class Mateli(nn.Module):
254
+ def __init__(self, cfg: dict):
255
+ super().__init__()
256
+ self.cfg = cfg
257
+ d = cfg["d_model"]
258
+ self.frontend = FrontEnd(cfg["n_mels"], d)
259
+ self.encoder = Encoder(cfg)
260
+ self.prednet = PredictionNetwork(len(cfg["vocab"]), cfg["pred_hidden"])
261
+ self.joiner = Joiner(d, cfg["pred_hidden"], cfg["joint_dim"], len(cfg["vocab"]))
262
+
263
+ @classmethod
264
+ def from_pretrained(cls, model_dir=".", device: str | None = None) -> "Mateli":
265
+ from safetensors.torch import load_file
266
+ d = Path(model_dir)
267
+ model = cls(json.loads((d / "config.json").read_text(encoding="utf-8")))
268
+ model.load_state_dict(load_file(str(d / "model.safetensors")))
269
+ device = device or ("cuda" if torch.cuda.is_available() else "cpu")
270
+ return model.to(device).eval()
271
+
272
+ @property
273
+ def device(self):
274
+ return self.joiner.out.weight.device
275
+
276
+ @torch.inference_mode()
277
+ def transcribe(self, samples) -> Transcript:
278
+ """float32 mono 16 kHz samples in [-1, 1] -> words with times."""
279
+ cfg = self.cfg
280
+ wav = torch.as_tensor(samples, dtype=torch.float32, device=self.device)
281
+ if wav.ndim != 1:
282
+ raise ValueError(f"expected mono samples of shape [n], got {tuple(wav.shape)}; mix channels down first")
283
+ wav = wav[None]
284
+ if wav.shape[1] <= self.frontend.logmel.n_fft // 2:
285
+ return Transcript([])
286
+ mel = self.frontend.logmel(wav) # [1, M, 80]
287
+ n_chunk, ctx = cfg["chunk_mel_frames"], 4 # 4 mel frames = one 40 ms frame (total stride 4)
288
+ state = self.encoder.initial_state(self.device)
289
+ blank, space = cfg["blank_id"], cfg["space_id"]
290
+ pred, h = self.prednet.step(blank, torch.zeros(1, cfg["pred_hidden"], device=self.device))
291
+ pred_proj = self.joiner.pred_proj(pred)
292
+ words, chars, t0, t1, frame = [], "", 0, 0, 0
293
+ fs = cfg["frame_seconds"]
294
+ for start in range(0, mel.shape[1], n_chunk):
295
+ # the subsampler sees the chunk plus 4 earlier mel frames; the first output frame,
296
+ # which only exists because of that context, is dropped
297
+ lo = max(0, start - ctx)
298
+ x = self.frontend.subsample(mel[:, lo:start + n_chunk])
299
+ x = x[:, 1:] if lo < start else x
300
+ enc, state = self.encoder(x, state)
301
+ enc_proj = self.joiner.enc_proj(enc)[0]
302
+ for e in enc_proj:
303
+ for _ in range(cfg["max_symbols_per_frame"]):
304
+ k = int(self.joiner.out(torch.tanh(e + pred_proj[0])).argmax())
305
+ if k == blank:
306
+ break
307
+ if k == space:
308
+ if chars:
309
+ words.append(Word(chars, round((t0 + 1) * fs, 2), round((t1 + 1) * fs, 2)))
310
+ chars = ""
311
+ else:
312
+ if not chars:
313
+ t0 = frame
314
+ chars, t1 = chars + cfg["vocab"][k], frame
315
+ pred, h = self.prednet.step(k, h)
316
+ pred_proj = self.joiner.pred_proj(pred)
317
+ frame += 1
318
+ if chars:
319
+ words.append(Word(chars, round((t0 + 1) * fs, 2), round((t1 + 1) * fs, 2)))
320
+ return Transcript(words)
321
+
322
+
323
+ def load_audio(path, sample_rate: int = 16000):
324
+ import numpy as np
325
+ import soundfile as sf
326
+ x, sr = sf.read(str(path), dtype="float32", always_2d=True)
327
+ x = x.mean(axis=1)
328
+ if sr != sample_rate:
329
+ from scipy.signal import resample_poly
330
+ g = math.gcd(sr, sample_rate)
331
+ x = resample_poly(x, sample_rate // g, sr // g).astype(np.float32)
332
+ return x
333
+
334
+
335
+ def main():
336
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
337
+ ap.add_argument("audio")
338
+ ap.add_argument("--model-dir", default=str(Path(__file__).resolve().parent))
339
+ ap.add_argument("--device", default=None)
340
+ ap.add_argument("--words", action="store_true", help="print words with start and end times")
341
+ a = ap.parse_args()
342
+ asr = Mateli.from_pretrained(a.model_dir, a.device)
343
+ t = asr.transcribe(load_audio(a.audio, asr.cfg["sample_rate"]))
344
+ if a.words:
345
+ for w in t.words:
346
+ print(f"{w.start:7.2f} {w.end:7.2f} {w.text}")
347
+ else:
348
+ print(t.text)
349
+
350
+
351
+ if __name__ == "__main__":
352
+ main()
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f9c1a41a645b41ea24fa54ef9660c1e97813bda21c8622f77767551dac195e8
3
+ size 238443016