SabaPivot commited on
Commit
99d0b03
·
verified ·
1 Parent(s): 6da639f

Publish trilingual Audio8 checkpoint at step 808430

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ tokenizer.json 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,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ pipeline_tag: automatic-speech-recognition
4
+ base_model: Edge0/Audio8-ASR-0.1B
5
+ language: [ko, en, zh]
6
+ license: cc-by-nc-4.0
7
+ tags: [audio, asr, fine-tuned]
8
+ ---
9
+
10
+ # STT-demo
11
+
12
+ A Korean, English, and Mandarin Chinese speech recognition model fine-tuned from [Edge0/Audio8-ASR-0.1B](https://huggingface.co/Edge0/Audio8-ASR-0.1B/tree/8487da63d581fa4fc9b5c60444cb57c3a523d7aa). This release contains the fine-tuned inference weights at optimizer step 808,430.
13
+
14
+ ## Validation
15
+
16
+ We selected the checkpoint with the lowest unweighted mean of the three language error rates across 159 checkpoints evaluated on the same internal development split. We used greedy decoding and normalized corpus error rates. These are development results used for model selection.
17
+
18
+ | Language | Dev clips | Metric | Error |
19
+ |---|---:|---|---:|
20
+ | Korean | 1,000 | CER | 4.49% |
21
+ | English | 1,047 | WER | 12.22% |
22
+ | Mandarin Chinese | 949 | CER | 5.58% |
23
+ | Three-language average | 2,996 | Macro error | 7.43% |
24
+
25
+ ## Usage
26
+
27
+ With Transformers 4.57.6, load this repository with `AutoProcessor.from_pretrained` and `AutoModelForCausalLM.from_pretrained`, setting `trust_remote_code=True` for both. The processor accepts 16 kHz audio. See the [upstream inference example](https://huggingface.co/Edge0/Audio8-ASR-0.1B#transformers-inference) and substitute this repository ID for the base model ID.
28
+
29
+ The upstream model and this adaptation use the [CC BY-NC 4.0 license](./LICENSE).
added_tokens.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|assistant|>": 151650,
3
+ "<|audio|>": 151646,
4
+ "<|begin_of_audio|>": 151648,
5
+ "<|end_of_audio|>": 151649,
6
+ "<|endoftext|>": 151643,
7
+ "<|im_end|>": 151645,
8
+ "<|im_start|>": 151644,
9
+ "<|system|>": 151651,
10
+ "<|user|>": 151647
11
+ }
chat_template.jinja ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system
2
+ You are a helpful assistant<|im_end|>
3
+ ' }}{% endif %}{{'<|im_start|>' + message['role'] + '
4
+ ' + message['content'] + '<|im_end|>' + '
5
+ '}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
6
+ ' }}{% endif %}
config.json ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_type": "qwen3_asr_mlp_tower",
3
+ "architectures": [
4
+ "ArkasrForConditionalGeneration"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "audio_backend": "qwen3_asr_mlp_tower",
8
+ "audio_token_id": 151646,
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_arkasr.ArkasrConfig",
11
+ "AutoModelForCausalLM": "modeling_arkasr.ArkasrForConditionalGeneration"
12
+ },
13
+ "bos_token_id": 151643,
14
+ "dtype": "float32",
15
+ "eos_token_id": 151645,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 512,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 1408,
20
+ "layer_types": [
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention"
29
+ ],
30
+ "max_position_embeddings": 32768,
31
+ "max_whisper_length": 1500,
32
+ "max_window_layers": 28,
33
+ "merge_factor": 4,
34
+ "mlp_adapter_act": "gelu",
35
+ "model_type": "arkasr",
36
+ "num_attention_heads": 8,
37
+ "num_hidden_layers": 8,
38
+ "num_key_value_heads": 8,
39
+ "pad_token_id": 151643,
40
+ "qwen3_asr_audio_config": {
41
+ "activation_dropout": 0,
42
+ "activation_function": "gelu",
43
+ "attention_dropout": 0,
44
+ "conv_chunksize": 500,
45
+ "d_model": 896,
46
+ "downsample_hidden_size": 480,
47
+ "dropout": 0,
48
+ "encoder_attention_heads": 14,
49
+ "encoder_ffn_dim": 3584,
50
+ "encoder_layers": 18,
51
+ "initializer_range": 0.02,
52
+ "max_source_positions": 1500,
53
+ "model_type": "qwen3_asr_audio_encoder",
54
+ "n_window": 50,
55
+ "n_window_infer": 800,
56
+ "num_hidden_layers": 18,
57
+ "num_mel_bins": 128,
58
+ "output_dim": 1024,
59
+ "scale_embedding": false
60
+ },
61
+ "qwen3_asr_mlp_tower_dropout": 0.0,
62
+ "qwen3_asr_mlp_tower_hidden_size": 0,
63
+ "qwen3_asr_mlp_tower_layers": 4,
64
+ "rms_norm_eps": 1e-06,
65
+ "rope_scaling": null,
66
+ "rope_theta": 1000000.0,
67
+ "sliding_window": null,
68
+ "spec_aug": false,
69
+ "tie_word_embeddings": true,
70
+ "transformers_version": "4.57.6",
71
+ "use_cache": true,
72
+ "use_rope": false,
73
+ "use_sliding_window": false,
74
+ "vocab_size": 151936,
75
+ "whisper_config": {
76
+ "_name_or_path": "openai/whisper-small",
77
+ "activation_dropout": 0.0,
78
+ "activation_function": "gelu",
79
+ "apply_spec_augment": false,
80
+ "architectures": [
81
+ "WhisperForConditionalGeneration"
82
+ ],
83
+ "attention_dropout": 0.0,
84
+ "begin_suppress_tokens": [
85
+ 220,
86
+ 50257
87
+ ],
88
+ "bos_token_id": 50257,
89
+ "classifier_proj_size": 256,
90
+ "d_model": 768,
91
+ "decoder_attention_heads": 12,
92
+ "decoder_ffn_dim": 3072,
93
+ "decoder_layerdrop": 0.0,
94
+ "decoder_layers": 12,
95
+ "decoder_start_token_id": 50258,
96
+ "dropout": 0.0,
97
+ "dtype": "float32",
98
+ "encoder_attention_heads": 12,
99
+ "encoder_ffn_dim": 3072,
100
+ "encoder_layerdrop": 0.0,
101
+ "encoder_layers": 12,
102
+ "eos_token_id": 50257,
103
+ "forced_decoder_ids": [
104
+ [
105
+ 1,
106
+ 50259
107
+ ],
108
+ [
109
+ 2,
110
+ 50359
111
+ ],
112
+ [
113
+ 3,
114
+ 50363
115
+ ]
116
+ ],
117
+ "init_std": 0.02,
118
+ "mask_feature_length": 10,
119
+ "mask_feature_min_masks": 0,
120
+ "mask_feature_prob": 0.0,
121
+ "mask_time_length": 10,
122
+ "mask_time_min_masks": 2,
123
+ "mask_time_prob": 0.05,
124
+ "max_length": 448,
125
+ "max_source_positions": 1500,
126
+ "max_target_positions": 448,
127
+ "median_filter_width": 7,
128
+ "model_type": "whisper",
129
+ "num_hidden_layers": 12,
130
+ "num_mel_bins": 80,
131
+ "pad_token_id": 50257,
132
+ "scale_embedding": false,
133
+ "suppress_tokens": [
134
+ 1,
135
+ 2,
136
+ 7,
137
+ 8,
138
+ 9,
139
+ 10,
140
+ 14,
141
+ 25,
142
+ 26,
143
+ 27,
144
+ 28,
145
+ 29,
146
+ 31,
147
+ 58,
148
+ 59,
149
+ 60,
150
+ 61,
151
+ 62,
152
+ 63,
153
+ 90,
154
+ 91,
155
+ 92,
156
+ 93,
157
+ 359,
158
+ 503,
159
+ 522,
160
+ 542,
161
+ 873,
162
+ 893,
163
+ 902,
164
+ 918,
165
+ 922,
166
+ 931,
167
+ 1350,
168
+ 1853,
169
+ 1982,
170
+ 2460,
171
+ 2627,
172
+ 3246,
173
+ 3253,
174
+ 3268,
175
+ 3536,
176
+ 3846,
177
+ 3961,
178
+ 4183,
179
+ 4667,
180
+ 6585,
181
+ 6647,
182
+ 7273,
183
+ 9061,
184
+ 9383,
185
+ 10428,
186
+ 10929,
187
+ 11938,
188
+ 12033,
189
+ 12331,
190
+ 12562,
191
+ 13793,
192
+ 14157,
193
+ 14635,
194
+ 15265,
195
+ 15618,
196
+ 16553,
197
+ 16604,
198
+ 18362,
199
+ 18956,
200
+ 20075,
201
+ 21675,
202
+ 22520,
203
+ 26130,
204
+ 26161,
205
+ 26435,
206
+ 28279,
207
+ 29464,
208
+ 31650,
209
+ 32302,
210
+ 32470,
211
+ 36865,
212
+ 42863,
213
+ 47425,
214
+ 49870,
215
+ 50254,
216
+ 50258,
217
+ 50360,
218
+ 50361,
219
+ 50362
220
+ ],
221
+ "use_cache": true,
222
+ "use_weighted_layer_sum": false,
223
+ "vocab_size": 51865
224
+ }
225
+ }
configuration_arkasr.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, Optional, Union
4
+
5
+ from transformers import Qwen2Config, WhisperConfig
6
+
7
+ from .qwen3_asr_audio_config import Qwen3ASRAudioEncoderConfig
8
+
9
+
10
+ class ArkasrConfig(Qwen2Config):
11
+ model_type = "arkasr"
12
+ is_composition = True
13
+
14
+ def __init__(
15
+ self,
16
+ whisper_config: Optional[Union[Dict[str, Any], WhisperConfig]] = None,
17
+ qwen3_asr_audio_config: Optional[Union[Dict[str, Any], Qwen3ASRAudioEncoderConfig]] = None,
18
+ adapter_type: str = "qwen3_asr_mlp_tower",
19
+ merge_factor: int = 4,
20
+ spec_aug: bool = False,
21
+ use_rope: bool = False,
22
+ max_whisper_length: int = 1500,
23
+ mlp_adapter_act: str = "gelu",
24
+ qwen3_asr_mlp_tower_layers: int = 4,
25
+ qwen3_asr_mlp_tower_hidden_size: int = 0,
26
+ qwen3_asr_mlp_tower_dropout: float = 0.0,
27
+ **kwargs,
28
+ ):
29
+ super().__init__(**kwargs)
30
+
31
+ if isinstance(whisper_config, dict):
32
+ self.whisper_config = WhisperConfig(**whisper_config)
33
+ elif isinstance(whisper_config, WhisperConfig):
34
+ self.whisper_config = whisper_config
35
+ else:
36
+ self.whisper_config = WhisperConfig()
37
+
38
+ if isinstance(qwen3_asr_audio_config, dict):
39
+ self.qwen3_asr_audio_config = Qwen3ASRAudioEncoderConfig(**qwen3_asr_audio_config)
40
+ elif isinstance(qwen3_asr_audio_config, Qwen3ASRAudioEncoderConfig):
41
+ self.qwen3_asr_audio_config = qwen3_asr_audio_config
42
+ else:
43
+ self.qwen3_asr_audio_config = Qwen3ASRAudioEncoderConfig(
44
+ num_mel_bins=128,
45
+ encoder_layers=18,
46
+ encoder_attention_heads=14,
47
+ encoder_ffn_dim=3584,
48
+ d_model=896,
49
+ max_source_positions=1500,
50
+ n_window=50,
51
+ output_dim=1024,
52
+ n_window_infer=800,
53
+ conv_chunksize=500,
54
+ downsample_hidden_size=480,
55
+ )
56
+
57
+ self.adapter_type = adapter_type
58
+ self.merge_factor = int(merge_factor)
59
+ self.spec_aug = bool(spec_aug)
60
+ self.use_rope = bool(use_rope)
61
+ self.max_whisper_length = int(max_whisper_length)
62
+ self.mlp_adapter_act = mlp_adapter_act
63
+ self.qwen3_asr_mlp_tower_layers = int(qwen3_asr_mlp_tower_layers)
64
+ self.qwen3_asr_mlp_tower_hidden_size = int(qwen3_asr_mlp_tower_hidden_size)
65
+ self.qwen3_asr_mlp_tower_dropout = float(qwen3_asr_mlp_tower_dropout)
66
+
67
+ def to_dict(self):
68
+ output = super().to_dict()
69
+ output["whisper_config"] = self.whisper_config.to_dict()
70
+ output["qwen3_asr_audio_config"] = self.qwen3_asr_audio_config.to_dict()
71
+ output["qwen3_asr_mlp_tower_layers"] = self.qwen3_asr_mlp_tower_layers
72
+ output["qwen3_asr_mlp_tower_hidden_size"] = self.qwen3_asr_mlp_tower_hidden_size
73
+ output["qwen3_asr_mlp_tower_dropout"] = self.qwen3_asr_mlp_tower_dropout
74
+ return output
75
+
76
+
77
+ __all__ = ["ArkasrConfig"]
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "pad_token_id": 151643,
6
+ "transformers_version": "4.57.6"
7
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ab91ab18a507e9e36128fb767f76ce013846ab13f3206ae0830ac252565be44
3
+ size 1296011920
modeling_arkasr.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Optional
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+ from transformers import Qwen2ForCausalLM
9
+ from transformers.generation import GenerationMixin
10
+ from transformers.modeling_outputs import CausalLMOutputWithPast
11
+ from transformers.modeling_utils import PreTrainedModel
12
+
13
+ from .configuration_arkasr import ArkasrConfig
14
+ from .qwen3_asr_audio_config import Qwen3ASRAudioEncoderConfig
15
+ from .qwen3_asr_audio_model import Qwen3ASRAudioEncoder
16
+
17
+
18
+ class Qwen3AsrMlpTowerBlock(nn.Module):
19
+ def __init__(self, hidden_size: int, intermediate_size: Optional[int] = None, dropout: float = 0.0):
20
+ super().__init__()
21
+ hidden_size = int(hidden_size)
22
+ intermediate_size = int(intermediate_size or hidden_size * 4)
23
+ self.norm = nn.LayerNorm(hidden_size)
24
+ self.fc1 = nn.Linear(hidden_size, intermediate_size)
25
+ self.act = nn.GELU()
26
+ self.dropout = nn.Dropout(float(dropout))
27
+ self.fc2 = nn.Linear(intermediate_size, hidden_size)
28
+
29
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
30
+ residual = hidden_states
31
+ hidden_states = self.norm(hidden_states)
32
+ hidden_states = self.fc1(hidden_states)
33
+ hidden_states = self.act(hidden_states)
34
+ hidden_states = self.dropout(hidden_states)
35
+ hidden_states = self.fc2(hidden_states)
36
+ hidden_states = self.dropout(hidden_states)
37
+ return residual + hidden_states
38
+
39
+
40
+ class Qwen3AsrMlpTower(nn.Module):
41
+ def __init__(
42
+ self,
43
+ hidden_size: int,
44
+ num_layers: int = 4,
45
+ intermediate_size: Optional[int] = None,
46
+ dropout: float = 0.0,
47
+ ):
48
+ super().__init__()
49
+ hidden_size = int(hidden_size)
50
+ num_layers = int(num_layers)
51
+ intermediate_size = int(intermediate_size or hidden_size * 4)
52
+ self.hidden_size = hidden_size
53
+ self.intermediate_size = intermediate_size
54
+ self.num_layers = num_layers
55
+ self.dropout = float(dropout)
56
+ self.layers = nn.ModuleList(
57
+ [
58
+ Qwen3AsrMlpTowerBlock(
59
+ hidden_size=hidden_size,
60
+ intermediate_size=intermediate_size,
61
+ dropout=dropout,
62
+ )
63
+ for _ in range(num_layers)
64
+ ]
65
+ )
66
+ self.final_norm = nn.LayerNorm(hidden_size)
67
+
68
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
69
+ for layer in self.layers:
70
+ hidden_states = layer(hidden_states)
71
+ return self.final_norm(hidden_states)
72
+
73
+
74
+ class ArkasrForConditionalGeneration(PreTrainedModel, GenerationMixin):
75
+ config_class = ArkasrConfig
76
+ base_model_prefix = "language_model"
77
+ _no_split_modules = ["Qwen3ASRAudioEncoder"]
78
+ _tied_weights_keys = ["language_model.lm_head.weight", "language_model.model.embed_tokens.weight"]
79
+
80
+ def __init__(self, config: ArkasrConfig):
81
+ super().__init__(config)
82
+ self.audio_token_id = getattr(config, "audio_token_id", None)
83
+ if self.audio_token_id is None:
84
+ raise ValueError("`audio_token_id` must be defined in config.")
85
+
86
+ audio_config = getattr(config, "qwen3_asr_audio_config", None)
87
+ if isinstance(audio_config, dict):
88
+ audio_config = Qwen3ASRAudioEncoderConfig(**audio_config)
89
+ if audio_config is None:
90
+ raise ValueError("`qwen3_asr_audio_config` must be defined in config.")
91
+
92
+ self.language_model = Qwen2ForCausalLM(config)
93
+ self.audio_encoder = Qwen3ASRAudioEncoder(audio_config)
94
+ audio_dim = int(getattr(audio_config, "output_dim", 0) or 0)
95
+ if audio_dim <= 0:
96
+ raise ValueError("qwen3_asr_audio_config.output_dim must be positive.")
97
+
98
+ layers = int(getattr(config, "qwen3_asr_mlp_tower_layers", 4) or 4)
99
+ intermediate_size = int(getattr(config, "qwen3_asr_mlp_tower_hidden_size", 0) or audio_dim * 4)
100
+ dropout = float(getattr(config, "qwen3_asr_mlp_tower_dropout", 0.0) or 0.0)
101
+ self.audio_mlp_tower = Qwen3AsrMlpTower(
102
+ hidden_size=audio_dim,
103
+ num_layers=layers,
104
+ intermediate_size=intermediate_size,
105
+ dropout=dropout,
106
+ )
107
+ self.audio_projector = nn.Sequential(
108
+ nn.LayerNorm(audio_dim),
109
+ nn.Linear(audio_dim, int(config.hidden_size)),
110
+ )
111
+ self.all_tied_weights_keys = {}
112
+
113
+ def get_input_embeddings(self):
114
+ return self.language_model.get_input_embeddings()
115
+
116
+ def set_input_embeddings(self, value):
117
+ return self.language_model.set_input_embeddings(value)
118
+
119
+ def get_output_embeddings(self):
120
+ return self.language_model.get_output_embeddings()
121
+
122
+ def set_output_embeddings(self, new_embeddings):
123
+ return self.language_model.set_output_embeddings(new_embeddings)
124
+
125
+ def resize_token_embeddings(self, *args, **kwargs):
126
+ return self.language_model.resize_token_embeddings(*args, **kwargs)
127
+
128
+ @staticmethod
129
+ def _cache_seq_len(past_key_values) -> int:
130
+ if past_key_values is None:
131
+ return 0
132
+ if hasattr(past_key_values, "get_seq_length"):
133
+ try:
134
+ return int(past_key_values.get_seq_length())
135
+ except Exception:
136
+ return 0
137
+ try:
138
+ return int(past_key_values[0][0].shape[-2])
139
+ except Exception:
140
+ return 0
141
+
142
+ def _project_audio_row(
143
+ self,
144
+ input_features: torch.Tensor,
145
+ token_count: int,
146
+ dtype: torch.dtype,
147
+ feature_length: Optional[int] = None,
148
+ ) -> torch.Tensor:
149
+ token_count = int(token_count)
150
+ if token_count <= 0:
151
+ return input_features.new_zeros((0, self.get_input_embeddings().embedding_dim), dtype=dtype)
152
+ if input_features.dim() == 3 and input_features.size(0) == 1:
153
+ input_features = input_features.squeeze(0)
154
+ if input_features.dim() != 2:
155
+ raise ValueError(f"Expected audio features with shape [mel, frames], got {tuple(input_features.shape)}")
156
+
157
+ expected_mels = int(getattr(self.audio_encoder.config, "num_mel_bins", input_features.size(0)))
158
+ if input_features.size(0) != expected_mels and input_features.size(1) == expected_mels:
159
+ input_features = input_features.transpose(0, 1)
160
+ if input_features.size(0) != expected_mels:
161
+ raise ValueError(f"Audio feature bins mismatch: expected {expected_mels}, got {input_features.size(0)}")
162
+
163
+ feature_length = int(feature_length) if feature_length is not None else int(input_features.size(1))
164
+ feature_length = max(1, min(feature_length, int(input_features.size(1))))
165
+ input_features = input_features[:, :feature_length]
166
+
167
+ encoder_param = next(self.audio_encoder.parameters())
168
+ encoded = self.audio_encoder(
169
+ input_features.to(device=encoder_param.device, dtype=encoder_param.dtype),
170
+ feature_lens=torch.tensor([feature_length], dtype=torch.long, device=encoder_param.device),
171
+ )
172
+ hidden = getattr(encoded, "last_hidden_state", encoded)
173
+ if isinstance(hidden, (tuple, list)):
174
+ hidden = hidden[0]
175
+ if hidden.dim() == 3 and hidden.size(0) == 1:
176
+ hidden = hidden.squeeze(0)
177
+ if hidden.dim() != 2:
178
+ raise ValueError(f"Expected audio encoder output [time, dim], got {tuple(hidden.shape)}")
179
+
180
+ tower_param = next(self.audio_mlp_tower.parameters())
181
+ hidden = self.audio_mlp_tower(hidden.to(device=tower_param.device, dtype=tower_param.dtype))
182
+ projector_param = next(self.audio_projector.parameters())
183
+ hidden = hidden.to(device=projector_param.device, dtype=projector_param.dtype)
184
+ if int(hidden.size(0)) != token_count:
185
+ hidden = F.adaptive_avg_pool1d(
186
+ hidden.transpose(0, 1).float().unsqueeze(0),
187
+ output_size=token_count,
188
+ ).squeeze(0).transpose(0, 1).to(dtype=projector_param.dtype)
189
+ return self.audio_projector(hidden).to(dtype=dtype)
190
+
191
+ def _inject_audio_embeddings(
192
+ self,
193
+ input_ids: torch.Tensor,
194
+ input_features: Optional[torch.Tensor] = None,
195
+ feature_lens: Optional[torch.Tensor] = None,
196
+ audios: Optional[torch.Tensor] = None,
197
+ audio_feature_lengths: Optional[torch.Tensor] = None,
198
+ ) -> torch.Tensor:
199
+ input_embeddings = self.get_input_embeddings()(input_ids).clone()
200
+ if input_features is None:
201
+ input_features = audios
202
+ if feature_lens is None:
203
+ feature_lens = audio_feature_lengths
204
+ if input_features is None:
205
+ return input_embeddings
206
+
207
+ input_features = input_features.to(device=input_embeddings.device)
208
+ if input_features.dim() == 4 and input_features.size(1) == 1:
209
+ input_features = input_features.squeeze(1)
210
+ if feature_lens is not None and not torch.is_tensor(feature_lens):
211
+ feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=input_embeddings.device)
212
+ if torch.is_tensor(feature_lens):
213
+ feature_lens = feature_lens.to(device=input_embeddings.device)
214
+
215
+ audio_mask = input_ids.eq(self.audio_token_id)
216
+ for batch_i in range(int(input_ids.size(0))):
217
+ positions = torch.nonzero(audio_mask[batch_i], as_tuple=False).flatten()
218
+ if positions.numel() == 0:
219
+ continue
220
+ feature_length = None
221
+ if torch.is_tensor(feature_lens) and batch_i < int(feature_lens.numel()):
222
+ feature_length = int(feature_lens[batch_i].item())
223
+ projected = self._project_audio_row(
224
+ input_features[batch_i],
225
+ int(positions.numel()),
226
+ input_embeddings.dtype,
227
+ feature_length=feature_length,
228
+ )
229
+ input_embeddings[batch_i, positions, :] = projected.to(device=input_embeddings.device)
230
+ return input_embeddings
231
+
232
+ def forward(
233
+ self,
234
+ input_ids: Optional[torch.LongTensor] = None,
235
+ input_features: Optional[torch.Tensor] = None,
236
+ feature_lens: Optional[torch.Tensor] = None,
237
+ audios: Optional[torch.Tensor] = None,
238
+ audio_feature_lengths: Optional[torch.Tensor] = None,
239
+ attention_mask: Optional[torch.Tensor] = None,
240
+ position_ids: Optional[torch.Tensor] = None,
241
+ past_key_values: Optional[Any] = None,
242
+ inputs_embeds: Optional[torch.Tensor] = None,
243
+ use_cache: Optional[bool] = None,
244
+ labels: Optional[torch.LongTensor] = None,
245
+ output_attentions: Optional[bool] = None,
246
+ output_hidden_states: Optional[bool] = None,
247
+ logits_to_keep: int | torch.Tensor = 0,
248
+ **kwargs,
249
+ ) -> CausalLMOutputWithPast:
250
+ if inputs_embeds is None:
251
+ if input_ids is None:
252
+ raise ValueError("Either `input_ids` or `inputs_embeds` must be provided.")
253
+ inputs_embeds = self.language_model.model.embed_tokens(input_ids)
254
+
255
+ past_len = self._cache_seq_len(past_key_values)
256
+ audio_inputs = input_features if input_features is not None else audios
257
+ audio_lengths = feature_lens if feature_lens is not None else audio_feature_lengths
258
+ if audio_inputs is not None and input_ids is not None and past_len == 0:
259
+ inputs_embeds = self._inject_audio_embeddings(
260
+ input_ids=input_ids,
261
+ input_features=audio_inputs,
262
+ feature_lens=audio_lengths,
263
+ )
264
+
265
+ outputs = self.language_model.model(
266
+ input_ids=None,
267
+ attention_mask=attention_mask,
268
+ position_ids=position_ids,
269
+ past_key_values=past_key_values,
270
+ inputs_embeds=inputs_embeds,
271
+ use_cache=use_cache,
272
+ output_attentions=output_attentions,
273
+ output_hidden_states=output_hidden_states,
274
+ )
275
+ hidden_states = outputs[0]
276
+
277
+ if isinstance(logits_to_keep, int) and logits_to_keep > 0:
278
+ hidden_for_logits = hidden_states[:, -logits_to_keep:, :]
279
+ elif isinstance(logits_to_keep, torch.Tensor):
280
+ hidden_for_logits = hidden_states[:, logits_to_keep, :]
281
+ else:
282
+ hidden_for_logits = hidden_states
283
+ logits = self.language_model.lm_head(hidden_for_logits)
284
+
285
+ loss = None
286
+ if labels is not None:
287
+ loss = self.language_model.loss_function(
288
+ logits=logits,
289
+ labels=labels,
290
+ vocab_size=self.config.vocab_size,
291
+ **kwargs,
292
+ )
293
+
294
+ return CausalLMOutputWithPast(
295
+ loss=loss,
296
+ logits=logits,
297
+ past_key_values=outputs.past_key_values,
298
+ hidden_states=outputs.hidden_states,
299
+ attentions=outputs.attentions,
300
+ )
301
+
302
+ def prepare_inputs_for_generation(
303
+ self,
304
+ input_ids,
305
+ past_key_values=None,
306
+ attention_mask=None,
307
+ inputs_embeds=None,
308
+ **kwargs,
309
+ ):
310
+ past_len = self._cache_seq_len(past_key_values)
311
+ if past_len > 0:
312
+ input_ids = input_ids[:, -1:]
313
+
314
+ model_inputs = {
315
+ "input_ids": input_ids,
316
+ "past_key_values": past_key_values,
317
+ "use_cache": kwargs.get("use_cache"),
318
+ "attention_mask": attention_mask,
319
+ "input_features": kwargs.get("input_features", kwargs.get("audios", None)),
320
+ "feature_lens": kwargs.get("feature_lens", kwargs.get("audio_feature_lengths", None)),
321
+ }
322
+ if inputs_embeds is not None and past_key_values is None:
323
+ model_inputs["inputs_embeds"] = inputs_embeds
324
+ del model_inputs["input_ids"]
325
+ return model_inputs
326
+
327
+
328
+ __all__ = [
329
+ "ArkasrForConditionalGeneration",
330
+ "Qwen3AsrMlpTower",
331
+ "Qwen3AsrMlpTowerBlock",
332
+ ]
preprocessor_config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_arkasr.ArkasrProcessor"
4
+ },
5
+ "chunk_length": 30,
6
+ "dither": 0.0,
7
+ "feature_extractor_type": "WhisperFeatureExtractor",
8
+ "feature_size": 128,
9
+ "hop_length": 160,
10
+ "n_fft": 400,
11
+ "n_samples": 480000,
12
+ "nb_max_frames": 3000,
13
+ "padding_side": "right",
14
+ "padding_value": 0.0,
15
+ "processor_class": "ArkasrProcessor",
16
+ "return_attention_mask": false,
17
+ "sampling_rate": 16000
18
+ }
processing_arkasr.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import io
6
+ import json
7
+ import os
8
+ from typing import Any, Dict, List, Optional, Union
9
+
10
+ import numpy as np
11
+ import torch
12
+ import librosa
13
+ import soundfile as sf # Used for BytesIO fallback decoding.
14
+
15
+ from transformers import AutoTokenizer, WhisperFeatureExtractor
16
+ from transformers.feature_extraction_utils import BatchFeature
17
+ from transformers.processing_utils import ProcessorMixin
18
+ from transformers.utils import logging
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+ _AUDIO_MARKER = "<<AUDIO_TOKENS>>"
23
+
24
+ def _normalize_dtype_name(name: str) -> str:
25
+ name = name.strip().lower()
26
+ alias = {
27
+ "fp16": "float16",
28
+ "float16": "float16",
29
+ "half": "float16",
30
+ "bf16": "bfloat16",
31
+ "bfloat16": "bfloat16",
32
+ "fp32": "float32",
33
+ "float32": "float32",
34
+ "float": "float32",
35
+ }
36
+ return alias.get(name, name)
37
+
38
+
39
+ def _resolve_torch_dtype(x: Any, default: str = "float32") -> torch.dtype:
40
+ if isinstance(x, torch.dtype):
41
+ return x
42
+ if x is None:
43
+ x = default
44
+ if isinstance(x, str):
45
+ name = _normalize_dtype_name(x)
46
+ if not hasattr(torch, name):
47
+ raise ValueError(f"Unknown torch dtype string: {x} (normalized: {name})")
48
+ return getattr(torch, name)
49
+ raise TypeError(f"audio_dtype/audio_torch_dtype must be str or torch.dtype or None, got {type(x)}")
50
+
51
+
52
+ class ArkasrProcessor(ProcessorMixin):
53
+ attributes = ["feature_extractor", "tokenizer"]
54
+ valid_kwargs = ["merge_factor", "audio_token", "audio_dtype"]
55
+ feature_extractor_class = ("WhisperFeatureExtractor", "SequenceFeatureExtractor")
56
+ tokenizer_class = ("PreTrainedTokenizerFast", "PreTrainedTokenizer")
57
+
58
+ def __init__(
59
+ self,
60
+ feature_extractor,
61
+ tokenizer,
62
+ merge_factor: int = 4,
63
+ audio_token: str = "<|audio|>",
64
+ audio_dtype: str = "float32",
65
+ **kwargs,
66
+ ):
67
+ super().__init__(feature_extractor, tokenizer)
68
+ self.merge_factor = int(merge_factor)
69
+ self.audio_token = str(audio_token)
70
+ self.audio_dtype = str(audio_dtype)
71
+
72
+ self.bos_audio_token = "<|begin_of_audio|>"
73
+ self.eos_audio_token = "<|end_of_audio|>"
74
+ self.user_token = "<|user|>"
75
+ self.assistant_token = "<|assistant|>"
76
+ self.assistant_end_token = "<|im_end|>"
77
+
78
+ @classmethod
79
+ def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs) -> "ArkasrProcessor":
80
+ trust_remote_code = bool(kwargs.pop("trust_remote_code", False))
81
+ passthrough_keys = {"cache_dir", "force_download", "local_files_only", "token", "revision", "subfolder"}
82
+ shared_kwargs = {k: kwargs[k] for k in list(kwargs.keys()) if k in passthrough_keys}
83
+
84
+ merge_factor = 4
85
+ audio_token = "<|audio|>"
86
+ audio_dtype = "float32"
87
+ tokenizer_cfg: Dict[str, Any] = {}
88
+ feat_cfg: Dict[str, Any] = {}
89
+
90
+ proc_cfg_path = os.path.join(pretrained_model_name_or_path, "processor_config.json")
91
+ if os.path.isfile(proc_cfg_path):
92
+ with open(proc_cfg_path, "r", encoding="utf-8") as f:
93
+ proc_cfg = json.load(f)
94
+ merge_factor = int(proc_cfg.get("merge_factor", merge_factor))
95
+ audio_token = str(proc_cfg.get("audio_token", audio_token))
96
+ audio_dtype = str(proc_cfg.get("audio_dtype", audio_dtype))
97
+ tokenizer_cfg = proc_cfg.get("tokenizer_config", {}) or {}
98
+ feat_cfg = proc_cfg.get("feature_extractor_config", {}) or {}
99
+
100
+ feature_extractor = WhisperFeatureExtractor.from_pretrained(pretrained_model_name_or_path, **shared_kwargs)
101
+ for k, v in feat_cfg.items():
102
+ if hasattr(feature_extractor, k):
103
+ try: setattr(feature_extractor, k, v)
104
+ except Exception: pass
105
+
106
+ tokenizer = AutoTokenizer.from_pretrained(
107
+ pretrained_model_name_or_path, use_fast=True, trust_remote_code=trust_remote_code, **shared_kwargs
108
+ )
109
+ for k, v in tokenizer_cfg.items():
110
+ if hasattr(tokenizer, k):
111
+ try: setattr(tokenizer, k, v)
112
+ except Exception: pass
113
+
114
+ return cls(
115
+ feature_extractor=feature_extractor,
116
+ tokenizer=tokenizer,
117
+ merge_factor=merge_factor,
118
+ audio_token=audio_token,
119
+ audio_dtype=audio_dtype,
120
+ )
121
+
122
+ # =========================
123
+ # Audio helpers.
124
+ # =========================
125
+ def _load_audio_file(self, path: str, sampling_rate: int = 16000, offset: float = 0.0, duration: Optional[float] = None) -> np.ndarray:
126
+ # librosa supports offset and duration for file inputs.
127
+ audio_array, _ = librosa.load(path, sr=int(sampling_rate), mono=True, offset=offset, duration=duration)
128
+ return np.asarray(audio_array, dtype=np.float32)
129
+
130
+ def _strip_data_url_prefix(self, b64: str) -> str:
131
+ if "," in b64 and b64[:30].lower().startswith("data:"):
132
+ return b64.split(",", 1)[1]
133
+ return b64
134
+
135
+ def _load_audio_base64(self, b64: str, sampling_rate: int = 16000, offset: float = 0.0, duration: Optional[float] = None) -> np.ndarray:
136
+ b64 = self._strip_data_url_prefix(b64)
137
+ raw = base64.b64decode(b64)
138
+ bio = io.BytesIO(raw)
139
+
140
+ # librosa also supports offset and duration for BytesIO inputs.
141
+ try:
142
+ wav, _sr = librosa.load(bio, sr=int(sampling_rate), mono=True, offset=offset, duration=duration)
143
+ return np.asarray(wav, dtype=np.float32)
144
+ except Exception as e:
145
+ # Fallback path with manual slicing.
146
+ try:
147
+ bio.seek(0)
148
+ data, sr = sf.read(bio, dtype="float32", always_2d=True)
149
+ wav = data.mean(axis=1)
150
+ if int(sr) != int(sampling_rate):
151
+ wav = librosa.resample(wav, orig_sr=int(sr), target_sr=int(sampling_rate))
152
+
153
+ start_sample = int(offset * sampling_rate)
154
+ end_sample = None
155
+ if duration is not None:
156
+ end_sample = start_sample + int(duration * sampling_rate)
157
+
158
+ return np.asarray(wav[start_sample:end_sample], dtype=np.float32)
159
+ except Exception as e2:
160
+ raise ValueError("Failed to decode base64 audio.") from e2
161
+
162
+ def calculate_audio_token_count(self, mel_frames: int) -> int:
163
+ downsampled = (int(mel_frames) + 1) // 2
164
+ merged = downsampled // max(self.merge_factor, 1)
165
+ return max(int(merged), 1)
166
+
167
+ def _build_templates_and_audios(
168
+ self,
169
+ conversations: List[List[dict]],
170
+ sampling_rate: int,
171
+ add_generation_prompt: bool,
172
+ ) -> tuple[List[str], List[np.ndarray], List[int]]:
173
+ prompts_template: List[str] = []
174
+ audios_raw: List[np.ndarray] = []
175
+ prompt_audio_counts: List[int] = []
176
+
177
+ for conv in conversations:
178
+ conv_str = ""
179
+ last_role = None
180
+ audio_count_this_conv = 0
181
+
182
+ for msg in conv:
183
+ role = msg["role"]
184
+ last_role = role
185
+ content = msg["content"]
186
+
187
+ if role == "user": conv_str += f"{self.user_token}"
188
+ elif role == "assistant": conv_str += f"{self.assistant_token}"
189
+ else: conv_str += f"<|{role}|>"
190
+
191
+ if isinstance(content, str):
192
+ conv_str += f"{content}"
193
+ elif isinstance(content, list):
194
+ for part in content:
195
+ ptype = part.get("type")
196
+ if ptype == "audio":
197
+ # Optional segment selection from begin_time/end_time.
198
+ begin_time = part.get("begin_time", -1)
199
+ end_time = part.get("end_time", -1)
200
+
201
+ offset = 0.0
202
+ duration = None
203
+
204
+ # Apply slicing only when begin_time is valid.
205
+ if begin_time is not None and begin_time >= 0:
206
+ offset = float(begin_time)
207
+ if end_time is not None and end_time > begin_time:
208
+ duration = float(end_time) - float(begin_time)
209
+
210
+ audio_raw_this = None
211
+ if "array" in part:
212
+ arr = part["array"]
213
+ if isinstance(arr, torch.Tensor):
214
+ arr = arr.detach().cpu().numpy()
215
+ full_arr = np.asarray(arr, dtype=np.float32).reshape(-1)
216
+
217
+ # Slice in-memory audio arrays as needed.
218
+ start_idx = int(offset * sampling_rate)
219
+ end_idx = None
220
+ if duration is not None:
221
+ end_idx = start_idx + int(duration * sampling_rate)
222
+ audio_raw_this = full_arr[start_idx:end_idx]
223
+
224
+ elif "path" in part:
225
+ audio_raw_this = self._load_audio_file(
226
+ part["path"],
227
+ sampling_rate=sampling_rate,
228
+ offset=offset,
229
+ duration=duration
230
+ )
231
+ elif "base64" in part:
232
+ audio_raw_this = self._load_audio_base64(
233
+ part["base64"],
234
+ sampling_rate=sampling_rate,
235
+ offset=offset,
236
+ duration=duration
237
+ )
238
+ else:
239
+ raise ValueError("Audio part must contain 'path' or 'array' or 'base64'.")
240
+
241
+ audios_raw.append(audio_raw_this)
242
+ audio_count_this_conv += 1
243
+ conv_str += f"{self.bos_audio_token}{_AUDIO_MARKER}{self.eos_audio_token}"
244
+
245
+ elif ptype == "text":
246
+ conv_str += f"{part.get('text', '')}"
247
+ else:
248
+ raise ValueError(f"Unknown content part type: {ptype}")
249
+ else:
250
+ raise ValueError(f"Unsupported message content type: {type(content)}")
251
+
252
+ if add_generation_prompt:
253
+ if last_role == "user": conv_str += f"{self.assistant_token}"
254
+ elif last_role == "assistant": conv_str += f"{self.assistant_end_token}"
255
+ else: conv_str += f"{self.assistant_token}"
256
+
257
+ prompts_template.append(conv_str)
258
+ prompt_audio_counts.append(audio_count_this_conv)
259
+
260
+ return prompts_template, audios_raw, prompt_audio_counts
261
+
262
+ def _calculate_audio_token_counts_per_sample(
263
+ self,
264
+ audios_raw: List[np.ndarray],
265
+ sampling_rate: int,
266
+ audio_max_length: Optional[int],
267
+ audio_pad_to_multiple_of: Optional[int],
268
+ ) -> List[int]:
269
+ del sampling_rate, audio_pad_to_multiple_of
270
+
271
+ hop_length = int(getattr(self.feature_extractor, "hop_length", 160))
272
+ max_audio_samples = int(audio_max_length) if audio_max_length is not None else None
273
+ token_counts: List[int] = []
274
+
275
+ for audio_raw in audios_raw:
276
+ audio_np = np.asarray(audio_raw, dtype=np.float32).reshape(-1)
277
+ effective_len = int(audio_np.shape[0])
278
+ if max_audio_samples is not None:
279
+ effective_len = min(effective_len, max_audio_samples)
280
+
281
+ mel_frames = effective_len // max(hop_length, 1)
282
+ token_counts.append(self.calculate_audio_token_count(int(mel_frames)))
283
+
284
+ return token_counts
285
+
286
+ # =========================
287
+ # apply_chat_template
288
+ # =========================
289
+ def apply_chat_template(
290
+ self,
291
+ conversation: Union[List[dict], List[List[dict]]],
292
+ chat_template: Optional[str] = None,
293
+ add_generation_prompt: bool = True,
294
+ **kwargs,
295
+ ) -> Union[BatchFeature, str, List[str]]:
296
+ if chat_template is not None:
297
+ logger.warning("chat_template argument is ignored.")
298
+
299
+ tokenize = kwargs.pop("tokenize", True)
300
+ return_tensors = kwargs.pop("return_tensors", "pt")
301
+ kwargs.pop("return_dict", None)
302
+
303
+ audio_torch_dtype = kwargs.pop("audio_torch_dtype", None)
304
+ audio_dtype_override = kwargs.pop("audio_dtype", None)
305
+ dtype_source = audio_torch_dtype if audio_torch_dtype is not None else audio_dtype_override
306
+ target_dtype = _resolve_torch_dtype(dtype_source, default=getattr(self, "audio_dtype", "float32"))
307
+
308
+ text_kwargs = dict(kwargs.pop("text_kwargs", {}) or {})
309
+ for k in ("padding", "truncation", "max_length", "add_special_tokens"):
310
+ if k in kwargs and k not in text_kwargs:
311
+ text_kwargs[k] = kwargs.pop(k)
312
+
313
+ sampling_rate = int(kwargs.pop("sampling_rate", 16000))
314
+ audio_padding = kwargs.pop("audio_padding", "longest")
315
+ audio_max_length = kwargs.pop("audio_max_length", None)
316
+ audio_pad_to_multiple_of = kwargs.pop("audio_pad_to_multiple_of", None)
317
+
318
+ if kwargs:
319
+ logger.warning(f"Ignored unused kwargs: {list(kwargs.keys())}")
320
+
321
+ if isinstance(conversation, list) and conversation and isinstance(conversation[0], dict):
322
+ conversations = [conversation]
323
+ is_single = True
324
+ else:
325
+ conversations = conversation
326
+ is_single = False
327
+
328
+ prompt_templates, audios_raw, prompt_audio_counts = self._build_templates_and_audios(
329
+ conversations=conversations,
330
+ sampling_rate=sampling_rate,
331
+ add_generation_prompt=add_generation_prompt,
332
+ )
333
+
334
+ input_features = None
335
+ audio_token_counts: List[int] = []
336
+
337
+ if len(audios_raw) > 0:
338
+ feat = self.feature_extractor(
339
+ audios_raw,
340
+ sampling_rate=sampling_rate,
341
+ return_tensors="np",
342
+ return_attention_mask=False,
343
+ padding=audio_padding,
344
+ max_length=audio_max_length,
345
+ pad_to_multiple_of=audio_pad_to_multiple_of,
346
+ )
347
+ input_features = feat["input_features"]
348
+ if not isinstance(input_features, np.ndarray):
349
+ input_features = np.asarray(input_features)
350
+
351
+ audio_token_counts = self._calculate_audio_token_counts_per_sample(
352
+ audios_raw=audios_raw,
353
+ sampling_rate=sampling_rate,
354
+ audio_max_length=audio_max_length,
355
+ audio_pad_to_multiple_of=audio_pad_to_multiple_of,
356
+ )
357
+
358
+ prompts: List[str] = []
359
+ audio_idx = 0
360
+ for prompt_template, audio_count in zip(prompt_templates, prompt_audio_counts):
361
+ prompt = prompt_template
362
+ for _ in range(audio_count):
363
+ if audio_idx >= len(audio_token_counts):
364
+ raise ValueError("Audio token count mismatch while building prompts.")
365
+ audio_tokens_str = "".join([self.audio_token] * audio_token_counts[audio_idx])
366
+ prompt = prompt.replace(_AUDIO_MARKER, audio_tokens_str, 1)
367
+ audio_idx += 1
368
+ if _AUDIO_MARKER in prompt:
369
+ raise ValueError("Unresolved audio marker remained in prompt.")
370
+ prompts.append(prompt)
371
+
372
+ if audio_idx != len(audio_token_counts):
373
+ raise ValueError("Unused audio token counts remained after prompt construction.")
374
+
375
+ if not tokenize:
376
+ return prompts[0] if is_single else prompts
377
+
378
+ text_kwargs.setdefault("padding", "longest")
379
+ text_kwargs.setdefault("add_special_tokens", False)
380
+ text_kwargs["return_tensors"] = return_tensors
381
+
382
+ enc = self.tokenizer(prompts, **text_kwargs)
383
+ data: Dict[str, Any] = dict(enc)
384
+
385
+ if input_features is not None:
386
+ audio_tensor = torch.tensor(input_features, dtype=target_dtype)
387
+ data["input_features"] = audio_tensor
388
+ data["audios"] = audio_tensor
389
+
390
+ return BatchFeature(data=data, tensor_type=return_tensors)
391
+
392
+ # Tokenizer proxy methods and direct audio-array path.
393
+ def batch_decode(self, *args, **kwargs):
394
+ return self.tokenizer.batch_decode(*args, **kwargs)
395
+
396
+ def decode(self, *args, **kwargs):
397
+ return self.tokenizer.decode(*args, **kwargs)
398
+
399
+ def __call__(
400
+ self,
401
+ text: Union[str, List[str]],
402
+ audios: Union[np.ndarray, torch.Tensor, List[Union[np.ndarray, torch.Tensor]]],
403
+ sampling_rate: int = 16000,
404
+ return_tensors: str = "pt",
405
+ **tokenizer_kwargs,
406
+ ) -> BatchFeature:
407
+ # Direct audio-array path; segment slicing is handled by apply_chat_template.
408
+ audios_list = []
409
+ def flatten_audios(obj):
410
+ if isinstance(obj, (list, tuple)):
411
+ if len(obj) > 0 and isinstance(obj[0], (float, int)):
412
+ audios_list.append(obj)
413
+ else:
414
+ for item in obj: flatten_audios(item)
415
+ elif isinstance(obj, (np.ndarray, torch.Tensor)):
416
+ audios_list.append(obj)
417
+ flatten_audios(audios)
418
+
419
+ audios_np: List[np.ndarray] = []
420
+ for a in audios_list:
421
+ if isinstance(a, torch.Tensor): a = a.detach().cpu().numpy()
422
+ a = np.asarray(a, dtype=np.float32).reshape(-1)
423
+ audios_np.append(a)
424
+
425
+ input_features = None
426
+ if audios_np:
427
+ feat = self.feature_extractor(audios_np, sampling_rate=int(sampling_rate), return_tensors="np", return_attention_mask=False, padding="longest")
428
+ input_features = feat["input_features"]
429
+ if not isinstance(input_features, np.ndarray): input_features = np.asarray(input_features)
430
+
431
+ tokenizer_kwargs = dict(tokenizer_kwargs or {})
432
+ tokenizer_kwargs.setdefault("padding", "longest")
433
+ tokenizer_kwargs.setdefault("add_special_tokens", False)
434
+ tokenizer_kwargs["return_tensors"] = return_tensors
435
+
436
+ enc = self.tokenizer(text, **tokenizer_kwargs)
437
+ data: Dict[str, Any] = dict(enc)
438
+ if input_features is not None:
439
+ audio_tensor = torch.tensor(input_features, dtype=_resolve_torch_dtype(getattr(self, "audio_dtype", "float32")))
440
+ data["input_features"] = audio_tensor
441
+ data["audios"] = audio_tensor
442
+ return BatchFeature(data=data, tensor_type=return_tensors)
443
+
444
+ @property
445
+ def model_input_names(self):
446
+ return ["input_ids", "attention_mask", "input_features", "audios"]
processor_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "audio_dtype": "bfloat16",
3
+ "audio_token": "<|audio|>",
4
+ "auto_map": {
5
+ "AutoProcessor": "processing_arkasr.ArkasrProcessor"
6
+ },
7
+ "merge_factor": 4,
8
+ "processor_class": "ArkasrProcessor"
9
+ }
qwen3_asr_audio_config.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2026 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from transformers.configuration_utils import PretrainedConfig
16
+ from transformers.utils import logging
17
+
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ class Qwen3ASRAudioEncoderConfig(PretrainedConfig):
23
+ r"""
24
+ This is the configuration class to store the configuration of a [`Qwen3ASRAudioEncoder`]. It is used to instantiate a
25
+ Qwen3-ASR audio encoder according to the specified arguments, defining the model architecture. Instantiating a
26
+ configuration with the defaults will yield a similar configuration to that of the audio encoder of the Qwen2-Audio
27
+ architecture.
28
+
29
+ e.g. [Qwen/Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B)
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ num_mel_bins (`int`, *optional*, defaults to 128):
36
+ Number of mel features used per input features. Should correspond to the value used in the
37
+ `Qwen3ASRProcessor` class.
38
+ encoder_layers (`int`, *optional*, defaults to 32):
39
+ Number of encoder layers.
40
+ encoder_attention_heads (`int`, *optional*, defaults to 20):
41
+ Number of attention heads for each attention layer in the Transformer encoder.
42
+ encoder_ffn_dim (`int`, *optional*, defaults to 5120):
43
+ Dimensionality of the "intermediate" (often named feed-forward) layer in encoder.
44
+ d_model (`int`, *optional*, defaults to 1280):
45
+ Dimensionality of the layers.
46
+ dropout (`float`, *optional*, defaults to 0.0):
47
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
48
+ attention_dropout (`float`, *optional*, defaults to 0.0):
49
+ The dropout ratio for the attention probabilities.
50
+ activation_function (`str`, *optional*, defaults to `"gelu"`):
51
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
52
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
53
+ activation_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for activations inside the fully connected layer.
55
+ scale_embedding (`bool`, *optional*, defaults to `False`):
56
+ Scale embeddings by diving by sqrt(d_model).
57
+ initializer_range (`float`, *optional*, defaults to 0.02):
58
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
59
+ max_source_positions (`int`, *optional*, defaults to 1500):
60
+ The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
61
+ n_window (`int`, *optional*, defaults to 100):
62
+ The chunk for conv and flash attn in AudioEncoder.
63
+ output_dim (`int`, *optional*, defaults to 3584):
64
+ The output dimension of AudioEncoder.
65
+
66
+ Example:
67
+
68
+ ```python
69
+ >>> from transformers import Qwen3ASRAudioEncoderConfig, Qwen3ASRAudioEncoder
70
+
71
+ >>> # Initializing a Qwen3ASRAudioEncoderConfig
72
+ >>> configuration = Qwen3ASRAudioEncoderConfig()
73
+
74
+ >>> # Initializing a Qwen3ASRAudioEncoder (with random weights)
75
+ >>> model = Qwen3ASRAudioEncoder(configuration)
76
+
77
+ >>> # Accessing the model configuration
78
+ >>> configuration = model.config
79
+ ```"""
80
+
81
+ model_type = "qwen3_asr_audio_encoder"
82
+
83
+ def __init__(
84
+ self,
85
+ num_mel_bins=128,
86
+ encoder_layers=32,
87
+ encoder_attention_heads=20,
88
+ encoder_ffn_dim=5120,
89
+ d_model=1280,
90
+ dropout=0,
91
+ attention_dropout=0,
92
+ activation_function="gelu",
93
+ activation_dropout=0,
94
+ scale_embedding=False,
95
+ initializer_range=0.02,
96
+ max_source_positions=1500,
97
+ n_window=100,
98
+ output_dim=3584,
99
+ n_window_infer=400,
100
+ conv_chunksize=500,
101
+ downsample_hidden_size=480,
102
+ **kwargs,
103
+ ):
104
+ super().__init__(**kwargs)
105
+
106
+ self.num_mel_bins = num_mel_bins
107
+ self.d_model = d_model
108
+ self.encoder_layers = encoder_layers
109
+ self.encoder_attention_heads = encoder_attention_heads
110
+ self.encoder_ffn_dim = encoder_ffn_dim
111
+ self.dropout = dropout
112
+ self.attention_dropout = attention_dropout
113
+ self.activation_function = activation_function
114
+ self.activation_dropout = activation_dropout
115
+ self.num_hidden_layers = encoder_layers
116
+ self.initializer_range = initializer_range
117
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
118
+ self.max_source_positions = max_source_positions
119
+ self.n_window = n_window
120
+ self.output_dim = output_dim
121
+ self.n_window_infer = n_window_infer
122
+ self.conv_chunksize = conv_chunksize
123
+ self.downsample_hidden_size = downsample_hidden_size
124
+
125
+
126
+ class Qwen3ASRTextConfig(PretrainedConfig):
127
+ r"""
128
+ This is the configuration class to store the configuration of a [`Qwen3ASRTextModel`]. It is used to instantiate a
129
+ Qwen3-ASR model according to the specified arguments, defining the model architecture. Instantiating a configuration
130
+ with the defaults will yield a similar configuration to that of
131
+ Qwen3-ASR-1.7B [Qwen/Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B)
132
+
133
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
134
+ documentation from [`PretrainedConfig`] for more information.
135
+
136
+ Args:
137
+ vocab_size (`int`, *optional*, defaults to 151936):
138
+ Vocabulary size of the Qwen3ASR model. Defines the number of different tokens that can be represented by the
139
+ `inputs_ids` passed when calling [`Qwen3ASRModel`]
140
+ hidden_size (`int`, *optional*, defaults to 4096):
141
+ Dimension of the hidden representations.
142
+ intermediate_size (`int`, *optional*, defaults to 22016):
143
+ Dimension of the MLP representations.
144
+ num_hidden_layers (`int`, *optional*, defaults to 32):
145
+ Number of hidden layers in the Transformer encoder.
146
+ num_attention_heads (`int`, *optional*, defaults to 32):
147
+ Number of attention heads for each attention layer in the Transformer encoder.
148
+ num_key_value_heads (`int`, *optional*, defaults to 32):
149
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
150
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
151
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
152
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
153
+ by meanpooling all the original heads within that group. For more details, check out [this
154
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
155
+ head_dim (`int`, *optional*, defaults to 128):
156
+ The dimension of the head. If not specified, will default to `hidden_size // num_attention_heads`.
157
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
158
+ The non-linear activation function (function or string) in the decoder.
159
+ max_position_embeddings (`int`, *optional*, defaults to 128000):
160
+ The maximum sequence length that this model might ever be used with.
161
+ initializer_range (`float`, *optional*, defaults to 0.02):
162
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
163
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
164
+ The epsilon used by the rms normalization layers.
165
+ use_cache (`bool`, *optional*, defaults to `True`):
166
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
167
+ relevant if `config.is_decoder=True`.
168
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
169
+ Whether the model's input and output word embeddings should be tied.
170
+ rope_theta (`float`, *optional*, defaults to 5000000.0):
171
+ The base period of the RoPE embeddings.
172
+ rope_scaling (`Dict`, *optional*):
173
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
174
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
175
+ accordingly.
176
+ Expected contents:
177
+ `rope_type` (`str`):
178
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
179
+ 'llama3'], with 'default' being the original RoPE implementation.
180
+ `factor` (`float`, *optional*):
181
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
182
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
183
+ original maximum pre-trained length.
184
+ `original_max_position_embeddings` (`int`, *optional*):
185
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
186
+ pretraining.
187
+ `attention_factor` (`float`, *optional*):
188
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
189
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
190
+ `factor` field to infer the suggested value.
191
+ `beta_fast` (`float`, *optional*):
192
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
193
+ ramp function. If unspecified, it defaults to 32.
194
+ `beta_slow` (`float`, *optional*):
195
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
196
+ ramp function. If unspecified, it defaults to 1.
197
+ `short_factor` (`list[float]`, *optional*):
198
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
199
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
200
+ size divided by the number of attention heads divided by 2
201
+ `long_factor` (`list[float]`, *optional*):
202
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
203
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
204
+ size divided by the number of attention heads divided by 2
205
+ `low_freq_factor` (`float`, *optional*):
206
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
207
+ `high_freq_factor` (`float`, *optional*):
208
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
209
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
210
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
211
+ attention_dropout (`float`, *optional*, defaults to 0.0):
212
+ The dropout ratio for the attention probabilities.
213
+
214
+ ```python
215
+ >>> from transformers import Qwen3ASRTextModel, Qwen3ASRTextConfig
216
+
217
+ >>> # Initializing a Qwen3ASR style configuration
218
+ >>> configuration = Qwen3ASRTextConfig()
219
+
220
+ >>> # Initializing a model from the Qwen3-VL-7B style configuration
221
+ >>> model = Qwen3ASRTextModel(configuration)
222
+
223
+ >>> # Accessing the model configuration
224
+ >>> configuration = model.config
225
+ ```"""
226
+
227
+ model_type = "qwen3_asr_text"
228
+ base_config_key = "text_config"
229
+
230
+ def __init__(
231
+ self,
232
+ vocab_size=151936,
233
+ hidden_size=4096,
234
+ intermediate_size=22016,
235
+ num_hidden_layers=32,
236
+ num_attention_heads=32,
237
+ num_key_value_heads=32,
238
+ head_dim=128,
239
+ hidden_act="silu",
240
+ max_position_embeddings=128000,
241
+ initializer_range=0.02,
242
+ rms_norm_eps=1e-6,
243
+ use_cache=True,
244
+ tie_word_embeddings=False,
245
+ rope_theta=5000000.0,
246
+ rope_scaling=None,
247
+ attention_bias=False,
248
+ attention_dropout=0.0,
249
+ **kwargs,
250
+ ):
251
+ self.vocab_size = vocab_size
252
+ self.max_position_embeddings = max_position_embeddings
253
+ self.hidden_size = hidden_size
254
+ self.intermediate_size = intermediate_size
255
+ self.num_hidden_layers = num_hidden_layers
256
+ self.num_attention_heads = num_attention_heads
257
+
258
+ # for backward compatibility
259
+ if num_key_value_heads is None:
260
+ num_key_value_heads = num_attention_heads
261
+
262
+ self.num_key_value_heads = num_key_value_heads
263
+ self.head_dim = head_dim
264
+ self.hidden_act = hidden_act
265
+ self.initializer_range = initializer_range
266
+ self.rms_norm_eps = rms_norm_eps
267
+ self.use_cache = use_cache
268
+ self.rope_theta = rope_theta
269
+ self.rope_scaling = rope_scaling
270
+ self.attention_bias = attention_bias
271
+ self.attention_dropout = attention_dropout
272
+ # Validate the correctness of rotary position embeddings parameters
273
+ # BC: if there is a 'type' field, move it to 'rope_type'.
274
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
275
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
276
+
277
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
278
+
279
+
280
+ class Qwen3ASRThinkerConfig(PretrainedConfig):
281
+ r"""
282
+ This is the configuration class to store the configuration of a [`Qwen3ASRThinker`]. It is used to instantiate a
283
+ Qwen3-ASR-Thinker model according to the specified arguments, defining the model architecture. Instantiating a
284
+ configuration with the defaults will yield a similar configuration to that of the thinker component of the Qwen3-Omni
285
+ architecture.
286
+
287
+ e.g. [Qwen/Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B)
288
+
289
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
290
+ documentation from [`PretrainedConfig`] for more information.
291
+
292
+ Args:
293
+ audio_config (`dict`, *optional*):
294
+ The config dictionary of the audio backbone.
295
+ text_config (`dict`, *optional*):
296
+ The config dictionary of the text backbone.
297
+ audio_token_id (`int`, *optional*, defaults to 151646):
298
+ The audio token id to encode the audio prompt.
299
+ audio_start_token_id (`int`, *optional*, defaults to 151647):
300
+ The audio start token id to encode the audio prompt.
301
+ user_token_id (`int`, *optional*, defaults to 872):
302
+ The user token id to encode the user token.
303
+ initializer_range (`float`, *optional*, defaults to 0.02):
304
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
305
+
306
+ Example:
307
+
308
+ ```python
309
+ >>> from transformers import Qwen3ASRThinkerModel, Qwen3ASRThinkerConfig
310
+
311
+ >>> # Initializing a default Qwen3ASRThinkerConfig
312
+ >>> configuration = Qwen3ASRThinkerConfig()
313
+
314
+ >>> # Initializing a model (with random weights) from the default configuration
315
+ >>> model = Qwen3ASRThinkerModel(configuration)
316
+
317
+ >>> # Accessing the model configuration
318
+ >>> configuration = model.config
319
+ ```"""
320
+
321
+ model_type = "qwen3_asr_thinker"
322
+
323
+ attribute_map = {}
324
+ sub_configs = {
325
+ "audio_config": Qwen3ASRAudioEncoderConfig,
326
+ "text_config": Qwen3ASRTextConfig,
327
+ }
328
+
329
+ def __init__(
330
+ self,
331
+ audio_config=None,
332
+ text_config=None,
333
+ audio_token_id=151646,
334
+ audio_start_token_id=151647,
335
+ user_token_id=872,
336
+ initializer_range=0.02,
337
+ **kwargs,
338
+ ):
339
+ super().__init__(**kwargs)
340
+ self.user_token_id = user_token_id
341
+ self.audio_start_token_id = audio_start_token_id
342
+ self.initializer_range = initializer_range
343
+
344
+ if isinstance(audio_config, dict):
345
+ audio_config = Qwen3ASRAudioEncoderConfig(**audio_config)
346
+ elif audio_config is None:
347
+ audio_config = Qwen3ASRAudioEncoderConfig()
348
+ self.audio_config = audio_config
349
+
350
+ if isinstance(text_config, dict):
351
+ text_config = Qwen3ASRTextConfig(**text_config)
352
+ elif text_config is None:
353
+ text_config = Qwen3ASRTextConfig()
354
+ self.text_config = text_config
355
+ self.audio_token_id = audio_token_id
356
+
357
+
358
+ class Qwen3ASRConfig(PretrainedConfig):
359
+ """
360
+ This is the configuration class to store the configuration of a [`Qwen3ASRForConditionalGeneration`]. It is used to instantiate a Qwen3ASR
361
+ model according to the specified sub-models configurations, defining the model architecture.
362
+
363
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the
364
+ [Qwen/Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B) architecture.
365
+
366
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
367
+ documentation from [`PretrainedConfig`] for more information.
368
+
369
+ Args:
370
+ thinker_config (`dict`, *optional*): Configuration of the underlying thinker sub-model.
371
+ support_languages (`List[str]`, *optional*): The languages supported by the model.
372
+
373
+ Example:
374
+
375
+ ```python
376
+ >>> from transformers import (
377
+ ... Qwen3ASRThinkerConfig,
378
+ ... Qwen3ASRForConditionalGeneration,
379
+ ... Qwen3ASRConfig,
380
+ ... )
381
+
382
+ >>> # Initializing a Qwen3ASR style configuration
383
+ >>> configuration = Qwen3ASRConfig()
384
+
385
+ >>> # Initializing a model from the configuration
386
+ >>> model = Qwen3ASRForConditionalGeneration(configuration)
387
+
388
+ >>> # Accessing the model configuration
389
+ >>> configuration = model.config
390
+ ```"""
391
+
392
+ model_type = "qwen3_asr"
393
+ sub_configs = {
394
+ "thinker_config": Qwen3ASRThinkerConfig,
395
+ }
396
+
397
+ def __init__(
398
+ self,
399
+ thinker_config=None,
400
+ support_languages=None,
401
+ **kwargs,
402
+ ):
403
+ super().__init__(**kwargs)
404
+ if thinker_config is None:
405
+ thinker_config = {}
406
+
407
+ self.thinker_config = Qwen3ASRThinkerConfig(**thinker_config)
408
+ self.support_languages = support_languages
409
+
410
+ def get_text_config(self, decoder=False) -> "PretrainedConfig":
411
+ """
412
+ Returns the config that is meant to be used with text IO. On most models, it is the original config instance
413
+ itself. On specific composite models, it is under a set of valid names.
414
+
415
+ Args:
416
+ decoder (`Optional[bool]`, *optional*, defaults to `False`):
417
+ If set to `True`, then only search for decoder config names.
418
+ """
419
+ # Overridden for deeply nested config like Qwen2.5-Omni. We don't have any omni model
420
+ # except for Qwen yet. This has to be generalized if more deeply nested configs are
421
+ # added. NOTE: currently method used only by vLLM
422
+ return self.thinker_config.get_text_config()
423
+
424
+
425
+ __all__ = ["Qwen3ASRConfig", "Qwen3ASRThinkerConfig", "Qwen3ASRAudioEncoderConfig"]
qwen3_asr_audio_model.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from typing import Optional
5
+
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from torch import nn
10
+ from transformers.activations import ACT2FN
11
+ from transformers.modeling_outputs import BaseModelOutput
12
+ from transformers.modeling_utils import PreTrainedModel
13
+
14
+ from .qwen3_asr_audio_config import Qwen3ASRAudioEncoderConfig
15
+
16
+
17
+ def _get_feat_extract_output_lengths(input_lengths: torch.Tensor) -> torch.Tensor:
18
+ input_lengths = torch.clamp(input_lengths.long(), min=1)
19
+ input_lengths_leave = input_lengths % 100
20
+ feat_lengths = (input_lengths_leave - 1) // 2 + 1
21
+ return ((feat_lengths - 1) // 2 + 1 - 1) // 2 + 1 + (input_lengths // 100) * 13
22
+
23
+
24
+ def _block_diagonal_attention_mask(hidden_states: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
25
+ seq_length = int(hidden_states.shape[0])
26
+ mask = torch.full(
27
+ (1, 1, seq_length, seq_length),
28
+ torch.finfo(hidden_states.dtype).min,
29
+ dtype=hidden_states.dtype,
30
+ device=hidden_states.device,
31
+ )
32
+ for i in range(1, int(cu_seqlens.numel())):
33
+ start = int(cu_seqlens[i - 1].item())
34
+ end = int(cu_seqlens[i].item())
35
+ mask[..., start:end, start:end] = 0
36
+ return mask
37
+
38
+
39
+ class Qwen3ASRAudioAttention(nn.Module):
40
+ def __init__(self, config: Qwen3ASRAudioEncoderConfig):
41
+ super().__init__()
42
+ self.embed_dim = int(config.d_model)
43
+ self.num_heads = int(config.encoder_attention_heads)
44
+ self.head_dim = self.embed_dim // self.num_heads
45
+ if self.head_dim * self.num_heads != self.embed_dim:
46
+ raise ValueError("d_model must be divisible by encoder_attention_heads")
47
+ self.scaling = self.head_dim**-0.5
48
+ self.attention_dropout = float(config.attention_dropout)
49
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
50
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
51
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
52
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=True)
53
+
54
+ def forward(
55
+ self,
56
+ hidden_states: torch.Tensor,
57
+ cu_seqlens: torch.Tensor,
58
+ attention_mask: Optional[torch.Tensor] = None,
59
+ ) -> torch.Tensor:
60
+ del attention_mask
61
+ seq_length = int(hidden_states.size(0))
62
+ query = self.q_proj(hidden_states).reshape(seq_length, self.num_heads, self.head_dim).transpose(0, 1)
63
+ key = self.k_proj(hidden_states).reshape(seq_length, self.num_heads, self.head_dim).transpose(0, 1)
64
+ value = self.v_proj(hidden_states).reshape(seq_length, self.num_heads, self.head_dim).transpose(0, 1)
65
+ query = query.unsqueeze(0)
66
+ key = key.unsqueeze(0)
67
+ value = value.unsqueeze(0)
68
+ mask = _block_diagonal_attention_mask(hidden_states, cu_seqlens)
69
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * self.scaling
70
+ attn_weights = attn_weights + mask
71
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
72
+ attn_weights = F.dropout(attn_weights, p=self.attention_dropout, training=self.training)
73
+ attn_output = torch.matmul(attn_weights, value)
74
+ attn_output = attn_output.transpose(1, 2).contiguous()
75
+ attn_output = attn_output.reshape(seq_length, self.embed_dim)
76
+ return self.out_proj(attn_output)
77
+
78
+
79
+ class Qwen3ASRAudioEncoderLayer(nn.Module):
80
+ def __init__(self, config: Qwen3ASRAudioEncoderConfig):
81
+ super().__init__()
82
+ self.embed_dim = int(config.d_model)
83
+ self.self_attn = Qwen3ASRAudioAttention(config)
84
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
85
+ self.activation_fn = ACT2FN[config.activation_function]
86
+ self.fc1 = nn.Linear(self.embed_dim, int(config.encoder_ffn_dim))
87
+ self.fc2 = nn.Linear(int(config.encoder_ffn_dim), self.embed_dim)
88
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
89
+
90
+ def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor) -> tuple[torch.Tensor]:
91
+ residual = hidden_states
92
+ hidden_states = self.self_attn_layer_norm(hidden_states)
93
+ hidden_states = self.self_attn(hidden_states=hidden_states, cu_seqlens=cu_seqlens)
94
+ hidden_states = residual + hidden_states
95
+ residual = hidden_states
96
+ hidden_states = self.final_layer_norm(hidden_states)
97
+ hidden_states = self.fc1(hidden_states)
98
+ hidden_states = self.activation_fn(hidden_states)
99
+ hidden_states = self.fc2(hidden_states)
100
+ hidden_states = residual + hidden_states
101
+ if hidden_states.dtype == torch.float16:
102
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
103
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
104
+ return (hidden_states,)
105
+
106
+
107
+ class SinusoidsPositionEmbedding(nn.Module):
108
+ def __init__(self, length: int, channels: int, max_timescale: int = 10000):
109
+ super().__init__()
110
+ if channels % 2 != 0:
111
+ raise ValueError("SinusoidsPositionEmbedding requires an even channel count")
112
+ log_timescale_increment = np.log(max_timescale) / (channels // 2 - 1)
113
+ inv_timescales = torch.exp(-log_timescale_increment * torch.arange(channels // 2).float())
114
+ scaled_time = torch.arange(length)[:, np.newaxis] * inv_timescales[np.newaxis, :]
115
+ self.register_buffer(
116
+ "positional_embedding",
117
+ torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1),
118
+ persistent=False,
119
+ )
120
+
121
+ def forward(self, seqlen: int):
122
+ return self.positional_embedding[:seqlen, :]
123
+
124
+
125
+ class Qwen3ASRAudioEncoder(PreTrainedModel):
126
+ config_class = Qwen3ASRAudioEncoderConfig
127
+ main_input_name = "input_features"
128
+ _no_split_modules = ["Qwen3ASRAudioEncoderLayer"]
129
+
130
+ def __init__(self, config: Qwen3ASRAudioEncoderConfig):
131
+ super().__init__(config)
132
+ embed_dim = int(config.d_model)
133
+ self.dropout = float(config.dropout)
134
+ self.num_mel_bins = int(config.num_mel_bins)
135
+ self.max_source_positions = int(config.max_source_positions)
136
+ self.embed_scale = math.sqrt(embed_dim) if bool(config.scale_embedding) else 1.0
137
+ self.n_window = int(config.n_window)
138
+ self.positional_embedding = SinusoidsPositionEmbedding(self.max_source_positions, embed_dim)
139
+ self.layers = nn.ModuleList([Qwen3ASRAudioEncoderLayer(config) for _ in range(int(config.encoder_layers))])
140
+ self.ln_post = nn.LayerNorm(embed_dim)
141
+ self.gradient_checkpointing = False
142
+ self.conv2d1 = nn.Conv2d(1, int(config.downsample_hidden_size), 3, 2, padding=1)
143
+ self.conv2d2 = nn.Conv2d(int(config.downsample_hidden_size), int(config.downsample_hidden_size), 3, 2, padding=1)
144
+ self.conv2d3 = nn.Conv2d(int(config.downsample_hidden_size), int(config.downsample_hidden_size), 3, 2, padding=1)
145
+ conv_freq = ((((int(config.num_mel_bins) + 1) // 2 + 1) // 2 + 1) // 2)
146
+ self.conv_out = nn.Linear(int(config.downsample_hidden_size) * conv_freq, embed_dim, bias=False)
147
+ self.proj1 = nn.Linear(embed_dim, embed_dim)
148
+ self.act = ACT2FN[config.activation_function]
149
+ self.proj2 = nn.Linear(embed_dim, int(config.output_dim))
150
+ self.n_window_infer = int(config.n_window_infer)
151
+ self.conv_chunksize = int(config.conv_chunksize)
152
+ self.post_init()
153
+
154
+ def _freeze_parameters(self):
155
+ for param in self.parameters():
156
+ param.requires_grad = False
157
+ self._requires_grad = False
158
+
159
+ def _prepare_attention_mask(self, inputs_tensor: torch.Tensor, cu_seqlens: torch.Tensor) -> torch.Tensor:
160
+ return _block_diagonal_attention_mask(inputs_tensor, cu_seqlens)
161
+
162
+ def forward(
163
+ self,
164
+ input_features: torch.Tensor,
165
+ feature_lens: Optional[torch.Tensor] = None,
166
+ aftercnn_lens: Optional[torch.Tensor] = None,
167
+ ):
168
+ if feature_lens is None:
169
+ feature_lens = torch.tensor([input_features.shape[-1]], dtype=torch.long, device=input_features.device)
170
+ feature_lens = feature_lens.to(device=input_features.device, dtype=torch.long)
171
+ if aftercnn_lens is None:
172
+ aftercnn_lens = _get_feat_extract_output_lengths(feature_lens)
173
+ aftercnn_lens = aftercnn_lens.to(device=input_features.device, dtype=torch.long)
174
+
175
+ chunk_num = torch.ceil(feature_lens / (self.n_window * 2)).long()
176
+ chunk_lengths = torch.tensor(
177
+ [self.n_window * 2] * int(chunk_num.sum().item()),
178
+ dtype=torch.long,
179
+ device=feature_lens.device,
180
+ )
181
+ tail_chunk_index = F.pad(chunk_num, (1, 0), value=-1).cumsum(0)[1:]
182
+ chunk_lengths[tail_chunk_index] = feature_lens % (self.n_window * 2)
183
+ chunk_lengths[chunk_lengths == 0] = self.n_window * 2
184
+
185
+ chunk_list = input_features.T.split(chunk_lengths.tolist(), dim=0)
186
+ padded_feature = nn.utils.rnn.pad_sequence(chunk_list, batch_first=True).transpose(1, 2)
187
+ feature_lens_after_cnn = _get_feat_extract_output_lengths(chunk_lengths)
188
+ padded_mask_after_cnn = nn.utils.rnn.pad_sequence(
189
+ [torch.ones(int(length.item()), dtype=torch.bool, device=padded_feature.device) for length in feature_lens_after_cnn],
190
+ batch_first=True,
191
+ )
192
+ padded_feature = padded_feature.unsqueeze(1)
193
+ padded_embeds = []
194
+ for chunk in padded_feature.split(self.conv_chunksize, dim=0):
195
+ padded_embed = F.gelu(self.conv2d1(chunk))
196
+ padded_embed = F.gelu(self.conv2d2(padded_embed))
197
+ padded_embed = F.gelu(self.conv2d3(padded_embed))
198
+ padded_embeds.append(padded_embed)
199
+ padded_embed = torch.cat(padded_embeds, dim=0)
200
+ bsz, channels, freq, time = padded_embed.size()
201
+ padded_embed = self.conv_out(padded_embed.permute(0, 3, 1, 2).contiguous().view(bsz, time, channels * freq))
202
+
203
+ positional_embedding = (
204
+ self.positional_embedding.positional_embedding[: padded_embed.shape[1], :]
205
+ .unsqueeze(0)
206
+ .to(padded_embed.dtype)
207
+ )
208
+ padded_embed = padded_embed + positional_embedding
209
+ hidden_states = padded_embed[padded_mask_after_cnn]
210
+ cu_chunk_lens = [0]
211
+ window_aftercnn = padded_mask_after_cnn.shape[-1] * (self.n_window_infer // (self.n_window * 2))
212
+ for cnn_len in aftercnn_lens:
213
+ cnn_len_int = int(cnn_len.item())
214
+ cu_chunk_lens += [window_aftercnn] * (cnn_len_int // window_aftercnn)
215
+ remainder = cnn_len_int % window_aftercnn
216
+ if remainder != 0:
217
+ cu_chunk_lens += [remainder]
218
+ cu_seqlens = torch.tensor(cu_chunk_lens, device=aftercnn_lens.device).cumsum(-1, dtype=torch.int32)
219
+
220
+ for encoder_layer in self.layers:
221
+ hidden_states = encoder_layer(hidden_states, cu_seqlens)[0]
222
+
223
+ hidden_states = self.ln_post(hidden_states)
224
+ hidden_states = self.proj1(hidden_states)
225
+ hidden_states = self.act(hidden_states)
226
+ hidden_states = self.proj2(hidden_states)
227
+ return BaseModelOutput(last_hidden_state=hidden_states)
228
+
229
+
230
+ __all__ = ["Qwen3ASRAudioEncoder", "Qwen3ASRAudioEncoderLayer", "Qwen3ASRAudioAttention"]
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|user|>",
4
+ "<|begin_of_audio|>",
5
+ "<|end_of_audio|>",
6
+ "<|assistant|>",
7
+ "<|system|>"
8
+ ],
9
+ "eos_token": {
10
+ "content": "<|im_end|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:08da04ccd72fab7d7d6da9e429c70fe59d7ed3bd5354a93f8994ec4c7c327f52
3
+ size 11419692
tokenizer_config.json ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "151646": {
29
+ "content": "<|audio|>",
30
+ "lstrip": false,
31
+ "normalized": true,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": false
35
+ },
36
+ "151647": {
37
+ "content": "<|user|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "151648": {
45
+ "content": "<|begin_of_audio|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "151649": {
53
+ "content": "<|end_of_audio|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "151650": {
61
+ "content": "<|assistant|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "151651": {
69
+ "content": "<|system|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ }
76
+ },
77
+ "additional_special_tokens": [
78
+ "<|user|>",
79
+ "<|begin_of_audio|>",
80
+ "<|end_of_audio|>",
81
+ "<|assistant|>",
82
+ "<|system|>"
83
+ ],
84
+ "auto_map": {
85
+ "AutoProcessor": "processing_arkasr.ArkasrProcessor"
86
+ },
87
+ "bos_token": null,
88
+ "clean_up_tokenization_spaces": false,
89
+ "eos_token": "<|im_end|>",
90
+ "errors": "replace",
91
+ "extra_special_tokens": {},
92
+ "model_max_length": 32768,
93
+ "pad_token": "<|endoftext|>",
94
+ "processor_class": "ArkasrProcessor",
95
+ "split_special_tokens": false,
96
+ "tokenizer_class": "Qwen2Tokenizer",
97
+ "unk_token": null
98
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff