RetentionLabs commited on
Commit
45b5d4f
·
verified ·
1 Parent(s): 17d6e03

Release the EmoTra-TTS reproduction on CosyVoice2-0.5B

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,631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This repository is distributed under two licenses.
2
+
3
+ 1. The model weights (model.safetensors, speech_tokenizer.safetensors, speaker_embedding.safetensors,
4
+ stage1/, stage2/) are licensed under the Creative Commons Attribution-NonCommercial 4.0
5
+ International License (CC BY-NC 4.0), reproduced in Part 1 below.
6
+
7
+ 2. The source code files (*.py) are licensed under the Apache License, Version 2.0, reproduced in
8
+ Part 2 below, except for the BigVGAN functions named in NOTICE, which are under the MIT License
9
+ quoted in NOTICE.
10
+
11
+ See NOTICE for attribution.
12
+
13
+ ================================================================================
14
+ Part 1. Creative Commons Attribution-NonCommercial 4.0 International (model weights)
15
+ ================================================================================
16
+
17
+ Attribution-NonCommercial 4.0 International
18
+
19
+ =======================================================================
20
+
21
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
22
+ does not provide legal services or legal advice. Distribution of
23
+ Creative Commons public licenses does not create a lawyer-client or
24
+ other relationship. Creative Commons makes its licenses and related
25
+ information available on an "as-is" basis. Creative Commons gives no
26
+ warranties regarding its licenses, any material licensed under their
27
+ terms and conditions, or any related information. Creative Commons
28
+ disclaims all liability for damages resulting from their use to the
29
+ fullest extent possible.
30
+
31
+ Using Creative Commons Public Licenses
32
+
33
+ Creative Commons public licenses provide a standard set of terms and
34
+ conditions that creators and other rights holders may use to share
35
+ original works of authorship and other material subject to copyright
36
+ and certain other rights specified in the public license below. The
37
+ following considerations are for informational purposes only, are not
38
+ exhaustive, and do not form part of our licenses.
39
+
40
+ Considerations for licensors: Our public licenses are
41
+ intended for use by those authorized to give the public
42
+ permission to use material in ways otherwise restricted by
43
+ copyright and certain other rights. Our licenses are
44
+ irrevocable. Licensors should read and understand the terms
45
+ and conditions of the license they choose before applying it.
46
+ Licensors should also secure all rights necessary before
47
+ applying our licenses so that the public can reuse the
48
+ material as expected. Licensors should clearly mark any
49
+ material not subject to the license. This includes other CC-
50
+ licensed material, or material used under an exception or
51
+ limitation to copyright. More considerations for licensors:
52
+ wiki.creativecommons.org/Considerations_for_licensors
53
+
54
+ Considerations for the public: By using one of our public
55
+ licenses, a licensor grants the public permission to use the
56
+ licensed material under specified terms and conditions. If
57
+ the licensor's permission is not necessary for any reason--for
58
+ example, because of any applicable exception or limitation to
59
+ copyright--then that use is not regulated by the license. Our
60
+ licenses grant only permissions under copyright and certain
61
+ other rights that a licensor has authority to grant. Use of
62
+ the licensed material may still be restricted for other
63
+ reasons, including because others have copyright or other
64
+ rights in the material. A licensor may make special requests,
65
+ such as asking that all changes be marked or described.
66
+ Although not required by our licenses, you are encouraged to
67
+ respect those requests where reasonable. More considerations
68
+ for the public:
69
+ wiki.creativecommons.org/Considerations_for_licensees
70
+
71
+ =======================================================================
72
+
73
+ Creative Commons Attribution-NonCommercial 4.0 International Public
74
+ License
75
+
76
+ By exercising the Licensed Rights (defined below), You accept and agree
77
+ to be bound by the terms and conditions of this Creative Commons
78
+ Attribution-NonCommercial 4.0 International Public License ("Public
79
+ License"). To the extent this Public License may be interpreted as a
80
+ contract, You are granted the Licensed Rights in consideration of Your
81
+ acceptance of these terms and conditions, and the Licensor grants You
82
+ such rights in consideration of benefits the Licensor receives from
83
+ making the Licensed Material available under these terms and
84
+ conditions.
85
+
86
+
87
+ Section 1 -- Definitions.
88
+
89
+ a. Adapted Material means material subject to Copyright and Similar
90
+ Rights that is derived from or based upon the Licensed Material
91
+ and in which the Licensed Material is translated, altered,
92
+ arranged, transformed, or otherwise modified in a manner requiring
93
+ permission under the Copyright and Similar Rights held by the
94
+ Licensor. For purposes of this Public License, where the Licensed
95
+ Material is a musical work, performance, or sound recording,
96
+ Adapted Material is always produced where the Licensed Material is
97
+ synched in timed relation with a moving image.
98
+
99
+ b. Adapter's License means the license You apply to Your Copyright
100
+ and Similar Rights in Your contributions to Adapted Material in
101
+ accordance with the terms and conditions of this Public License.
102
+
103
+ c. Copyright and Similar Rights means copyright and/or similar rights
104
+ closely related to copyright including, without limitation,
105
+ performance, broadcast, sound recording, and Sui Generis Database
106
+ Rights, without regard to how the rights are labeled or
107
+ categorized. For purposes of this Public License, the rights
108
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
109
+ Rights.
110
+ d. Effective Technological Measures means those measures that, in the
111
+ absence of proper authority, may not be circumvented under laws
112
+ fulfilling obligations under Article 11 of the WIPO Copyright
113
+ Treaty adopted on December 20, 1996, and/or similar international
114
+ agreements.
115
+
116
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
117
+ any other exception or limitation to Copyright and Similar Rights
118
+ that applies to Your use of the Licensed Material.
119
+
120
+ f. Licensed Material means the artistic or literary work, database,
121
+ or other material to which the Licensor applied this Public
122
+ License.
123
+
124
+ g. Licensed Rights means the rights granted to You subject to the
125
+ terms and conditions of this Public License, which are limited to
126
+ all Copyright and Similar Rights that apply to Your use of the
127
+ Licensed Material and that the Licensor has authority to license.
128
+
129
+ h. Licensor means the individual(s) or entity(ies) granting rights
130
+ under this Public License.
131
+
132
+ i. NonCommercial means not primarily intended for or directed towards
133
+ commercial advantage or monetary compensation. For purposes of
134
+ this Public License, the exchange of the Licensed Material for
135
+ other material subject to Copyright and Similar Rights by digital
136
+ file-sharing or similar means is NonCommercial provided there is
137
+ no payment of monetary compensation in connection with the
138
+ exchange.
139
+
140
+ j. Share means to provide material to the public by any means or
141
+ process that requires permission under the Licensed Rights, such
142
+ as reproduction, public display, public performance, distribution,
143
+ dissemination, communication, or importation, and to make material
144
+ available to the public including in ways that members of the
145
+ public may access the material from a place and at a time
146
+ individually chosen by them.
147
+
148
+ k. Sui Generis Database Rights means rights other than copyright
149
+ resulting from Directive 96/9/EC of the European Parliament and of
150
+ the Council of 11 March 1996 on the legal protection of databases,
151
+ as amended and/or succeeded, as well as other essentially
152
+ equivalent rights anywhere in the world.
153
+
154
+ l. You means the individual or entity exercising the Licensed Rights
155
+ under this Public License. Your has a corresponding meaning.
156
+
157
+
158
+ Section 2 -- Scope.
159
+
160
+ a. License grant.
161
+
162
+ 1. Subject to the terms and conditions of this Public License,
163
+ the Licensor hereby grants You a worldwide, royalty-free,
164
+ non-sublicensable, non-exclusive, irrevocable license to
165
+ exercise the Licensed Rights in the Licensed Material to:
166
+
167
+ a. reproduce and Share the Licensed Material, in whole or
168
+ in part, for NonCommercial purposes only; and
169
+
170
+ b. produce, reproduce, and Share Adapted Material for
171
+ NonCommercial purposes only.
172
+
173
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
174
+ Exceptions and Limitations apply to Your use, this Public
175
+ License does not apply, and You do not need to comply with
176
+ its terms and conditions.
177
+
178
+ 3. Term. The term of this Public License is specified in Section
179
+ 6(a).
180
+
181
+ 4. Media and formats; technical modifications allowed. The
182
+ Licensor authorizes You to exercise the Licensed Rights in
183
+ all media and formats whether now known or hereafter created,
184
+ and to make technical modifications necessary to do so. The
185
+ Licensor waives and/or agrees not to assert any right or
186
+ authority to forbid You from making technical modifications
187
+ necessary to exercise the Licensed Rights, including
188
+ technical modifications necessary to circumvent Effective
189
+ Technological Measures. For purposes of this Public License,
190
+ simply making modifications authorized by this Section 2(a)
191
+ (4) never produces Adapted Material.
192
+
193
+ 5. Downstream recipients.
194
+
195
+ a. Offer from the Licensor -- Licensed Material. Every
196
+ recipient of the Licensed Material automatically
197
+ receives an offer from the Licensor to exercise the
198
+ Licensed Rights under the terms and conditions of this
199
+ Public License.
200
+
201
+ b. No downstream restrictions. You may not offer or impose
202
+ any additional or different terms or conditions on, or
203
+ apply any Effective Technological Measures to, the
204
+ Licensed Material if doing so restricts exercise of the
205
+ Licensed Rights by any recipient of the Licensed
206
+ Material.
207
+
208
+ 6. No endorsement. Nothing in this Public License constitutes or
209
+ may be construed as permission to assert or imply that You
210
+ are, or that Your use of the Licensed Material is, connected
211
+ with, or sponsored, endorsed, or granted official status by,
212
+ the Licensor or others designated to receive attribution as
213
+ provided in Section 3(a)(1)(A)(i).
214
+
215
+ b. Other rights.
216
+
217
+ 1. Moral rights, such as the right of integrity, are not
218
+ licensed under this Public License, nor are publicity,
219
+ privacy, and/or other similar personality rights; however, to
220
+ the extent possible, the Licensor waives and/or agrees not to
221
+ assert any such rights held by the Licensor to the limited
222
+ extent necessary to allow You to exercise the Licensed
223
+ Rights, but not otherwise.
224
+
225
+ 2. Patent and trademark rights are not licensed under this
226
+ Public License.
227
+
228
+ 3. To the extent possible, the Licensor waives any right to
229
+ collect royalties from You for the exercise of the Licensed
230
+ Rights, whether directly or through a collecting society
231
+ under any voluntary or waivable statutory or compulsory
232
+ licensing scheme. In all other cases the Licensor expressly
233
+ reserves any right to collect such royalties, including when
234
+ the Licensed Material is used other than for NonCommercial
235
+ purposes.
236
+
237
+
238
+ Section 3 -- License Conditions.
239
+
240
+ Your exercise of the Licensed Rights is expressly made subject to the
241
+ following conditions.
242
+
243
+ a. Attribution.
244
+
245
+ 1. If You Share the Licensed Material (including in modified
246
+ form), You must:
247
+
248
+ a. retain the following if it is supplied by the Licensor
249
+ with the Licensed Material:
250
+
251
+ i. identification of the creator(s) of the Licensed
252
+ Material and any others designated to receive
253
+ attribution, in any reasonable manner requested by
254
+ the Licensor (including by pseudonym if
255
+ designated);
256
+
257
+ ii. a copyright notice;
258
+
259
+ iii. a notice that refers to this Public License;
260
+
261
+ iv. a notice that refers to the disclaimer of
262
+ warranties;
263
+
264
+ v. a URI or hyperlink to the Licensed Material to the
265
+ extent reasonably practicable;
266
+
267
+ b. indicate if You modified the Licensed Material and
268
+ retain an indication of any previous modifications; and
269
+
270
+ c. indicate the Licensed Material is licensed under this
271
+ Public License, and include the text of, or the URI or
272
+ hyperlink to, this Public License.
273
+
274
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
275
+ reasonable manner based on the medium, means, and context in
276
+ which You Share the Licensed Material. For example, it may be
277
+ reasonable to satisfy the conditions by providing a URI or
278
+ hyperlink to a resource that includes the required
279
+ information.
280
+
281
+ 3. If requested by the Licensor, You must remove any of the
282
+ information required by Section 3(a)(1)(A) to the extent
283
+ reasonably practicable.
284
+
285
+ 4. If You Share Adapted Material You produce, the Adapter's
286
+ License You apply must not prevent recipients of the Adapted
287
+ Material from complying with this Public License.
288
+
289
+
290
+ Section 4 -- Sui Generis Database Rights.
291
+
292
+ Where the Licensed Rights include Sui Generis Database Rights that
293
+ apply to Your use of the Licensed Material:
294
+
295
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
296
+ to extract, reuse, reproduce, and Share all or a substantial
297
+ portion of the contents of the database for NonCommercial purposes
298
+ only;
299
+
300
+ b. if You include all or a substantial portion of the database
301
+ contents in a database in which You have Sui Generis Database
302
+ Rights, then the database in which You have Sui Generis Database
303
+ Rights (but not its individual contents) is Adapted Material; and
304
+
305
+ c. You must comply with the conditions in Section 3(a) if You Share
306
+ all or a substantial portion of the contents of the database.
307
+
308
+ For the avoidance of doubt, this Section 4 supplements and does not
309
+ replace Your obligations under this Public License where the Licensed
310
+ Rights include other Copyright and Similar Rights.
311
+
312
+
313
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
314
+
315
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
316
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
317
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
318
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
319
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
320
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
321
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
322
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
323
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
324
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
325
+
326
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
327
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
328
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
329
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
330
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
331
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
332
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
333
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
334
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
335
+
336
+ c. The disclaimer of warranties and limitation of liability provided
337
+ above shall be interpreted in a manner that, to the extent
338
+ possible, most closely approximates an absolute disclaimer and
339
+ waiver of all liability.
340
+
341
+
342
+ Section 6 -- Term and Termination.
343
+
344
+ a. This Public License applies for the term of the Copyright and
345
+ Similar Rights licensed here. However, if You fail to comply with
346
+ this Public License, then Your rights under this Public License
347
+ terminate automatically.
348
+
349
+ b. Where Your right to use the Licensed Material has terminated under
350
+ Section 6(a), it reinstates:
351
+
352
+ 1. automatically as of the date the violation is cured, provided
353
+ it is cured within 30 days of Your discovery of the
354
+ violation; or
355
+
356
+ 2. upon express reinstatement by the Licensor.
357
+
358
+ For the avoidance of doubt, this Section 6(b) does not affect any
359
+ right the Licensor may have to seek remedies for Your violations
360
+ of this Public License.
361
+
362
+ c. For the avoidance of doubt, the Licensor may also offer the
363
+ Licensed Material under separate terms or conditions or stop
364
+ distributing the Licensed Material at any time; however, doing so
365
+ will not terminate this Public License.
366
+
367
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
368
+ License.
369
+
370
+
371
+ Section 7 -- Other Terms and Conditions.
372
+
373
+ a. The Licensor shall not be bound by any additional or different
374
+ terms or conditions communicated by You unless expressly agreed.
375
+
376
+ b. Any arrangements, understandings, or agreements regarding the
377
+ Licensed Material not stated herein are separate from and
378
+ independent of the terms and conditions of this Public License.
379
+
380
+
381
+ Section 8 -- Interpretation.
382
+
383
+ a. For the avoidance of doubt, this Public License does not, and
384
+ shall not be interpreted to, reduce, limit, restrict, or impose
385
+ conditions on any use of the Licensed Material that could lawfully
386
+ be made without permission under this Public License.
387
+
388
+ b. To the extent possible, if any provision of this Public License is
389
+ deemed unenforceable, it shall be automatically reformed to the
390
+ minimum extent necessary to make it enforceable. If the provision
391
+ cannot be reformed, it shall be severed from this Public License
392
+ without affecting the enforceability of the remaining terms and
393
+ conditions.
394
+
395
+ c. No term or condition of this Public License will be waived and no
396
+ failure to comply consented to unless expressly agreed to by the
397
+ Licensor.
398
+
399
+ d. Nothing in this Public License constitutes or may be interpreted
400
+ as a limitation upon, or waiver of, any privileges and immunities
401
+ that apply to the Licensor or You, including from the legal
402
+ processes of any jurisdiction or authority.
403
+
404
+ =======================================================================
405
+
406
+ Creative Commons is not a party to its public
407
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
408
+ its public licenses to material it publishes and in those instances
409
+ will be considered the “Licensor.” The text of the Creative Commons
410
+ public licenses is dedicated to the public domain under the CC0 Public
411
+ Domain Dedication. Except for the limited purpose of indicating that
412
+ material is shared under a Creative Commons public license or as
413
+ otherwise permitted by the Creative Commons policies published at
414
+ creativecommons.org/policies, Creative Commons does not authorize the
415
+ use of the trademark "Creative Commons" or any other trademark or logo
416
+ of Creative Commons without its prior written consent including,
417
+ without limitation, in connection with any unauthorized modifications
418
+ to any of its public licenses or any other arrangements,
419
+ understandings, or agreements concerning use of licensed material. For
420
+ the avoidance of doubt, this paragraph does not form part of the
421
+ public licenses.
422
+
423
+ Creative Commons may be contacted at creativecommons.org.
424
+
425
+
426
+ ================================================================================
427
+ Part 2. Apache License, Version 2.0 (source code)
428
+ ================================================================================
429
+
430
+
431
+ Apache License
432
+ Version 2.0, January 2004
433
+ http://www.apache.org/licenses/
434
+
435
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
436
+
437
+ 1. Definitions.
438
+
439
+ "License" shall mean the terms and conditions for use, reproduction,
440
+ and distribution as defined by Sections 1 through 9 of this document.
441
+
442
+ "Licensor" shall mean the copyright owner or entity authorized by
443
+ the copyright owner that is granting the License.
444
+
445
+ "Legal Entity" shall mean the union of the acting entity and all
446
+ other entities that control, are controlled by, or are under common
447
+ control with that entity. For the purposes of this definition,
448
+ "control" means (i) the power, direct or indirect, to cause the
449
+ direction or management of such entity, whether by contract or
450
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
451
+ outstanding shares, or (iii) beneficial ownership of such entity.
452
+
453
+ "You" (or "Your") shall mean an individual or Legal Entity
454
+ exercising permissions granted by this License.
455
+
456
+ "Source" form shall mean the preferred form for making modifications,
457
+ including but not limited to software source code, documentation
458
+ source, and configuration files.
459
+
460
+ "Object" form shall mean any form resulting from mechanical
461
+ transformation or translation of a Source form, including but
462
+ not limited to compiled object code, generated documentation,
463
+ and conversions to other media types.
464
+
465
+ "Work" shall mean the work of authorship, whether in Source or
466
+ Object form, made available under the License, as indicated by a
467
+ copyright notice that is included in or attached to the work
468
+ (an example is provided in the Appendix below).
469
+
470
+ "Derivative Works" shall mean any work, whether in Source or Object
471
+ form, that is based on (or derived from) the Work and for which the
472
+ editorial revisions, annotations, elaborations, or other modifications
473
+ represent, as a whole, an original work of authorship. For the purposes
474
+ of this License, Derivative Works shall not include works that remain
475
+ separable from, or merely link (or bind by name) to the interfaces of,
476
+ the Work and Derivative Works thereof.
477
+
478
+ "Contribution" shall mean any work of authorship, including
479
+ the original version of the Work and any modifications or additions
480
+ to that Work or Derivative Works thereof, that is intentionally
481
+ submitted to Licensor for inclusion in the Work by the copyright owner
482
+ or by an individual or Legal Entity authorized to submit on behalf of
483
+ the copyright owner. For the purposes of this definition, "submitted"
484
+ means any form of electronic, verbal, or written communication sent
485
+ to the Licensor or its representatives, including but not limited to
486
+ communication on electronic mailing lists, source code control systems,
487
+ and issue tracking systems that are managed by, or on behalf of, the
488
+ Licensor for the purpose of discussing and improving the Work, but
489
+ excluding communication that is conspicuously marked or otherwise
490
+ designated in writing by the copyright owner as "Not a Contribution."
491
+
492
+ "Contributor" shall mean Licensor and any individual or Legal Entity
493
+ on behalf of whom a Contribution has been received by Licensor and
494
+ subsequently incorporated within the Work.
495
+
496
+ 2. Grant of Copyright License. Subject to the terms and conditions of
497
+ this License, each Contributor hereby grants to You a perpetual,
498
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
499
+ copyright license to reproduce, prepare Derivative Works of,
500
+ publicly display, publicly perform, sublicense, and distribute the
501
+ Work and such Derivative Works in Source or Object form.
502
+
503
+ 3. Grant of Patent License. Subject to the terms and conditions of
504
+ this License, each Contributor hereby grants to You a perpetual,
505
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
506
+ (except as stated in this section) patent license to make, have made,
507
+ use, offer to sell, sell, import, and otherwise transfer the Work,
508
+ where such license applies only to those patent claims licensable
509
+ by such Contributor that are necessarily infringed by their
510
+ Contribution(s) alone or by combination of their Contribution(s)
511
+ with the Work to which such Contribution(s) was submitted. If You
512
+ institute patent litigation against any entity (including a
513
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
514
+ or a Contribution incorporated within the Work constitutes direct
515
+ or contributory patent infringement, then any patent licenses
516
+ granted to You under this License for that Work shall terminate
517
+ as of the date such litigation is filed.
518
+
519
+ 4. Redistribution. You may reproduce and distribute copies of the
520
+ Work or Derivative Works thereof in any medium, with or without
521
+ modifications, and in Source or Object form, provided that You
522
+ meet the following conditions:
523
+
524
+ (a) You must give any other recipients of the Work or
525
+ Derivative Works a copy of this License; and
526
+
527
+ (b) You must cause any modified files to carry prominent notices
528
+ stating that You changed the files; and
529
+
530
+ (c) You must retain, in the Source form of any Derivative Works
531
+ that You distribute, all copyright, patent, trademark, and
532
+ attribution notices from the Source form of the Work,
533
+ excluding those notices that do not pertain to any part of
534
+ the Derivative Works; and
535
+
536
+ (d) If the Work includes a "NOTICE" text file as part of its
537
+ distribution, then any Derivative Works that You distribute must
538
+ include a readable copy of the attribution notices contained
539
+ within such NOTICE file, excluding those notices that do not
540
+ pertain to any part of the Derivative Works, in at least one
541
+ of the following places: within a NOTICE text file distributed
542
+ as part of the Derivative Works; within the Source form or
543
+ documentation, if provided along with the Derivative Works; or,
544
+ within a display generated by the Derivative Works, if and
545
+ wherever such third-party notices normally appear. The contents
546
+ of the NOTICE file are for informational purposes only and
547
+ do not modify the License. You may add Your own attribution
548
+ notices within Derivative Works that You distribute, alongside
549
+ or as an addendum to the NOTICE text from the Work, provided
550
+ that such additional attribution notices cannot be construed
551
+ as modifying the License.
552
+
553
+ You may add Your own copyright statement to Your modifications and
554
+ may provide additional or different license terms and conditions
555
+ for use, reproduction, or distribution of Your modifications, or
556
+ for any such Derivative Works as a whole, provided Your use,
557
+ reproduction, and distribution of the Work otherwise complies with
558
+ the conditions stated in this License.
559
+
560
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
561
+ any Contribution intentionally submitted for inclusion in the Work
562
+ by You to the Licensor shall be under the terms and conditions of
563
+ this License, without any additional terms or conditions.
564
+ Notwithstanding the above, nothing herein shall supersede or modify
565
+ the terms of any separate license agreement you may have executed
566
+ with Licensor regarding such Contributions.
567
+
568
+ 6. Trademarks. This License does not grant permission to use the trade
569
+ names, trademarks, service marks, or product names of the Licensor,
570
+ except as required for reasonable and customary use in describing the
571
+ origin of the Work and reproducing the content of the NOTICE file.
572
+
573
+ 7. Disclaimer of Warranty. Unless required by applicable law or
574
+ agreed to in writing, Licensor provides the Work (and each
575
+ Contributor provides its Contributions) on an "AS IS" BASIS,
576
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
577
+ implied, including, without limitation, any warranties or conditions
578
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
579
+ PARTICULAR PURPOSE. You are solely responsible for determining the
580
+ appropriateness of using or redistributing the Work and assume any
581
+ risks associated with Your exercise of permissions under this License.
582
+
583
+ 8. Limitation of Liability. In no event and under no legal theory,
584
+ whether in tort (including negligence), contract, or otherwise,
585
+ unless required by applicable law (such as deliberate and grossly
586
+ negligent acts) or agreed to in writing, shall any Contributor be
587
+ liable to You for damages, including any direct, indirect, special,
588
+ incidental, or consequential damages of any character arising as a
589
+ result of this License or out of the use or inability to use the
590
+ Work (including but not limited to damages for loss of goodwill,
591
+ work stoppage, computer failure or malfunction, or any and all
592
+ other commercial damages or losses), even if such Contributor
593
+ has been advised of the possibility of such damages.
594
+
595
+ 9. Accepting Warranty or Additional Liability. While redistributing
596
+ the Work or Derivative Works thereof, You may choose to offer,
597
+ and charge a fee for, acceptance of support, warranty, indemnity,
598
+ or other liability obligations and/or rights consistent with this
599
+ License. However, in accepting such obligations, You may act only
600
+ on Your own behalf and on Your sole responsibility, not on behalf
601
+ of any other Contributor, and only if You agree to indemnify,
602
+ defend, and hold each Contributor harmless for any liability
603
+ incurred by, or claims asserted against, such Contributor by reason
604
+ of your accepting any such warranty or additional liability.
605
+
606
+ END OF TERMS AND CONDITIONS
607
+
608
+ APPENDIX: How to apply the Apache License to your work.
609
+
610
+ To apply the Apache License to your work, attach the following
611
+ boilerplate notice, with the fields enclosed by brackets "[]"
612
+ replaced with your own identifying information. (Don't include
613
+ the brackets!) The text should be enclosed in the appropriate
614
+ comment syntax for the file format. We also recommend that a
615
+ file or class name and description of purpose be included on the
616
+ same "printed page" as the copyright notice for easier
617
+ identification within third-party archives.
618
+
619
+ Copyright [yyyy] [name of copyright owner]
620
+
621
+ Licensed under the Apache License, Version 2.0 (the "License");
622
+ you may not use this file except in compliance with the License.
623
+ You may obtain a copy of the License at
624
+
625
+ http://www.apache.org/licenses/LICENSE-2.0
626
+
627
+ Unless required by applicable law or agreed to in writing, software
628
+ distributed under the License is distributed on an "AS IS" BASIS,
629
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
630
+ See the License for the specific language governing permissions and
631
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ EmoTra-TTS reproduction on CosyVoice2-0.5B
2
+ Copyright 2026 TICTAP-11 and b-re-w (Retention Labs)
3
+
4
+ This is a research reproduction of EmoTra-TTS trained by TICTAP-11 and b-re-w. It is not an official
5
+ checkpoint of the EmoTra-TTS authors.
6
+
7
+ Model weights
8
+ -------------
9
+ The model weights in this repository (model.safetensors, stage1/, stage2/, speaker_embedding.safetensors,
10
+ speech_tokenizer.safetensors) are licensed under CC BY-NC 4.0, for non-commercial academic research,
11
+ following the EmoTra-TTS authors' stated intent in the paper's Ethical Statement ("released under an
12
+ open-source license ... restricted to non-commercial academic research").
13
+
14
+ The weights are fine tuned from FunAudioLLM/CosyVoice2-0.5B (Apache License 2.0, Copyright Alibaba Inc.).
15
+ The speech tokenizer weights are read out of speech_tokenizer_v2.onnx of FunAudioLLM/CosyVoice2-0.5B.
16
+ The speaker embedding was computed with the CAM++ speaker encoder (funasr/campplus).
17
+
18
+ Training data: RetentionLabs/emotra-ash-transition-50k, built from yhaha/EmoVoice-DB.
19
+
20
+ Source code
21
+ -----------
22
+ The source code files (*.py) are licensed under the Apache License, Version 2.0, as derived from
23
+ EmoTra-TTS and CosyVoice:
24
+
25
+ - EmoTra-TTS, https://github.com/Liu-Tianchi/EmoTra-TTS (commit 23fe9e4)
26
+ Copyright (C) 2026 LightSpeed (Author: Tianchi Liu). Licensed under Apache-2.0.
27
+ Tianchi Liu, Zeyang Song, Tianrui Wang, Zhipeng Li, Chenglin Xu, Yiwen Guo. EmoTra-TTS: Smooth
28
+ Intra-Utterance Emotion Transitions for Speech Synthesis. EMNLP 2026.
29
+ - CosyVoice, https://github.com/FunAudioLLM/CosyVoice
30
+ Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du). Licensed under Apache-2.0.
31
+ - The CosyVoice2 classes are copied from their transformers port in voicestudio
32
+ (https://pypi.org/project/voicestudio/, version 5.18.1), Apache-2.0.
33
+ - The EmoTra-TTS port and its training code: Copyright 2026 TICTAP-11 and b-re-w, Apache-2.0.
34
+
35
+ The upstream EmoTra-TTS README states: "Patent Notice. The core method of EmoTra-TTS has been submitted
36
+ for patent protection. Please see the License section for details."
37
+
38
+ BigVGAN
39
+ -------
40
+ The functions dynamic_range_compression and mel_spectrogram in modeling_emotra_tts.py are taken from
41
+ BigVGAN (https://github.com/NVIDIA/BigVGAN) under the MIT License:
42
+
43
+ MIT License
44
+
45
+ Copyright (c) 2024 NVIDIA CORPORATION.
46
+
47
+ Permission is hereby granted, free of charge, to any person obtaining a copy
48
+ of this software and associated documentation files (the "Software"), to deal
49
+ in the Software without restriction, including without limitation the rights
50
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
51
+ copies of the Software, and to permit persons to whom the Software is
52
+ furnished to do so, subject to the following conditions:
53
+
54
+ The above copyright notice and this permission notice shall be included in all
55
+ copies or substantial portions of the Software.
56
+
57
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
58
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
59
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
60
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
61
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
62
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
63
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ language:
4
+ - en
5
+ library_name: transformers
6
+ pipeline_tag: text-to-speech
7
+ base_model: FunAudioLLM/CosyVoice2-0.5B
8
+ datasets:
9
+ - RetentionLabs/emotra-ash-transition-50k
10
+ - yhaha/EmoVoice-DB
11
+ tags:
12
+ - emotional-tts
13
+ - emotion-transition
14
+ - cosyvoice2
15
+ - emotra-tts
16
+ ---
17
+
18
+ # EmoTra-TTS
19
+
20
+ This is a research reproduction of EmoTra-TTS, trained by us for research comparison. It is not an official checkpoint of the EmoTra-TTS authors.
21
+
22
+ EmoTra-TTS (Liu et al., EMNLP 2026) fine tunes CosyVoice2 so that the emotion inside one utterance moves from a start VAD (arousal, valence, dominance) to an end VAD. This repository holds our reproduction on `FunAudioLLM/CosyVoice2-0.5B`, trained with the upstream recipe on one English speaker (`ash` of EmoVoice-DB), in the `transformers` format with self-contained remote code.
23
+
24
+ - Paper: Tianchi Liu, Zeyang Song, Tianrui Wang, Zhipeng Li, Chenglin Xu, Yiwen Guo. *EmoTra-TTS: Smooth Intra-Utterance Emotion Transitions for Speech Synthesis.* EMNLP 2026. [arXiv:2608.23791](https://arxiv.org/abs/2608.23791)
25
+ - Original code: [github.com/Liu-Tianchi/EmoTra-TTS](https://github.com/Liu-Tianchi/EmoTra-TTS), traced at commit `23fe9e4`
26
+ - Base model: [FunAudioLLM/CosyVoice2-0.5B](https://huggingface.co/FunAudioLLM/CosyVoice2-0.5B)
27
+
28
+ ## Model summary
29
+
30
+ | | |
31
+ |---|---|
32
+ | Input | English text, a start VAD and an end VAD, each `[arousal, valence, dominance]` in $[0, 1]$ |
33
+ | Output | 24 kHz waveform |
34
+ | Speaker | One fixed speaker (`ash` of EmoVoice-DB); the model is not zero shot |
35
+ | Networks | Qwen2 speech token language model (0.5B), chunk aware flow matching model, HiFT vocoder |
36
+ | Precision | BF16 parameters, see [Precision](#precision) |
37
+ | Training data | [RetentionLabs/emotra-ash-transition-50k](https://huggingface.co/datasets/RetentionLabs/emotra-ash-transition-50k) |
38
+
39
+ ## Architecture
40
+
41
+ EmoTra-TTS changes two of the three CosyVoice2 networks and keeps the vocoder.
42
+
43
+ - **Language model (Stage I).** The start and end VAD are interpolated into 5 points, token $k$ carrying $(1-\alpha_k)\mathbf v_{start}+\alpha_k\mathbf v_{end}$ with $\alpha_k=k/4$. Each point is projected to one input embedding (`llm.vad_projection`), and the 5 VAD tokens sit between the start of sequence embedding and the text: `[sos, VAD_0 ... VAD_4, text, task_id, speech]`. An auxiliary perceptron (`llm.hidden_reconstructor`) maps the first and the last VAD token to the pooled hidden states of the audEERING w2v2 VAD regressor on the two reference utterances. The loss is $\mathcal L_{CE}+0.1\,\mathcal L_{hidden}$.
44
+ - **Flow matching model (Stage II).** A per frame emotion embedding is added to the speaker input of the estimator: $\hat e(t)=e+\epsilon\,\mathrm{LN}(\psi_{down}(\phi_{recon}(\phi_{proj}(\mathbf v(t)))))$ with $\epsilon=0.07$. $\phi_{proj}$ and $\phi_{recon}$ are copies of the two Stage I modules, $\psi_{down}$ is `flow.vad_downsample` and LN is `flow.emo_layer_norm`. $\mathbf v(t)$ holds the start VAD for the first 40 % of the mel frames, moves linearly to the end VAD until 70 %, and holds the end VAD after it. Generation runs without a prompt and with zero mel conditioning.
45
+
46
+ ## Usage
47
+
48
+ ```python
49
+ import soundfile as sf
50
+ import torch
51
+ from transformers import AutoModel, AutoProcessor
52
+
53
+ model = AutoModel.from_pretrained("RetentionLabs/EmoTra-TTS", trust_remote_code=True).to("cuda").eval()
54
+ processor = AutoProcessor.from_pretrained("RetentionLabs/EmoTra-TTS", trust_remote_code=True)
55
+
56
+ inputs = processor(text="The weather was so bad that day, and then I suddenly saw something that made me angry.")
57
+ # [arousal, valence, dominance] in [0, 1], the order of the training data
58
+ vad_start = torch.tensor([[0.27, 0.25, 0.31]], dtype=torch.bfloat16, device="cuda")
59
+ vad_end = torch.tensor([[0.85, 0.20, 0.86]], dtype=torch.bfloat16, device="cuda")
60
+
61
+ torch.manual_seed(0)
62
+ with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
63
+ waveform = model.generate(
64
+ input_ids=inputs["input_ids"].to("cuda"),
65
+ speaker_embedding=inputs["speaker_embedding"].to("cuda", torch.bfloat16),
66
+ vad_start=vad_start,
67
+ vad_end=vad_end,
68
+ )
69
+ sf.write("output.wav", waveform[0].float().cpu().numpy(), model.config.sample_rate)
70
+ ```
71
+
72
+ The remote code needs `transformers` (tested with 5.19.0), `torch`, `torchaudio`, `numpy` and `safetensors`. Loading downloads nothing besides this repository. `generate` samples speech tokens with repetition aware sampling (top p 0.8, top k 25), so the output depends on the seed. Run it under BF16 autocast as above: the flow matching model returns an FP32 mel spectrogram and the BF16 vocoder takes it through autocast, which is how our evaluation generated audio.
73
+
74
+ The processor tokenizes the text as it is (no text normalization; write numbers as words) and returns `speaker_embedding`, the fixed CAM++ embedding of one neutral recording of the speaker (`gpt4o_6212_neutral_ash.wav` of EmoVoice-DB) that the flow matching model was trained with. The VAD order is the training data's `[arousal, valence, dominance]`, not the $(V, A, D)$ of the paper's notation.
75
+
76
+ ## Files
77
+
78
+ | File | Content |
79
+ |---|---|
80
+ | `model.safetensors` | Merged weights: CosyVoice2-0.5B, the Stage I language model, the flow VAD modules copied from it, and the Stage II flow emotion modules, as the training code assembles them for generation |
81
+ | `config.json` | `EmoTraTTSConfig` |
82
+ | `configuration_emotra_tts.py`, `modeling_emotra_tts.py`, `generation_emotra_tts.py` | Model code. The CosyVoice2 classes are copied in; only `transformers` and `torch` are imported |
83
+ | `processing_emotra_tts.py`, `feature_extraction_emotra_tts.py` | Processor: text tokenizer, fixed speaker embedding, and for training inputs the CosyVoice2 speech tokenizer and the 24 kHz mel extractor |
84
+ | `tokenizer.json`, `tokenizer_config.json`, `chat_template.jinja` | The CosyVoice2 text tokenizer (Qwen2 of `CosyVoice-BlankEN` with the CosyVoice2 special tokens) |
85
+ | `speaker_embedding.safetensors` | The fixed speaker embedding (192) |
86
+ | `speech_tokenizer.safetensors` | The CosyVoice2 speech tokenizer, read out of `speech_tokenizer_v2.onnx` of CosyVoice2-0.5B |
87
+ | `processor_config.json` | Processor and mel extractor settings |
88
+ | `train.py` | Training code of both stages (see [Training](#training)) |
89
+ | `stage1/` | Stage I checkpoint at step 2,048: `trainable.safetensors` (every `llm.*` parameter, BF16), `config.json`, `trainer_state.json` |
90
+ | `stage2/` | Stage II checkpoint at step 1,316: `trainable.safetensors` (`flow.vad_downsample` and `flow.emo_layer_norm`, BF16), `config.json`, `trainer_state.json` |
91
+
92
+ `stage1/` and `stage2/` are the raw training checkpoints. `train.load_for_generation` rebuilds the merged weights from them and the CosyVoice2-0.5B backbone.
93
+
94
+ ## Training
95
+
96
+ Both stages follow the upstream recipes (`conf/cosyvoice2_EmoTra_sft_LLM.yaml`, `conf/cosyvoice2_EmoTra_sft_Flow_Lynorm_fixs.yaml`). Stage I trains the whole language model, as the upstream code does; the paper text says only the VAD modules, the code trains all of `llm`. Both stages keep the model in BF16 with BF16 autocast and step FP32 master copies of the trainable parameters with Adam. Hardware: 2 NVIDIA RTX PRO 6000 Blackwell GPUs, data parallel.
97
+
98
+ | | Stage I | Stage II |
99
+ |---|---|---|
100
+ | Trainable | Whole language model (`llm.*`) | `flow.vad_downsample`, `flow.emo_layer_norm` (283,120 parameters) |
101
+ | Starting point | CosyVoice2-0.5B, EmoTra-TTS modules newly initialized | Frozen CosyVoice2-0.5B flow model, VAD modules copied from Stage I step 2,048 |
102
+ | Training records | 45,000 | 39,451 (records whose Stage I decode kept at least 100 tokens) |
103
+ | Held-out records | 5,000 | 4,411 |
104
+ | Optimizer | Adam, lr $10^{-5}$, constant, no weight decay | Adam, lr $5\times10^{-5}$, constant, eps $10^{-8}$, L2 weight decay $10^{-6}$ |
105
+ | Gradient clipping | 5 | 1 |
106
+ | Batch per update | 176 (44 per GPU, 2 GPUs, accumulation 2) | 120 (30 per GPU, 2 GPUs, accumulation 2) |
107
+ | Steps | 2,048 (8 epochs) | 1,316 (4 epochs) |
108
+ | Held-out loss at the last step | 2.7353 ($\mathcal L_{CE}+0.1\,\mathcal L_{hidden}$) | 0.8509 (conditional flow matching loss) |
109
+
110
+ Stage II inputs are the speech tokens the Stage I model decodes for each record (0.5 to 1.5 times the ground truth length, cut or padded to it, records under 100 tokens dropped), as upstream's `precompute_llm_tokens_sft_LLM.py` does. Half of the Stage II batches run in streaming mode. The held-out losses are on the held-out split of the transition data, which the runs did not train on.
111
+
112
+ `train.py` holds this training code without the data preparation. Its docstring gives the record format it reads. It loads the CosyVoice2-0.5B backbone from the upstream files and imports the model files of this repository.
113
+
114
+ ## Training data
115
+
116
+ The training data is [RetentionLabs/emotra-ash-transition-50k](https://huggingface.co/datasets/RetentionLabs/emotra-ash-transition-50k): 50,000 synthetic intra-utterance emotion transitions of the speaker `ash`, split into 45,000 training and 5,000 held-out records, built with the upstream data scripts (`step0` to `step2`). Its source recordings are from [yhaha/EmoVoice-DB](https://huggingface.co/datasets/yhaha/EmoVoice-DB), an emotional speech corpus generated with GPT-4o. Each transition record pairs two EmoVoice-DB recordings of the speaker (A and B) and holds CosyVoice2 speech of the text of A whose emotion moves from that of A to that of B. The license status of model weights trained on GPT-4o generated speech may be ambiguous.
117
+
118
+ ## Precision
119
+
120
+ All model parameters and floating point buffers are BF16 (`config.dtype`). A BF16 load also casts the non-persistent rotary `inv_freq` buffers of the Qwen2 decoder to BF16, as the training and evaluation code did with `model.to(torch.bfloat16)`. The exceptions are operations BF16 cannot compute or represent:
121
+
122
+ | Part | dtype | Reason |
123
+ |---|---|---|
124
+ | HiFT STFT and ISTFT | FP32 | The vocoder's spectral transforms run on FP32 inputs and return the input dtype |
125
+ | Speech tokenizer finite scalar quantizer (`quantizer.project_in`) | FP32 | Token ids reach $3^8-1=6560$; BF16 represents integers exactly only up to 256 |
126
+ | Vocoder input | BF16 autocast | The flow matching model returns an FP32 mel spectrogram |
127
+
128
+ The processor's speech tokenizer is BF16 except the quantizer. The speech tokens of the training data were extracted with the speech tokenizer in FP32; on one held-out recording the BF16 tokenizer reproduces 114 of 116 of those tokens and the FP32 tokenizer all 116.
129
+
130
+ ## Verification
131
+
132
+ The released folder, loaded in a fresh process with `trust_remote_code=True` and without the training code installed, was compared with the model the training code assembles from `stage1/`, `stage2/` and CosyVoice2-0.5B (BF16, one NVIDIA B300, one held-out record of the transition data):
133
+
134
+ | Check | Result |
135
+ |---|---|
136
+ | State dict | 1,773 tensors, bitwise equal |
137
+ | Stage I teacher forced logits (139 positions, 6,564 classes) | max abs diff 0 |
138
+ | Flow matching mel spectrogram (fixed noise, 232 frames) | max abs diff 0 |
139
+ | `generate` with seed 0, waveform (120,960 samples) | max abs diff 0 |
140
+ | Processor text ids and speaker embedding | equal |
141
+
142
+ ## Checkpoints of the authors
143
+
144
+ No official EmoTra-TTS checkpoint is public. Searched on 2026-10-12: the Hugging Face Hub (models, datasets, Spaces for `emotra`, `emotra-tts` and the author), the upstream repository (no releases, tags or download links), Zenodo and the demo page. In upstream issue [#1](https://github.com/Liu-Tianchi/EmoTra-TTS/issues/1) the first author wrote on 2026-09-08 that the checkpoints of the paper and demo cannot be released.
145
+
146
+ ## Patent notice
147
+
148
+ The upstream README states:
149
+
150
+ > **Patent Notice.** The core method of EmoTra-TTS has been submitted for patent protection. Please see the License section for details.
151
+
152
+ ## License
153
+
154
+ The model weights are released under CC BY-NC 4.0 (`LICENSE`), for non-commercial academic research, following the authors' stated intent in the paper's Ethical Statement. The code files are Apache-2.0, as derived from EmoTra-TTS and CosyVoice; `dynamic_range_compression` and `mel_spectrogram` in `modeling_emotra_tts.py` are from BigVGAN (MIT). See `NOTICE`.
155
+
156
+ ## Citation
157
+
158
+ ```bibtex
159
+ @inproceedings{liu2026emotra,
160
+ title={EmoTra-TTS: Smooth Intra-Utterance Emotion Transitions for Speech Synthesis},
161
+ author={Liu, Tianchi and Song, Zeyang and Wang, Tianrui and Li, Zhipeng and Xu, Chenglin and Guo, Yiwen},
162
+ booktitle={Proceedings of the 2026 Conference on Empirical Methods in Natural Language Processing},
163
+ year={2026}
164
+ }
165
+ ```
166
+
167
+ Reproduction by TICTAP-11 and b-re-w (Retention Labs).
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,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "EmoTraTTSForConditionalGeneration"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_emotra_tts.EmoTraTTSConfig",
7
+ "AutoModel": "modeling_emotra_tts.EmoTraTTSForConditionalGeneration"
8
+ },
9
+ "dtype": "bfloat16",
10
+ "emotion_scale": 0.07,
11
+ "emotion_transition_end": 0.7,
12
+ "emotion_transition_start": 0.4,
13
+ "estimator_channels": [
14
+ 256
15
+ ],
16
+ "estimator_dropout": 0.0,
17
+ "estimator_ffn_mult": 4,
18
+ "estimator_group_norm_groups": 8,
19
+ "estimator_head_dim": 64,
20
+ "estimator_in_channels": 320,
21
+ "estimator_num_blocks": 4,
22
+ "estimator_num_decoding_left_chunks": -1,
23
+ "estimator_num_heads": 8,
24
+ "estimator_num_mid_blocks": 12,
25
+ "estimator_out_channels": 80,
26
+ "estimator_static_chunk_size": 50,
27
+ "f0_predictor_hidden_size": 512,
28
+ "flow_encoder_attention_dropout": 0.1,
29
+ "flow_encoder_chunk_size": 25,
30
+ "flow_encoder_dropout": 0.1,
31
+ "flow_encoder_ffn_dim": 2048,
32
+ "flow_encoder_hidden_act": "silu",
33
+ "flow_encoder_hidden_size": 512,
34
+ "flow_encoder_num_heads": 8,
35
+ "flow_encoder_num_layers": 6,
36
+ "flow_encoder_positional_dropout": 0.1,
37
+ "flow_encoder_up_num_layers": 4,
38
+ "flow_input_frame_rate": 25,
39
+ "flow_input_size": 512,
40
+ "flow_output_size": 80,
41
+ "hidden_loss_weight": 0.1,
42
+ "inference_cfg_rate": 0.7,
43
+ "initializer_range": 0.02,
44
+ "label_smoothing": 0.0,
45
+ "length_normalized_loss": true,
46
+ "length_regulator_sampling_ratios": [
47
+ 1,
48
+ 1,
49
+ 1,
50
+ 1
51
+ ],
52
+ "lm_attention_dropout": 0.0,
53
+ "lm_chunk_size": 1,
54
+ "lm_dropout": 0.1,
55
+ "lm_ffn_dim": 4096,
56
+ "lm_hidden_act": "relu",
57
+ "lm_hidden_size": 896,
58
+ "lm_input_projection_activation": true,
59
+ "lm_num_heads": 16,
60
+ "lm_num_layers": 14,
61
+ "lm_positional_dropout": 0.1,
62
+ "max_source_positions": 5000,
63
+ "mix_ratio": [
64
+ 5,
65
+ 15
66
+ ],
67
+ "model_type": "emotra_tts",
68
+ "noise_length": 15000,
69
+ "noise_seed": 0,
70
+ "num_flow_inference_steps": 10,
71
+ "num_speech_special_tokens": 3,
72
+ "num_vad_tokens": 5,
73
+ "pre_lookahead_channels": 512,
74
+ "pre_lookahead_len": 3,
75
+ "sample_rate": 24000,
76
+ "sigma_min": 1e-06,
77
+ "speaker_embedding_dim": 192,
78
+ "speech_tokenizer_conv_stride": 2,
79
+ "speech_tokenizer_ffn_dim": 5120,
80
+ "speech_tokenizer_fsmn_kernel_size": 31,
81
+ "speech_tokenizer_fsq_levels": [
82
+ 3,
83
+ 3,
84
+ 3,
85
+ 3,
86
+ 3,
87
+ 3,
88
+ 3,
89
+ 3
90
+ ],
91
+ "speech_tokenizer_hidden_size": 1280,
92
+ "speech_tokenizer_max_position_embeddings": 2048,
93
+ "speech_tokenizer_max_source_positions": null,
94
+ "speech_tokenizer_num_heads": 20,
95
+ "speech_tokenizer_num_layers": 6,
96
+ "speech_tokenizer_num_mel_bins": 128,
97
+ "speech_tokenizer_rope_theta": 10000.0,
98
+ "speech_vocab_size": 6561,
99
+ "t_scheduler": "cosine",
100
+ "text_config": {
101
+ "architectures": [
102
+ "Qwen2ForCausalLM"
103
+ ],
104
+ "attention_dropout": 0.0,
105
+ "bos_token_id": 151643,
106
+ "dtype": "bfloat16",
107
+ "eos_token_id": 151645,
108
+ "hidden_act": "silu",
109
+ "hidden_size": 896,
110
+ "initializer_range": 0.02,
111
+ "intermediate_size": 4864,
112
+ "layer_types": [
113
+ "full_attention",
114
+ "full_attention",
115
+ "full_attention",
116
+ "full_attention",
117
+ "full_attention",
118
+ "full_attention",
119
+ "full_attention",
120
+ "full_attention",
121
+ "full_attention",
122
+ "full_attention",
123
+ "full_attention",
124
+ "full_attention",
125
+ "full_attention",
126
+ "full_attention",
127
+ "full_attention",
128
+ "full_attention",
129
+ "full_attention",
130
+ "full_attention",
131
+ "full_attention",
132
+ "full_attention",
133
+ "full_attention",
134
+ "full_attention",
135
+ "full_attention",
136
+ "full_attention"
137
+ ],
138
+ "max_position_embeddings": 32768,
139
+ "max_window_layers": 24,
140
+ "model_type": "qwen2",
141
+ "num_attention_heads": 14,
142
+ "num_hidden_layers": 24,
143
+ "num_key_value_heads": 2,
144
+ "pad_token_id": null,
145
+ "rms_norm_eps": 1e-06,
146
+ "rope_parameters": {
147
+ "rope_theta": 1000000.0,
148
+ "rope_type": "default"
149
+ },
150
+ "sliding_window": null,
151
+ "tie_word_embeddings": true,
152
+ "use_cache": true,
153
+ "use_sliding_window": false,
154
+ "vocab_size": 151936
155
+ },
156
+ "text_encoder_attention_dropout": 0.0,
157
+ "text_encoder_chunk_size": 1,
158
+ "text_encoder_dropout": 0.1,
159
+ "text_encoder_ffn_dim": 4096,
160
+ "text_encoder_hidden_act": "silu",
161
+ "text_encoder_hidden_size": 1024,
162
+ "text_encoder_input_size": 512,
163
+ "text_encoder_num_heads": 16,
164
+ "text_encoder_num_layers": 6,
165
+ "text_encoder_positional_dropout": 0.1,
166
+ "text_vocab_size": 51866,
167
+ "token_mel_ratio": 2,
168
+ "training_cfg_rate": 0.2,
169
+ "transformers_version": "5.19.0",
170
+ "vad_downsample_hidden_size": 256,
171
+ "vad_dropout": 0.1,
172
+ "vad_hidden_state_size": 1024,
173
+ "vad_projection_hidden_size": 256,
174
+ "vad_reconstructor_hidden_size": 512,
175
+ "vocoder_audio_limit": 0.99,
176
+ "vocoder_base_channels": 512,
177
+ "vocoder_in_channels": 80,
178
+ "vocoder_istft_hop_length": 4,
179
+ "vocoder_istft_n_fft": 16,
180
+ "vocoder_leaky_relu_slope": 0.1,
181
+ "vocoder_mel_loss_coeff": 45.0,
182
+ "vocoder_mel_loss_fmax": null,
183
+ "vocoder_mel_loss_fmin": 0.0,
184
+ "vocoder_mel_loss_hop_length": 480,
185
+ "vocoder_mel_loss_n_fft": 1920,
186
+ "vocoder_mel_loss_num_mel_bins": 80,
187
+ "vocoder_mel_loss_win_length": 1920,
188
+ "vocoder_num_harmonics": 8,
189
+ "vocoder_resblock_dilation_sizes": [
190
+ [
191
+ 1,
192
+ 3,
193
+ 5
194
+ ],
195
+ [
196
+ 1,
197
+ 3,
198
+ 5
199
+ ],
200
+ [
201
+ 1,
202
+ 3,
203
+ 5
204
+ ]
205
+ ],
206
+ "vocoder_resblock_kernel_sizes": [
207
+ 3,
208
+ 7,
209
+ 11
210
+ ],
211
+ "vocoder_source_amplitude": 0.1,
212
+ "vocoder_source_noise_std": 0.003,
213
+ "vocoder_source_resblock_dilation_sizes": [
214
+ [
215
+ 1,
216
+ 3,
217
+ 5
218
+ ],
219
+ [
220
+ 1,
221
+ 3,
222
+ 5
223
+ ],
224
+ [
225
+ 1,
226
+ 3,
227
+ 5
228
+ ]
229
+ ],
230
+ "vocoder_source_resblock_kernel_sizes": [
231
+ 7,
232
+ 7,
233
+ 11
234
+ ],
235
+ "vocoder_upsample_kernel_sizes": [
236
+ 16,
237
+ 11,
238
+ 7
239
+ ],
240
+ "vocoder_upsample_rates": [
241
+ 8,
242
+ 5,
243
+ 3
244
+ ],
245
+ "vocoder_voiced_threshold": 10
246
+ }
configuration_emotra_tts.py ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The EmoTra-TTS Authors (LightSpeed, Tianchi Liu), Alibaba Inc. (CosyVoice, authors: Xiang Lyu,
2
+ # Zhihao Du), the HuggingFace Inc. team, TICTAP-11 and b-re-w. 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
+ """Configuration classes for EmoTra-TTS on CosyVoice2."""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
19
+
20
+
21
+ __all__ = [
22
+ "CosyVoiceV1Config",
23
+ "CosyVoiceV2Config",
24
+ "EmoTraTTSConfig",
25
+ ]
26
+
27
+
28
+ class CosyVoiceV1Config(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a
31
+ [`CosyVoiceV1ForConditionalGeneration`]. It is used to instantiate the three networks that make up
32
+ CosyVoice v1: an autoregressive text-to-speech-token language model, a conditional flow matching
33
+ model that turns speech tokens into a mel spectrogram, and a HiFTNet vocoder that turns the mel
34
+ spectrogram into a waveform.
35
+
36
+ Instantiating a configuration with the defaults yields the geometry of the released
37
+ `FunAudioLLM/CosyVoice-300M` checkpoint.
38
+
39
+ Args:
40
+ sample_rate (`int`, *optional*, defaults to 22050):
41
+ Sampling rate of the waveform produced by the vocoder.
42
+ text_vocab_size (`int`, *optional*, defaults to 51866):
43
+ Size of the text token vocabulary, matching the multilingual Whisper tokenizer.
44
+ speech_vocab_size (`int`, *optional*, defaults to 4096):
45
+ Number of supervised semantic speech tokens. The language model head predicts
46
+ `speech_vocab_size + 1` classes, the extra class being the end of speech token.
47
+ speaker_embedding_dim (`int`, *optional*, defaults to 192):
48
+ Dimension of the utterance level speaker embedding fed to both the language model and the
49
+ flow matching model.
50
+ text_encoder_input_size (`int`, *optional*, defaults to 512):
51
+ Dimension of the text embedding table, which is the input of the text encoder.
52
+ text_encoder_hidden_size (`int`, *optional*, defaults to 1024):
53
+ Hidden size of the text encoder.
54
+ text_encoder_num_heads (`int`, *optional*, defaults to 16):
55
+ Number of attention heads in the text encoder.
56
+ text_encoder_ffn_dim (`int`, *optional*, defaults to 4096):
57
+ Inner dimension of the text encoder feed forward layers.
58
+ text_encoder_num_layers (`int`, *optional*, defaults to 6):
59
+ Number of text encoder layers.
60
+ text_encoder_hidden_act (`str`, *optional*, defaults to `"silu"`):
61
+ Activation of the text encoder feed forward layers.
62
+ text_encoder_dropout (`float`, *optional*, defaults to 0.1):
63
+ Dropout applied after the input projection and after each text encoder sublayer.
64
+ text_encoder_positional_dropout (`float`, *optional*, defaults to 0.1):
65
+ Dropout applied to the scaled inputs and to the relative positional embeddings.
66
+ text_encoder_attention_dropout (`float`, *optional*, defaults to 0.0):
67
+ Dropout applied to the text encoder attention probabilities.
68
+ text_encoder_chunk_size (`int`, *optional*, defaults to 1):
69
+ Static chunk size of the text encoder attention mask. A value of 1 makes the text encoder
70
+ fully causal, 0 makes it bidirectional.
71
+ lm_hidden_size (`int`, *optional*, defaults to 1024):
72
+ Hidden size of the autoregressive language model.
73
+ lm_num_heads (`int`, *optional*, defaults to 16):
74
+ Number of attention heads in the language model.
75
+ lm_ffn_dim (`int`, *optional*, defaults to 4096):
76
+ Inner dimension of the language model feed forward layers.
77
+ lm_num_layers (`int`, *optional*, defaults to 14):
78
+ Number of language model layers.
79
+ lm_hidden_act (`str`, *optional*, defaults to `"relu"`):
80
+ Activation of the language model feed forward layers.
81
+ lm_dropout (`float`, *optional*, defaults to 0.1):
82
+ Dropout applied after the input projection and after each language model sublayer.
83
+ lm_positional_dropout (`float`, *optional*, defaults to 0.1):
84
+ Dropout applied to the scaled inputs and to the relative positional embeddings.
85
+ lm_attention_dropout (`float`, *optional*, defaults to 0.0):
86
+ Dropout applied to the language model attention probabilities.
87
+ lm_chunk_size (`int`, *optional*, defaults to 1):
88
+ Static chunk size of the language model attention mask. A value of 1 makes it causal.
89
+ lm_input_projection_activation (`bool`, *optional*, defaults to `True`):
90
+ Whether the language model input projection ends with a ReLU, as the legacy linear input
91
+ layer of the original implementation does.
92
+ max_source_positions (`int`, *optional*, defaults to 5000):
93
+ Length used to precompute the relative positional embedding table.
94
+ label_smoothing (`float`, *optional*, defaults to 0.0):
95
+ Label smoothing of the speech token cross entropy loss.
96
+ length_normalized_loss (`bool`, *optional*, defaults to `True`):
97
+ Whether the speech token loss is divided by the number of unmasked targets instead of the
98
+ batch size.
99
+ flow_input_size (`int`, *optional*, defaults to 512):
100
+ Dimension of the speech token embedding table of the flow matching model.
101
+ flow_output_size (`int`, *optional*, defaults to 80):
102
+ Number of mel bins produced by the flow matching model.
103
+ flow_encoder_hidden_size (`int`, *optional*, defaults to 512):
104
+ Hidden size of the flow matching encoder.
105
+ flow_encoder_num_heads (`int`, *optional*, defaults to 8):
106
+ Number of attention heads in the flow matching encoder.
107
+ flow_encoder_ffn_dim (`int`, *optional*, defaults to 2048):
108
+ Inner dimension of the flow matching encoder feed forward layers.
109
+ flow_encoder_num_layers (`int`, *optional*, defaults to 6):
110
+ Number of flow matching encoder layers.
111
+ flow_encoder_hidden_act (`str`, *optional*, defaults to `"silu"`):
112
+ Activation of the flow matching encoder feed forward layers.
113
+ flow_encoder_dropout (`float`, *optional*, defaults to 0.1):
114
+ Dropout applied after the input projection and after each flow encoder sublayer.
115
+ flow_encoder_positional_dropout (`float`, *optional*, defaults to 0.1):
116
+ Dropout applied to the scaled inputs and to the relative positional embeddings.
117
+ flow_encoder_attention_dropout (`float`, *optional*, defaults to 0.1):
118
+ Dropout applied to the flow matching encoder attention probabilities.
119
+ flow_encoder_chunk_size (`int`, *optional*, defaults to 0):
120
+ Static chunk size of the flow matching encoder attention mask. 0 makes it bidirectional.
121
+ flow_input_frame_rate (`int`, *optional*, defaults to 50):
122
+ Number of speech tokens per second.
123
+ length_regulator_sampling_ratios (`list[int]`, *optional*, defaults to `[1, 1, 1, 1]`):
124
+ One convolution, group norm and Mish block is created per entry.
125
+ estimator_in_channels (`int`, *optional*, defaults to 320):
126
+ Number of channels entering the flow matching estimator, that is the noisy mel, the encoder
127
+ output, the speaker embedding and the conditioning mel stacked on the channel axis.
128
+ estimator_out_channels (`int`, *optional*, defaults to 80):
129
+ Number of mel bins predicted by the flow matching estimator.
130
+ estimator_channels (`list[int]`, *optional*, defaults to `[256, 256]`):
131
+ Channels of the estimator down blocks, mirrored for the up blocks.
132
+ estimator_num_blocks (`int`, *optional*, defaults to 4):
133
+ Number of transformer blocks inside every down, mid and up block.
134
+ estimator_num_mid_blocks (`int`, *optional*, defaults to 12):
135
+ Number of estimator mid blocks.
136
+ estimator_num_heads (`int`, *optional*, defaults to 8):
137
+ Number of attention heads in the estimator transformer blocks.
138
+ estimator_head_dim (`int`, *optional*, defaults to 64):
139
+ Dimension of every estimator attention head.
140
+ estimator_dropout (`float`, *optional*, defaults to 0.0):
141
+ Dropout of the estimator transformer blocks.
142
+ estimator_ffn_mult (`int`, *optional*, defaults to 4):
143
+ Feed forward expansion factor of the estimator transformer blocks.
144
+ estimator_group_norm_groups (`int`, *optional*, defaults to 8):
145
+ Number of groups of the estimator convolutional blocks group norm.
146
+ sigma_min (`float`, *optional*, defaults to 1e-06):
147
+ Minimum noise level of the optimal transport conditional flow matching path.
148
+ t_scheduler (`str`, *optional*, defaults to `"cosine"`):
149
+ Timestep schedule of the Euler solver, either `"cosine"` or linear.
150
+ training_cfg_rate (`float`, *optional*, defaults to 0.2):
151
+ Probability of dropping the conditioning while computing the flow matching loss.
152
+ inference_cfg_rate (`float`, *optional*, defaults to 0.7):
153
+ Classifier free guidance scale used by the Euler solver.
154
+ num_flow_inference_steps (`int`, *optional*, defaults to 10):
155
+ Number of Euler steps taken when decoding speech tokens into a mel spectrogram.
156
+ vocoder_in_channels (`int`, *optional*, defaults to 80):
157
+ Number of mel bins entering the vocoder.
158
+ vocoder_base_channels (`int`, *optional*, defaults to 512):
159
+ Channels of the first vocoder convolution.
160
+ vocoder_num_harmonics (`int`, *optional*, defaults to 8):
161
+ Number of harmonics above f0 generated by the neural source filter.
162
+ vocoder_source_amplitude (`float`, *optional*, defaults to 0.1):
163
+ Amplitude of the sine excitation.
164
+ vocoder_source_noise_std (`float`, *optional*, defaults to 0.003):
165
+ Standard deviation of the noise added to the sine excitation on voiced frames.
166
+ vocoder_voiced_threshold (`float`, *optional*, defaults to 10):
167
+ f0 above which a frame counts as voiced.
168
+ vocoder_upsample_rates (`list[int]`, *optional*, defaults to `[8, 8]`):
169
+ Stride of every vocoder transposed convolution.
170
+ vocoder_upsample_kernel_sizes (`list[int]`, *optional*, defaults to `[16, 16]`):
171
+ Kernel size of every vocoder transposed convolution.
172
+ vocoder_istft_n_fft (`int`, *optional*, defaults to 16):
173
+ Window size of the inverse short time Fourier transform head.
174
+ vocoder_istft_hop_length (`int`, *optional*, defaults to 4):
175
+ Hop size of the inverse short time Fourier transform head.
176
+ vocoder_resblock_kernel_sizes (`list[int]`, *optional*, defaults to `[3, 7, 11]`):
177
+ Kernel sizes of the vocoder residual blocks.
178
+ vocoder_resblock_dilation_sizes (`list[list[int]]`, *optional*, defaults to `[[1, 3, 5], [1, 3, 5], [1, 3, 5]]`):
179
+ Dilations of the vocoder residual blocks.
180
+ vocoder_source_resblock_kernel_sizes (`list[int]`, *optional*, defaults to `[7, 11]`):
181
+ Kernel sizes of the residual blocks applied to the downsampled excitation.
182
+ vocoder_source_resblock_dilation_sizes (`list[list[int]]`, *optional*, defaults to `[[1, 3, 5], [1, 3, 5]]`):
183
+ Dilations of the residual blocks applied to the downsampled excitation.
184
+ vocoder_leaky_relu_slope (`float`, *optional*, defaults to 0.1):
185
+ Negative slope of the vocoder leaky ReLU.
186
+ vocoder_audio_limit (`float`, *optional*, defaults to 0.99):
187
+ Absolute value the generated waveform is clamped to.
188
+ f0_predictor_hidden_size (`int`, *optional*, defaults to 512):
189
+ Channels of the convolutional f0 predictor.
190
+ vocoder_mel_loss_n_fft (`int`, *optional*, defaults to 1024):
191
+ Size of the Fourier transform of the mel spectrogram the vocoder is regressed onto.
192
+ vocoder_mel_loss_hop_length (`int`, *optional*, defaults to 256):
193
+ Hop of that mel spectrogram.
194
+ vocoder_mel_loss_win_length (`int`, *optional*, defaults to 1024):
195
+ Analysis window of that mel spectrogram.
196
+ vocoder_mel_loss_num_mel_bins (`int`, *optional*, defaults to 80):
197
+ Number of mel bins of that mel spectrogram.
198
+ vocoder_mel_loss_fmin (`float`, *optional*, defaults to 0.0):
199
+ Lowest frequency of its mel filter bank.
200
+ vocoder_mel_loss_fmax (`float`, *optional*):
201
+ Highest frequency of its mel filter bank. `None` means half the sampling rate, which is
202
+ what the vocoder objective uses and what sets it apart from the mel the model consumes.
203
+ vocoder_mel_loss_coeff (`float`, *optional*, defaults to 45.0):
204
+ Weight of the mel reconstruction term of the vocoder objective.
205
+ speech_tokenizer_num_mel_bins (`int`, *optional*, defaults to 128):
206
+ Number of mel bins of the log mel spectrogram the speech tokenizer consumes.
207
+ speech_tokenizer_hidden_size (`int`, *optional*, defaults to 1280):
208
+ Hidden size of the speech tokenizer encoder.
209
+ speech_tokenizer_num_heads (`int`, *optional*, defaults to 20):
210
+ Number of attention heads in the speech tokenizer encoder.
211
+ speech_tokenizer_ffn_dim (`int`, *optional*, defaults to 5120):
212
+ Inner dimension of the speech tokenizer feed forward layers.
213
+ speech_tokenizer_num_layers (`int`, *optional*, defaults to 6):
214
+ Number of speech tokenizer encoder layers.
215
+ speech_tokenizer_conv_stride (`int`, *optional*, defaults to 1):
216
+ Stride of the first of the two convolutions the speech tokenizer opens with. The second
217
+ always strides by two, so the token rate is the mel frame rate divided by twice this.
218
+ speech_tokenizer_max_source_positions (`int`, *optional*, defaults to 1500):
219
+ Length of the learned position table added to the speech tokenizer encoder input. `None`
220
+ means the encoder carries no position table.
221
+ initializer_range (`float`, *optional*, defaults to 0.02):
222
+ Standard deviation of the truncated normal initializer.
223
+ """
224
+
225
+ model_type = "cosyvoice_v1"
226
+
227
+ def __init__(
228
+ self,
229
+ sample_rate: int = 22050,
230
+ text_vocab_size: int = 51866,
231
+ speech_vocab_size: int = 4096,
232
+ speaker_embedding_dim: int = 192,
233
+ text_encoder_input_size: int = 512,
234
+ text_encoder_hidden_size: int = 1024,
235
+ text_encoder_num_heads: int = 16,
236
+ text_encoder_ffn_dim: int = 4096,
237
+ text_encoder_num_layers: int = 6,
238
+ text_encoder_hidden_act: str = "silu",
239
+ text_encoder_dropout: float = 0.1,
240
+ text_encoder_positional_dropout: float = 0.1,
241
+ text_encoder_attention_dropout: float = 0.0,
242
+ text_encoder_chunk_size: int = 1,
243
+ lm_hidden_size: int = 1024,
244
+ lm_num_heads: int = 16,
245
+ lm_ffn_dim: int = 4096,
246
+ lm_num_layers: int = 14,
247
+ lm_hidden_act: str = "relu",
248
+ lm_dropout: float = 0.1,
249
+ lm_positional_dropout: float = 0.1,
250
+ lm_attention_dropout: float = 0.0,
251
+ lm_chunk_size: int = 1,
252
+ lm_input_projection_activation: bool = True,
253
+ max_source_positions: int = 5000,
254
+ label_smoothing: float = 0.0,
255
+ length_normalized_loss: bool = True,
256
+ flow_input_size: int = 512,
257
+ flow_output_size: int = 80,
258
+ flow_encoder_hidden_size: int = 512,
259
+ flow_encoder_num_heads: int = 8,
260
+ flow_encoder_ffn_dim: int = 2048,
261
+ flow_encoder_num_layers: int = 6,
262
+ flow_encoder_hidden_act: str = "silu",
263
+ flow_encoder_dropout: float = 0.1,
264
+ flow_encoder_positional_dropout: float = 0.1,
265
+ flow_encoder_attention_dropout: float = 0.1,
266
+ flow_encoder_chunk_size: int = 0,
267
+ flow_input_frame_rate: int = 50,
268
+ length_regulator_sampling_ratios: list[int] | None = None,
269
+ estimator_in_channels: int = 320,
270
+ estimator_out_channels: int = 80,
271
+ estimator_channels: list[int] | None = None,
272
+ estimator_num_blocks: int = 4,
273
+ estimator_num_mid_blocks: int = 12,
274
+ estimator_num_heads: int = 8,
275
+ estimator_head_dim: int = 64,
276
+ estimator_dropout: float = 0.0,
277
+ estimator_ffn_mult: int = 4,
278
+ estimator_group_norm_groups: int = 8,
279
+ sigma_min: float = 1e-06,
280
+ t_scheduler: str = "cosine",
281
+ training_cfg_rate: float = 0.2,
282
+ inference_cfg_rate: float = 0.7,
283
+ num_flow_inference_steps: int = 10,
284
+ vocoder_in_channels: int = 80,
285
+ vocoder_base_channels: int = 512,
286
+ vocoder_num_harmonics: int = 8,
287
+ vocoder_source_amplitude: float = 0.1,
288
+ vocoder_source_noise_std: float = 0.003,
289
+ vocoder_voiced_threshold: float = 10,
290
+ vocoder_upsample_rates: list[int] | None = None,
291
+ vocoder_upsample_kernel_sizes: list[int] | None = None,
292
+ vocoder_istft_n_fft: int = 16,
293
+ vocoder_istft_hop_length: int = 4,
294
+ vocoder_resblock_kernel_sizes: list[int] | None = None,
295
+ vocoder_resblock_dilation_sizes: list[list[int]] | None = None,
296
+ vocoder_source_resblock_kernel_sizes: list[int] | None = None,
297
+ vocoder_source_resblock_dilation_sizes: list[list[int]] | None = None,
298
+ vocoder_leaky_relu_slope: float = 0.1,
299
+ vocoder_audio_limit: float = 0.99,
300
+ f0_predictor_hidden_size: int = 512,
301
+ vocoder_mel_loss_n_fft: int = 1024,
302
+ vocoder_mel_loss_hop_length: int = 256,
303
+ vocoder_mel_loss_win_length: int = 1024,
304
+ vocoder_mel_loss_num_mel_bins: int = 80,
305
+ vocoder_mel_loss_fmin: float = 0.0,
306
+ vocoder_mel_loss_fmax: float | None = None,
307
+ vocoder_mel_loss_coeff: float = 45.0,
308
+ speech_tokenizer_num_mel_bins: int = 128,
309
+ speech_tokenizer_hidden_size: int = 1280,
310
+ speech_tokenizer_num_heads: int = 20,
311
+ speech_tokenizer_ffn_dim: int = 5120,
312
+ speech_tokenizer_num_layers: int = 6,
313
+ speech_tokenizer_conv_stride: int = 1,
314
+ speech_tokenizer_max_source_positions: int | None = 1500,
315
+ initializer_range: float = 0.02,
316
+ **kwargs,
317
+ ):
318
+ self.sample_rate = sample_rate
319
+ self.text_vocab_size = text_vocab_size
320
+ self.speech_vocab_size = speech_vocab_size
321
+ self.speaker_embedding_dim = speaker_embedding_dim
322
+
323
+ self.text_encoder_input_size = text_encoder_input_size
324
+ self.text_encoder_hidden_size = text_encoder_hidden_size
325
+ self.text_encoder_num_heads = text_encoder_num_heads
326
+ self.text_encoder_ffn_dim = text_encoder_ffn_dim
327
+ self.text_encoder_num_layers = text_encoder_num_layers
328
+ self.text_encoder_hidden_act = text_encoder_hidden_act
329
+ self.text_encoder_dropout = text_encoder_dropout
330
+ self.text_encoder_positional_dropout = text_encoder_positional_dropout
331
+ self.text_encoder_attention_dropout = text_encoder_attention_dropout
332
+ self.text_encoder_chunk_size = text_encoder_chunk_size
333
+
334
+ self.lm_hidden_size = lm_hidden_size
335
+ self.lm_num_heads = lm_num_heads
336
+ self.lm_ffn_dim = lm_ffn_dim
337
+ self.lm_num_layers = lm_num_layers
338
+ self.lm_hidden_act = lm_hidden_act
339
+ self.lm_dropout = lm_dropout
340
+ self.lm_positional_dropout = lm_positional_dropout
341
+ self.lm_attention_dropout = lm_attention_dropout
342
+ self.lm_chunk_size = lm_chunk_size
343
+ self.lm_input_projection_activation = lm_input_projection_activation
344
+ self.max_source_positions = max_source_positions
345
+ self.label_smoothing = label_smoothing
346
+ self.length_normalized_loss = length_normalized_loss
347
+
348
+ self.flow_input_size = flow_input_size
349
+ self.flow_output_size = flow_output_size
350
+ self.flow_encoder_hidden_size = flow_encoder_hidden_size
351
+ self.flow_encoder_num_heads = flow_encoder_num_heads
352
+ self.flow_encoder_ffn_dim = flow_encoder_ffn_dim
353
+ self.flow_encoder_num_layers = flow_encoder_num_layers
354
+ self.flow_encoder_hidden_act = flow_encoder_hidden_act
355
+ self.flow_encoder_dropout = flow_encoder_dropout
356
+ self.flow_encoder_positional_dropout = flow_encoder_positional_dropout
357
+ self.flow_encoder_attention_dropout = flow_encoder_attention_dropout
358
+ self.flow_encoder_chunk_size = flow_encoder_chunk_size
359
+ self.flow_input_frame_rate = flow_input_frame_rate
360
+ self.length_regulator_sampling_ratios = (
361
+ [1, 1, 1, 1] if length_regulator_sampling_ratios is None else length_regulator_sampling_ratios
362
+ )
363
+
364
+ self.estimator_in_channels = estimator_in_channels
365
+ self.estimator_out_channels = estimator_out_channels
366
+ self.estimator_channels = [256, 256] if estimator_channels is None else estimator_channels
367
+ self.estimator_num_blocks = estimator_num_blocks
368
+ self.estimator_num_mid_blocks = estimator_num_mid_blocks
369
+ self.estimator_num_heads = estimator_num_heads
370
+ self.estimator_head_dim = estimator_head_dim
371
+ self.estimator_dropout = estimator_dropout
372
+ self.estimator_ffn_mult = estimator_ffn_mult
373
+ self.estimator_group_norm_groups = estimator_group_norm_groups
374
+ self.sigma_min = sigma_min
375
+ self.t_scheduler = t_scheduler
376
+ self.training_cfg_rate = training_cfg_rate
377
+ self.inference_cfg_rate = inference_cfg_rate
378
+ self.num_flow_inference_steps = num_flow_inference_steps
379
+
380
+ self.vocoder_in_channels = vocoder_in_channels
381
+ self.vocoder_base_channels = vocoder_base_channels
382
+ self.vocoder_num_harmonics = vocoder_num_harmonics
383
+ self.vocoder_source_amplitude = vocoder_source_amplitude
384
+ self.vocoder_source_noise_std = vocoder_source_noise_std
385
+ self.vocoder_voiced_threshold = vocoder_voiced_threshold
386
+ self.vocoder_upsample_rates = [8, 8] if vocoder_upsample_rates is None else vocoder_upsample_rates
387
+ self.vocoder_upsample_kernel_sizes = (
388
+ [16, 16] if vocoder_upsample_kernel_sizes is None else vocoder_upsample_kernel_sizes
389
+ )
390
+ self.vocoder_istft_n_fft = vocoder_istft_n_fft
391
+ self.vocoder_istft_hop_length = vocoder_istft_hop_length
392
+ self.vocoder_resblock_kernel_sizes = (
393
+ [3, 7, 11] if vocoder_resblock_kernel_sizes is None else vocoder_resblock_kernel_sizes
394
+ )
395
+ self.vocoder_resblock_dilation_sizes = (
396
+ [[1, 3, 5], [1, 3, 5], [1, 3, 5]]
397
+ if vocoder_resblock_dilation_sizes is None
398
+ else vocoder_resblock_dilation_sizes
399
+ )
400
+ self.vocoder_source_resblock_kernel_sizes = (
401
+ [7, 11] if vocoder_source_resblock_kernel_sizes is None else vocoder_source_resblock_kernel_sizes
402
+ )
403
+ self.vocoder_source_resblock_dilation_sizes = (
404
+ [[1, 3, 5], [1, 3, 5]]
405
+ if vocoder_source_resblock_dilation_sizes is None
406
+ else vocoder_source_resblock_dilation_sizes
407
+ )
408
+ self.vocoder_leaky_relu_slope = vocoder_leaky_relu_slope
409
+ self.vocoder_audio_limit = vocoder_audio_limit
410
+ self.f0_predictor_hidden_size = f0_predictor_hidden_size
411
+ self.vocoder_mel_loss_n_fft = vocoder_mel_loss_n_fft
412
+ self.vocoder_mel_loss_hop_length = vocoder_mel_loss_hop_length
413
+ self.vocoder_mel_loss_win_length = vocoder_mel_loss_win_length
414
+ self.vocoder_mel_loss_num_mel_bins = vocoder_mel_loss_num_mel_bins
415
+ self.vocoder_mel_loss_fmin = vocoder_mel_loss_fmin
416
+ self.vocoder_mel_loss_fmax = vocoder_mel_loss_fmax
417
+ self.vocoder_mel_loss_coeff = vocoder_mel_loss_coeff
418
+ self.speech_tokenizer_num_mel_bins = speech_tokenizer_num_mel_bins
419
+ self.speech_tokenizer_hidden_size = speech_tokenizer_hidden_size
420
+ self.speech_tokenizer_num_heads = speech_tokenizer_num_heads
421
+ self.speech_tokenizer_ffn_dim = speech_tokenizer_ffn_dim
422
+ self.speech_tokenizer_num_layers = speech_tokenizer_num_layers
423
+ self.speech_tokenizer_conv_stride = speech_tokenizer_conv_stride
424
+ self.speech_tokenizer_max_source_positions = speech_tokenizer_max_source_positions
425
+
426
+ self.initializer_range = initializer_range
427
+ super().__init__(**kwargs)
428
+
429
+
430
+ class CosyVoiceV2Config(CosyVoiceV1Config):
431
+ r"""
432
+ This is the configuration class to store the configuration of a
433
+ [`CosyVoiceV2ForConditionalGeneration`]. CosyVoice v2 keeps the three network layout of
434
+ [`CosyVoiceV1Config`] but replaces the language model with a pretrained Qwen2 decoder, upsamples
435
+ the flow matching encoder by `token_mel_ratio` instead of interpolating it, and makes the flow
436
+ matching estimator and the encoder chunk aware so that they can run on a stream.
437
+
438
+ Instantiating a configuration with the defaults yields the geometry of the released
439
+ `FunAudioLLM/CosyVoice2-0.5B` checkpoint.
440
+
441
+ Args:
442
+ text_config (`Qwen2Config` or `dict`, *optional*):
443
+ Configuration of the Qwen2 decoder that carries the language model. Defaults to the
444
+ geometry of the `CosyVoice-BlankEN` directory shipped with the checkpoint.
445
+ num_speech_special_tokens (`int`, *optional*, defaults to 3):
446
+ Number of ids appended to the speech vocabulary. The first is the end of speech token and
447
+ the third is the fill token that separates the text and speech groups of a bistream
448
+ sequence.
449
+ mix_ratio (`list[int]`, *optional*, defaults to `[5, 15]`):
450
+ Number of text tokens and of speech tokens in one group of a bistream training sequence.
451
+ token_mel_ratio (`int`, *optional*, defaults to 2):
452
+ Number of mel frames produced per speech token.
453
+ pre_lookahead_len (`int`, *optional*, defaults to 3):
454
+ Number of future speech tokens the flow matching encoder is allowed to look at.
455
+ pre_lookahead_channels (`int`, *optional*, defaults to 512):
456
+ Inner channels of the lookahead convolution of the flow matching encoder.
457
+ flow_encoder_up_num_layers (`int`, *optional*, defaults to 4):
458
+ Number of flow matching encoder layers that run after the upsampling layer.
459
+ estimator_static_chunk_size (`int`, *optional*, defaults to 50):
460
+ Static chunk size of the flow matching estimator attention mask while streaming, in mel
461
+ frames.
462
+ estimator_num_decoding_left_chunks (`int`, *optional*, defaults to -1):
463
+ Value of `num_decoding_left_chunks` in upstream's `cosyvoice2.yaml` and `cosyvoice3.yaml`.
464
+ Upstream's estimator stores it and passes -1 to its chunk mask at every call, so a
465
+ streaming chunk always attends to all past chunks. The estimator here does the same and
466
+ does not read this field.
467
+ noise_length (`int`, *optional*, defaults to 15000):
468
+ Length in mel frames of the fixed noise the Euler solver starts from.
469
+ noise_seed (`int`, *optional*, defaults to 0):
470
+ Seed the fixed noise is drawn with.
471
+ speech_tokenizer_fsmn_kernel_size (`int`, *optional*, defaults to 31):
472
+ Kernel size of the depthwise memory convolution the speech tokenizer attention adds to
473
+ its value projection.
474
+ speech_tokenizer_rope_theta (`float`, *optional*, defaults to 10000.0):
475
+ Base of the rotary embedding of the speech tokenizer attention.
476
+ speech_tokenizer_max_position_embeddings (`int`, *optional*, defaults to 2048):
477
+ Longest sequence the rotary embedding of the speech tokenizer is built for.
478
+ speech_tokenizer_fsq_levels (`list[int]`, *optional*, defaults to `[3, 3, 3, 3, 3, 3, 3, 3]`):
479
+ Number of levels of each dimension of the finite scalar quantizer the speech tokenizer
480
+ closes with. Their product is the size of the speech vocabulary.
481
+ kwargs:
482
+ Forwarded to [`CosyVoiceV1Config`], whose defaults are overridden to the v2 geometry.
483
+ """
484
+
485
+ model_type = "cosyvoice_v2"
486
+ sub_configs = {"text_config": Qwen2Config}
487
+
488
+ def __init__(
489
+ self,
490
+ text_config: "Qwen2Config | dict | None" = None,
491
+ num_speech_special_tokens: int = 3,
492
+ mix_ratio: list[int] | None = None,
493
+ token_mel_ratio: int = 2,
494
+ pre_lookahead_len: int = 3,
495
+ pre_lookahead_channels: int = 512,
496
+ flow_encoder_up_num_layers: int = 4,
497
+ estimator_static_chunk_size: int = 50,
498
+ estimator_num_decoding_left_chunks: int = -1,
499
+ noise_length: int = 15000,
500
+ noise_seed: int = 0,
501
+ speech_tokenizer_fsmn_kernel_size: int = 31,
502
+ speech_tokenizer_rope_theta: float = 10000.0,
503
+ speech_tokenizer_max_position_embeddings: int = 2048,
504
+ speech_tokenizer_fsq_levels: list[int] | None = None,
505
+ **kwargs,
506
+ ):
507
+ defaults = {
508
+ "sample_rate": 24000,
509
+ "speech_vocab_size": 6561,
510
+ "lm_hidden_size": 896,
511
+ "flow_input_size": 512,
512
+ "flow_encoder_hidden_size": 512,
513
+ "flow_encoder_num_heads": 8,
514
+ "flow_encoder_ffn_dim": 2048,
515
+ "flow_encoder_num_layers": 6,
516
+ "flow_encoder_attention_dropout": 0.1,
517
+ "flow_encoder_chunk_size": 25,
518
+ "flow_input_frame_rate": 25,
519
+ "estimator_channels": [256],
520
+ "vocoder_upsample_rates": [8, 5, 3],
521
+ "vocoder_upsample_kernel_sizes": [16, 11, 7],
522
+ "vocoder_source_resblock_kernel_sizes": [7, 7, 11],
523
+ "vocoder_source_resblock_dilation_sizes": [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
524
+ "vocoder_mel_loss_n_fft": 1920,
525
+ "vocoder_mel_loss_hop_length": 480,
526
+ "vocoder_mel_loss_win_length": 1920,
527
+ "speech_tokenizer_conv_stride": 2,
528
+ "speech_tokenizer_max_source_positions": None,
529
+ }
530
+ for name, value in defaults.items():
531
+ kwargs.setdefault(name, value)
532
+
533
+ if text_config is None:
534
+ text_config = Qwen2Config(
535
+ vocab_size=151936,
536
+ hidden_size=896,
537
+ intermediate_size=4864,
538
+ num_hidden_layers=24,
539
+ num_attention_heads=14,
540
+ num_key_value_heads=2,
541
+ hidden_act="silu",
542
+ max_position_embeddings=32768,
543
+ rms_norm_eps=1e-06,
544
+ rope_theta=1000000.0,
545
+ tie_word_embeddings=True,
546
+ bos_token_id=151643,
547
+ eos_token_id=151645,
548
+ )
549
+ elif isinstance(text_config, dict):
550
+ text_config = Qwen2Config(**text_config)
551
+ self.text_config = text_config
552
+
553
+ self.num_speech_special_tokens = num_speech_special_tokens
554
+ self.mix_ratio = [5, 15] if mix_ratio is None else mix_ratio
555
+ self.token_mel_ratio = token_mel_ratio
556
+ self.pre_lookahead_len = pre_lookahead_len
557
+ self.pre_lookahead_channels = pre_lookahead_channels
558
+ self.flow_encoder_up_num_layers = flow_encoder_up_num_layers
559
+ self.estimator_static_chunk_size = estimator_static_chunk_size
560
+ self.estimator_num_decoding_left_chunks = estimator_num_decoding_left_chunks
561
+ self.noise_length = noise_length
562
+ self.noise_seed = noise_seed
563
+ self.speech_tokenizer_fsmn_kernel_size = speech_tokenizer_fsmn_kernel_size
564
+ self.speech_tokenizer_rope_theta = speech_tokenizer_rope_theta
565
+ self.speech_tokenizer_max_position_embeddings = speech_tokenizer_max_position_embeddings
566
+ self.speech_tokenizer_fsq_levels = (
567
+ [3] * 8 if speech_tokenizer_fsq_levels is None else speech_tokenizer_fsq_levels
568
+ )
569
+ super().__init__(**kwargs)
570
+
571
+ # One dtype governs the whole composite. The Qwen2 directory the released checkpoint ships
572
+ # declares bfloat16 in its own config.json, which would otherwise build the language model
573
+ # backbone in bfloat16 while every sibling module stays at the default dtype, and the first
574
+ # matrix multiply across that boundary raises.
575
+ for field in ("dtype", "torch_dtype"):
576
+ if not hasattr(self.text_config, field) or not hasattr(self, field):
577
+ continue
578
+ try:
579
+ setattr(self.text_config, field, getattr(self, field))
580
+ except AttributeError:
581
+ pass
582
+
583
+ @property
584
+ def speech_head_size(self) -> int:
585
+ r"""
586
+ Returns:
587
+ `int`: Number of classes the language model head predicts.
588
+ """
589
+ return self.speech_vocab_size + self.num_speech_special_tokens
590
+
591
+
592
+ class EmoTraTTSConfig(CosyVoiceV2Config):
593
+ r"""
594
+ This is the configuration class to store the configuration of a [`EmoTraTTSForConditionalGeneration`]. It is the
595
+ CosyVoice2 configuration with the VAD conditioning of EmoTra-TTS added. The defaults are the values of the upstream
596
+ recipes `cosyvoice2_EmoTra_sft_LLM.yaml` and `cosyvoice2_EmoTra_sft_Flow_Lynorm_fixs.yaml`.
597
+
598
+ It takes every argument of [`CosyVoiceV2Config`], and:
599
+
600
+ Args:
601
+ num_vad_tokens (`int`, *optional*, defaults to 5):
602
+ Number of VAD tokens placed between the start of sequence embedding and the text. Token $k$ carries
603
+ $(1-\alpha_k)\mathbf v_{start}+\alpha_k\mathbf v_{end}$ with $\alpha_k=k/(N-1)$.
604
+ vad_projection_hidden_size (`int`, *optional*, defaults to 256):
605
+ Inner width of `vad_projection`, which maps a 3 dimensional VAD vector to `lm_hidden_size`.
606
+ vad_reconstructor_hidden_size (`int`, *optional*, defaults to 512):
607
+ Inner width of `hidden_reconstructor`, which maps a VAD token to `vad_hidden_state_size`.
608
+ vad_hidden_state_size (`int`, *optional*, defaults to 1024):
609
+ Size of the pooled hidden state of the w2v2 VAD regressor the reconstruction loss targets.
610
+ vad_dropout (`float`, *optional*, defaults to 0.1):
611
+ Dropout inside `vad_projection` and `hidden_reconstructor`.
612
+ hidden_loss_weight (`float`, *optional*, defaults to 0.1):
613
+ Weight $\lambda$ of the reconstruction loss in $\mathcal L=\mathcal L_{CE}+\lambda\mathcal L_{hidden}$.
614
+ vad_downsample_hidden_size (`int`, *optional*, defaults to 256):
615
+ Inner width of `vad_downsample`, which maps `vad_hidden_state_size` to `flow_output_size`.
616
+ emotion_scale (`float`, *optional*, defaults to 0.07):
617
+ Fixed scale $\epsilon$ of the layer normalized emotion embedding added to the speaker input of the flow
618
+ matching estimator.
619
+ emotion_transition_start (`float`, *optional*, defaults to 0.4):
620
+ Fraction of the mel frames before which the flow emotion stays at the start VAD.
621
+ emotion_transition_end (`float`, *optional*, defaults to 0.7):
622
+ Fraction of the mel frames from which the flow emotion stays at the end VAD.
623
+ """
624
+
625
+ model_type = "emotra_tts"
626
+
627
+ def __init__(
628
+ self,
629
+ num_vad_tokens: int = 5,
630
+ vad_projection_hidden_size: int = 256,
631
+ vad_reconstructor_hidden_size: int = 512,
632
+ vad_hidden_state_size: int = 1024,
633
+ vad_dropout: float = 0.1,
634
+ hidden_loss_weight: float = 0.1,
635
+ vad_downsample_hidden_size: int = 256,
636
+ emotion_scale: float = 0.07,
637
+ emotion_transition_start: float = 0.4,
638
+ emotion_transition_end: float = 0.7,
639
+ **kwargs,
640
+ ):
641
+ self.num_vad_tokens = num_vad_tokens
642
+ self.vad_projection_hidden_size = vad_projection_hidden_size
643
+ self.vad_reconstructor_hidden_size = vad_reconstructor_hidden_size
644
+ self.vad_hidden_state_size = vad_hidden_state_size
645
+ self.vad_dropout = vad_dropout
646
+ self.hidden_loss_weight = hidden_loss_weight
647
+ self.vad_downsample_hidden_size = vad_downsample_hidden_size
648
+ self.emotion_scale = emotion_scale
649
+ self.emotion_transition_start = emotion_transition_start
650
+ self.emotion_transition_end = emotion_transition_end
651
+ if "dtype" not in kwargs and "torch_dtype" not in kwargs:
652
+ kwargs["dtype"] = "bfloat16"
653
+ super().__init__(**kwargs)
feature_extraction_emotra_tts.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The EmoTra-TTS Authors (LightSpeed, Tianchi Liu), Alibaba Inc. (CosyVoice, authors: Xiang Lyu,
2
+ # Zhihao Du), the HuggingFace Inc. team, TICTAP-11 and b-re-w. 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
+ """Feature extractor class for EmoTra-TTS on CosyVoice2."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ import torchaudio
22
+ from transformers.audio_utils import mel_filter_bank
23
+ from transformers.feature_extraction_sequence_utils import SequenceFeatureExtractor
24
+ from transformers.feature_extraction_utils import BatchFeature
25
+
26
+
27
+ __all__ = [
28
+ "CosyVoiceV1FeatureExtractor",
29
+ "CosyVoiceV2FeatureExtractor",
30
+ "broadcast_sampling_rates",
31
+ "make_list_of_waveforms",
32
+ ]
33
+
34
+
35
+ _WINDOW_CACHE = {}
36
+
37
+
38
+ def make_list_of_waveforms(raw_speech) -> list[torch.Tensor]:
39
+ """
40
+ Splits the waveform argument of a processor into one tensor per utterance.
41
+
42
+ Args:
43
+ raw_speech (`np.ndarray`, `torch.Tensor` or `list`):
44
+ A waveform of shape `(num_samples,)` or `(1, num_samples)`, a flat list of samples, a
45
+ list of waveforms, or an array or tensor of shape `(batch_size, num_samples)`.
46
+
47
+ Returns:
48
+ `list[torch.Tensor]`: One waveform per utterance.
49
+
50
+ Raises:
51
+ ValueError: If an array or tensor has more than two dimensions, or the list is empty.
52
+ """
53
+ if isinstance(raw_speech, (list, tuple)):
54
+ if len(raw_speech) == 0:
55
+ raise ValueError("expected at least one waveform, got an empty list")
56
+ if np.ndim(raw_speech[0]) == 0:
57
+ return [torch.as_tensor(np.asarray(raw_speech))]
58
+ return [
59
+ item if isinstance(item, torch.Tensor) else torch.as_tensor(np.asarray(item)) for item in raw_speech
60
+ ]
61
+ waveform = raw_speech if isinstance(raw_speech, torch.Tensor) else torch.as_tensor(np.asarray(raw_speech))
62
+ if waveform.ndim > 2:
63
+ raise ValueError(f"expected a waveform of at most two dimensions, got shape {tuple(waveform.shape)}")
64
+ if waveform.ndim == 2 and waveform.shape[0] > 1:
65
+ return list(waveform)
66
+ return [waveform]
67
+
68
+
69
+ def broadcast_sampling_rates(sampling_rate, batch_size: int) -> list[Optional[int]]:
70
+ """
71
+ Args:
72
+ sampling_rate (`int`, `list[int]` or `None`):
73
+ One rate for every waveform, or one per waveform.
74
+ batch_size (`int`):
75
+ Number of waveforms.
76
+
77
+ Returns:
78
+ `list[int or None]`: One rate per waveform.
79
+
80
+ Raises:
81
+ ValueError: If a list of rates does not hold `batch_size` entries.
82
+ """
83
+ if isinstance(sampling_rate, (list, tuple)):
84
+ if len(sampling_rate) != batch_size:
85
+ raise ValueError(f"got {len(sampling_rate)} sampling rates for {batch_size} waveforms")
86
+ return list(sampling_rate)
87
+ return [sampling_rate] * batch_size
88
+
89
+
90
+ class CosyVoiceV1FeatureExtractor(SequenceFeatureExtractor):
91
+ r"""
92
+ Constructs a CosyVoice v1 feature extractor, which turns a waveform into the log mel spectrogram
93
+ the flow matching model is conditioned on and trained against.
94
+
95
+ Args:
96
+ feature_size (`int`, *optional*, defaults to 80):
97
+ Number of mel bins.
98
+ sampling_rate (`int`, *optional*, defaults to 24000):
99
+ Rate the incoming waveform is resampled to before the mel spectrogram is taken.
100
+ mel_sampling_rate (`int`, *optional*, defaults to 22050):
101
+ Rate the mel filter bank is built for.
102
+ n_fft (`int`, *optional*, defaults to 1024):
103
+ Size of the Fourier transform.
104
+ hop_length (`int`, *optional*, defaults to 256):
105
+ Hop between two consecutive frames.
106
+ win_length (`int`, *optional*, defaults to 1024):
107
+ Size of the analysis window.
108
+ fmin (`float`, *optional*, defaults to 0.0):
109
+ Lowest frequency of the mel filter bank.
110
+ fmax (`float`, *optional*, defaults to 8000.0):
111
+ Highest frequency of the mel filter bank.
112
+ padding_value (`float`, *optional*, defaults to 0.0):
113
+ Value used to pad batches of spectrograms.
114
+ """
115
+
116
+ model_input_names = ["speech_feat"]
117
+
118
+ def __init__(
119
+ self,
120
+ feature_size: int = 80,
121
+ sampling_rate: int = 24000,
122
+ mel_sampling_rate: int = 22050,
123
+ n_fft: int = 1024,
124
+ hop_length: int = 256,
125
+ win_length: int = 1024,
126
+ fmin: float = 0.0,
127
+ fmax: float = 8000.0,
128
+ padding_value: float = 0.0,
129
+ **kwargs,
130
+ ):
131
+ super().__init__(
132
+ feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs
133
+ )
134
+ self.mel_sampling_rate = mel_sampling_rate
135
+ self.n_fft = n_fft
136
+ self.hop_length = hop_length
137
+ self.win_length = win_length
138
+ self.fmin = fmin
139
+ self.fmax = fmax
140
+ self.mel_filters = mel_filter_bank(
141
+ num_frequency_bins=1 + n_fft // 2,
142
+ num_mel_filters=feature_size,
143
+ min_frequency=fmin,
144
+ max_frequency=fmax,
145
+ sampling_rate=mel_sampling_rate,
146
+ norm="slaney",
147
+ mel_scale="slaney",
148
+ ).T.astype(np.float32)
149
+
150
+ def _get_window(self, device) -> torch.Tensor:
151
+ key = (self.win_length, device)
152
+ if key not in _WINDOW_CACHE:
153
+ _WINDOW_CACHE[key] = torch.hann_window(self.win_length, device=device)
154
+ return _WINDOW_CACHE[key]
155
+
156
+ def _mel_spectrogram(self, waveform: torch.Tensor) -> torch.Tensor:
157
+ """
158
+ Args:
159
+ waveform (`torch.Tensor` of shape `(batch_size, num_samples)`):
160
+ Waveform sampled at `sampling_rate`.
161
+
162
+ Returns:
163
+ `torch.Tensor` of shape `(batch_size, feature_size, num_frames)`: the log mel spectrogram.
164
+ """
165
+ padding = int((self.n_fft - self.hop_length) / 2)
166
+ waveform = torch.nn.functional.pad(waveform.unsqueeze(1), (padding, padding), mode="reflect").squeeze(1)
167
+ spectrogram = torch.stft(
168
+ waveform,
169
+ self.n_fft,
170
+ hop_length=self.hop_length,
171
+ win_length=self.win_length,
172
+ window=self._get_window(waveform.device),
173
+ center=False,
174
+ pad_mode="reflect",
175
+ normalized=False,
176
+ onesided=True,
177
+ return_complex=True,
178
+ )
179
+ spectrogram = torch.view_as_real(spectrogram)
180
+ spectrogram = torch.sqrt(spectrogram.pow(2).sum(-1) + 1e-9)
181
+ mel_filters = torch.from_numpy(self.mel_filters).to(spectrogram)
182
+ return torch.log(torch.clamp(torch.matmul(mel_filters, spectrogram), min=1e-5))
183
+
184
+ def __call__(
185
+ self,
186
+ raw_speech: Union[np.ndarray, torch.Tensor, list],
187
+ sampling_rate: Optional[Union[int, list[Optional[int]]]] = None,
188
+ return_tensors: str = "pt",
189
+ **kwargs,
190
+ ) -> BatchFeature:
191
+ """
192
+ Args:
193
+ raw_speech (`np.ndarray`, `torch.Tensor` or `list`):
194
+ One mono waveform of shape `(num_samples,)` or `(1, num_samples)`, or a batch of them: a
195
+ list of waveforms, or an array or tensor of shape `(batch_size, num_samples)` with
196
+ `batch_size` above one.
197
+ sampling_rate (`int` or `list[int]`, *optional*):
198
+ Rate of `raw_speech`, one per waveform or one for all of them. Each waveform is
199
+ resampled to `self.sampling_rate` when the two differ.
200
+ return_tensors (`str`, *optional*, defaults to `"pt"`):
201
+ Only `"pt"` is supported.
202
+
203
+ Returns:
204
+ [`BatchFeature`]: `speech_feat` of shape `(batch_size, num_frames, feature_size)`, padded
205
+ with `padding_value` up to the longest spectrogram, and `speech_feat_lengths` of shape
206
+ `(batch_size,)`.
207
+
208
+ Raises:
209
+ ValueError: If `return_tensors` is not `"pt"`, or `sampling_rate` is a list whose length
210
+ differs from the number of waveforms.
211
+ """
212
+ if return_tensors != "pt":
213
+ raise ValueError(f"{self.__class__.__name__} only supports return_tensors='pt'")
214
+ waveforms = make_list_of_waveforms(raw_speech)
215
+ rates = broadcast_sampling_rates(sampling_rate, len(waveforms))
216
+ spectrograms = []
217
+ for waveform, rate in zip(waveforms, rates):
218
+ waveform = waveform.reshape(1, -1).float()
219
+ if rate is not None and rate != self.sampling_rate:
220
+ waveform = torchaudio.functional.resample(waveform, rate, self.sampling_rate)
221
+ spectrograms.append(self._mel_spectrogram(waveform).transpose(1, 2)[0])
222
+ lengths = torch.tensor([spectrogram.shape[0] for spectrogram in spectrograms], dtype=torch.int32)
223
+ speech_feat = torch.nn.utils.rnn.pad_sequence(
224
+ spectrograms, batch_first=True, padding_value=self.padding_value
225
+ )
226
+ return BatchFeature({"speech_feat": speech_feat, "speech_feat_lengths": lengths})
227
+
228
+
229
+ class CosyVoiceV2FeatureExtractor(CosyVoiceV1FeatureExtractor):
230
+ r"""
231
+ Constructs a CosyVoice v2 feature extractor, which turns a waveform into the 24 kHz log mel
232
+ spectrogram the flow matching model is conditioned on and trained against.
233
+
234
+ Args:
235
+ feature_size (`int`, *optional*, defaults to 80):
236
+ Number of mel bins.
237
+ sampling_rate (`int`, *optional*, defaults to 24000):
238
+ Rate the incoming waveform is resampled to before the mel spectrogram is taken.
239
+ mel_sampling_rate (`int`, *optional*, defaults to 24000):
240
+ Rate the mel filter bank is built for.
241
+ n_fft (`int`, *optional*, defaults to 1920):
242
+ Size of the Fourier transform.
243
+ hop_length (`int`, *optional*, defaults to 480):
244
+ Hop between two consecutive frames.
245
+ win_length (`int`, *optional*, defaults to 1920):
246
+ Size of the analysis window.
247
+ fmin (`float`, *optional*, defaults to 0.0):
248
+ Lowest frequency of the mel filter bank.
249
+ fmax (`float`, *optional*, defaults to 8000.0):
250
+ Highest frequency of the mel filter bank.
251
+ padding_value (`float`, *optional*, defaults to 0.0):
252
+ Value used to pad batches of spectrograms.
253
+ """
254
+
255
+ def __init__(
256
+ self,
257
+ feature_size: int = 80,
258
+ sampling_rate: int = 24000,
259
+ mel_sampling_rate: int = 24000,
260
+ n_fft: int = 1920,
261
+ hop_length: int = 480,
262
+ win_length: int = 1920,
263
+ fmin: float = 0.0,
264
+ fmax: float = 8000.0,
265
+ padding_value: float = 0.0,
266
+ **kwargs,
267
+ ):
268
+ super().__init__(
269
+ feature_size=feature_size,
270
+ sampling_rate=sampling_rate,
271
+ mel_sampling_rate=mel_sampling_rate,
272
+ n_fft=n_fft,
273
+ hop_length=hop_length,
274
+ win_length=win_length,
275
+ fmin=fmin,
276
+ fmax=fmax,
277
+ padding_value=padding_value,
278
+ **kwargs,
279
+ )
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "output_attentions": false,
6
+ "output_hidden_states": false,
7
+ "transformers_version": "5.19.0",
8
+ "use_cache": true
9
+ }
generation_emotra_tts.py ADDED
@@ -0,0 +1,1669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The EmoTra-TTS Authors (LightSpeed, Tianchi Liu), Alibaba Inc. (CosyVoice, authors: Xiang Lyu,
2
+ # Zhihao Du), the HuggingFace Inc. team, TICTAP-11 and b-re-w. 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
+ """Generation utilities for EmoTra-TTS on CosyVoice2."""
16
+
17
+ from types import GeneratorType
18
+ from typing import Generator, Iterator, Optional, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn.functional as F
23
+
24
+
25
+ __all__ = [
26
+ "CosyVoiceV1GenerationMixin",
27
+ "CosyVoiceV2GenerationMixin",
28
+ "fade_in_out",
29
+ "left_pad",
30
+ "nucleus_sampling",
31
+ "random_sampling",
32
+ "repetition_aware_sampling",
33
+ "right_pad",
34
+ "row_lengths",
35
+ "sample_batch_step",
36
+ "trim_row",
37
+ ]
38
+
39
+
40
+ def nucleus_sampling(scores: torch.Tensor, top_p: float = 0.8, top_k: int = 25) -> int:
41
+ """
42
+ Samples one speech token from the smallest set of tokens whose cumulative probability stays below
43
+ `top_p`, capped at `top_k` tokens.
44
+
45
+ Args:
46
+ scores (`torch.Tensor` of shape `(speech_vocab_size + 1,)`):
47
+ Log probabilities of the next speech token.
48
+ top_p (`float`, *optional*, defaults to 0.8):
49
+ Cumulative probability the candidate set is grown to.
50
+ top_k (`int`, *optional*, defaults to 25):
51
+ Largest number of candidates.
52
+
53
+ Returns:
54
+ `int`: the sampled token id.
55
+ """
56
+ sorted_value, sorted_index = scores.softmax(dim=0).sort(descending=True, stable=True)
57
+ cumulative = torch.cumsum(sorted_value, dim=0)
58
+ keep = int(torch.searchsorted(cumulative, cumulative.new_tensor(top_p)).item()) + 1
59
+ keep = max(1, min(keep, top_k, sorted_value.numel()))
60
+ probabilities = sorted_value[:keep]
61
+ return sorted_index[probabilities.multinomial(1, replacement=True)].item()
62
+
63
+
64
+ def random_sampling(scores: torch.Tensor) -> int:
65
+ """
66
+ Samples one speech token from the full distribution.
67
+
68
+ Args:
69
+ scores (`torch.Tensor` of shape `(speech_vocab_size + 1,)`):
70
+ Log probabilities of the next speech token.
71
+
72
+ Returns:
73
+ `int`: the sampled token id.
74
+ """
75
+ return scores.softmax(dim=0).multinomial(1, replacement=True).item()
76
+
77
+
78
+ def repetition_aware_sampling(
79
+ scores: torch.Tensor,
80
+ decoded_tokens: list[int],
81
+ top_p: float = 0.8,
82
+ top_k: int = 25,
83
+ window_size: int = 10,
84
+ repetition_threshold: float = 0.1,
85
+ ) -> int:
86
+ """
87
+ Nucleus sampling that falls back to sampling from the full distribution when the drawn token
88
+ already occupies too much of the recent window, as introduced by VALL-E 2.
89
+
90
+ Args:
91
+ scores (`torch.Tensor` of shape `(speech_vocab_size + 1,)`):
92
+ Log probabilities of the next speech token.
93
+ decoded_tokens (`list[int]`):
94
+ Speech tokens decoded so far.
95
+ top_p (`float`, *optional*, defaults to 0.8):
96
+ Cumulative probability the candidate set is grown to.
97
+ top_k (`int`, *optional*, defaults to 25):
98
+ Largest number of candidates.
99
+ window_size (`int`, *optional*, defaults to 10):
100
+ Number of recent tokens inspected for repetitions.
101
+ repetition_threshold (`float`, *optional*, defaults to 0.1):
102
+ Fraction of the window above which the drawn token is rejected.
103
+
104
+ Returns:
105
+ `int`: the sampled token id.
106
+ """
107
+ token_id = nucleus_sampling(scores, top_p=top_p, top_k=top_k)
108
+ recent = decoded_tokens[-window_size:]
109
+ repetitions = sum(1 for token in recent if token == token_id)
110
+ if repetitions >= window_size * repetition_threshold:
111
+ scores = scores.clone()
112
+ scores[token_id] = -float("inf")
113
+ token_id = random_sampling(scores)
114
+ return token_id
115
+
116
+
117
+ def fade_in_out(fade_in: torch.Tensor, fade_out: torch.Tensor, window: torch.Tensor) -> torch.Tensor:
118
+ """
119
+ Cross fades the head of a chunk with the tail of the previous one.
120
+
121
+ Args:
122
+ fade_in (`torch.Tensor`):
123
+ Chunk whose head is faded in.
124
+ fade_out (`torch.Tensor`):
125
+ Tail of the previous chunk, faded out.
126
+ window (`torch.Tensor` of shape `(2 * overlap,)`):
127
+ Symmetric window, the first half fading in and the second half fading out.
128
+
129
+ Returns:
130
+ `torch.Tensor`: the cross faded chunk.
131
+ """
132
+ overlap = window.shape[0] // 2
133
+ window = window.to(fade_in.device, fade_in.dtype)
134
+ fade_in = fade_in.clone()
135
+ fade_in[..., :overlap] = fade_in[..., :overlap] * window[:overlap] + fade_out[..., -overlap:] * window[overlap:]
136
+ return fade_in
137
+
138
+
139
+ def right_pad(sequences: list[torch.Tensor]) -> torch.Tensor:
140
+ """
141
+ Args:
142
+ sequences (`list[torch.Tensor]`):
143
+ One one dimensional tensor of token ids per row.
144
+
145
+ Returns:
146
+ `torch.Tensor` of shape `(batch_size, max_length)`: the rows, right padded with 0.
147
+ """
148
+ return torch.nn.utils.rnn.pad_sequence(sequences, batch_first=True, padding_value=0)
149
+
150
+
151
+ def row_lengths(lengths: Optional[torch.Tensor], ids: Optional[torch.Tensor], batch_size: int) -> list[int]:
152
+ """
153
+ Reads the number of valid steps of every row of a right padded batch.
154
+
155
+ Args:
156
+ lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
157
+ Number of valid steps of every row.
158
+ ids (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
159
+ The padded batch, whose full width every row is taken to fill when `lengths` is left out.
160
+ batch_size (`int`):
161
+ Number of rows, used when `ids` is left out too.
162
+
163
+ Returns:
164
+ `list[int]`: the length of every row, all 0 when both `lengths` and `ids` are left out.
165
+ """
166
+ if lengths is not None:
167
+ return [int(length) for length in lengths]
168
+ if ids is None:
169
+ return [0] * batch_size
170
+ return [ids.shape[1]] * ids.shape[0]
171
+
172
+
173
+ def trim_row(tensor: Optional[torch.Tensor], lengths: Optional[torch.Tensor]) -> Optional[torch.Tensor]:
174
+ """
175
+ Args:
176
+ tensor (`torch.Tensor` of shape `(1, sequence_length, ...)`, *optional*):
177
+ One right padded row.
178
+ lengths (`torch.Tensor` of shape `(1,)`, *optional*):
179
+ Its number of valid steps.
180
+
181
+ Returns:
182
+ `torch.Tensor`, *optional*: the row without its padding, or `tensor` itself when `lengths` is
183
+ left out.
184
+ """
185
+ if tensor is None or lengths is None:
186
+ return tensor
187
+ return tensor[:, : int(lengths[0])]
188
+
189
+
190
+ def left_pad(sequences: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
191
+ """
192
+ Stacks sequences of embeddings, padding them on the left so that every row ends on the last step.
193
+
194
+ Args:
195
+ sequences (`list[torch.Tensor]`):
196
+ One tensor of shape `(sequence_length, hidden_size)` per row.
197
+
198
+ Returns:
199
+ `tuple(torch.Tensor)`: the padded batch of shape `(batch_size, max_length, hidden_size)` and a
200
+ boolean mask of shape `(batch_size, max_length)` that is `True` on the valid steps.
201
+ """
202
+ max_length = max(sequence.shape[0] for sequence in sequences)
203
+ batch = sequences[0].new_zeros(len(sequences), max_length, sequences[0].shape[1])
204
+ mask = torch.zeros(len(sequences), max_length, dtype=torch.bool, device=batch.device)
205
+ for row, sequence in enumerate(sequences):
206
+ batch[row, max_length - sequence.shape[0] :] = sequence
207
+ mask[row, max_length - sequence.shape[0] :] = True
208
+ return batch, mask
209
+
210
+
211
+ def sample_batch_step(
212
+ log_probs: torch.Tensor,
213
+ step: int,
214
+ decoded_tokens: list[list[int]],
215
+ finished: list[bool],
216
+ min_lengths: list[int],
217
+ max_lengths: list[int],
218
+ stop_token_ids: list[int],
219
+ top_p: float,
220
+ top_k: int,
221
+ window_size: int,
222
+ repetition_threshold: float,
223
+ ) -> list[int]:
224
+ """
225
+ Samples the next speech token of every unfinished row of a batch, with the per row rules of the
226
+ single utterance loop: a row stops once it has decoded `max_lengths[row]` steps or draws a stop
227
+ token, its stop tokens are masked below `min_lengths[row]`, and repetition aware sampling only
228
+ looks at the tokens that row decoded itself. Rows are sampled in order, so a row draws from the
229
+ random stream in the same way the single utterance loop does.
230
+
231
+ Args:
232
+ log_probs (`torch.Tensor` of shape `(batch_size, vocab_size)`):
233
+ Log probabilities of the next token of every row.
234
+ step (`int`):
235
+ Number of decoding steps taken so far.
236
+ decoded_tokens (`list[list[int]]`):
237
+ Speech tokens every row decoded so far, extended in place.
238
+ finished (`list[bool]`):
239
+ Whether every row has finished, updated in place.
240
+ min_lengths (`list[int]`):
241
+ Number of steps below which a row may not stop.
242
+ max_lengths (`list[int]`):
243
+ Number of steps after which a row stops.
244
+ stop_token_ids (`list[int]`):
245
+ Tokens that end a row.
246
+ top_p (`float`):
247
+ Cumulative probability the candidate set is grown to.
248
+ top_k (`int`):
249
+ Largest number of candidates.
250
+ window_size (`int`):
251
+ Number of recent tokens inspected for repetitions.
252
+ repetition_threshold (`float`):
253
+ Fraction of the window above which the drawn token is rejected.
254
+
255
+ Returns:
256
+ `list[int]`: the token every row is fed next. A finished row is fed its last token, or 0, and
257
+ whatever the model predicts from it is discarded.
258
+ """
259
+ next_tokens = []
260
+ for row in range(log_probs.shape[0]):
261
+ if not finished[row] and step >= max_lengths[row]:
262
+ finished[row] = True
263
+ if finished[row]:
264
+ next_tokens.append(decoded_tokens[row][-1] if decoded_tokens[row] else 0)
265
+ continue
266
+ row_log_probs = log_probs[row]
267
+ if step < min_lengths[row]:
268
+ row_log_probs[stop_token_ids] = -float("inf")
269
+ token_id = repetition_aware_sampling(
270
+ row_log_probs, decoded_tokens[row], top_p, top_k, window_size, repetition_threshold
271
+ )
272
+ if token_id in stop_token_ids:
273
+ finished[row] = True
274
+ next_tokens.append(decoded_tokens[row][-1] if decoded_tokens[row] else 0)
275
+ continue
276
+ decoded_tokens[row].append(token_id)
277
+ next_tokens.append(token_id)
278
+ return next_tokens
279
+
280
+
281
+ class CosyVoiceV1GenerationMixin:
282
+ """
283
+ Speech token decoding and token to waveform rendering for [`CosyVoiceV1ForConditionalGeneration`].
284
+
285
+ The language model samples speech tokens one at a time with repetition aware sampling, the flow
286
+ matching model turns them into a mel spectrogram and the vocoder renders the waveform. In streaming
287
+ mode the mel spectrogram and the waveform of consecutive chunks are cross faded, and the flow
288
+ matching cache keeps the prompt and the chunk overlap fixed across chunks.
289
+ """
290
+
291
+ token_overlap_len = 20
292
+ mel_cache_len = 20
293
+ stream_scale_factor = 1
294
+
295
+ @torch.inference_mode()
296
+ def generate_speech_tokens(
297
+ self,
298
+ input_ids: torch.Tensor,
299
+ speaker_embedding: torch.Tensor,
300
+ prompt_input_ids: Optional[torch.Tensor] = None,
301
+ prompt_speech_token_ids: Optional[torch.Tensor] = None,
302
+ min_token_text_ratio: float = 2.0,
303
+ max_token_text_ratio: float = 20.0,
304
+ top_p: float = 0.8,
305
+ top_k: int = 25,
306
+ window_size: int = 10,
307
+ repetition_threshold: float = 0.1,
308
+ ) -> Generator[int, None, None]:
309
+ """
310
+ Samples speech tokens for one utterance and yields them one at a time.
311
+
312
+ Args:
313
+ input_ids (`torch.Tensor` of shape `(1, text_length)`):
314
+ Text token ids of the sentence to synthesize.
315
+ speaker_embedding (`torch.Tensor` of shape `(1, speaker_embedding_dim)`):
316
+ Utterance level speaker embedding, or an empty tensor to leave the speaker
317
+ conditioning out.
318
+ prompt_input_ids (`torch.Tensor` of shape `(1, prompt_text_length)`, *optional*):
319
+ Text token ids of the prompt utterance.
320
+ prompt_speech_token_ids (`torch.Tensor` of shape `(1, prompt_speech_length)`, *optional*):
321
+ Speech tokens of the prompt utterance.
322
+ min_token_text_ratio (`float`, *optional*, defaults to 2.0):
323
+ Smallest number of speech tokens generated per text token.
324
+ max_token_text_ratio (`float`, *optional*, defaults to 20.0):
325
+ Largest number of speech tokens generated per text token.
326
+ top_p (`float`, *optional*, defaults to 0.8):
327
+ Cumulative probability the candidate set is grown to.
328
+ top_k (`int`, *optional*, defaults to 25):
329
+ Largest number of candidates.
330
+ window_size (`int`, *optional*, defaults to 10):
331
+ Number of recent tokens inspected for repetitions.
332
+ repetition_threshold (`float`, *optional*, defaults to 0.1):
333
+ Fraction of the window above which the drawn token is rejected.
334
+
335
+ Yields:
336
+ `int`: the next speech token id.
337
+ """
338
+ device = input_ids.device
339
+ text_length = input_ids.shape[1]
340
+ if prompt_input_ids is None:
341
+ prompt_input_ids = input_ids.new_zeros(1, 0)
342
+ input_ids = torch.concat([prompt_input_ids, input_ids], dim=1)
343
+ input_lengths = torch.tensor([input_ids.shape[1]], dtype=torch.int32, device=device)
344
+
345
+ text_hidden_states = self.llm.encode_text(input_ids, input_lengths)
346
+ if speaker_embedding.shape[0] != 0:
347
+ speaker_hidden_states = self.llm.encode_speaker(speaker_embedding)
348
+ else:
349
+ speaker_hidden_states = text_hidden_states.new_zeros(1, 0, self.config.lm_hidden_size)
350
+
351
+ sos_embed = self.llm.llm_embedding.weight[self.llm.sos_index].reshape(1, 1, -1)
352
+ task_id_embed = self.llm.llm_embedding.weight[self.llm.task_id_index].reshape(1, 1, -1)
353
+ if prompt_speech_token_ids is not None and prompt_speech_token_ids.shape[1] != 0:
354
+ prompt_hidden_states = self.llm.speech_embedding(prompt_speech_token_ids)
355
+ else:
356
+ prompt_hidden_states = text_hidden_states.new_zeros(1, 0, self.config.lm_hidden_size)
357
+ hidden_states = torch.concat(
358
+ [sos_embed, speaker_hidden_states, text_hidden_states, task_id_embed, prompt_hidden_states], dim=1
359
+ )
360
+
361
+ min_length = int(text_length * min_token_text_ratio)
362
+ max_length = int(text_length * max_token_text_ratio)
363
+
364
+ decoded_tokens: list[int] = []
365
+ past_key_values = None
366
+ for step in range(max_length):
367
+ padding_mask = hidden_states.new_ones(
368
+ 1, hidden_states.shape[1] + (0 if past_key_values is None else past_key_values[0][0].shape[2]),
369
+ dtype=torch.bool,
370
+ )
371
+ outputs, past_key_values = self.llm.llm(hidden_states, padding_mask, past_key_values)
372
+ log_probs = self.llm.llm_decoder(outputs[:, -1]).log_softmax(dim=-1).squeeze(dim=0)
373
+ if step < min_length:
374
+ log_probs[self.llm.eos_token_id] = -float("inf")
375
+ token_id = repetition_aware_sampling(
376
+ log_probs, decoded_tokens, top_p, top_k, window_size, repetition_threshold
377
+ )
378
+ if token_id == self.llm.eos_token_id:
379
+ break
380
+ yield token_id
381
+ decoded_tokens.append(token_id)
382
+ hidden_states = self.llm.speech_embedding.weight[token_id].reshape(1, 1, -1)
383
+
384
+ @torch.inference_mode()
385
+ def generate_speech_tokens_batch(
386
+ self,
387
+ input_ids: torch.Tensor,
388
+ speaker_embedding: Optional[torch.Tensor],
389
+ input_lengths: Optional[torch.Tensor] = None,
390
+ prompt_input_ids: Optional[torch.Tensor] = None,
391
+ prompt_input_lengths: Optional[torch.Tensor] = None,
392
+ prompt_speech_token_ids: Optional[torch.Tensor] = None,
393
+ prompt_speech_token_lengths: Optional[torch.Tensor] = None,
394
+ min_token_text_ratio: float = 2.0,
395
+ max_token_text_ratio: float = 20.0,
396
+ top_p: float = 0.8,
397
+ top_k: int = 25,
398
+ window_size: int = 10,
399
+ repetition_threshold: float = 0.1,
400
+ ) -> list[list[int]]:
401
+ """
402
+ Samples speech tokens for a right padded batch of utterances in one decoding loop that shares
403
+ the key value cache across rows.
404
+
405
+ Every row is packed as [`~CosyVoiceV1GenerationMixin.generate_speech_tokens`] packs it, then the
406
+ rows are left padded so that they all end on the step being decoded. The padding is masked out
407
+ of every attention, and since the relative position embedding only depends on the distance
408
+ between two steps, a row sees the same positions it would see on its own. Each row keeps its
409
+ own minimum and maximum length, computed from its own text length, its own stop handling and
410
+ its own repetition aware sampling history. A row that has finished keeps being fed so that the
411
+ batch stays aligned, and its outputs are discarded.
412
+
413
+ Args:
414
+ input_ids (`torch.Tensor` of shape `(batch_size, text_length)`):
415
+ Text token ids of the sentences to synthesize, right padded.
416
+ speaker_embedding (`torch.Tensor` of shape `(batch_size, speaker_embedding_dim)`, *optional*):
417
+ Utterance level speaker embeddings. `None` or an empty tensor leaves the speaker
418
+ conditioning out of every row.
419
+ input_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
420
+ Number of text tokens of every row. Defaults to the full width of `input_ids`.
421
+ prompt_input_ids (`torch.Tensor` of shape `(batch_size, prompt_text_length)`, *optional*):
422
+ Text token ids of the prompt utterances, right padded.
423
+ prompt_input_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
424
+ Number of prompt text tokens of every row.
425
+ prompt_speech_token_ids (`torch.Tensor` of shape `(batch_size, prompt_speech_length)`, *optional*):
426
+ Speech tokens of the prompt utterances, right padded.
427
+ prompt_speech_token_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
428
+ Number of prompt speech tokens of every row.
429
+ min_token_text_ratio (`float`, *optional*, defaults to 2.0):
430
+ Smallest number of speech tokens generated per text token of the row.
431
+ max_token_text_ratio (`float`, *optional*, defaults to 20.0):
432
+ Largest number of speech tokens generated per text token of the row.
433
+ top_p (`float`, *optional*, defaults to 0.8):
434
+ Cumulative probability the candidate set is grown to.
435
+ top_k (`int`, *optional*, defaults to 25):
436
+ Largest number of candidates.
437
+ window_size (`int`, *optional*, defaults to 10):
438
+ Number of recent tokens inspected for repetitions.
439
+ repetition_threshold (`float`, *optional*, defaults to 0.1):
440
+ Fraction of the window above which the drawn token is rejected.
441
+
442
+ Returns:
443
+ `list[list[int]]`: the speech tokens of every row, stop token excluded.
444
+ """
445
+ batch_size = input_ids.shape[0]
446
+ text_lengths = row_lengths(input_lengths, input_ids, batch_size)
447
+ prompt_text_lengths = row_lengths(prompt_input_lengths, prompt_input_ids, batch_size)
448
+ prompt_speech_lengths = row_lengths(prompt_speech_token_lengths, prompt_speech_token_ids, batch_size)
449
+
450
+ texts = []
451
+ for row in range(batch_size):
452
+ pieces = [input_ids[row, : text_lengths[row]]]
453
+ if prompt_input_ids is not None:
454
+ pieces.insert(0, prompt_input_ids[row, : prompt_text_lengths[row]])
455
+ texts.append(torch.concat(pieces))
456
+ packed_lengths = torch.tensor([text.shape[0] for text in texts], dtype=torch.int32, device=input_ids.device)
457
+ text_hidden_states = self.llm.encode_text(right_pad(texts), packed_lengths)
458
+
459
+ use_speaker = speaker_embedding is not None and speaker_embedding.shape[0] != 0
460
+ if use_speaker:
461
+ speaker_hidden_states = self.llm.encode_speaker(speaker_embedding)
462
+ sos_embed = self.llm.llm_embedding.weight[self.llm.sos_index].reshape(1, -1)
463
+ task_id_embed = self.llm.llm_embedding.weight[self.llm.task_id_index].reshape(1, -1)
464
+
465
+ sequences = []
466
+ for row in range(batch_size):
467
+ pieces = [sos_embed]
468
+ if use_speaker:
469
+ pieces.append(speaker_hidden_states[row])
470
+ pieces += [text_hidden_states[row, : int(packed_lengths[row])], task_id_embed]
471
+ if prompt_speech_token_ids is not None and prompt_speech_lengths[row] != 0:
472
+ pieces.append(self.llm.speech_embedding(prompt_speech_token_ids[row, : prompt_speech_lengths[row]]))
473
+ sequences.append(torch.concat(pieces))
474
+ hidden_states, padding_mask = left_pad(sequences)
475
+
476
+ min_lengths = [int(length * min_token_text_ratio) for length in text_lengths]
477
+ max_lengths = [int(length * max_token_text_ratio) for length in text_lengths]
478
+ decoded_tokens: list[list[int]] = [[] for _ in range(batch_size)]
479
+ finished = [False] * batch_size
480
+ past_key_values = None
481
+ for step in range(max(max_lengths)):
482
+ outputs, past_key_values = self.llm.llm(hidden_states, padding_mask, past_key_values)
483
+ log_probs = self.llm.llm_decoder(outputs[:, -1]).log_softmax(dim=-1)
484
+ next_tokens = sample_batch_step(
485
+ log_probs, step, decoded_tokens, finished, min_lengths, max_lengths, [self.llm.eos_token_id],
486
+ top_p, top_k, window_size, repetition_threshold,
487
+ )
488
+ if all(finished):
489
+ break
490
+ hidden_states = self.llm.speech_embedding.weight[next_tokens].unsqueeze(1)
491
+ padding_mask = torch.concat([padding_mask, padding_mask.new_ones(batch_size, 1)], dim=1)
492
+ return decoded_tokens
493
+
494
+ @torch.inference_mode()
495
+ def token2wav(
496
+ self,
497
+ speech_token_ids: torch.Tensor,
498
+ prompt_speech_token_ids: torch.Tensor,
499
+ prompt_speech_feat: torch.Tensor,
500
+ speaker_embedding: torch.Tensor,
501
+ state: dict,
502
+ finalize: bool = True,
503
+ speed: float = 1.0,
504
+ ) -> torch.Tensor:
505
+ """
506
+ Renders one chunk of speech tokens into a waveform.
507
+
508
+ Args:
509
+ speech_token_ids (`torch.Tensor` of shape `(1, speech_length)`):
510
+ Speech tokens of the chunk.
511
+ prompt_speech_token_ids (`torch.Tensor` of shape `(1, prompt_speech_length)`):
512
+ Speech tokens of the prompt utterance.
513
+ prompt_speech_feat (`torch.Tensor` of shape `(1, prompt_mel_length, flow_output_size)`):
514
+ Mel spectrogram of the prompt utterance.
515
+ speaker_embedding (`torch.Tensor` of shape `(1, speaker_embedding_dim)`):
516
+ Utterance level speaker embedding.
517
+ state (`dict`):
518
+ Mutable streaming state holding the flow matching cache, the mel overlap and the
519
+ vocoder cache.
520
+ finalize (`bool`, *optional*, defaults to `True`):
521
+ Whether this is the last chunk of the utterance.
522
+ speed (`float`, *optional*, defaults to 1.0):
523
+ Playback speed, only available on the last chunk of a non streaming call.
524
+
525
+ Returns:
526
+ `torch.Tensor` of shape `(1, num_samples)`: the waveform of the chunk.
527
+
528
+ Raises:
529
+ ValueError: If `speed` is changed while streaming.
530
+ """
531
+ device = speech_token_ids.device
532
+ mel, state["flow_cache"] = self.flow.inference(
533
+ speech_token_ids=speech_token_ids.to(device=device, dtype=torch.int32),
534
+ speech_token_lengths=torch.tensor([speech_token_ids.shape[1]], dtype=torch.int32, device=device),
535
+ prompt_token_ids=prompt_speech_token_ids.to(device=device, dtype=torch.int32),
536
+ prompt_token_lengths=torch.tensor(
537
+ [prompt_speech_token_ids.shape[1]], dtype=torch.int32, device=device
538
+ ),
539
+ prompt_feat=prompt_speech_feat.to(device),
540
+ speaker_embedding=speaker_embedding.to(device),
541
+ num_steps=self.config.num_flow_inference_steps,
542
+ cache=state["flow_cache"],
543
+ )
544
+
545
+ if state["mel_overlap"].shape[2] != 0:
546
+ mel = fade_in_out(mel, state["mel_overlap"], state["mel_window"])
547
+
548
+ if state["hift_cache"] is not None:
549
+ mel = torch.concat([state["hift_cache"]["mel"], mel], dim=2)
550
+ cache_source = state["hift_cache"]["source"]
551
+ else:
552
+ cache_source = mel.new_zeros(1, 1, 0)
553
+
554
+ if not finalize:
555
+ state["mel_overlap"] = mel[:, :, -state["mel_overlap_len"] :]
556
+ mel = mel[:, :, : -state["mel_overlap_len"]]
557
+ waveform, source = self.hift.inference(mel, cache_source)
558
+ if state["hift_cache"] is not None:
559
+ waveform = fade_in_out(waveform, state["hift_cache"]["speech"], state["speech_window"])
560
+ state["hift_cache"] = {
561
+ "mel": mel[:, :, -self.mel_cache_len :],
562
+ "source": source[:, :, -state["source_cache_len"] :],
563
+ "speech": waveform[:, -state["source_cache_len"] :],
564
+ }
565
+ return waveform[:, : -state["source_cache_len"]]
566
+
567
+ if speed != 1.0:
568
+ if state["hift_cache"] is not None:
569
+ raise ValueError("speed can only be changed in non streaming mode")
570
+ mel = F.interpolate(mel, size=int(mel.shape[2] / speed), mode="linear")
571
+ waveform, _ = self.hift.inference(mel, cache_source)
572
+ if state["hift_cache"] is not None:
573
+ waveform = fade_in_out(waveform, state["hift_cache"]["speech"], state["speech_window"])
574
+ return waveform
575
+
576
+ def init_streaming_state(self) -> dict:
577
+ """
578
+ Returns:
579
+ `dict`: a fresh streaming state for [`~CosyVoiceV1GenerationMixin.token2wav`].
580
+ """
581
+ mel_overlap_len = int(self.token_overlap_len / self.config.flow_input_frame_rate * 22050 / 256)
582
+ source_cache_len = int(self.mel_cache_len * 256)
583
+ return {
584
+ "flow_cache": None,
585
+ "mel_overlap": torch.zeros(1, self.config.flow_output_size, 0),
586
+ "mel_overlap_len": mel_overlap_len,
587
+ "mel_window": torch.from_numpy(np.hamming(2 * mel_overlap_len).astype(np.float32)),
588
+ "hift_cache": None,
589
+ "source_cache_len": source_cache_len,
590
+ "speech_window": torch.from_numpy(np.hamming(2 * source_cache_len).astype(np.float32)),
591
+ }
592
+
593
+ def generate(
594
+ self,
595
+ input_ids: torch.Tensor,
596
+ speaker_embedding: torch.Tensor,
597
+ prompt_input_ids: Optional[torch.Tensor] = None,
598
+ prompt_speech_token_ids: Optional[torch.Tensor] = None,
599
+ flow_prompt_speech_token_ids: Optional[torch.Tensor] = None,
600
+ prompt_speech_feat: Optional[torch.Tensor] = None,
601
+ source_speech_token_ids: Optional[torch.Tensor] = None,
602
+ stream: bool = False,
603
+ speed: float = 1.0,
604
+ input_lengths: Optional[torch.Tensor] = None,
605
+ prompt_input_lengths: Optional[torch.Tensor] = None,
606
+ prompt_speech_token_lengths: Optional[torch.Tensor] = None,
607
+ flow_prompt_speech_token_lengths: Optional[torch.Tensor] = None,
608
+ prompt_speech_feat_lengths: Optional[torch.Tensor] = None,
609
+ source_speech_token_lengths: Optional[torch.Tensor] = None,
610
+ **sampling_kwargs,
611
+ ) -> "torch.Tensor | list[torch.Tensor] | Generator[torch.Tensor, None, None]":
612
+ """
613
+ Synthesizes one utterance, or a batch of utterances decoded together.
614
+
615
+ A batch is the right padded output of the processor, with the lengths it returns passed
616
+ alongside. Its rows share one language model loop and one pass of the flow matching model,
617
+ each row masked to its own text, prompt, speaker embedding and length, and the vocoder then
618
+ renders every row on its own. With deterministic sampling every row comes out as it would on
619
+ its own, up to floating point rounding.
620
+
621
+ Args:
622
+ input_ids (`torch.Tensor` of shape `(batch_size, text_length)`):
623
+ Text token ids of the sentences to synthesize.
624
+ speaker_embedding (`torch.Tensor` of shape `(batch_size, speaker_embedding_dim)`):
625
+ Utterance level speaker embedding.
626
+ prompt_input_ids (`torch.Tensor` of shape `(batch_size, prompt_text_length)`, *optional*):
627
+ Text token ids of the prompt utterance, prepended to `input_ids` before the text
628
+ encoder runs.
629
+ prompt_speech_token_ids (`torch.Tensor` of shape `(batch_size, prompt_speech_length)`, *optional*):
630
+ Speech tokens of the prompt utterance the language model continues from. Leaving it
631
+ out while `flow_prompt_speech_token_ids` is given is what makes the generation
632
+ cross lingual: the language model then only sees the speaker embedding.
633
+ flow_prompt_speech_token_ids (`torch.Tensor` of shape `(batch_size, prompt_speech_length)`, *optional*):
634
+ Speech tokens the flow matching model is conditioned on, alongside
635
+ `prompt_speech_feat`. Defaults to `prompt_speech_token_ids`.
636
+ prompt_speech_feat (`torch.Tensor` of shape `(batch_size, prompt_mel_length, flow_output_size)`, *optional*):
637
+ Mel spectrogram of the prompt utterance.
638
+ source_speech_token_ids (`torch.Tensor` of shape `(batch_size, speech_length)`, *optional*):
639
+ Speech tokens to render directly, which bypasses the language model and performs voice
640
+ conversion instead of text to speech.
641
+ stream (`bool`, *optional*, defaults to `False`):
642
+ Whether to return a generator yielding the waveform chunk by chunk instead of the
643
+ whole waveform. Only available for a single utterance.
644
+ speed (`float`, *optional*, defaults to 1.0):
645
+ Playback speed, only available when `stream` is `False`.
646
+ input_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
647
+ Number of valid tokens of every row of `input_ids`. Defaults to its full width.
648
+ prompt_input_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
649
+ Number of valid tokens of every row of `prompt_input_ids`.
650
+ prompt_speech_token_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
651
+ Number of valid tokens of every row of `prompt_speech_token_ids`.
652
+ flow_prompt_speech_token_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
653
+ Number of valid tokens of every row of `flow_prompt_speech_token_ids`. Defaults to
654
+ `prompt_speech_token_lengths` when `flow_prompt_speech_token_ids` is left out.
655
+ prompt_speech_feat_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
656
+ Number of valid frames of every row of `prompt_speech_feat`, the processor's
657
+ `speech_feat_lengths`.
658
+ source_speech_token_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
659
+ Number of valid tokens of every row of `source_speech_token_ids`.
660
+ sampling_kwargs:
661
+ Forwarded to [`~CosyVoiceV1GenerationMixin.generate_speech_tokens`], or to
662
+ [`~CosyVoiceV1GenerationMixin.generate_speech_tokens_batch`] for a batch.
663
+
664
+ Returns:
665
+ For a single utterance, a `torch.Tensor` of shape `(1, num_samples)`, or a generator of
666
+ such tensors when `stream` is `True`. For a batch, a list holding one `torch.Tensor` of
667
+ shape `(1, num_samples)` per row, each as long as that row's own waveform, the way
668
+ [`CsmForConditionalGeneration`] returns a batch of audio.
669
+
670
+ Raises:
671
+ ValueError: If `stream` is `True` for a batch of more than one utterance.
672
+ """
673
+ batch_size = input_ids.shape[0] if source_speech_token_ids is None else source_speech_token_ids.shape[0]
674
+ if flow_prompt_speech_token_ids is None:
675
+ flow_prompt_speech_token_ids = prompt_speech_token_ids
676
+ if flow_prompt_speech_token_lengths is None:
677
+ flow_prompt_speech_token_lengths = prompt_speech_token_lengths
678
+ if batch_size != 1:
679
+ if stream:
680
+ raise ValueError(
681
+ f"stream=True synthesizes one utterance at a time but the batch holds {batch_size}; "
682
+ "use stream=False to decode the batch together, or split it with `processor.unbatch` "
683
+ "and stream each item"
684
+ )
685
+ return self._generate_batch(
686
+ input_ids,
687
+ speaker_embedding,
688
+ prompt_input_ids,
689
+ prompt_speech_token_ids,
690
+ flow_prompt_speech_token_ids,
691
+ prompt_speech_feat,
692
+ source_speech_token_ids,
693
+ speed,
694
+ input_lengths,
695
+ prompt_input_lengths,
696
+ prompt_speech_token_lengths,
697
+ flow_prompt_speech_token_lengths,
698
+ prompt_speech_feat_lengths,
699
+ source_speech_token_lengths,
700
+ **sampling_kwargs,
701
+ )
702
+ input_ids, prompt_input_ids, prompt_speech_token_ids, flow_prompt_speech_token_ids = (
703
+ trim_row(tensor, lengths)
704
+ for tensor, lengths in (
705
+ (input_ids, input_lengths),
706
+ (prompt_input_ids, prompt_input_lengths),
707
+ (prompt_speech_token_ids, prompt_speech_token_lengths),
708
+ (flow_prompt_speech_token_ids, flow_prompt_speech_token_lengths),
709
+ )
710
+ )
711
+ prompt_speech_feat = trim_row(prompt_speech_feat, prompt_speech_feat_lengths)
712
+ source_speech_token_ids = trim_row(source_speech_token_ids, source_speech_token_lengths)
713
+ if stream:
714
+ return self._generate_stream(
715
+ input_ids,
716
+ speaker_embedding,
717
+ prompt_input_ids,
718
+ prompt_speech_token_ids,
719
+ flow_prompt_speech_token_ids,
720
+ prompt_speech_feat,
721
+ source_speech_token_ids,
722
+ **sampling_kwargs,
723
+ )
724
+ return self._generate_single(
725
+ input_ids,
726
+ speaker_embedding,
727
+ prompt_input_ids,
728
+ prompt_speech_token_ids,
729
+ flow_prompt_speech_token_ids,
730
+ prompt_speech_feat,
731
+ source_speech_token_ids,
732
+ speed,
733
+ **sampling_kwargs,
734
+ )
735
+
736
+ def _speech_token_batch(
737
+ self,
738
+ input_ids: torch.Tensor,
739
+ speaker_embedding: torch.Tensor,
740
+ input_lengths: Optional[torch.Tensor],
741
+ prompt_input_ids: Optional[torch.Tensor],
742
+ prompt_input_lengths: Optional[torch.Tensor],
743
+ prompt_speech_token_ids: Optional[torch.Tensor],
744
+ prompt_speech_token_lengths: Optional[torch.Tensor],
745
+ source_speech_token_ids: Optional[torch.Tensor],
746
+ source_speech_token_lengths: Optional[torch.Tensor],
747
+ **sampling_kwargs,
748
+ ) -> list[list[int]]:
749
+ if source_speech_token_ids is not None:
750
+ lengths = row_lengths(source_speech_token_lengths, source_speech_token_ids, 0)
751
+ return [source_speech_token_ids[row, : lengths[row]].tolist() for row in range(len(lengths))]
752
+ return self.generate_speech_tokens_batch(
753
+ input_ids,
754
+ speaker_embedding,
755
+ input_lengths=input_lengths,
756
+ prompt_input_ids=prompt_input_ids,
757
+ prompt_input_lengths=prompt_input_lengths,
758
+ prompt_speech_token_ids=prompt_speech_token_ids,
759
+ prompt_speech_token_lengths=prompt_speech_token_lengths,
760
+ **sampling_kwargs,
761
+ )
762
+
763
+ def _render_batch(
764
+ self,
765
+ tokens: list[list[int]],
766
+ speaker_embedding: torch.Tensor,
767
+ flow_prompt_speech_token_ids: Optional[torch.Tensor],
768
+ flow_prompt_speech_token_lengths: Optional[torch.Tensor],
769
+ prompt_speech_feat: Optional[torch.Tensor],
770
+ prompt_speech_feat_lengths: Optional[torch.Tensor],
771
+ ) -> list[torch.Tensor]:
772
+ device = self.device
773
+ batch_size = len(tokens)
774
+ speech_token_ids = right_pad(
775
+ [torch.tensor(row, dtype=torch.int32, device=device) for row in tokens]
776
+ )
777
+ speech_token_lengths = torch.tensor([len(row) for row in tokens], dtype=torch.int32, device=device)
778
+ if flow_prompt_speech_token_ids is None:
779
+ flow_prompt_speech_token_ids = torch.zeros(batch_size, 0, dtype=torch.int32, device=device)
780
+ if prompt_speech_feat is None:
781
+ prompt_speech_feat = torch.zeros(batch_size, 0, self.config.flow_output_size, device=device)
782
+ prompt_lengths = row_lengths(flow_prompt_speech_token_lengths, flow_prompt_speech_token_ids, batch_size)
783
+ feat_lengths = row_lengths(prompt_speech_feat_lengths, prompt_speech_feat, batch_size)
784
+ return self.flow.batch_inference(
785
+ speech_token_ids=speech_token_ids,
786
+ speech_token_lengths=speech_token_lengths,
787
+ prompt_token_ids=flow_prompt_speech_token_ids.to(device=device, dtype=torch.int32),
788
+ prompt_token_lengths=torch.tensor(prompt_lengths, dtype=torch.int32, device=device),
789
+ prompt_feat=prompt_speech_feat.to(device),
790
+ prompt_feat_lengths=torch.tensor(feat_lengths, dtype=torch.int32, device=device),
791
+ speaker_embedding=speaker_embedding.to(device),
792
+ num_steps=self.config.num_flow_inference_steps,
793
+ )
794
+
795
+ def _vocode(self, mel: torch.Tensor, speed: float) -> torch.Tensor:
796
+ """
797
+ Renders the mel spectrogram of one utterance the way the last chunk of
798
+ [`~CosyVoiceV1GenerationMixin.token2wav`] does when nothing was streamed before it.
799
+ """
800
+ if speed != 1.0:
801
+ mel = F.interpolate(mel, size=int(mel.shape[2] / speed), mode="linear")
802
+ waveform, _ = self.hift.inference(mel, mel.new_zeros(1, 1, 0))
803
+ return waveform
804
+
805
+ @torch.inference_mode()
806
+ def _generate_batch(
807
+ self,
808
+ input_ids: torch.Tensor,
809
+ speaker_embedding: torch.Tensor,
810
+ prompt_input_ids: Optional[torch.Tensor],
811
+ prompt_speech_token_ids: Optional[torch.Tensor],
812
+ flow_prompt_speech_token_ids: Optional[torch.Tensor],
813
+ prompt_speech_feat: Optional[torch.Tensor],
814
+ source_speech_token_ids: Optional[torch.Tensor],
815
+ speed: float,
816
+ input_lengths: Optional[torch.Tensor],
817
+ prompt_input_lengths: Optional[torch.Tensor],
818
+ prompt_speech_token_lengths: Optional[torch.Tensor],
819
+ flow_prompt_speech_token_lengths: Optional[torch.Tensor],
820
+ prompt_speech_feat_lengths: Optional[torch.Tensor],
821
+ source_speech_token_lengths: Optional[torch.Tensor],
822
+ **sampling_kwargs,
823
+ ) -> list[torch.Tensor]:
824
+ tokens = self._speech_token_batch(
825
+ input_ids, speaker_embedding, input_lengths, prompt_input_ids, prompt_input_lengths,
826
+ prompt_speech_token_ids, prompt_speech_token_lengths, source_speech_token_ids,
827
+ source_speech_token_lengths, **sampling_kwargs,
828
+ )
829
+ mels = self._render_batch(
830
+ tokens, speaker_embedding, flow_prompt_speech_token_ids, flow_prompt_speech_token_lengths,
831
+ prompt_speech_feat, prompt_speech_feat_lengths,
832
+ )
833
+ # The vocoder's convolutions are not masked and would read the padding past the end of a
834
+ # shorter row, so every row is rendered at its own length.
835
+ return [self._vocode(mel, speed) for mel in mels]
836
+
837
+ def _speech_token_stream(
838
+ self,
839
+ input_ids: torch.Tensor,
840
+ speaker_embedding: torch.Tensor,
841
+ prompt_input_ids: Optional[torch.Tensor],
842
+ prompt_speech_token_ids: Optional[torch.Tensor],
843
+ source_speech_token_ids: Optional[torch.Tensor],
844
+ **sampling_kwargs,
845
+ ):
846
+ if source_speech_token_ids is not None:
847
+ return iter(source_speech_token_ids.flatten().tolist())
848
+ return self.generate_speech_tokens(
849
+ input_ids,
850
+ speaker_embedding,
851
+ prompt_input_ids=prompt_input_ids,
852
+ prompt_speech_token_ids=prompt_speech_token_ids,
853
+ **sampling_kwargs,
854
+ )
855
+
856
+ @torch.inference_mode()
857
+ def _generate_single(
858
+ self,
859
+ input_ids: torch.Tensor,
860
+ speaker_embedding: torch.Tensor,
861
+ prompt_input_ids: Optional[torch.Tensor],
862
+ prompt_speech_token_ids: Optional[torch.Tensor],
863
+ flow_prompt_speech_token_ids: Optional[torch.Tensor],
864
+ prompt_speech_feat: Optional[torch.Tensor],
865
+ source_speech_token_ids: Optional[torch.Tensor],
866
+ speed: float,
867
+ **sampling_kwargs,
868
+ ) -> torch.Tensor:
869
+ device = input_ids.device
870
+ if flow_prompt_speech_token_ids is None:
871
+ flow_prompt_speech_token_ids = input_ids.new_zeros(1, 0)
872
+ if prompt_speech_feat is None:
873
+ prompt_speech_feat = torch.zeros(1, 0, self.config.flow_output_size, device=device)
874
+
875
+ state = self.init_streaming_state()
876
+ token_stream = self._speech_token_stream(
877
+ input_ids, speaker_embedding, prompt_input_ids, prompt_speech_token_ids,
878
+ source_speech_token_ids, **sampling_kwargs,
879
+ )
880
+ tokens = list(token_stream)
881
+ speech_token_ids = torch.tensor([tokens], dtype=torch.int32, device=device)
882
+ return self.token2wav(
883
+ speech_token_ids, flow_prompt_speech_token_ids, prompt_speech_feat, speaker_embedding, state,
884
+ finalize=True, speed=speed,
885
+ )
886
+
887
+ @torch.inference_mode()
888
+ def _generate_stream(
889
+ self,
890
+ input_ids: torch.Tensor,
891
+ speaker_embedding: torch.Tensor,
892
+ prompt_input_ids: Optional[torch.Tensor],
893
+ prompt_speech_token_ids: Optional[torch.Tensor],
894
+ flow_prompt_speech_token_ids: Optional[torch.Tensor],
895
+ prompt_speech_feat: Optional[torch.Tensor],
896
+ source_speech_token_ids: Optional[torch.Tensor],
897
+ **sampling_kwargs,
898
+ ) -> Generator[torch.Tensor, None, None]:
899
+ device = input_ids.device
900
+ if flow_prompt_speech_token_ids is None:
901
+ flow_prompt_speech_token_ids = input_ids.new_zeros(1, 0)
902
+ if prompt_speech_feat is None:
903
+ prompt_speech_feat = torch.zeros(1, 0, self.config.flow_output_size, device=device)
904
+
905
+ state = self.init_streaming_state()
906
+ token_stream = self._speech_token_stream(
907
+ input_ids, speaker_embedding, prompt_input_ids, prompt_speech_token_ids,
908
+ source_speech_token_ids, **sampling_kwargs,
909
+ )
910
+
911
+ token_hop_len = 2 * self.config.flow_input_frame_rate
912
+ token_max_hop_len = 4 * self.config.flow_input_frame_rate
913
+ tokens: list[int] = []
914
+ for token_id in token_stream:
915
+ tokens.append(token_id)
916
+ while len(tokens) >= token_hop_len + self.token_overlap_len:
917
+ chunk = torch.tensor([tokens[: token_hop_len + self.token_overlap_len]], dtype=torch.int32, device=device)
918
+ yield self.token2wav(
919
+ chunk, flow_prompt_speech_token_ids, prompt_speech_feat, speaker_embedding, state,
920
+ finalize=False,
921
+ )
922
+ tokens = tokens[token_hop_len:]
923
+ token_hop_len = min(token_max_hop_len, int(token_hop_len * self.stream_scale_factor))
924
+ chunk = torch.tensor([tokens], dtype=torch.int32, device=device)
925
+ yield self.token2wav(
926
+ chunk, flow_prompt_speech_token_ids, prompt_speech_feat, speaker_embedding, state, finalize=True
927
+ )
928
+
929
+
930
+ class CosyVoiceV2GenerationMixin:
931
+ """
932
+ Speech token decoding and token to waveform rendering for [`CosyVoiceV2ForConditionalGeneration`].
933
+
934
+ The Qwen2 language model samples speech tokens one at a time with repetition aware sampling and a
935
+ key value cache, the flow matching model turns the whole sequence decoded so far into a mel
936
+ spectrogram, and the vocoder renders the waveform. In streaming mode each chunk re-encodes the
937
+ sequence from its start and `token_offset` selects the mel frames that were not rendered yet, so
938
+ only the vocoder carries a cache across chunks.
939
+ """
940
+
941
+ token_hop_len = 25
942
+ stream_scale_factor = 2
943
+ mel_cache_len = 8
944
+
945
+ def generate_speech_tokens(
946
+ self,
947
+ input_ids: Union[torch.Tensor, Iterator[torch.Tensor]],
948
+ prompt_input_ids: Optional[torch.Tensor] = None,
949
+ prompt_speech_token_ids: Optional[torch.Tensor] = None,
950
+ min_token_text_ratio: float = 2.0,
951
+ max_token_text_ratio: float = 20.0,
952
+ top_p: float = 0.8,
953
+ top_k: int = 25,
954
+ window_size: int = 10,
955
+ repetition_threshold: float = 0.1,
956
+ ) -> Generator[int, None, None]:
957
+ """
958
+ Samples speech tokens for one utterance and yields them one at a time.
959
+
960
+ Args:
961
+ input_ids (`torch.Tensor` of shape `(1, text_length)`, or a generator of such tensors):
962
+ Text token ids of the sentence to synthesize. A generator selects the interleaved
963
+ layout instead: the text is read as it arrives and speech tokens are decoded between
964
+ the groups, in the same `mix_ratio` proportion the interleaved training layout uses.
965
+ `min_token_text_ratio` and `max_token_text_ratio` are not used there, since the text
966
+ length is not known while decoding.
967
+ prompt_input_ids (`torch.Tensor` of shape `(1, prompt_text_length)`, *optional*):
968
+ Text token ids of the prompt utterance, prepended to `input_ids`.
969
+ prompt_speech_token_ids (`torch.Tensor` of shape `(1, prompt_speech_length)`, *optional*):
970
+ Speech tokens of the prompt utterance the language model continues from.
971
+ min_token_text_ratio (`float`, *optional*, defaults to 2.0):
972
+ Smallest number of speech tokens generated per text token.
973
+ max_token_text_ratio (`float`, *optional*, defaults to 20.0):
974
+ Largest number of speech tokens generated per text token.
975
+ top_p (`float`, *optional*, defaults to 0.8):
976
+ Cumulative probability the candidate set is grown to.
977
+ top_k (`int`, *optional*, defaults to 25):
978
+ Largest number of candidates.
979
+ window_size (`int`, *optional*, defaults to 10):
980
+ Number of recent tokens inspected for repetitions.
981
+ repetition_threshold (`float`, *optional*, defaults to 0.1):
982
+ Fraction of the window above which the drawn token is rejected.
983
+
984
+ Yields:
985
+ `int`: the next speech token id.
986
+ """
987
+ if isinstance(input_ids, GeneratorType):
988
+ return self._decode_interleaved(
989
+ input_ids,
990
+ prompt_input_ids,
991
+ prompt_speech_token_ids,
992
+ top_p,
993
+ top_k,
994
+ window_size,
995
+ repetition_threshold,
996
+ )
997
+ return self._decode(
998
+ input_ids,
999
+ prompt_input_ids,
1000
+ prompt_speech_token_ids,
1001
+ min_token_text_ratio,
1002
+ max_token_text_ratio,
1003
+ top_p,
1004
+ top_k,
1005
+ window_size,
1006
+ repetition_threshold,
1007
+ )
1008
+
1009
+ def split_prompt_text(self, prompt_input_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
1010
+ """
1011
+ Splits the prompt text of an interleaved decode into the part that opens the sequence and the
1012
+ part that is interleaved with the speech tokens.
1013
+
1014
+ Args:
1015
+ prompt_input_ids (`torch.Tensor` of shape `(1, prompt_text_length)`):
1016
+ Text token ids of the prompt utterance.
1017
+
1018
+ Returns:
1019
+ `tuple[torch.Tensor, torch.Tensor]`: the opening part, empty in v2, and the interleaved
1020
+ part.
1021
+ """
1022
+ return prompt_input_ids[:, :0], prompt_input_ids
1023
+
1024
+ @torch.inference_mode()
1025
+ def _decode(
1026
+ self,
1027
+ input_ids: torch.Tensor,
1028
+ prompt_input_ids: Optional[torch.Tensor],
1029
+ prompt_speech_token_ids: Optional[torch.Tensor],
1030
+ min_token_text_ratio: float,
1031
+ max_token_text_ratio: float,
1032
+ top_p: float,
1033
+ top_k: int,
1034
+ window_size: int,
1035
+ repetition_threshold: float,
1036
+ ) -> Generator[int, None, None]:
1037
+ text_length = input_ids.shape[1]
1038
+ if prompt_input_ids is None:
1039
+ prompt_input_ids = input_ids.new_zeros(1, 0)
1040
+ input_ids = torch.concat([prompt_input_ids, input_ids], dim=1)
1041
+ text_embeds = self.llm.embed_text(input_ids)
1042
+
1043
+ sos_embed = self.llm.llm_embedding.weight[self.llm.sos_index].reshape(1, 1, -1)
1044
+ task_id_embed = self.llm.llm_embedding.weight[self.llm.task_id_index].reshape(1, 1, -1)
1045
+ if prompt_speech_token_ids is not None and prompt_speech_token_ids.shape[1] != 0:
1046
+ prompt_embeds = self.llm.speech_embedding(prompt_speech_token_ids)
1047
+ else:
1048
+ prompt_embeds = text_embeds.new_zeros(1, 0, self.config.lm_hidden_size)
1049
+ hidden_states = torch.concat([sos_embed, text_embeds, task_id_embed, prompt_embeds], dim=1)
1050
+
1051
+ min_length = int(text_length * min_token_text_ratio)
1052
+ max_length = int(text_length * max_token_text_ratio)
1053
+
1054
+ decoded_tokens: list[int] = []
1055
+ past_key_values = None
1056
+ for step in range(max_length):
1057
+ logits, past_key_values = self.llm(hidden_states, past_key_values=past_key_values, use_cache=True)
1058
+ log_probs = logits[:, -1].log_softmax(dim=-1).squeeze(dim=0)
1059
+ if step < min_length:
1060
+ # Any stop token ends decoding below, so every one of them is masked.
1061
+ log_probs[self.llm.stop_token_ids] = -float("inf")
1062
+ token_id = repetition_aware_sampling(
1063
+ log_probs, decoded_tokens, top_p, top_k, window_size, repetition_threshold
1064
+ )
1065
+ if token_id in self.llm.stop_token_ids:
1066
+ break
1067
+ yield token_id
1068
+ decoded_tokens.append(token_id)
1069
+ hidden_states = self.llm.speech_embedding.weight[token_id].reshape(1, 1, -1)
1070
+
1071
+ @torch.inference_mode()
1072
+ def generate_speech_tokens_batch(
1073
+ self,
1074
+ input_ids: torch.Tensor,
1075
+ input_lengths: Optional[torch.Tensor] = None,
1076
+ prompt_input_ids: Optional[torch.Tensor] = None,
1077
+ prompt_input_lengths: Optional[torch.Tensor] = None,
1078
+ prompt_speech_token_ids: Optional[torch.Tensor] = None,
1079
+ prompt_speech_token_lengths: Optional[torch.Tensor] = None,
1080
+ min_token_text_ratio: float = 2.0,
1081
+ max_token_text_ratio: float = 20.0,
1082
+ top_p: float = 0.8,
1083
+ top_k: int = 25,
1084
+ window_size: int = 10,
1085
+ repetition_threshold: float = 0.1,
1086
+ ) -> list[list[int]]:
1087
+ """
1088
+ Samples speech tokens for a right padded batch of utterances in one decoding loop that shares
1089
+ the key value cache across rows.
1090
+
1091
+ Every row is packed as the unistream layout of
1092
+ [`~CosyVoiceV2GenerationMixin.generate_speech_tokens`] packs it, then the rows are left padded
1093
+ so that they all end on the step being decoded. The attention mask hides the padding and the
1094
+ position ids restart at 0 on every row's first real step, so a row sees the positions it would
1095
+ see on its own. Each row keeps its own minimum and maximum length, computed from its own text
1096
+ length, its own stop handling and its own repetition aware sampling history. A row that has
1097
+ finished keeps being fed so that the batch stays aligned, and its outputs are discarded.
1098
+
1099
+ Args:
1100
+ input_ids (`torch.Tensor` of shape `(batch_size, text_length)`):
1101
+ Text token ids of the sentences to synthesize, right padded.
1102
+ input_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
1103
+ Number of text tokens of every row. Defaults to the full width of `input_ids`.
1104
+ prompt_input_ids (`torch.Tensor` of shape `(batch_size, prompt_text_length)`, *optional*):
1105
+ Text token ids of the prompt utterances, right padded.
1106
+ prompt_input_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
1107
+ Number of prompt text tokens of every row.
1108
+ prompt_speech_token_ids (`torch.Tensor` of shape `(batch_size, prompt_speech_length)`, *optional*):
1109
+ Speech tokens of the prompt utterances, right padded.
1110
+ prompt_speech_token_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
1111
+ Number of prompt speech tokens of every row.
1112
+ min_token_text_ratio (`float`, *optional*, defaults to 2.0):
1113
+ Smallest number of speech tokens generated per text token of the row.
1114
+ max_token_text_ratio (`float`, *optional*, defaults to 20.0):
1115
+ Largest number of speech tokens generated per text token of the row.
1116
+ top_p (`float`, *optional*, defaults to 0.8):
1117
+ Cumulative probability the candidate set is grown to.
1118
+ top_k (`int`, *optional*, defaults to 25):
1119
+ Largest number of candidates.
1120
+ window_size (`int`, *optional*, defaults to 10):
1121
+ Number of recent tokens inspected for repetitions.
1122
+ repetition_threshold (`float`, *optional*, defaults to 0.1):
1123
+ Fraction of the window above which the drawn token is rejected.
1124
+
1125
+ Returns:
1126
+ `list[list[int]]`: the speech tokens of every row, stop token excluded.
1127
+ """
1128
+ batch_size = input_ids.shape[0]
1129
+ text_lengths = row_lengths(input_lengths, input_ids, batch_size)
1130
+ prompt_text_lengths = row_lengths(prompt_input_lengths, prompt_input_ids, batch_size)
1131
+ prompt_speech_lengths = row_lengths(prompt_speech_token_lengths, prompt_speech_token_ids, batch_size)
1132
+ sos_embed = self.llm.llm_embedding.weight[self.llm.sos_index].reshape(1, -1)
1133
+ task_id_embed = self.llm.llm_embedding.weight[self.llm.task_id_index].reshape(1, -1)
1134
+
1135
+ sequences = []
1136
+ for row in range(batch_size):
1137
+ text = input_ids[row, : text_lengths[row]]
1138
+ if prompt_input_ids is not None:
1139
+ text = torch.concat([prompt_input_ids[row, : prompt_text_lengths[row]], text])
1140
+ pieces = [sos_embed, self.llm.embed_text(text), task_id_embed]
1141
+ if prompt_speech_token_ids is not None and prompt_speech_lengths[row] != 0:
1142
+ pieces.append(self.llm.speech_embedding(prompt_speech_token_ids[row, : prompt_speech_lengths[row]]))
1143
+ sequences.append(torch.concat(pieces))
1144
+ hidden_states, attention_mask = left_pad(sequences)
1145
+ attention_mask = attention_mask.long()
1146
+ position_ids = (attention_mask.cumsum(dim=-1) - 1).clamp(min=0)
1147
+
1148
+ min_lengths = [int(length * min_token_text_ratio) for length in text_lengths]
1149
+ max_lengths = [int(length * max_token_text_ratio) for length in text_lengths]
1150
+ decoded_tokens: list[list[int]] = [[] for _ in range(batch_size)]
1151
+ finished = [False] * batch_size
1152
+ past_key_values = None
1153
+ for step in range(max(max_lengths)):
1154
+ outputs = self.llm.model(
1155
+ inputs_embeds=hidden_states,
1156
+ attention_mask=attention_mask,
1157
+ position_ids=position_ids,
1158
+ past_key_values=past_key_values,
1159
+ use_cache=True,
1160
+ )
1161
+ past_key_values = outputs.past_key_values
1162
+ log_probs = self.llm.llm_decoder(outputs.last_hidden_state[:, -1]).log_softmax(dim=-1)
1163
+ next_tokens = sample_batch_step(
1164
+ log_probs, step, decoded_tokens, finished, min_lengths, max_lengths, self.llm.stop_token_ids,
1165
+ top_p, top_k, window_size, repetition_threshold,
1166
+ )
1167
+ if all(finished):
1168
+ break
1169
+ hidden_states = self.llm.speech_embedding.weight[next_tokens].unsqueeze(1)
1170
+ attention_mask = torch.concat([attention_mask, attention_mask.new_ones(batch_size, 1)], dim=1)
1171
+ position_ids = position_ids[:, -1:] + 1
1172
+ return decoded_tokens
1173
+
1174
+ @torch.inference_mode()
1175
+ def _decode_interleaved(
1176
+ self,
1177
+ input_ids: Iterator[torch.Tensor],
1178
+ prompt_input_ids: Optional[torch.Tensor],
1179
+ prompt_speech_token_ids: Optional[torch.Tensor],
1180
+ top_p: float,
1181
+ top_k: int,
1182
+ window_size: int,
1183
+ repetition_threshold: float,
1184
+ ) -> Generator[int, None, None]:
1185
+ text_ratio, speech_ratio = self.llm.mix_ratio
1186
+ sos_embed = self.llm.llm_embedding.weight[self.llm.sos_index].reshape(1, 1, -1)
1187
+ task_id_embed = self.llm.llm_embedding.weight[self.llm.task_id_index].reshape(1, 1, -1)
1188
+
1189
+ if prompt_input_ids is None:
1190
+ prompt_input_ids = torch.zeros(1, 0, dtype=torch.int32, device=sos_embed.device)
1191
+ opening_ids, interleaved_ids = self.split_prompt_text(prompt_input_ids)
1192
+ hidden_states = torch.concat([sos_embed, self.llm.embed_text(opening_ids)], dim=1)
1193
+ text_cache = self.llm.embed_text(interleaved_ids)
1194
+
1195
+ prompt_length = 0 if prompt_speech_token_ids is None else prompt_speech_token_ids.shape[1]
1196
+ if prompt_length != 0:
1197
+ prompt_embeds = self.llm.speech_embedding(prompt_speech_token_ids)
1198
+ else:
1199
+ prompt_embeds = sos_embed.new_zeros(1, 0, self.config.lm_hidden_size)
1200
+ # The prompt speech tokens stand in for the speech tokens of the groups they fill, so the
1201
+ # first fill token falls where the group they end in would have ended.
1202
+ next_fill_index = (prompt_length // speech_ratio + 1) * speech_ratio - prompt_length
1203
+
1204
+ decoded_tokens: list[int] = []
1205
+ past_key_values = None
1206
+ for chunk in input_ids:
1207
+ text_cache = torch.concat([text_cache, self.llm.embed_text(chunk)], dim=1)
1208
+ while prompt_embeds.shape[1] != 0 and text_cache.shape[1] >= text_ratio:
1209
+ hidden_states = torch.concat(
1210
+ [hidden_states, text_cache[:, :text_ratio], prompt_embeds[:, :speech_ratio]], dim=1
1211
+ )
1212
+ text_cache = text_cache[:, text_ratio:]
1213
+ prompt_embeds = prompt_embeds[:, speech_ratio:]
1214
+ if prompt_embeds.shape[1] != 0:
1215
+ continue
1216
+ opening = not decoded_tokens and hidden_states.shape[1] == 1
1217
+ if opening or decoded_tokens[-1:] == [self.llm.fill_token_id]:
1218
+ if text_cache.shape[1] < text_ratio:
1219
+ continue
1220
+ group = text_cache[:, :text_ratio]
1221
+ # A fill token closes a group, so the cache already holds everything before the one
1222
+ # the model is being handed here.
1223
+ hidden_states = torch.concat([hidden_states, group], dim=1) if opening else group
1224
+ text_cache = text_cache[:, text_ratio:]
1225
+ while True:
1226
+ logits, past_key_values = self.llm(hidden_states, past_key_values=past_key_values, use_cache=True)
1227
+ log_probs = logits[:, -1].log_softmax(dim=-1).squeeze(dim=0)
1228
+ log_probs[self.llm.eos_token_id] = -float("inf")
1229
+ if len(decoded_tokens) == next_fill_index:
1230
+ token_id = self.llm.fill_token_id
1231
+ else:
1232
+ token_id = repetition_aware_sampling(
1233
+ log_probs, decoded_tokens, top_p, top_k, window_size, repetition_threshold
1234
+ )
1235
+ if token_id == self.llm.fill_token_id:
1236
+ next_fill_index = len(decoded_tokens) + speech_ratio + 1
1237
+ decoded_tokens.append(token_id)
1238
+ if token_id >= self.llm.speech_vocab_size:
1239
+ if token_id == self.llm.fill_token_id:
1240
+ break
1241
+ raise ValueError(f"speech token {token_id} cannot close an interleaved group")
1242
+ yield token_id
1243
+ hidden_states = self.llm.speech_embedding.weight[token_id].reshape(1, 1, -1)
1244
+
1245
+ hidden_states = torch.concat([hidden_states, text_cache, task_id_embed], dim=1)
1246
+ while True:
1247
+ logits, past_key_values = self.llm(hidden_states, past_key_values=past_key_values, use_cache=True)
1248
+ log_probs = logits[:, -1].log_softmax(dim=-1).squeeze(dim=0)
1249
+ token_id = repetition_aware_sampling(
1250
+ log_probs, decoded_tokens, top_p, top_k, window_size, repetition_threshold
1251
+ )
1252
+ decoded_tokens.append(token_id)
1253
+ if token_id >= self.llm.speech_vocab_size:
1254
+ if token_id == self.llm.eos_token_id:
1255
+ break
1256
+ raise ValueError(f"speech token {token_id} cannot end an utterance")
1257
+ yield token_id
1258
+ hidden_states = self.llm.speech_embedding.weight[token_id].reshape(1, 1, -1)
1259
+
1260
+ def init_streaming_state(self) -> dict:
1261
+ """
1262
+ Returns:
1263
+ `dict`: a fresh streaming state for [`~CosyVoiceV2GenerationMixin.token2wav`].
1264
+ """
1265
+ source_cache_len = int(self.mel_cache_len * np.prod(self.config.vocoder_upsample_rates)
1266
+ * self.config.vocoder_istft_hop_length)
1267
+ return {
1268
+ "hift_cache": None,
1269
+ "source_cache_len": source_cache_len,
1270
+ "speech_window": torch.from_numpy(np.hamming(2 * source_cache_len).astype(np.float32)),
1271
+ }
1272
+
1273
+ @torch.inference_mode()
1274
+ def token2wav(
1275
+ self,
1276
+ speech_token_ids: torch.Tensor,
1277
+ prompt_speech_token_ids: torch.Tensor,
1278
+ prompt_speech_feat: torch.Tensor,
1279
+ speaker_embedding: torch.Tensor,
1280
+ state: dict,
1281
+ token_offset: int = 0,
1282
+ stream: bool = False,
1283
+ finalize: bool = True,
1284
+ speed: float = 1.0,
1285
+ ) -> torch.Tensor:
1286
+ """
1287
+ Renders the speech tokens decoded so far into the waveform of one chunk.
1288
+
1289
+ Args:
1290
+ speech_token_ids (`torch.Tensor` of shape `(1, speech_length)`):
1291
+ Every speech token decoded so far, prompt excluded.
1292
+ prompt_speech_token_ids (`torch.Tensor` of shape `(1, prompt_speech_length)`):
1293
+ Speech tokens of the prompt utterance.
1294
+ prompt_speech_feat (`torch.Tensor` of shape `(1, prompt_mel_length, flow_output_size)`):
1295
+ Mel spectrogram of the prompt utterance.
1296
+ speaker_embedding (`torch.Tensor` of shape `(1, speaker_embedding_dim)`):
1297
+ Utterance level speaker embedding.
1298
+ state (`dict`):
1299
+ Mutable streaming state holding the vocoder cache.
1300
+ token_offset (`int`, *optional*, defaults to 0):
1301
+ Number of speech tokens whose mel frames were rendered by a previous call.
1302
+ stream (`bool`, *optional*, defaults to `False`):
1303
+ Whether the flow matching model attends within chunks only.
1304
+ finalize (`bool`, *optional*, defaults to `True`):
1305
+ Whether this is the last chunk of the utterance.
1306
+ speed (`float`, *optional*, defaults to 1.0):
1307
+ Playback speed, only available on the last chunk of a non streaming call.
1308
+
1309
+ Returns:
1310
+ `torch.Tensor` of shape `(1, num_samples)`: the waveform of the chunk.
1311
+
1312
+ Raises:
1313
+ ValueError: If `speed` is changed while streaming.
1314
+ """
1315
+ device = speech_token_ids.device
1316
+ mel = self.flow.inference(
1317
+ speech_token_ids=speech_token_ids.to(device=device, dtype=torch.int32),
1318
+ speech_token_lengths=torch.tensor([speech_token_ids.shape[1]], dtype=torch.int32, device=device),
1319
+ prompt_token_ids=prompt_speech_token_ids.to(device=device, dtype=torch.int32),
1320
+ prompt_token_lengths=torch.tensor(
1321
+ [prompt_speech_token_ids.shape[1]], dtype=torch.int32, device=device
1322
+ ),
1323
+ prompt_feat=prompt_speech_feat.to(device),
1324
+ speaker_embedding=speaker_embedding.to(device),
1325
+ num_steps=self.config.num_flow_inference_steps,
1326
+ streaming=stream,
1327
+ finalize=finalize,
1328
+ )
1329
+ mel = mel[:, :, token_offset * self.config.token_mel_ratio :]
1330
+
1331
+ if state["hift_cache"] is not None:
1332
+ mel = torch.concat([state["hift_cache"]["mel"], mel], dim=2)
1333
+ cache_source = state["hift_cache"]["source"]
1334
+ else:
1335
+ cache_source = mel.new_zeros(1, 1, 0)
1336
+
1337
+ if not finalize:
1338
+ waveform, source = self.hift.inference(mel, cache_source)
1339
+ if state["hift_cache"] is not None:
1340
+ waveform = fade_in_out(waveform, state["hift_cache"]["speech"], state["speech_window"])
1341
+ state["hift_cache"] = {
1342
+ "mel": mel[:, :, -self.mel_cache_len :],
1343
+ "source": source[:, :, -state["source_cache_len"] :],
1344
+ "speech": waveform[:, -state["source_cache_len"] :],
1345
+ }
1346
+ return waveform[:, : -state["source_cache_len"]]
1347
+
1348
+ if speed != 1.0:
1349
+ if state["hift_cache"] is not None:
1350
+ raise ValueError("speed can only be changed in non streaming mode")
1351
+ mel = F.interpolate(mel, size=int(mel.shape[2] / speed), mode="linear")
1352
+ waveform, _ = self.hift.inference(mel, cache_source)
1353
+ if state["hift_cache"] is not None:
1354
+ waveform = fade_in_out(waveform, state["hift_cache"]["speech"], state["speech_window"])
1355
+ return waveform
1356
+
1357
+ def generate(
1358
+ self,
1359
+ input_ids: Union[torch.Tensor, Iterator[torch.Tensor]],
1360
+ speaker_embedding: torch.Tensor,
1361
+ prompt_input_ids: Optional[torch.Tensor] = None,
1362
+ prompt_speech_token_ids: Optional[torch.Tensor] = None,
1363
+ flow_prompt_speech_token_ids: Optional[torch.Tensor] = None,
1364
+ prompt_speech_feat: Optional[torch.Tensor] = None,
1365
+ source_speech_token_ids: Optional[torch.Tensor] = None,
1366
+ stream: bool = False,
1367
+ speed: float = 1.0,
1368
+ input_lengths: Optional[torch.Tensor] = None,
1369
+ prompt_input_lengths: Optional[torch.Tensor] = None,
1370
+ prompt_speech_token_lengths: Optional[torch.Tensor] = None,
1371
+ flow_prompt_speech_token_lengths: Optional[torch.Tensor] = None,
1372
+ prompt_speech_feat_lengths: Optional[torch.Tensor] = None,
1373
+ source_speech_token_lengths: Optional[torch.Tensor] = None,
1374
+ **sampling_kwargs,
1375
+ ) -> "torch.Tensor | list[torch.Tensor] | Generator[torch.Tensor, None, None]":
1376
+ """
1377
+ Synthesizes one utterance, or a batch of utterances decoded together.
1378
+
1379
+ A batch is the right padded output of the processor, with the lengths it returns passed
1380
+ alongside. Its rows share one language model loop and one pass of the flow matching model,
1381
+ each row masked to its own text, prompt, speaker embedding and length, and the vocoder then
1382
+ renders every row on its own. With deterministic sampling every row comes out as it would on
1383
+ its own, up to floating point rounding.
1384
+
1385
+ Args:
1386
+ input_ids (`torch.Tensor` of shape `(batch_size, text_length)`, or a generator of such tensors):
1387
+ Text token ids of the sentences to synthesize. A generator interleaves the text with
1388
+ the speech tokens as it arrives, so synthesis can start before the sentence is
1389
+ complete, and holds a single utterance.
1390
+ speaker_embedding (`torch.Tensor` of shape `(batch_size, speaker_embedding_dim)`):
1391
+ Utterance level speaker embedding. It conditions the flow matching model only, since
1392
+ the v2 language model does not read it.
1393
+ prompt_input_ids (`torch.Tensor` of shape `(batch_size, prompt_text_length)`, *optional*):
1394
+ Text token ids of the prompt utterance.
1395
+ prompt_speech_token_ids (`torch.Tensor` of shape `(batch_size, prompt_speech_length)`, *optional*):
1396
+ Speech tokens of the prompt utterance the language model continues from.
1397
+ flow_prompt_speech_token_ids (`torch.Tensor` of shape `(batch_size, prompt_speech_length)`, *optional*):
1398
+ Speech tokens the flow matching model is conditioned on, alongside
1399
+ `prompt_speech_feat`. Defaults to `prompt_speech_token_ids`.
1400
+ prompt_speech_feat (`torch.Tensor` of shape `(batch_size, prompt_mel_length, flow_output_size)`, *optional*):
1401
+ Mel spectrogram of the prompt utterance.
1402
+ source_speech_token_ids (`torch.Tensor` of shape `(batch_size, speech_length)`, *optional*):
1403
+ Speech tokens to render directly, which bypasses the language model and performs voice
1404
+ conversion instead of text to speech.
1405
+ stream (`bool`, *optional*, defaults to `False`):
1406
+ Whether to return a generator yielding the waveform chunk by chunk. Only available for
1407
+ a single utterance.
1408
+ speed (`float`, *optional*, defaults to 1.0):
1409
+ Playback speed, only available when `stream` is `False`.
1410
+ input_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
1411
+ Number of valid tokens of every row of `input_ids`. Defaults to its full width.
1412
+ prompt_input_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
1413
+ Number of valid tokens of every row of `prompt_input_ids`.
1414
+ prompt_speech_token_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
1415
+ Number of valid tokens of every row of `prompt_speech_token_ids`.
1416
+ flow_prompt_speech_token_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
1417
+ Number of valid tokens of every row of `flow_prompt_speech_token_ids`. Defaults to
1418
+ `prompt_speech_token_lengths` when `flow_prompt_speech_token_ids` is left out.
1419
+ prompt_speech_feat_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
1420
+ Number of valid frames of every row of `prompt_speech_feat`, the processor's
1421
+ `speech_feat_lengths`.
1422
+ source_speech_token_lengths (`torch.Tensor` of shape `(batch_size,)`, *optional*):
1423
+ Number of valid tokens of every row of `source_speech_token_ids`.
1424
+ sampling_kwargs:
1425
+ Forwarded to [`~CosyVoiceV2GenerationMixin.generate_speech_tokens`], or to
1426
+ [`~CosyVoiceV2GenerationMixin.generate_speech_tokens_batch`] for a batch.
1427
+
1428
+ Returns:
1429
+ For a single utterance, a `torch.Tensor` of shape `(1, num_samples)`, or a generator of
1430
+ such tensors when `stream` is `True`. For a batch, a list holding one `torch.Tensor` of
1431
+ shape `(1, num_samples)` per row, each as long as that row's own waveform, the way
1432
+ [`CsmForConditionalGeneration`] returns a batch of audio.
1433
+
1434
+ Raises:
1435
+ ValueError: If `stream` is `True` for a batch of more than one utterance.
1436
+ """
1437
+ if source_speech_token_ids is not None:
1438
+ batch_size = source_speech_token_ids.shape[0]
1439
+ elif isinstance(input_ids, GeneratorType):
1440
+ batch_size = 1
1441
+ else:
1442
+ batch_size = input_ids.shape[0]
1443
+ if flow_prompt_speech_token_ids is None:
1444
+ flow_prompt_speech_token_ids = prompt_speech_token_ids
1445
+ if flow_prompt_speech_token_lengths is None:
1446
+ flow_prompt_speech_token_lengths = prompt_speech_token_lengths
1447
+ if batch_size != 1:
1448
+ if stream:
1449
+ raise ValueError(
1450
+ f"stream=True synthesizes one utterance at a time but the batch holds {batch_size}; "
1451
+ "use stream=False to decode the batch together, or split it with `processor.unbatch` "
1452
+ "and stream each item"
1453
+ )
1454
+ return self._generate_batch(
1455
+ input_ids,
1456
+ speaker_embedding,
1457
+ prompt_input_ids,
1458
+ prompt_speech_token_ids,
1459
+ flow_prompt_speech_token_ids,
1460
+ prompt_speech_feat,
1461
+ source_speech_token_ids,
1462
+ speed,
1463
+ input_lengths,
1464
+ prompt_input_lengths,
1465
+ prompt_speech_token_lengths,
1466
+ flow_prompt_speech_token_lengths,
1467
+ prompt_speech_feat_lengths,
1468
+ source_speech_token_lengths,
1469
+ **sampling_kwargs,
1470
+ )
1471
+ if not isinstance(input_ids, GeneratorType):
1472
+ input_ids = trim_row(input_ids, input_lengths)
1473
+ prompt_input_ids = trim_row(prompt_input_ids, prompt_input_lengths)
1474
+ prompt_speech_token_ids = trim_row(prompt_speech_token_ids, prompt_speech_token_lengths)
1475
+ flow_prompt_speech_token_ids = trim_row(flow_prompt_speech_token_ids, flow_prompt_speech_token_lengths)
1476
+ prompt_speech_feat = trim_row(prompt_speech_feat, prompt_speech_feat_lengths)
1477
+ source_speech_token_ids = trim_row(source_speech_token_ids, source_speech_token_lengths)
1478
+ if stream:
1479
+ return self._generate_stream(
1480
+ input_ids,
1481
+ speaker_embedding,
1482
+ prompt_input_ids,
1483
+ prompt_speech_token_ids,
1484
+ flow_prompt_speech_token_ids,
1485
+ prompt_speech_feat,
1486
+ source_speech_token_ids,
1487
+ **sampling_kwargs,
1488
+ )
1489
+ return self._generate_single(
1490
+ input_ids,
1491
+ speaker_embedding,
1492
+ prompt_input_ids,
1493
+ prompt_speech_token_ids,
1494
+ flow_prompt_speech_token_ids,
1495
+ prompt_speech_feat,
1496
+ source_speech_token_ids,
1497
+ speed,
1498
+ **sampling_kwargs,
1499
+ )
1500
+
1501
+ def _speech_token_batch(
1502
+ self,
1503
+ input_ids: torch.Tensor,
1504
+ input_lengths: Optional[torch.Tensor],
1505
+ prompt_input_ids: Optional[torch.Tensor],
1506
+ prompt_input_lengths: Optional[torch.Tensor],
1507
+ prompt_speech_token_ids: Optional[torch.Tensor],
1508
+ prompt_speech_token_lengths: Optional[torch.Tensor],
1509
+ source_speech_token_ids: Optional[torch.Tensor],
1510
+ source_speech_token_lengths: Optional[torch.Tensor],
1511
+ **sampling_kwargs,
1512
+ ) -> list[list[int]]:
1513
+ if source_speech_token_ids is not None:
1514
+ lengths = row_lengths(source_speech_token_lengths, source_speech_token_ids, 0)
1515
+ return [source_speech_token_ids[row, : lengths[row]].tolist() for row in range(len(lengths))]
1516
+ return self.generate_speech_tokens_batch(
1517
+ input_ids,
1518
+ input_lengths=input_lengths,
1519
+ prompt_input_ids=prompt_input_ids,
1520
+ prompt_input_lengths=prompt_input_lengths,
1521
+ prompt_speech_token_ids=prompt_speech_token_ids,
1522
+ prompt_speech_token_lengths=prompt_speech_token_lengths,
1523
+ **sampling_kwargs,
1524
+ )
1525
+
1526
+ _render_batch = CosyVoiceV1GenerationMixin._render_batch
1527
+ _vocode = CosyVoiceV1GenerationMixin._vocode
1528
+
1529
+ @torch.inference_mode()
1530
+ def _generate_batch(
1531
+ self,
1532
+ input_ids: torch.Tensor,
1533
+ speaker_embedding: torch.Tensor,
1534
+ prompt_input_ids: Optional[torch.Tensor],
1535
+ prompt_speech_token_ids: Optional[torch.Tensor],
1536
+ flow_prompt_speech_token_ids: Optional[torch.Tensor],
1537
+ prompt_speech_feat: Optional[torch.Tensor],
1538
+ source_speech_token_ids: Optional[torch.Tensor],
1539
+ speed: float,
1540
+ input_lengths: Optional[torch.Tensor],
1541
+ prompt_input_lengths: Optional[torch.Tensor],
1542
+ prompt_speech_token_lengths: Optional[torch.Tensor],
1543
+ flow_prompt_speech_token_lengths: Optional[torch.Tensor],
1544
+ prompt_speech_feat_lengths: Optional[torch.Tensor],
1545
+ source_speech_token_lengths: Optional[torch.Tensor],
1546
+ **sampling_kwargs,
1547
+ ) -> list[torch.Tensor]:
1548
+ tokens = self._speech_token_batch(
1549
+ input_ids, input_lengths, prompt_input_ids, prompt_input_lengths, prompt_speech_token_ids,
1550
+ prompt_speech_token_lengths, source_speech_token_ids, source_speech_token_lengths,
1551
+ **sampling_kwargs,
1552
+ )
1553
+ mels = self._render_batch(
1554
+ tokens, speaker_embedding, flow_prompt_speech_token_ids, flow_prompt_speech_token_lengths,
1555
+ prompt_speech_feat, prompt_speech_feat_lengths,
1556
+ )
1557
+ # The vocoder's convolutions are not masked and would read the padding past the end of a
1558
+ # shorter row, so every row is rendered at its own length.
1559
+ return [self._vocode(mel, speed) for mel in mels]
1560
+
1561
+ def _speech_token_stream(
1562
+ self,
1563
+ input_ids: Union[torch.Tensor, Iterator[torch.Tensor]],
1564
+ prompt_input_ids: Optional[torch.Tensor],
1565
+ prompt_speech_token_ids: Optional[torch.Tensor],
1566
+ source_speech_token_ids: Optional[torch.Tensor],
1567
+ **sampling_kwargs,
1568
+ ):
1569
+ if source_speech_token_ids is not None:
1570
+ return iter(source_speech_token_ids.flatten().tolist())
1571
+ return self.generate_speech_tokens(
1572
+ input_ids,
1573
+ prompt_input_ids=prompt_input_ids,
1574
+ prompt_speech_token_ids=prompt_speech_token_ids,
1575
+ **sampling_kwargs,
1576
+ )
1577
+
1578
+ def _prompt_defaults(
1579
+ self,
1580
+ device: torch.device,
1581
+ flow_prompt_speech_token_ids: Optional[torch.Tensor],
1582
+ prompt_speech_feat: Optional[torch.Tensor],
1583
+ ) -> tuple[torch.Tensor, torch.Tensor]:
1584
+ if flow_prompt_speech_token_ids is None:
1585
+ flow_prompt_speech_token_ids = torch.zeros(1, 0, dtype=torch.int32, device=device)
1586
+ if prompt_speech_feat is None:
1587
+ prompt_speech_feat = torch.zeros(1, 0, self.config.flow_output_size, device=device)
1588
+ return flow_prompt_speech_token_ids, prompt_speech_feat
1589
+
1590
+ @torch.inference_mode()
1591
+ def _generate_single(
1592
+ self,
1593
+ input_ids: Union[torch.Tensor, Iterator[torch.Tensor]],
1594
+ speaker_embedding: torch.Tensor,
1595
+ prompt_input_ids: Optional[torch.Tensor],
1596
+ prompt_speech_token_ids: Optional[torch.Tensor],
1597
+ flow_prompt_speech_token_ids: Optional[torch.Tensor],
1598
+ prompt_speech_feat: Optional[torch.Tensor],
1599
+ source_speech_token_ids: Optional[torch.Tensor],
1600
+ speed: float,
1601
+ **sampling_kwargs,
1602
+ ) -> torch.Tensor:
1603
+ device = self.device
1604
+ flow_prompt_speech_token_ids, prompt_speech_feat = self._prompt_defaults(
1605
+ device, flow_prompt_speech_token_ids, prompt_speech_feat
1606
+ )
1607
+ state = self.init_streaming_state()
1608
+ tokens = list(
1609
+ self._speech_token_stream(
1610
+ input_ids, prompt_input_ids, prompt_speech_token_ids, source_speech_token_ids,
1611
+ **sampling_kwargs,
1612
+ )
1613
+ )
1614
+ speech_token_ids = torch.tensor([tokens], dtype=torch.int32, device=device)
1615
+ return self.token2wav(
1616
+ speech_token_ids, flow_prompt_speech_token_ids, prompt_speech_feat, speaker_embedding, state,
1617
+ token_offset=0, stream=False, finalize=True, speed=speed,
1618
+ )
1619
+
1620
+ @torch.inference_mode()
1621
+ def _generate_stream(
1622
+ self,
1623
+ input_ids: Union[torch.Tensor, Iterator[torch.Tensor]],
1624
+ speaker_embedding: torch.Tensor,
1625
+ prompt_input_ids: Optional[torch.Tensor],
1626
+ prompt_speech_token_ids: Optional[torch.Tensor],
1627
+ flow_prompt_speech_token_ids: Optional[torch.Tensor],
1628
+ prompt_speech_feat: Optional[torch.Tensor],
1629
+ source_speech_token_ids: Optional[torch.Tensor],
1630
+ **sampling_kwargs,
1631
+ ) -> Generator[torch.Tensor, None, None]:
1632
+ device = self.device
1633
+ flow_prompt_speech_token_ids, prompt_speech_feat = self._prompt_defaults(
1634
+ device, flow_prompt_speech_token_ids, prompt_speech_feat
1635
+ )
1636
+ state = self.init_streaming_state()
1637
+ token_stream = self._speech_token_stream(
1638
+ input_ids, prompt_input_ids, prompt_speech_token_ids, source_speech_token_ids, **sampling_kwargs
1639
+ )
1640
+
1641
+ lookahead = self.config.pre_lookahead_len
1642
+ token_hop_len = self.token_hop_len
1643
+ token_max_hop_len = 4 * self.token_hop_len
1644
+ prompt_length = flow_prompt_speech_token_ids.shape[1]
1645
+ prompt_pad = int(np.ceil(prompt_length / self.token_hop_len) * self.token_hop_len - prompt_length)
1646
+
1647
+ tokens: list[int] = []
1648
+ token_offset = 0
1649
+ for token_id in token_stream:
1650
+ tokens.append(token_id)
1651
+ while True:
1652
+ hop = token_hop_len + prompt_pad if token_offset == 0 else token_hop_len
1653
+ if len(tokens) - token_offset < hop + lookahead:
1654
+ break
1655
+ chunk = torch.tensor(
1656
+ [tokens[: token_offset + hop + lookahead]], dtype=torch.int32, device=device
1657
+ )
1658
+ yield self.token2wav(
1659
+ chunk, flow_prompt_speech_token_ids, prompt_speech_feat, speaker_embedding, state,
1660
+ token_offset=token_offset, stream=True, finalize=False,
1661
+ )
1662
+ token_offset += hop
1663
+ token_hop_len = min(token_max_hop_len, token_hop_len * self.stream_scale_factor)
1664
+
1665
+ chunk = torch.tensor([tokens], dtype=torch.int32, device=device)
1666
+ yield self.token2wav(
1667
+ chunk, flow_prompt_speech_token_ids, prompt_speech_feat, speaker_embedding, state,
1668
+ token_offset=token_offset, stream=False, finalize=True,
1669
+ )
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c5bbdb2bf756a5aa4e9b16027ed45dd7d7e9dcd3aae55c697063a0cf9f5fd27
3
+ size 1284001854
modeling_emotra_tts.py ADDED
The diff for this file is too large to render. See raw diff
 
processing_emotra_tts.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The EmoTra-TTS Authors (LightSpeed, Tianchi Liu), Alibaba Inc. (CosyVoice, authors: Xiang Lyu,
2
+ # Zhihao Du), the HuggingFace Inc. team, TICTAP-11 and b-re-w. 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
+ """Processor class for EmoTra-TTS."""
16
+
17
+ import json
18
+ import os
19
+ from pathlib import Path
20
+ from typing import Optional, Union
21
+
22
+ import numpy as np
23
+ from safetensors.torch import load_file, save_file
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torchaudio
27
+ from transformers.feature_extraction_utils import BatchFeature
28
+ from transformers.models.qwen2.tokenization_qwen2 import Qwen2Tokenizer
29
+ from transformers.processing_utils import ProcessorMixin
30
+
31
+ from .configuration_emotra_tts import CosyVoiceV2Config
32
+ from .feature_extraction_emotra_tts import CosyVoiceV2FeatureExtractor
33
+ from .modeling_emotra_tts import configure_speech_tokenizer_precision, CosyVoiceV2SpeechTokenizer
34
+
35
+
36
+ __all__ = [
37
+ "EmoTraTTSProcessor",
38
+ "PROCESSOR_CONFIG",
39
+ "SPEAKER_EMBEDDING_FILE",
40
+ "SPEECH_TOKENIZER_WEIGHTS",
41
+ "cast_floating_inputs",
42
+ ]
43
+
44
+
45
+ PROCESSOR_CONFIG = "processor_config.json"
46
+ SPEECH_TOKENIZER_WEIGHTS = "speech_tokenizer.safetensors"
47
+ SPEAKER_EMBEDDING_FILE = "speaker_embedding.safetensors"
48
+
49
+
50
+ def cast_floating_inputs(module: torch.nn.Module, inputs: tuple) -> tuple:
51
+ r"""
52
+ Forward pre-hook that moves the floating point inputs of `module` to the device and dtype of its first parameter.
53
+
54
+ Args:
55
+ module (`torch.nn.Module`):
56
+ The hooked module.
57
+ inputs (`tuple`):
58
+ Positional inputs of the forward call.
59
+
60
+ Returns:
61
+ `tuple`: The inputs, with every floating point tensor cast.
62
+ """
63
+ parameter = next(module.parameters())
64
+ return tuple(
65
+ value.to(device=parameter.device, dtype=parameter.dtype)
66
+ if isinstance(value, torch.Tensor) and value.is_floating_point()
67
+ else value
68
+ for value in inputs
69
+ )
70
+
71
+
72
+ class EmoTraTTSProcessor(ProcessorMixin):
73
+ r"""
74
+ Constructs the EmoTra-TTS processor. It wraps the CosyVoice2 text tokenizer (Qwen2 with the CosyVoice2 special
75
+ tokens), the 24 kHz mel spectrogram extractor of the flow matching model, the CosyVoice2 supervised semantic speech
76
+ tokenizer and the fixed speaker embedding the model was trained with.
77
+
78
+ EmoTra-TTS is fine tuned on one speaker and its flow matching model reads one fixed CAM++ embedding of a neutral
79
+ recording of that speaker. [`~EmoTraTTSProcessor.__call__`] returns that embedding with the text ids. The speech
80
+ tokenizer and the mel extractor are only needed to build training inputs.
81
+
82
+ Args:
83
+ tokenizer ([`Qwen2Tokenizer`]):
84
+ Text tokenizer.
85
+ feature_extractor ([`CosyVoiceV2FeatureExtractor`]):
86
+ Mel spectrogram extractor of the flow matching model.
87
+ speaker_embedding (`torch.Tensor` of shape `(speaker_embedding_dim,)`):
88
+ The fixed speaker embedding.
89
+ speech_tokenizer_path (`str`, *optional*):
90
+ Path of `speech_tokenizer.safetensors`, loaded on first use.
91
+ speech_token_mel_bins (`int`, *optional*, defaults to 128):
92
+ Number of mel bins of the log mel spectrogram the speech tokenizer consumes.
93
+ token_mel_ratio (`int`, *optional*, defaults to 2):
94
+ Number of mel frames per speech token.
95
+ """
96
+
97
+ attributes: list[str] = []
98
+ speech_tokenizer_sampling_rate = 16000
99
+
100
+ def __init__(
101
+ self,
102
+ tokenizer: Qwen2Tokenizer,
103
+ feature_extractor: CosyVoiceV2FeatureExtractor,
104
+ speaker_embedding: torch.Tensor,
105
+ speech_tokenizer_path: Optional[str] = None,
106
+ speech_token_mel_bins: int = 128,
107
+ token_mel_ratio: int = 2,
108
+ **kwargs,
109
+ ):
110
+ self.tokenizer = tokenizer
111
+ self.feature_extractor = feature_extractor
112
+ self.speaker_embedding = speaker_embedding
113
+ self.speech_tokenizer_path = speech_tokenizer_path
114
+ self.speech_token_mel_bins = speech_token_mel_bins
115
+ self.token_mel_ratio = token_mel_ratio
116
+ self._speech_token_features = None
117
+ self._speech_tokenizer = None
118
+
119
+ @classmethod
120
+ def get_attributes(cls) -> list[str]:
121
+ return []
122
+
123
+ @classmethod
124
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "EmoTraTTSProcessor":
125
+ r"""
126
+ Reads the processor from a local folder or a Hub repository: `processor_config.json`, the tokenizer files,
127
+ `speaker_embedding.safetensors` and, on first use, `speech_tokenizer.safetensors`.
128
+
129
+ Args:
130
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
131
+ Folder or repository id.
132
+ kwargs:
133
+ `revision`, `cache_dir`, `token` and `local_files_only` go to the download; the rest overrides the
134
+ saved arguments.
135
+
136
+ Returns:
137
+ [`EmoTraTTSProcessor`]: The processor.
138
+ """
139
+ from transformers.utils.hub import cached_file
140
+
141
+ download = {key: kwargs.pop(key) for key in ("revision", "cache_dir", "token", "local_files_only") if key in kwargs}
142
+ for key in ("trust_remote_code", "_from_auto", "_commit_hash", "subfolder"):
143
+ kwargs.pop(key, None)
144
+ source = str(pretrained_model_name_or_path)
145
+ saved = json.loads(Path(cached_file(source, PROCESSOR_CONFIG, **download)).read_text())
146
+ for key in ("processor_class", "auto_map"):
147
+ saved.pop(key, None)
148
+ feature_extractor = CosyVoiceV2FeatureExtractor(**saved.pop("feature_extractor"))
149
+ tokenizer = Qwen2Tokenizer.from_pretrained(source, **download)
150
+ speaker_embedding = load_file(cached_file(source, SPEAKER_EMBEDDING_FILE, **download))["speaker_embedding"]
151
+ speech_tokenizer_path = cached_file(source, SPEECH_TOKENIZER_WEIGHTS, **download)
152
+ return cls(
153
+ tokenizer=tokenizer,
154
+ feature_extractor=feature_extractor,
155
+ speaker_embedding=speaker_embedding,
156
+ speech_tokenizer_path=speech_tokenizer_path,
157
+ **{**saved, **kwargs},
158
+ )
159
+
160
+ def save_pretrained(self, save_directory: Union[str, os.PathLike], **kwargs) -> list[str]:
161
+ r"""
162
+ Writes `processor_config.json`, the tokenizer files, `speaker_embedding.safetensors` and
163
+ `speech_tokenizer.safetensors`.
164
+
165
+ Args:
166
+ save_directory (`str` or `os.PathLike`):
167
+ Folder.
168
+ kwargs:
169
+ Unused.
170
+
171
+ Returns:
172
+ `list[str]`: The written files.
173
+ """
174
+ save_directory = Path(save_directory)
175
+ save_directory.mkdir(parents=True, exist_ok=True)
176
+ feature_extractor = self.feature_extractor.to_dict()
177
+ for key in ("mel_filters", "feature_extractor_type", "processor_class"):
178
+ feature_extractor.pop(key, None)
179
+ content = {
180
+ "processor_class": type(self).__name__,
181
+ "feature_extractor": feature_extractor,
182
+ "speech_token_mel_bins": self.speech_token_mel_bins,
183
+ "token_mel_ratio": self.token_mel_ratio,
184
+ "auto_map": {"AutoProcessor": f"processing_emotra_tts.{type(self).__name__}"},
185
+ }
186
+ written = [str(save_directory / PROCESSOR_CONFIG)]
187
+ (save_directory / PROCESSOR_CONFIG).write_text(json.dumps(content, indent=2) + "\n")
188
+ written += list(self.tokenizer.save_pretrained(str(save_directory)))
189
+ save_file({"speaker_embedding": self.speaker_embedding.contiguous()}, str(save_directory / SPEAKER_EMBEDDING_FILE))
190
+ written.append(str(save_directory / SPEAKER_EMBEDDING_FILE))
191
+ save_file(
192
+ {name: tensor.detach().cpu().contiguous() for name, tensor in self.speech_tokenizer.state_dict().items()},
193
+ str(save_directory / SPEECH_TOKENIZER_WEIGHTS),
194
+ )
195
+ written.append(str(save_directory / SPEECH_TOKENIZER_WEIGHTS))
196
+ return written
197
+
198
+ @property
199
+ def speech_token_feature_extractor(self):
200
+ """
201
+ Returns:
202
+ [`WhisperFeatureExtractor`]: The log mel extractor feeding the speech tokenizer.
203
+ """
204
+ if self._speech_token_features is None:
205
+ from transformers import WhisperFeatureExtractor
206
+
207
+ self._speech_token_features = WhisperFeatureExtractor(
208
+ feature_size=self.speech_token_mel_bins, sampling_rate=self.speech_tokenizer_sampling_rate
209
+ )
210
+ return self._speech_token_features
211
+
212
+ @property
213
+ def speech_tokenizer(self) -> CosyVoiceV2SpeechTokenizer:
214
+ """
215
+ Returns:
216
+ [`CosyVoiceV2SpeechTokenizer`]: The speech tokenizer in evaluation mode, BF16 except its finite scalar
217
+ quantizer, which stays FP32 (see [`configure_speech_tokenizer_precision`]).
218
+ """
219
+ if self._speech_tokenizer is None:
220
+ tokenizer = CosyVoiceV2SpeechTokenizer(CosyVoiceV2Config())
221
+ configure_speech_tokenizer_precision(tokenizer)
222
+ tokenizer.load_state_dict(load_file(self.speech_tokenizer_path))
223
+ tokenizer.register_forward_pre_hook(cast_floating_inputs)
224
+ self._speech_tokenizer = tokenizer.eval()
225
+ return self._speech_tokenizer
226
+
227
+ def _resample(self, waveform: torch.Tensor, sampling_rate: Optional[int], target_rate: int) -> torch.Tensor:
228
+ waveform = waveform.reshape(1, -1).float()
229
+ if sampling_rate is not None and sampling_rate != target_rate:
230
+ waveform = torchaudio.functional.resample(waveform, sampling_rate, target_rate)
231
+ return waveform
232
+
233
+ def encode_speech_tokens(
234
+ self, audio: Union[np.ndarray, torch.Tensor], sampling_rate: Optional[int] = None
235
+ ) -> tuple[torch.Tensor, torch.Tensor]:
236
+ """
237
+ Turns a waveform into supervised semantic speech tokens.
238
+
239
+ Args:
240
+ audio (`np.ndarray` or `torch.Tensor`):
241
+ Mono waveform.
242
+ sampling_rate (`int`, *optional*):
243
+ Rate of `audio`.
244
+
245
+ Returns:
246
+ `tuple(torch.Tensor)`: the speech token ids of shape `(1, speech_length)` and their length.
247
+
248
+ Raises:
249
+ ValueError: If the waveform is longer than thirty seconds.
250
+ """
251
+ waveform = self._resample(
252
+ audio if isinstance(audio, torch.Tensor) else torch.as_tensor(np.asarray(audio)),
253
+ sampling_rate,
254
+ self.speech_tokenizer_sampling_rate,
255
+ )
256
+ if waveform.shape[1] / self.speech_tokenizer_sampling_rate > 30:
257
+ raise ValueError("the CosyVoice v1 speech tokenizer does not support audio longer than 30 seconds")
258
+ features = self.speech_token_feature_extractor(
259
+ waveform.squeeze(0).numpy(),
260
+ sampling_rate=self.speech_tokenizer_sampling_rate,
261
+ padding=False,
262
+ return_tensors="pt",
263
+ ).input_features
264
+ lengths = torch.tensor([features.shape[2]], dtype=torch.int32)
265
+ with torch.no_grad():
266
+ speech_token_ids = self.speech_tokenizer(features, lengths).to(torch.int32)
267
+ return speech_token_ids, torch.tensor([speech_token_ids.shape[1]], dtype=torch.int32)
268
+
269
+ def speech_features(
270
+ self, waveforms: torch.Tensor, waveform_lengths: torch.Tensor, sampling_rate: int
271
+ ) -> list[torch.Tensor]:
272
+ r"""
273
+ Extracts the flow-model log mel features from same-device waveform batches.
274
+
275
+ Args:
276
+ waveforms (`torch.Tensor`):
277
+ Padded mono waveforms of shape `(batch_size, num_samples)`.
278
+ waveform_lengths (`torch.Tensor`):
279
+ Unpadded sample counts of shape `(batch_size,)`.
280
+ sampling_rate (`int`):
281
+ Rate of every waveform. It must equal the feature extractor's sampling rate.
282
+
283
+ Returns:
284
+ `list[torch.Tensor]`: One `(num_frames, feature_size)` feature matrix per input waveform.
285
+
286
+ Raises:
287
+ ValueError: If the tensors have invalid shapes, a waveform is too short for the reflection padding, or the
288
+ sampling rate differs from the extractor rate.
289
+ """
290
+ if waveforms.ndim != 2 or waveform_lengths.ndim != 1 or len(waveforms) != len(waveform_lengths):
291
+ raise ValueError("waveforms and waveform_lengths must have shapes (batch, samples) and (batch,)")
292
+ if waveforms.device != waveform_lengths.device:
293
+ raise ValueError("waveforms and waveform_lengths must share a device")
294
+ if sampling_rate != self.feature_extractor.sampling_rate:
295
+ raise ValueError("speech_features requires the feature extractor sampling rate")
296
+ if torch.any(waveform_lengths < 1) or torch.any(waveform_lengths > waveforms.shape[1]):
297
+ raise ValueError("waveform_lengths must select nonempty waveform prefixes")
298
+ padding = int((self.feature_extractor.n_fft - self.feature_extractor.hop_length) / 2)
299
+ if torch.any(waveform_lengths <= padding + 1):
300
+ raise ValueError(f"every waveform must be longer than {padding + 1} samples for the reflection padding")
301
+ padded = F.pad(waveforms.float(), (padding, padding))
302
+ for index, length in enumerate(waveform_lengths.tolist()):
303
+ padded[index, :padding] = waveforms[index, 1 : padding + 1].flip(0)
304
+ padded[index, padding + length : padding + length + padding] = waveforms[
305
+ index, length - padding - 1 : length - 1
306
+ ].flip(0)
307
+ spectrogram = torch.stft(
308
+ padded,
309
+ self.feature_extractor.n_fft,
310
+ hop_length=self.feature_extractor.hop_length,
311
+ win_length=self.feature_extractor.win_length,
312
+ window=torch.hann_window(self.feature_extractor.win_length, device=waveforms.device),
313
+ center=False,
314
+ pad_mode="reflect",
315
+ normalized=False,
316
+ onesided=True,
317
+ return_complex=True,
318
+ )
319
+ spectrogram = torch.sqrt(torch.view_as_real(spectrogram).pow(2).sum(-1) + 1e-9)
320
+ mel_filters = torch.from_numpy(self.feature_extractor.mel_filters).to(spectrogram)
321
+ features = torch.log(torch.clamp(torch.matmul(mel_filters, spectrogram), min=1e-5)).transpose(1, 2)
322
+ frame_lengths = (waveform_lengths + 2 * padding - self.feature_extractor.n_fft) // self.feature_extractor.hop_length + 1
323
+ return [feature[:length] for feature, length in zip(features, frame_lengths.tolist(), strict=True)]
324
+
325
+ def _tokenize(self, text: Union[str, list[str]], prefix: str, **kwargs) -> dict:
326
+ encoded = self.tokenizer(
327
+ text, add_special_tokens=False, return_tensors="pt", **{"padding": True, "padding_side": "right", **kwargs}
328
+ )
329
+ attention_mask = encoded["attention_mask"]
330
+ return {
331
+ f"{prefix}input_ids": encoded["input_ids"].to(torch.int32),
332
+ f"{prefix}input_lengths": attention_mask.sum(dim=1).to(torch.int32),
333
+ f"{prefix}attention_mask": attention_mask,
334
+ }
335
+
336
+ def __call__(self, text: Union[str, list[str]], **kwargs) -> BatchFeature:
337
+ """
338
+ Args:
339
+ text (`str` or `list[str]`):
340
+ Text to synthesize, or a batch of texts.
341
+ kwargs:
342
+ Forwarded to the text tokenizer.
343
+
344
+ Returns:
345
+ [`BatchFeature`]: `input_ids`, `input_lengths` and `attention_mask`, right padded, and
346
+ `speaker_embedding` of shape `(batch_size, speaker_embedding_dim)`, the fixed speaker embedding repeated
347
+ for every text.
348
+ """
349
+ data = self._tokenize(text, "", **kwargs)
350
+ batch_size = data["input_ids"].shape[0]
351
+ data["speaker_embedding"] = self.speaker_embedding.reshape(1, -1).expand(batch_size, -1).clone()
352
+ return BatchFeature(data)
processor_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "processor_class": "EmoTraTTSProcessor",
3
+ "feature_extractor": {
4
+ "feature_size": 80,
5
+ "sampling_rate": 24000,
6
+ "padding_value": 0.0,
7
+ "padding_side": "right",
8
+ "return_attention_mask": true,
9
+ "mel_sampling_rate": 24000,
10
+ "n_fft": 1920,
11
+ "hop_length": 480,
12
+ "win_length": 1920,
13
+ "fmin": 0.0,
14
+ "fmax": 8000.0
15
+ },
16
+ "speech_token_mel_bins": 128,
17
+ "token_mel_ratio": 2,
18
+ "auto_map": {
19
+ "AutoProcessor": "processing_emotra_tts.EmoTraTTSProcessor"
20
+ }
21
+ }
speaker_embedding.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1dddb26a4a84f69a60a961e4c11be43185572954e29601be965102cd61a6d250
3
+ size 856
speech_tokenizer.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f078ef8c2c14e06a872e37e29d54a537e8bf65394984374fc750d511af1f764d
3
+ size 247459960
stage1/config.json ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dtype": "bfloat16",
3
+ "emotion_scale": 0.07,
4
+ "emotion_transition_end": 0.7,
5
+ "emotion_transition_start": 0.4,
6
+ "estimator_channels": [
7
+ 256
8
+ ],
9
+ "estimator_dropout": 0.0,
10
+ "estimator_ffn_mult": 4,
11
+ "estimator_group_norm_groups": 8,
12
+ "estimator_head_dim": 64,
13
+ "estimator_in_channels": 320,
14
+ "estimator_num_blocks": 4,
15
+ "estimator_num_decoding_left_chunks": -1,
16
+ "estimator_num_heads": 8,
17
+ "estimator_num_mid_blocks": 12,
18
+ "estimator_out_channels": 80,
19
+ "estimator_static_chunk_size": 50,
20
+ "f0_predictor_hidden_size": 512,
21
+ "flow_encoder_attention_dropout": 0.1,
22
+ "flow_encoder_chunk_size": 25,
23
+ "flow_encoder_dropout": 0.1,
24
+ "flow_encoder_ffn_dim": 2048,
25
+ "flow_encoder_hidden_act": "silu",
26
+ "flow_encoder_hidden_size": 512,
27
+ "flow_encoder_num_heads": 8,
28
+ "flow_encoder_num_layers": 6,
29
+ "flow_encoder_positional_dropout": 0.1,
30
+ "flow_encoder_up_num_layers": 4,
31
+ "flow_input_frame_rate": 25,
32
+ "flow_input_size": 512,
33
+ "flow_output_size": 80,
34
+ "hidden_loss_weight": 0.1,
35
+ "inference_cfg_rate": 0.7,
36
+ "initializer_range": 0.02,
37
+ "label_smoothing": 0.0,
38
+ "length_normalized_loss": true,
39
+ "length_regulator_sampling_ratios": [
40
+ 1,
41
+ 1,
42
+ 1,
43
+ 1
44
+ ],
45
+ "lm_attention_dropout": 0.0,
46
+ "lm_chunk_size": 1,
47
+ "lm_dropout": 0.1,
48
+ "lm_ffn_dim": 4096,
49
+ "lm_hidden_act": "relu",
50
+ "lm_hidden_size": 896,
51
+ "lm_input_projection_activation": true,
52
+ "lm_num_heads": 16,
53
+ "lm_num_layers": 14,
54
+ "lm_positional_dropout": 0.1,
55
+ "max_source_positions": 5000,
56
+ "mix_ratio": [
57
+ 5,
58
+ 15
59
+ ],
60
+ "model_type": "emotra_tts",
61
+ "noise_length": 15000,
62
+ "noise_seed": 0,
63
+ "num_flow_inference_steps": 10,
64
+ "num_speech_special_tokens": 3,
65
+ "num_vad_tokens": 5,
66
+ "pre_lookahead_channels": 512,
67
+ "pre_lookahead_len": 3,
68
+ "sample_rate": 24000,
69
+ "sigma_min": 1e-06,
70
+ "speaker_embedding_dim": 192,
71
+ "speaker_encoder_bottleneck_size": 4,
72
+ "speaker_encoder_dilations": [
73
+ 1,
74
+ 2,
75
+ 2
76
+ ],
77
+ "speaker_encoder_front_end_channels": 32,
78
+ "speaker_encoder_front_end_num_blocks": [
79
+ 2,
80
+ 2
81
+ ],
82
+ "speaker_encoder_growth_rate": 32,
83
+ "speaker_encoder_init_channels": 128,
84
+ "speaker_encoder_kernel_sizes": [
85
+ 3,
86
+ 3,
87
+ 3
88
+ ],
89
+ "speaker_encoder_num_layers": [
90
+ 12,
91
+ 24,
92
+ 16
93
+ ],
94
+ "speaker_encoder_num_mel_bins": 80,
95
+ "speaker_encoder_reduction": 2,
96
+ "speaker_encoder_segment_length": 100,
97
+ "speech_tokenizer_conv_stride": 2,
98
+ "speech_tokenizer_ffn_dim": 5120,
99
+ "speech_tokenizer_fsmn_kernel_size": 31,
100
+ "speech_tokenizer_fsq_levels": [
101
+ 3,
102
+ 3,
103
+ 3,
104
+ 3,
105
+ 3,
106
+ 3,
107
+ 3,
108
+ 3
109
+ ],
110
+ "speech_tokenizer_hidden_size": 1280,
111
+ "speech_tokenizer_max_position_embeddings": 2048,
112
+ "speech_tokenizer_max_source_positions": null,
113
+ "speech_tokenizer_num_heads": 20,
114
+ "speech_tokenizer_num_layers": 6,
115
+ "speech_tokenizer_num_mel_bins": 128,
116
+ "speech_tokenizer_rope_theta": 10000.0,
117
+ "speech_vocab_size": 6561,
118
+ "t_scheduler": "cosine",
119
+ "text_config": {
120
+ "architectures": [
121
+ "Qwen2ForCausalLM"
122
+ ],
123
+ "attention_dropout": 0.0,
124
+ "bos_token_id": 151643,
125
+ "dtype": "bfloat16",
126
+ "eos_token_id": 151645,
127
+ "hidden_act": "silu",
128
+ "hidden_size": 896,
129
+ "initializer_range": 0.02,
130
+ "intermediate_size": 4864,
131
+ "layer_types": [
132
+ "full_attention",
133
+ "full_attention",
134
+ "full_attention",
135
+ "full_attention",
136
+ "full_attention",
137
+ "full_attention",
138
+ "full_attention",
139
+ "full_attention",
140
+ "full_attention",
141
+ "full_attention",
142
+ "full_attention",
143
+ "full_attention",
144
+ "full_attention",
145
+ "full_attention",
146
+ "full_attention",
147
+ "full_attention",
148
+ "full_attention",
149
+ "full_attention",
150
+ "full_attention",
151
+ "full_attention",
152
+ "full_attention",
153
+ "full_attention",
154
+ "full_attention",
155
+ "full_attention"
156
+ ],
157
+ "max_position_embeddings": 32768,
158
+ "max_window_layers": 24,
159
+ "model_type": "qwen2",
160
+ "num_attention_heads": 14,
161
+ "num_hidden_layers": 24,
162
+ "num_key_value_heads": 2,
163
+ "pad_token_id": null,
164
+ "rms_norm_eps": 1e-06,
165
+ "rope_parameters": {
166
+ "rope_theta": 1000000.0,
167
+ "rope_type": "default"
168
+ },
169
+ "sliding_window": null,
170
+ "tie_word_embeddings": true,
171
+ "use_cache": true,
172
+ "use_sliding_window": false,
173
+ "vocab_size": 151936
174
+ },
175
+ "text_encoder_attention_dropout": 0.0,
176
+ "text_encoder_chunk_size": 1,
177
+ "text_encoder_dropout": 0.1,
178
+ "text_encoder_ffn_dim": 4096,
179
+ "text_encoder_hidden_act": "silu",
180
+ "text_encoder_hidden_size": 1024,
181
+ "text_encoder_input_size": 512,
182
+ "text_encoder_num_heads": 16,
183
+ "text_encoder_num_layers": 6,
184
+ "text_encoder_positional_dropout": 0.1,
185
+ "text_vocab_size": 51866,
186
+ "token_mel_ratio": 2,
187
+ "training_cfg_rate": 0.2,
188
+ "transformers_version": "5.19.0",
189
+ "use_cache": false,
190
+ "vad_downsample_hidden_size": 256,
191
+ "vad_dropout": 0.1,
192
+ "vad_hidden_state_size": 1024,
193
+ "vad_projection_hidden_size": 256,
194
+ "vad_reconstructor_hidden_size": 512,
195
+ "vocoder_audio_limit": 0.99,
196
+ "vocoder_base_channels": 512,
197
+ "vocoder_in_channels": 80,
198
+ "vocoder_istft_hop_length": 4,
199
+ "vocoder_istft_n_fft": 16,
200
+ "vocoder_leaky_relu_slope": 0.1,
201
+ "vocoder_mel_loss_coeff": 45.0,
202
+ "vocoder_mel_loss_fmax": null,
203
+ "vocoder_mel_loss_fmin": 0.0,
204
+ "vocoder_mel_loss_hop_length": 480,
205
+ "vocoder_mel_loss_n_fft": 1920,
206
+ "vocoder_mel_loss_num_mel_bins": 80,
207
+ "vocoder_mel_loss_win_length": 1920,
208
+ "vocoder_num_harmonics": 8,
209
+ "vocoder_resblock_dilation_sizes": [
210
+ [
211
+ 1,
212
+ 3,
213
+ 5
214
+ ],
215
+ [
216
+ 1,
217
+ 3,
218
+ 5
219
+ ],
220
+ [
221
+ 1,
222
+ 3,
223
+ 5
224
+ ]
225
+ ],
226
+ "vocoder_resblock_kernel_sizes": [
227
+ 3,
228
+ 7,
229
+ 11
230
+ ],
231
+ "vocoder_source_amplitude": 0.1,
232
+ "vocoder_source_noise_std": 0.003,
233
+ "vocoder_source_resblock_dilation_sizes": [
234
+ [
235
+ 1,
236
+ 3,
237
+ 5
238
+ ],
239
+ [
240
+ 1,
241
+ 3,
242
+ 5
243
+ ],
244
+ [
245
+ 1,
246
+ 3,
247
+ 5
248
+ ]
249
+ ],
250
+ "vocoder_source_resblock_kernel_sizes": [
251
+ 7,
252
+ 7,
253
+ 11
254
+ ],
255
+ "vocoder_upsample_kernel_sizes": [
256
+ 16,
257
+ 11,
258
+ 7
259
+ ],
260
+ "vocoder_upsample_rates": [
261
+ 8,
262
+ 5,
263
+ 3
264
+ ],
265
+ "vocoder_voiced_threshold": 10
266
+ }
stage1/trainable.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0baf69be5cff7e03bd9d04aadf1285590ae684a71677e8d524706c1b2e28cc0c
3
+ size 1014077472
stage1/trainer_state.json ADDED
@@ -0,0 +1,1722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 8.0,
6
+ "eval_steps": 300,
7
+ "global_step": 2048,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.0390625,
14
+ "grad_norm": 1.140625,
15
+ "learning_rate": 1e-05,
16
+ "loss": 3.253611755371094,
17
+ "peak_memory_gb": 30.655770112,
18
+ "step": 10
19
+ },
20
+ {
21
+ "epoch": 0.078125,
22
+ "grad_norm": 0.74609375,
23
+ "learning_rate": 1e-05,
24
+ "loss": 3.091032028198242,
25
+ "peak_memory_gb": 30.655770112,
26
+ "step": 20
27
+ },
28
+ {
29
+ "epoch": 0.1171875,
30
+ "grad_norm": 0.58984375,
31
+ "learning_rate": 1e-05,
32
+ "loss": 3.028639030456543,
33
+ "peak_memory_gb": 30.655770112,
34
+ "step": 30
35
+ },
36
+ {
37
+ "epoch": 0.15625,
38
+ "grad_norm": 0.6171875,
39
+ "learning_rate": 1e-05,
40
+ "loss": 3.001031494140625,
41
+ "peak_memory_gb": 30.655770112,
42
+ "step": 40
43
+ },
44
+ {
45
+ "epoch": 0.1953125,
46
+ "grad_norm": 0.64453125,
47
+ "learning_rate": 1e-05,
48
+ "loss": 2.974678611755371,
49
+ "peak_memory_gb": 30.655770112,
50
+ "step": 50
51
+ },
52
+ {
53
+ "epoch": 0.234375,
54
+ "grad_norm": 0.5546875,
55
+ "learning_rate": 1e-05,
56
+ "loss": 2.9662445068359373,
57
+ "peak_memory_gb": 30.655770112,
58
+ "step": 60
59
+ },
60
+ {
61
+ "epoch": 0.2734375,
62
+ "grad_norm": 0.58984375,
63
+ "learning_rate": 1e-05,
64
+ "loss": 2.9532821655273436,
65
+ "peak_memory_gb": 30.655770112,
66
+ "step": 70
67
+ },
68
+ {
69
+ "epoch": 0.3125,
70
+ "grad_norm": 0.60546875,
71
+ "learning_rate": 1e-05,
72
+ "loss": 2.9440818786621095,
73
+ "peak_memory_gb": 30.799844864,
74
+ "step": 80
75
+ },
76
+ {
77
+ "epoch": 0.3515625,
78
+ "grad_norm": 0.65234375,
79
+ "learning_rate": 1e-05,
80
+ "loss": 2.9273284912109374,
81
+ "peak_memory_gb": 30.799844864,
82
+ "step": 90
83
+ },
84
+ {
85
+ "epoch": 0.390625,
86
+ "grad_norm": 0.57421875,
87
+ "learning_rate": 1e-05,
88
+ "loss": 2.9205894470214844,
89
+ "peak_memory_gb": 32.318029312,
90
+ "step": 100
91
+ },
92
+ {
93
+ "epoch": 0.4296875,
94
+ "grad_norm": 0.6328125,
95
+ "learning_rate": 1e-05,
96
+ "loss": 2.9089698791503906,
97
+ "peak_memory_gb": 33.261869056,
98
+ "step": 110
99
+ },
100
+ {
101
+ "epoch": 0.46875,
102
+ "grad_norm": 0.58203125,
103
+ "learning_rate": 1e-05,
104
+ "loss": 2.9027215957641603,
105
+ "peak_memory_gb": 33.261869056,
106
+ "step": 120
107
+ },
108
+ {
109
+ "epoch": 0.5078125,
110
+ "grad_norm": 0.60546875,
111
+ "learning_rate": 1e-05,
112
+ "loss": 2.9028148651123047,
113
+ "peak_memory_gb": 33.261869056,
114
+ "step": 130
115
+ },
116
+ {
117
+ "epoch": 0.546875,
118
+ "grad_norm": 0.6171875,
119
+ "learning_rate": 1e-05,
120
+ "loss": 2.8981601715087892,
121
+ "peak_memory_gb": 33.261869056,
122
+ "step": 140
123
+ },
124
+ {
125
+ "epoch": 0.5859375,
126
+ "grad_norm": 0.59375,
127
+ "learning_rate": 1e-05,
128
+ "loss": 2.887691879272461,
129
+ "peak_memory_gb": 33.261869056,
130
+ "step": 150
131
+ },
132
+ {
133
+ "epoch": 0.625,
134
+ "grad_norm": 0.60546875,
135
+ "learning_rate": 1e-05,
136
+ "loss": 2.8908462524414062,
137
+ "peak_memory_gb": 33.261869056,
138
+ "step": 160
139
+ },
140
+ {
141
+ "epoch": 0.6640625,
142
+ "grad_norm": 0.6328125,
143
+ "learning_rate": 1e-05,
144
+ "loss": 2.8811721801757812,
145
+ "peak_memory_gb": 33.261869056,
146
+ "step": 170
147
+ },
148
+ {
149
+ "epoch": 0.703125,
150
+ "grad_norm": 0.6171875,
151
+ "learning_rate": 1e-05,
152
+ "loss": 2.869950294494629,
153
+ "peak_memory_gb": 33.261869056,
154
+ "step": 180
155
+ },
156
+ {
157
+ "epoch": 0.7421875,
158
+ "grad_norm": 0.59765625,
159
+ "learning_rate": 1e-05,
160
+ "loss": 2.871914100646973,
161
+ "peak_memory_gb": 33.261869056,
162
+ "step": 190
163
+ },
164
+ {
165
+ "epoch": 0.78125,
166
+ "grad_norm": 0.62890625,
167
+ "learning_rate": 1e-05,
168
+ "loss": 2.8638410568237305,
169
+ "peak_memory_gb": 33.261869056,
170
+ "step": 200
171
+ },
172
+ {
173
+ "epoch": 0.8203125,
174
+ "grad_norm": 0.59765625,
175
+ "learning_rate": 1e-05,
176
+ "loss": 2.8646373748779297,
177
+ "peak_memory_gb": 33.261869056,
178
+ "step": 210
179
+ },
180
+ {
181
+ "epoch": 0.859375,
182
+ "grad_norm": 0.58984375,
183
+ "learning_rate": 1e-05,
184
+ "loss": 2.849362373352051,
185
+ "peak_memory_gb": 33.261869056,
186
+ "step": 220
187
+ },
188
+ {
189
+ "epoch": 0.8984375,
190
+ "grad_norm": 0.640625,
191
+ "learning_rate": 1e-05,
192
+ "loss": 2.854623794555664,
193
+ "peak_memory_gb": 33.261869056,
194
+ "step": 230
195
+ },
196
+ {
197
+ "epoch": 0.9375,
198
+ "grad_norm": 0.62890625,
199
+ "learning_rate": 1e-05,
200
+ "loss": 2.853439712524414,
201
+ "peak_memory_gb": 33.261869056,
202
+ "step": 240
203
+ },
204
+ {
205
+ "epoch": 0.9765625,
206
+ "grad_norm": 0.60546875,
207
+ "learning_rate": 1e-05,
208
+ "loss": 2.8456275939941404,
209
+ "peak_memory_gb": 33.261869056,
210
+ "step": 250
211
+ },
212
+ {
213
+ "epoch": 1.015625,
214
+ "grad_norm": 0.60546875,
215
+ "learning_rate": 1e-05,
216
+ "loss": 2.831919860839844,
217
+ "peak_memory_gb": 33.261869056,
218
+ "step": 260
219
+ },
220
+ {
221
+ "epoch": 1.0546875,
222
+ "grad_norm": 0.6015625,
223
+ "learning_rate": 1e-05,
224
+ "loss": 2.8136770248413088,
225
+ "peak_memory_gb": 33.261869056,
226
+ "step": 270
227
+ },
228
+ {
229
+ "epoch": 1.09375,
230
+ "grad_norm": 0.6328125,
231
+ "learning_rate": 1e-05,
232
+ "loss": 2.807277870178223,
233
+ "peak_memory_gb": 33.261869056,
234
+ "step": 280
235
+ },
236
+ {
237
+ "epoch": 1.1328125,
238
+ "grad_norm": 0.71484375,
239
+ "learning_rate": 1e-05,
240
+ "loss": 2.8104019165039062,
241
+ "peak_memory_gb": 33.261869056,
242
+ "step": 290
243
+ },
244
+ {
245
+ "epoch": 1.171875,
246
+ "grad_norm": 0.63671875,
247
+ "learning_rate": 1e-05,
248
+ "loss": 2.8081295013427736,
249
+ "peak_memory_gb": 33.261869056,
250
+ "step": 300
251
+ },
252
+ {
253
+ "epoch": 1.171875,
254
+ "eval_loss": 2.8209948539733887,
255
+ "eval_runtime": 5.4863,
256
+ "eval_samples_per_second": 911.357,
257
+ "eval_steps_per_second": 57.051,
258
+ "step": 300
259
+ },
260
+ {
261
+ "epoch": 1.2109375,
262
+ "grad_norm": 0.64453125,
263
+ "learning_rate": 1e-05,
264
+ "loss": 2.803227996826172,
265
+ "peak_memory_gb": 33.261869056,
266
+ "step": 310
267
+ },
268
+ {
269
+ "epoch": 1.25,
270
+ "grad_norm": 0.66796875,
271
+ "learning_rate": 1e-05,
272
+ "loss": 2.805625152587891,
273
+ "peak_memory_gb": 33.261869056,
274
+ "step": 320
275
+ },
276
+ {
277
+ "epoch": 1.2890625,
278
+ "grad_norm": 0.640625,
279
+ "learning_rate": 1e-05,
280
+ "loss": 2.799937057495117,
281
+ "peak_memory_gb": 33.261869056,
282
+ "step": 330
283
+ },
284
+ {
285
+ "epoch": 1.328125,
286
+ "grad_norm": 0.6484375,
287
+ "learning_rate": 1e-05,
288
+ "loss": 2.8027748107910155,
289
+ "peak_memory_gb": 33.261869056,
290
+ "step": 340
291
+ },
292
+ {
293
+ "epoch": 1.3671875,
294
+ "grad_norm": 0.70703125,
295
+ "learning_rate": 1e-05,
296
+ "loss": 2.8022483825683593,
297
+ "peak_memory_gb": 33.261869056,
298
+ "step": 350
299
+ },
300
+ {
301
+ "epoch": 1.40625,
302
+ "grad_norm": 0.66015625,
303
+ "learning_rate": 1e-05,
304
+ "loss": 2.7866031646728517,
305
+ "peak_memory_gb": 33.261869056,
306
+ "step": 360
307
+ },
308
+ {
309
+ "epoch": 1.4453125,
310
+ "grad_norm": 0.67578125,
311
+ "learning_rate": 1e-05,
312
+ "loss": 2.791153335571289,
313
+ "peak_memory_gb": 33.261869056,
314
+ "step": 370
315
+ },
316
+ {
317
+ "epoch": 1.484375,
318
+ "grad_norm": 0.65625,
319
+ "learning_rate": 1e-05,
320
+ "loss": 2.778514862060547,
321
+ "peak_memory_gb": 33.261869056,
322
+ "step": 380
323
+ },
324
+ {
325
+ "epoch": 1.5234375,
326
+ "grad_norm": 0.7421875,
327
+ "learning_rate": 1e-05,
328
+ "loss": 2.7769107818603516,
329
+ "peak_memory_gb": 33.261869056,
330
+ "step": 390
331
+ },
332
+ {
333
+ "epoch": 1.5625,
334
+ "grad_norm": 0.68359375,
335
+ "learning_rate": 1e-05,
336
+ "loss": 2.77652587890625,
337
+ "peak_memory_gb": 33.261869056,
338
+ "step": 400
339
+ },
340
+ {
341
+ "epoch": 1.6015625,
342
+ "grad_norm": 0.6796875,
343
+ "learning_rate": 1e-05,
344
+ "loss": 2.7853885650634767,
345
+ "peak_memory_gb": 33.261869056,
346
+ "step": 410
347
+ },
348
+ {
349
+ "epoch": 1.640625,
350
+ "grad_norm": 0.671875,
351
+ "learning_rate": 1e-05,
352
+ "loss": 2.7796741485595704,
353
+ "peak_memory_gb": 33.261869056,
354
+ "step": 420
355
+ },
356
+ {
357
+ "epoch": 1.6796875,
358
+ "grad_norm": 0.73046875,
359
+ "learning_rate": 1e-05,
360
+ "loss": 2.7735328674316406,
361
+ "peak_memory_gb": 33.261869056,
362
+ "step": 430
363
+ },
364
+ {
365
+ "epoch": 1.71875,
366
+ "grad_norm": 0.69140625,
367
+ "learning_rate": 1e-05,
368
+ "loss": 2.769553375244141,
369
+ "peak_memory_gb": 35.073275392,
370
+ "step": 440
371
+ },
372
+ {
373
+ "epoch": 1.7578125,
374
+ "grad_norm": 0.7265625,
375
+ "learning_rate": 1e-05,
376
+ "loss": 2.7759775161743163,
377
+ "peak_memory_gb": 35.073275392,
378
+ "step": 450
379
+ },
380
+ {
381
+ "epoch": 1.796875,
382
+ "grad_norm": 0.6875,
383
+ "learning_rate": 1e-05,
384
+ "loss": 2.766854667663574,
385
+ "peak_memory_gb": 35.073275392,
386
+ "step": 460
387
+ },
388
+ {
389
+ "epoch": 1.8359375,
390
+ "grad_norm": 0.71875,
391
+ "learning_rate": 1e-05,
392
+ "loss": 2.7699207305908202,
393
+ "peak_memory_gb": 35.073275392,
394
+ "step": 470
395
+ },
396
+ {
397
+ "epoch": 1.875,
398
+ "grad_norm": 0.71484375,
399
+ "learning_rate": 1e-05,
400
+ "loss": 2.7691329956054687,
401
+ "peak_memory_gb": 35.073275392,
402
+ "step": 480
403
+ },
404
+ {
405
+ "epoch": 1.9140625,
406
+ "grad_norm": 0.6875,
407
+ "learning_rate": 1e-05,
408
+ "loss": 2.7650177001953127,
409
+ "peak_memory_gb": 35.073275392,
410
+ "step": 490
411
+ },
412
+ {
413
+ "epoch": 1.953125,
414
+ "grad_norm": 0.72265625,
415
+ "learning_rate": 1e-05,
416
+ "loss": 2.7569034576416014,
417
+ "peak_memory_gb": 35.073275392,
418
+ "step": 500
419
+ },
420
+ {
421
+ "epoch": 1.9921875,
422
+ "grad_norm": 0.71484375,
423
+ "learning_rate": 1e-05,
424
+ "loss": 2.7650472640991213,
425
+ "peak_memory_gb": 35.073275392,
426
+ "step": 510
427
+ },
428
+ {
429
+ "epoch": 2.03125,
430
+ "grad_norm": 0.73046875,
431
+ "learning_rate": 1e-05,
432
+ "loss": 2.7320432662963867,
433
+ "peak_memory_gb": 35.073275392,
434
+ "step": 520
435
+ },
436
+ {
437
+ "epoch": 2.0703125,
438
+ "grad_norm": 0.7421875,
439
+ "learning_rate": 1e-05,
440
+ "loss": 2.7237575531005858,
441
+ "peak_memory_gb": 35.073275392,
442
+ "step": 530
443
+ },
444
+ {
445
+ "epoch": 2.109375,
446
+ "grad_norm": 0.73046875,
447
+ "learning_rate": 1e-05,
448
+ "loss": 2.7229169845581054,
449
+ "peak_memory_gb": 35.073275392,
450
+ "step": 540
451
+ },
452
+ {
453
+ "epoch": 2.1484375,
454
+ "grad_norm": 0.75390625,
455
+ "learning_rate": 1e-05,
456
+ "loss": 2.7249526977539062,
457
+ "peak_memory_gb": 35.073275392,
458
+ "step": 550
459
+ },
460
+ {
461
+ "epoch": 2.1875,
462
+ "grad_norm": 0.71875,
463
+ "learning_rate": 1e-05,
464
+ "loss": 2.7232284545898438,
465
+ "peak_memory_gb": 35.073275392,
466
+ "step": 560
467
+ },
468
+ {
469
+ "epoch": 2.2265625,
470
+ "grad_norm": 0.734375,
471
+ "learning_rate": 1e-05,
472
+ "loss": 2.7286935806274415,
473
+ "peak_memory_gb": 35.073275392,
474
+ "step": 570
475
+ },
476
+ {
477
+ "epoch": 2.265625,
478
+ "grad_norm": 0.71875,
479
+ "learning_rate": 1e-05,
480
+ "loss": 2.718952178955078,
481
+ "peak_memory_gb": 35.073275392,
482
+ "step": 580
483
+ },
484
+ {
485
+ "epoch": 2.3046875,
486
+ "grad_norm": 0.73828125,
487
+ "learning_rate": 1e-05,
488
+ "loss": 2.7255008697509764,
489
+ "peak_memory_gb": 36.162281472,
490
+ "step": 590
491
+ },
492
+ {
493
+ "epoch": 2.34375,
494
+ "grad_norm": 0.75390625,
495
+ "learning_rate": 1e-05,
496
+ "loss": 2.7197078704833983,
497
+ "peak_memory_gb": 36.162281472,
498
+ "step": 600
499
+ },
500
+ {
501
+ "epoch": 2.34375,
502
+ "eval_loss": 2.758209228515625,
503
+ "eval_runtime": 5.5466,
504
+ "eval_samples_per_second": 901.461,
505
+ "eval_steps_per_second": 56.431,
506
+ "step": 600
507
+ },
508
+ {
509
+ "epoch": 2.3828125,
510
+ "grad_norm": 0.7734375,
511
+ "learning_rate": 1e-05,
512
+ "loss": 2.7179801940917967,
513
+ "peak_memory_gb": 36.162281472,
514
+ "step": 610
515
+ },
516
+ {
517
+ "epoch": 2.421875,
518
+ "grad_norm": 0.7265625,
519
+ "learning_rate": 1e-05,
520
+ "loss": 2.7176647186279297,
521
+ "peak_memory_gb": 36.162281472,
522
+ "step": 620
523
+ },
524
+ {
525
+ "epoch": 2.4609375,
526
+ "grad_norm": 0.75390625,
527
+ "learning_rate": 1e-05,
528
+ "loss": 2.7148614883422852,
529
+ "peak_memory_gb": 36.162281472,
530
+ "step": 630
531
+ },
532
+ {
533
+ "epoch": 2.5,
534
+ "grad_norm": 0.75,
535
+ "learning_rate": 1e-05,
536
+ "loss": 2.7160934448242187,
537
+ "peak_memory_gb": 36.162281472,
538
+ "step": 640
539
+ },
540
+ {
541
+ "epoch": 2.5390625,
542
+ "grad_norm": 0.73046875,
543
+ "learning_rate": 1e-05,
544
+ "loss": 2.7181243896484375,
545
+ "peak_memory_gb": 36.162281472,
546
+ "step": 650
547
+ },
548
+ {
549
+ "epoch": 2.578125,
550
+ "grad_norm": 0.75,
551
+ "learning_rate": 1e-05,
552
+ "loss": 2.7166576385498047,
553
+ "peak_memory_gb": 36.162281472,
554
+ "step": 660
555
+ },
556
+ {
557
+ "epoch": 2.6171875,
558
+ "grad_norm": 0.75390625,
559
+ "learning_rate": 1e-05,
560
+ "loss": 2.711897850036621,
561
+ "peak_memory_gb": 36.162281472,
562
+ "step": 670
563
+ },
564
+ {
565
+ "epoch": 2.65625,
566
+ "grad_norm": 0.734375,
567
+ "learning_rate": 1e-05,
568
+ "loss": 2.707488441467285,
569
+ "peak_memory_gb": 36.162281472,
570
+ "step": 680
571
+ },
572
+ {
573
+ "epoch": 2.6953125,
574
+ "grad_norm": 0.734375,
575
+ "learning_rate": 1e-05,
576
+ "loss": 2.719575119018555,
577
+ "peak_memory_gb": 36.162281472,
578
+ "step": 690
579
+ },
580
+ {
581
+ "epoch": 2.734375,
582
+ "grad_norm": 0.74609375,
583
+ "learning_rate": 1e-05,
584
+ "loss": 2.705914306640625,
585
+ "peak_memory_gb": 36.162281472,
586
+ "step": 700
587
+ },
588
+ {
589
+ "epoch": 2.7734375,
590
+ "grad_norm": 0.765625,
591
+ "learning_rate": 1e-05,
592
+ "loss": 2.7060680389404297,
593
+ "peak_memory_gb": 36.162281472,
594
+ "step": 710
595
+ },
596
+ {
597
+ "epoch": 2.8125,
598
+ "grad_norm": 0.75,
599
+ "learning_rate": 1e-05,
600
+ "loss": 2.7111604690551756,
601
+ "peak_memory_gb": 36.162281472,
602
+ "step": 720
603
+ },
604
+ {
605
+ "epoch": 2.8515625,
606
+ "grad_norm": 0.765625,
607
+ "learning_rate": 1e-05,
608
+ "loss": 2.695046615600586,
609
+ "peak_memory_gb": 36.162281472,
610
+ "step": 730
611
+ },
612
+ {
613
+ "epoch": 2.890625,
614
+ "grad_norm": 0.7265625,
615
+ "learning_rate": 1e-05,
616
+ "loss": 2.7094518661499025,
617
+ "peak_memory_gb": 36.162281472,
618
+ "step": 740
619
+ },
620
+ {
621
+ "epoch": 2.9296875,
622
+ "grad_norm": 0.7734375,
623
+ "learning_rate": 1e-05,
624
+ "loss": 2.708672523498535,
625
+ "peak_memory_gb": 36.162281472,
626
+ "step": 750
627
+ },
628
+ {
629
+ "epoch": 2.96875,
630
+ "grad_norm": 0.75,
631
+ "learning_rate": 1e-05,
632
+ "loss": 2.709148406982422,
633
+ "peak_memory_gb": 36.162281472,
634
+ "step": 760
635
+ },
636
+ {
637
+ "epoch": 3.0078125,
638
+ "grad_norm": 0.79296875,
639
+ "learning_rate": 1e-05,
640
+ "loss": 2.6994747161865233,
641
+ "peak_memory_gb": 36.162281472,
642
+ "step": 770
643
+ },
644
+ {
645
+ "epoch": 3.046875,
646
+ "grad_norm": 0.80078125,
647
+ "learning_rate": 1e-05,
648
+ "loss": 2.6721710205078124,
649
+ "peak_memory_gb": 36.162281472,
650
+ "step": 780
651
+ },
652
+ {
653
+ "epoch": 3.0859375,
654
+ "grad_norm": 0.828125,
655
+ "learning_rate": 1e-05,
656
+ "loss": 2.6629398345947264,
657
+ "peak_memory_gb": 36.162281472,
658
+ "step": 790
659
+ },
660
+ {
661
+ "epoch": 3.125,
662
+ "grad_norm": 0.7890625,
663
+ "learning_rate": 1e-05,
664
+ "loss": 2.6726362228393556,
665
+ "peak_memory_gb": 36.162281472,
666
+ "step": 800
667
+ },
668
+ {
669
+ "epoch": 3.1640625,
670
+ "grad_norm": 0.80859375,
671
+ "learning_rate": 1e-05,
672
+ "loss": 2.670452117919922,
673
+ "peak_memory_gb": 36.162281472,
674
+ "step": 810
675
+ },
676
+ {
677
+ "epoch": 3.203125,
678
+ "grad_norm": 0.78515625,
679
+ "learning_rate": 1e-05,
680
+ "loss": 2.6675580978393554,
681
+ "peak_memory_gb": 36.162281472,
682
+ "step": 820
683
+ },
684
+ {
685
+ "epoch": 3.2421875,
686
+ "grad_norm": 0.76171875,
687
+ "learning_rate": 1e-05,
688
+ "loss": 2.6670658111572267,
689
+ "peak_memory_gb": 36.162281472,
690
+ "step": 830
691
+ },
692
+ {
693
+ "epoch": 3.28125,
694
+ "grad_norm": 0.80078125,
695
+ "learning_rate": 1e-05,
696
+ "loss": 2.6604549407958986,
697
+ "peak_memory_gb": 36.162281472,
698
+ "step": 840
699
+ },
700
+ {
701
+ "epoch": 3.3203125,
702
+ "grad_norm": 0.77734375,
703
+ "learning_rate": 1e-05,
704
+ "loss": 2.6784996032714843,
705
+ "peak_memory_gb": 36.162281472,
706
+ "step": 850
707
+ },
708
+ {
709
+ "epoch": 3.359375,
710
+ "grad_norm": 0.765625,
711
+ "learning_rate": 1e-05,
712
+ "loss": 2.673480987548828,
713
+ "peak_memory_gb": 36.162281472,
714
+ "step": 860
715
+ },
716
+ {
717
+ "epoch": 3.3984375,
718
+ "grad_norm": 0.80859375,
719
+ "learning_rate": 1e-05,
720
+ "loss": 2.675128936767578,
721
+ "peak_memory_gb": 36.162281472,
722
+ "step": 870
723
+ },
724
+ {
725
+ "epoch": 3.4375,
726
+ "grad_norm": 0.77734375,
727
+ "learning_rate": 1e-05,
728
+ "loss": 2.6588287353515625,
729
+ "peak_memory_gb": 36.162281472,
730
+ "step": 880
731
+ },
732
+ {
733
+ "epoch": 3.4765625,
734
+ "grad_norm": 0.7734375,
735
+ "learning_rate": 1e-05,
736
+ "loss": 2.6681121826171874,
737
+ "peak_memory_gb": 36.162281472,
738
+ "step": 890
739
+ },
740
+ {
741
+ "epoch": 3.515625,
742
+ "grad_norm": 0.80859375,
743
+ "learning_rate": 1e-05,
744
+ "loss": 2.674784851074219,
745
+ "peak_memory_gb": 36.162281472,
746
+ "step": 900
747
+ },
748
+ {
749
+ "epoch": 3.515625,
750
+ "eval_loss": 2.730496644973755,
751
+ "eval_runtime": 5.4299,
752
+ "eval_samples_per_second": 920.823,
753
+ "eval_steps_per_second": 57.644,
754
+ "step": 900
755
+ },
756
+ {
757
+ "epoch": 3.5546875,
758
+ "grad_norm": 0.84375,
759
+ "learning_rate": 1e-05,
760
+ "loss": 2.669995880126953,
761
+ "peak_memory_gb": 36.162281472,
762
+ "step": 910
763
+ },
764
+ {
765
+ "epoch": 3.59375,
766
+ "grad_norm": 0.8203125,
767
+ "learning_rate": 1e-05,
768
+ "loss": 2.6643184661865233,
769
+ "peak_memory_gb": 36.162281472,
770
+ "step": 920
771
+ },
772
+ {
773
+ "epoch": 3.6328125,
774
+ "grad_norm": 0.80078125,
775
+ "learning_rate": 1e-05,
776
+ "loss": 2.661349868774414,
777
+ "peak_memory_gb": 36.162281472,
778
+ "step": 930
779
+ },
780
+ {
781
+ "epoch": 3.671875,
782
+ "grad_norm": 0.7890625,
783
+ "learning_rate": 1e-05,
784
+ "loss": 2.6585548400878904,
785
+ "peak_memory_gb": 36.162281472,
786
+ "step": 940
787
+ },
788
+ {
789
+ "epoch": 3.7109375,
790
+ "grad_norm": 0.80078125,
791
+ "learning_rate": 1e-05,
792
+ "loss": 2.656528854370117,
793
+ "peak_memory_gb": 36.162281472,
794
+ "step": 950
795
+ },
796
+ {
797
+ "epoch": 3.75,
798
+ "grad_norm": 0.7890625,
799
+ "learning_rate": 1e-05,
800
+ "loss": 2.6740203857421876,
801
+ "peak_memory_gb": 36.162281472,
802
+ "step": 960
803
+ },
804
+ {
805
+ "epoch": 3.7890625,
806
+ "grad_norm": 0.81640625,
807
+ "learning_rate": 1e-05,
808
+ "loss": 2.6642642974853517,
809
+ "peak_memory_gb": 36.162281472,
810
+ "step": 970
811
+ },
812
+ {
813
+ "epoch": 3.828125,
814
+ "grad_norm": 0.8046875,
815
+ "learning_rate": 1e-05,
816
+ "loss": 2.6660499572753906,
817
+ "peak_memory_gb": 36.162281472,
818
+ "step": 980
819
+ },
820
+ {
821
+ "epoch": 3.8671875,
822
+ "grad_norm": 0.78515625,
823
+ "learning_rate": 1e-05,
824
+ "loss": 2.6650630950927736,
825
+ "peak_memory_gb": 36.162281472,
826
+ "step": 990
827
+ },
828
+ {
829
+ "epoch": 3.90625,
830
+ "grad_norm": 0.796875,
831
+ "learning_rate": 1e-05,
832
+ "loss": 2.6630496978759766,
833
+ "peak_memory_gb": 36.162281472,
834
+ "step": 1000
835
+ },
836
+ {
837
+ "epoch": 3.9453125,
838
+ "grad_norm": 0.77734375,
839
+ "learning_rate": 1e-05,
840
+ "loss": 2.673343849182129,
841
+ "peak_memory_gb": 36.162281472,
842
+ "step": 1010
843
+ },
844
+ {
845
+ "epoch": 3.984375,
846
+ "grad_norm": 0.83203125,
847
+ "learning_rate": 1e-05,
848
+ "loss": 2.6669689178466798,
849
+ "peak_memory_gb": 36.162281472,
850
+ "step": 1020
851
+ },
852
+ {
853
+ "epoch": 4.0234375,
854
+ "grad_norm": 0.82421875,
855
+ "learning_rate": 1e-05,
856
+ "loss": 2.6344816207885744,
857
+ "peak_memory_gb": 36.162281472,
858
+ "step": 1030
859
+ },
860
+ {
861
+ "epoch": 4.0625,
862
+ "grad_norm": 0.84375,
863
+ "learning_rate": 1e-05,
864
+ "loss": 2.619381141662598,
865
+ "peak_memory_gb": 36.162281472,
866
+ "step": 1040
867
+ },
868
+ {
869
+ "epoch": 4.1015625,
870
+ "grad_norm": 0.8359375,
871
+ "learning_rate": 1e-05,
872
+ "loss": 2.619989013671875,
873
+ "peak_memory_gb": 36.162281472,
874
+ "step": 1050
875
+ },
876
+ {
877
+ "epoch": 4.140625,
878
+ "grad_norm": 0.83203125,
879
+ "learning_rate": 1e-05,
880
+ "loss": 2.628530502319336,
881
+ "peak_memory_gb": 36.162281472,
882
+ "step": 1060
883
+ },
884
+ {
885
+ "epoch": 4.1796875,
886
+ "grad_norm": 0.8671875,
887
+ "learning_rate": 1e-05,
888
+ "loss": 2.6249130249023436,
889
+ "peak_memory_gb": 36.162281472,
890
+ "step": 1070
891
+ },
892
+ {
893
+ "epoch": 4.21875,
894
+ "grad_norm": 0.88671875,
895
+ "learning_rate": 1e-05,
896
+ "loss": 2.6236246109008787,
897
+ "peak_memory_gb": 36.162281472,
898
+ "step": 1080
899
+ },
900
+ {
901
+ "epoch": 4.2578125,
902
+ "grad_norm": 0.83984375,
903
+ "learning_rate": 1e-05,
904
+ "loss": 2.6338336944580076,
905
+ "peak_memory_gb": 36.162281472,
906
+ "step": 1090
907
+ },
908
+ {
909
+ "epoch": 4.296875,
910
+ "grad_norm": 0.82421875,
911
+ "learning_rate": 1e-05,
912
+ "loss": 2.626003646850586,
913
+ "peak_memory_gb": 36.162281472,
914
+ "step": 1100
915
+ },
916
+ {
917
+ "epoch": 4.3359375,
918
+ "grad_norm": 0.8203125,
919
+ "learning_rate": 1e-05,
920
+ "loss": 2.624416732788086,
921
+ "peak_memory_gb": 36.162281472,
922
+ "step": 1110
923
+ },
924
+ {
925
+ "epoch": 4.375,
926
+ "grad_norm": 0.828125,
927
+ "learning_rate": 1e-05,
928
+ "loss": 2.6280776977539064,
929
+ "peak_memory_gb": 36.162281472,
930
+ "step": 1120
931
+ },
932
+ {
933
+ "epoch": 4.4140625,
934
+ "grad_norm": 0.80859375,
935
+ "learning_rate": 1e-05,
936
+ "loss": 2.6391231536865236,
937
+ "peak_memory_gb": 36.162281472,
938
+ "step": 1130
939
+ },
940
+ {
941
+ "epoch": 4.453125,
942
+ "grad_norm": 0.8359375,
943
+ "learning_rate": 1e-05,
944
+ "loss": 2.6283512115478516,
945
+ "peak_memory_gb": 36.162281472,
946
+ "step": 1140
947
+ },
948
+ {
949
+ "epoch": 4.4921875,
950
+ "grad_norm": 0.81640625,
951
+ "learning_rate": 1e-05,
952
+ "loss": 2.633097457885742,
953
+ "peak_memory_gb": 36.162281472,
954
+ "step": 1150
955
+ },
956
+ {
957
+ "epoch": 4.53125,
958
+ "grad_norm": 0.80859375,
959
+ "learning_rate": 1e-05,
960
+ "loss": 2.6306251525878905,
961
+ "peak_memory_gb": 36.162281472,
962
+ "step": 1160
963
+ },
964
+ {
965
+ "epoch": 4.5703125,
966
+ "grad_norm": 0.8359375,
967
+ "learning_rate": 1e-05,
968
+ "loss": 2.631344032287598,
969
+ "peak_memory_gb": 36.162281472,
970
+ "step": 1170
971
+ },
972
+ {
973
+ "epoch": 4.609375,
974
+ "grad_norm": 0.8203125,
975
+ "learning_rate": 1e-05,
976
+ "loss": 2.634329605102539,
977
+ "peak_memory_gb": 36.162281472,
978
+ "step": 1180
979
+ },
980
+ {
981
+ "epoch": 4.6484375,
982
+ "grad_norm": 0.84375,
983
+ "learning_rate": 1e-05,
984
+ "loss": 2.636922073364258,
985
+ "peak_memory_gb": 36.162281472,
986
+ "step": 1190
987
+ },
988
+ {
989
+ "epoch": 4.6875,
990
+ "grad_norm": 0.81640625,
991
+ "learning_rate": 1e-05,
992
+ "loss": 2.6364368438720702,
993
+ "peak_memory_gb": 36.162281472,
994
+ "step": 1200
995
+ },
996
+ {
997
+ "epoch": 4.6875,
998
+ "eval_loss": 2.719906806945801,
999
+ "eval_runtime": 5.4962,
1000
+ "eval_samples_per_second": 909.717,
1001
+ "eval_steps_per_second": 56.948,
1002
+ "step": 1200
1003
+ },
1004
+ {
1005
+ "epoch": 4.7265625,
1006
+ "grad_norm": 0.8515625,
1007
+ "learning_rate": 1e-05,
1008
+ "loss": 2.624860382080078,
1009
+ "peak_memory_gb": 36.162281472,
1010
+ "step": 1210
1011
+ },
1012
+ {
1013
+ "epoch": 4.765625,
1014
+ "grad_norm": 0.79296875,
1015
+ "learning_rate": 1e-05,
1016
+ "loss": 2.6290973663330077,
1017
+ "peak_memory_gb": 36.162281472,
1018
+ "step": 1220
1019
+ },
1020
+ {
1021
+ "epoch": 4.8046875,
1022
+ "grad_norm": 0.8203125,
1023
+ "learning_rate": 1e-05,
1024
+ "loss": 2.639656829833984,
1025
+ "peak_memory_gb": 36.162281472,
1026
+ "step": 1230
1027
+ },
1028
+ {
1029
+ "epoch": 4.84375,
1030
+ "grad_norm": 0.82421875,
1031
+ "learning_rate": 1e-05,
1032
+ "loss": 2.6326671600341798,
1033
+ "peak_memory_gb": 36.162281472,
1034
+ "step": 1240
1035
+ },
1036
+ {
1037
+ "epoch": 4.8828125,
1038
+ "grad_norm": 0.8125,
1039
+ "learning_rate": 1e-05,
1040
+ "loss": 2.6296226501464846,
1041
+ "peak_memory_gb": 36.162281472,
1042
+ "step": 1250
1043
+ },
1044
+ {
1045
+ "epoch": 4.921875,
1046
+ "grad_norm": 0.84375,
1047
+ "learning_rate": 1e-05,
1048
+ "loss": 2.6387081146240234,
1049
+ "peak_memory_gb": 36.162281472,
1050
+ "step": 1260
1051
+ },
1052
+ {
1053
+ "epoch": 4.9609375,
1054
+ "grad_norm": 0.8125,
1055
+ "learning_rate": 1e-05,
1056
+ "loss": 2.6305362701416017,
1057
+ "peak_memory_gb": 36.162281472,
1058
+ "step": 1270
1059
+ },
1060
+ {
1061
+ "epoch": 5.0,
1062
+ "grad_norm": 0.82421875,
1063
+ "learning_rate": 1e-05,
1064
+ "loss": 2.6328319549560546,
1065
+ "peak_memory_gb": 36.162281472,
1066
+ "step": 1280
1067
+ },
1068
+ {
1069
+ "epoch": 5.0390625,
1070
+ "grad_norm": 0.92578125,
1071
+ "learning_rate": 1e-05,
1072
+ "loss": 2.582319641113281,
1073
+ "peak_memory_gb": 36.162281472,
1074
+ "step": 1290
1075
+ },
1076
+ {
1077
+ "epoch": 5.078125,
1078
+ "grad_norm": 0.8515625,
1079
+ "learning_rate": 1e-05,
1080
+ "loss": 2.5853641510009764,
1081
+ "peak_memory_gb": 36.162281472,
1082
+ "step": 1300
1083
+ },
1084
+ {
1085
+ "epoch": 5.1171875,
1086
+ "grad_norm": 0.86328125,
1087
+ "learning_rate": 1e-05,
1088
+ "loss": 2.585224914550781,
1089
+ "peak_memory_gb": 36.162281472,
1090
+ "step": 1310
1091
+ },
1092
+ {
1093
+ "epoch": 5.15625,
1094
+ "grad_norm": 0.88671875,
1095
+ "learning_rate": 1e-05,
1096
+ "loss": 2.585912895202637,
1097
+ "peak_memory_gb": 36.162281472,
1098
+ "step": 1320
1099
+ },
1100
+ {
1101
+ "epoch": 5.1953125,
1102
+ "grad_norm": 0.8828125,
1103
+ "learning_rate": 1e-05,
1104
+ "loss": 2.586836242675781,
1105
+ "peak_memory_gb": 36.162281472,
1106
+ "step": 1330
1107
+ },
1108
+ {
1109
+ "epoch": 5.234375,
1110
+ "grad_norm": 0.875,
1111
+ "learning_rate": 1e-05,
1112
+ "loss": 2.5931711196899414,
1113
+ "peak_memory_gb": 36.162281472,
1114
+ "step": 1340
1115
+ },
1116
+ {
1117
+ "epoch": 5.2734375,
1118
+ "grad_norm": 0.8671875,
1119
+ "learning_rate": 1e-05,
1120
+ "loss": 2.5919418334960938,
1121
+ "peak_memory_gb": 36.162281472,
1122
+ "step": 1350
1123
+ },
1124
+ {
1125
+ "epoch": 5.3125,
1126
+ "grad_norm": 0.875,
1127
+ "learning_rate": 1e-05,
1128
+ "loss": 2.5943426132202148,
1129
+ "peak_memory_gb": 36.162281472,
1130
+ "step": 1360
1131
+ },
1132
+ {
1133
+ "epoch": 5.3515625,
1134
+ "grad_norm": 0.90234375,
1135
+ "learning_rate": 1e-05,
1136
+ "loss": 2.5997901916503907,
1137
+ "peak_memory_gb": 36.162281472,
1138
+ "step": 1370
1139
+ },
1140
+ {
1141
+ "epoch": 5.390625,
1142
+ "grad_norm": 0.88671875,
1143
+ "learning_rate": 1e-05,
1144
+ "loss": 2.5947338104248048,
1145
+ "peak_memory_gb": 36.162281472,
1146
+ "step": 1380
1147
+ },
1148
+ {
1149
+ "epoch": 5.4296875,
1150
+ "grad_norm": 0.86328125,
1151
+ "learning_rate": 1e-05,
1152
+ "loss": 2.5950151443481446,
1153
+ "peak_memory_gb": 36.162281472,
1154
+ "step": 1390
1155
+ },
1156
+ {
1157
+ "epoch": 5.46875,
1158
+ "grad_norm": 0.8515625,
1159
+ "learning_rate": 1e-05,
1160
+ "loss": 2.599467468261719,
1161
+ "peak_memory_gb": 36.162281472,
1162
+ "step": 1400
1163
+ },
1164
+ {
1165
+ "epoch": 5.5078125,
1166
+ "grad_norm": 0.86328125,
1167
+ "learning_rate": 1e-05,
1168
+ "loss": 2.6039108276367187,
1169
+ "peak_memory_gb": 36.162281472,
1170
+ "step": 1410
1171
+ },
1172
+ {
1173
+ "epoch": 5.546875,
1174
+ "grad_norm": 0.859375,
1175
+ "learning_rate": 1e-05,
1176
+ "loss": 2.5986459732055662,
1177
+ "peak_memory_gb": 36.162281472,
1178
+ "step": 1420
1179
+ },
1180
+ {
1181
+ "epoch": 5.5859375,
1182
+ "grad_norm": 0.8671875,
1183
+ "learning_rate": 1e-05,
1184
+ "loss": 2.598154830932617,
1185
+ "peak_memory_gb": 36.162281472,
1186
+ "step": 1430
1187
+ },
1188
+ {
1189
+ "epoch": 5.625,
1190
+ "grad_norm": 0.86328125,
1191
+ "learning_rate": 1e-05,
1192
+ "loss": 2.600543212890625,
1193
+ "peak_memory_gb": 36.162281472,
1194
+ "step": 1440
1195
+ },
1196
+ {
1197
+ "epoch": 5.6640625,
1198
+ "grad_norm": 0.859375,
1199
+ "learning_rate": 1e-05,
1200
+ "loss": 2.605610656738281,
1201
+ "peak_memory_gb": 36.162281472,
1202
+ "step": 1450
1203
+ },
1204
+ {
1205
+ "epoch": 5.703125,
1206
+ "grad_norm": 0.87109375,
1207
+ "learning_rate": 1e-05,
1208
+ "loss": 2.609627342224121,
1209
+ "peak_memory_gb": 36.162281472,
1210
+ "step": 1460
1211
+ },
1212
+ {
1213
+ "epoch": 5.7421875,
1214
+ "grad_norm": 0.85546875,
1215
+ "learning_rate": 1e-05,
1216
+ "loss": 2.6009960174560547,
1217
+ "peak_memory_gb": 36.162281472,
1218
+ "step": 1470
1219
+ },
1220
+ {
1221
+ "epoch": 5.78125,
1222
+ "grad_norm": 0.8671875,
1223
+ "learning_rate": 1e-05,
1224
+ "loss": 2.6043052673339844,
1225
+ "peak_memory_gb": 36.162281472,
1226
+ "step": 1480
1227
+ },
1228
+ {
1229
+ "epoch": 5.8203125,
1230
+ "grad_norm": 0.84375,
1231
+ "learning_rate": 1e-05,
1232
+ "loss": 2.6037151336669924,
1233
+ "peak_memory_gb": 36.162281472,
1234
+ "step": 1490
1235
+ },
1236
+ {
1237
+ "epoch": 5.859375,
1238
+ "grad_norm": 0.87890625,
1239
+ "learning_rate": 1e-05,
1240
+ "loss": 2.6092369079589846,
1241
+ "peak_memory_gb": 36.162281472,
1242
+ "step": 1500
1243
+ },
1244
+ {
1245
+ "epoch": 5.859375,
1246
+ "eval_loss": 2.7162508964538574,
1247
+ "eval_runtime": 5.6246,
1248
+ "eval_samples_per_second": 888.946,
1249
+ "eval_steps_per_second": 55.648,
1250
+ "step": 1500
1251
+ },
1252
+ {
1253
+ "epoch": 5.8984375,
1254
+ "grad_norm": 0.84765625,
1255
+ "learning_rate": 1e-05,
1256
+ "loss": 2.5953659057617187,
1257
+ "peak_memory_gb": 36.162281472,
1258
+ "step": 1510
1259
+ },
1260
+ {
1261
+ "epoch": 5.9375,
1262
+ "grad_norm": 0.8671875,
1263
+ "learning_rate": 1e-05,
1264
+ "loss": 2.599634552001953,
1265
+ "peak_memory_gb": 36.162281472,
1266
+ "step": 1520
1267
+ },
1268
+ {
1269
+ "epoch": 5.9765625,
1270
+ "grad_norm": 0.85546875,
1271
+ "learning_rate": 1e-05,
1272
+ "loss": 2.603537940979004,
1273
+ "peak_memory_gb": 36.162281472,
1274
+ "step": 1530
1275
+ },
1276
+ {
1277
+ "epoch": 6.015625,
1278
+ "grad_norm": 0.88671875,
1279
+ "learning_rate": 1e-05,
1280
+ "loss": 2.5820938110351563,
1281
+ "peak_memory_gb": 36.162281472,
1282
+ "step": 1540
1283
+ },
1284
+ {
1285
+ "epoch": 6.0546875,
1286
+ "grad_norm": 0.94140625,
1287
+ "learning_rate": 1e-05,
1288
+ "loss": 2.554993438720703,
1289
+ "peak_memory_gb": 36.162281472,
1290
+ "step": 1550
1291
+ },
1292
+ {
1293
+ "epoch": 6.09375,
1294
+ "grad_norm": 0.93359375,
1295
+ "learning_rate": 1e-05,
1296
+ "loss": 2.55153751373291,
1297
+ "peak_memory_gb": 36.162281472,
1298
+ "step": 1560
1299
+ },
1300
+ {
1301
+ "epoch": 6.1328125,
1302
+ "grad_norm": 0.9296875,
1303
+ "learning_rate": 1e-05,
1304
+ "loss": 2.557958984375,
1305
+ "peak_memory_gb": 36.162281472,
1306
+ "step": 1570
1307
+ },
1308
+ {
1309
+ "epoch": 6.171875,
1310
+ "grad_norm": 0.91015625,
1311
+ "learning_rate": 1e-05,
1312
+ "loss": 2.553592300415039,
1313
+ "peak_memory_gb": 36.162281472,
1314
+ "step": 1580
1315
+ },
1316
+ {
1317
+ "epoch": 6.2109375,
1318
+ "grad_norm": 0.93359375,
1319
+ "learning_rate": 1e-05,
1320
+ "loss": 2.551940155029297,
1321
+ "peak_memory_gb": 36.162281472,
1322
+ "step": 1590
1323
+ },
1324
+ {
1325
+ "epoch": 6.25,
1326
+ "grad_norm": 0.9609375,
1327
+ "learning_rate": 1e-05,
1328
+ "loss": 2.5586257934570313,
1329
+ "peak_memory_gb": 36.162281472,
1330
+ "step": 1600
1331
+ },
1332
+ {
1333
+ "epoch": 6.2890625,
1334
+ "grad_norm": 0.9296875,
1335
+ "learning_rate": 1e-05,
1336
+ "loss": 2.5649234771728517,
1337
+ "peak_memory_gb": 36.162281472,
1338
+ "step": 1610
1339
+ },
1340
+ {
1341
+ "epoch": 6.328125,
1342
+ "grad_norm": 0.91796875,
1343
+ "learning_rate": 1e-05,
1344
+ "loss": 2.565362548828125,
1345
+ "peak_memory_gb": 36.162281472,
1346
+ "step": 1620
1347
+ },
1348
+ {
1349
+ "epoch": 6.3671875,
1350
+ "grad_norm": 0.9296875,
1351
+ "learning_rate": 1e-05,
1352
+ "loss": 2.569253921508789,
1353
+ "peak_memory_gb": 36.162281472,
1354
+ "step": 1630
1355
+ },
1356
+ {
1357
+ "epoch": 6.40625,
1358
+ "grad_norm": 0.921875,
1359
+ "learning_rate": 1e-05,
1360
+ "loss": 2.564670944213867,
1361
+ "peak_memory_gb": 36.162281472,
1362
+ "step": 1640
1363
+ },
1364
+ {
1365
+ "epoch": 6.4453125,
1366
+ "grad_norm": 0.90234375,
1367
+ "learning_rate": 1e-05,
1368
+ "loss": 2.561754035949707,
1369
+ "peak_memory_gb": 36.162281472,
1370
+ "step": 1650
1371
+ },
1372
+ {
1373
+ "epoch": 6.484375,
1374
+ "grad_norm": 0.8984375,
1375
+ "learning_rate": 1e-05,
1376
+ "loss": 2.567065620422363,
1377
+ "peak_memory_gb": 36.162281472,
1378
+ "step": 1660
1379
+ },
1380
+ {
1381
+ "epoch": 6.5234375,
1382
+ "grad_norm": 0.9296875,
1383
+ "learning_rate": 1e-05,
1384
+ "loss": 2.562160873413086,
1385
+ "peak_memory_gb": 36.162281472,
1386
+ "step": 1670
1387
+ },
1388
+ {
1389
+ "epoch": 6.5625,
1390
+ "grad_norm": 0.91015625,
1391
+ "learning_rate": 1e-05,
1392
+ "loss": 2.566408157348633,
1393
+ "peak_memory_gb": 36.162281472,
1394
+ "step": 1680
1395
+ },
1396
+ {
1397
+ "epoch": 6.6015625,
1398
+ "grad_norm": 0.92578125,
1399
+ "learning_rate": 1e-05,
1400
+ "loss": 2.5660804748535155,
1401
+ "peak_memory_gb": 36.162281472,
1402
+ "step": 1690
1403
+ },
1404
+ {
1405
+ "epoch": 6.640625,
1406
+ "grad_norm": 0.91796875,
1407
+ "learning_rate": 1e-05,
1408
+ "loss": 2.5780426025390626,
1409
+ "peak_memory_gb": 36.162281472,
1410
+ "step": 1700
1411
+ },
1412
+ {
1413
+ "epoch": 6.6796875,
1414
+ "grad_norm": 0.90625,
1415
+ "learning_rate": 1e-05,
1416
+ "loss": 2.564146041870117,
1417
+ "peak_memory_gb": 36.162281472,
1418
+ "step": 1710
1419
+ },
1420
+ {
1421
+ "epoch": 6.71875,
1422
+ "grad_norm": 0.9140625,
1423
+ "learning_rate": 1e-05,
1424
+ "loss": 2.575610542297363,
1425
+ "peak_memory_gb": 36.162281472,
1426
+ "step": 1720
1427
+ },
1428
+ {
1429
+ "epoch": 6.7578125,
1430
+ "grad_norm": 0.921875,
1431
+ "learning_rate": 1e-05,
1432
+ "loss": 2.567903518676758,
1433
+ "peak_memory_gb": 36.162281472,
1434
+ "step": 1730
1435
+ },
1436
+ {
1437
+ "epoch": 6.796875,
1438
+ "grad_norm": 0.890625,
1439
+ "learning_rate": 1e-05,
1440
+ "loss": 2.576120376586914,
1441
+ "peak_memory_gb": 36.162281472,
1442
+ "step": 1740
1443
+ },
1444
+ {
1445
+ "epoch": 6.8359375,
1446
+ "grad_norm": 0.91015625,
1447
+ "learning_rate": 1e-05,
1448
+ "loss": 2.568872833251953,
1449
+ "peak_memory_gb": 36.162281472,
1450
+ "step": 1750
1451
+ },
1452
+ {
1453
+ "epoch": 6.875,
1454
+ "grad_norm": 0.89453125,
1455
+ "learning_rate": 1e-05,
1456
+ "loss": 2.571665573120117,
1457
+ "peak_memory_gb": 36.162281472,
1458
+ "step": 1760
1459
+ },
1460
+ {
1461
+ "epoch": 6.9140625,
1462
+ "grad_norm": 0.91796875,
1463
+ "learning_rate": 1e-05,
1464
+ "loss": 2.5724184036254885,
1465
+ "peak_memory_gb": 36.162281472,
1466
+ "step": 1770
1467
+ },
1468
+ {
1469
+ "epoch": 6.953125,
1470
+ "grad_norm": 0.94140625,
1471
+ "learning_rate": 1e-05,
1472
+ "loss": 2.5727853775024414,
1473
+ "peak_memory_gb": 36.162281472,
1474
+ "step": 1780
1475
+ },
1476
+ {
1477
+ "epoch": 6.9921875,
1478
+ "grad_norm": 0.93359375,
1479
+ "learning_rate": 1e-05,
1480
+ "loss": 2.5712764739990233,
1481
+ "peak_memory_gb": 36.162281472,
1482
+ "step": 1790
1483
+ },
1484
+ {
1485
+ "epoch": 7.03125,
1486
+ "grad_norm": 0.9765625,
1487
+ "learning_rate": 1e-05,
1488
+ "loss": 2.5168699264526366,
1489
+ "peak_memory_gb": 36.162281472,
1490
+ "step": 1800
1491
+ },
1492
+ {
1493
+ "epoch": 7.03125,
1494
+ "eval_loss": 2.739610195159912,
1495
+ "eval_runtime": 5.6144,
1496
+ "eval_samples_per_second": 890.562,
1497
+ "eval_steps_per_second": 55.749,
1498
+ "step": 1800
1499
+ },
1500
+ {
1501
+ "epoch": 7.0703125,
1502
+ "grad_norm": 0.99609375,
1503
+ "learning_rate": 1e-05,
1504
+ "loss": 2.509218215942383,
1505
+ "peak_memory_gb": 36.162281472,
1506
+ "step": 1810
1507
+ },
1508
+ {
1509
+ "epoch": 7.109375,
1510
+ "grad_norm": 1.0078125,
1511
+ "learning_rate": 1e-05,
1512
+ "loss": 2.5171878814697264,
1513
+ "peak_memory_gb": 36.162281472,
1514
+ "step": 1820
1515
+ },
1516
+ {
1517
+ "epoch": 7.1484375,
1518
+ "grad_norm": 1.0390625,
1519
+ "learning_rate": 1e-05,
1520
+ "loss": 2.5115663528442385,
1521
+ "peak_memory_gb": 36.162281472,
1522
+ "step": 1830
1523
+ },
1524
+ {
1525
+ "epoch": 7.1875,
1526
+ "grad_norm": 1.0234375,
1527
+ "learning_rate": 1e-05,
1528
+ "loss": 2.522474670410156,
1529
+ "peak_memory_gb": 36.162281472,
1530
+ "step": 1840
1531
+ },
1532
+ {
1533
+ "epoch": 7.2265625,
1534
+ "grad_norm": 1.0078125,
1535
+ "learning_rate": 1e-05,
1536
+ "loss": 2.5254119873046874,
1537
+ "peak_memory_gb": 36.162281472,
1538
+ "step": 1850
1539
+ },
1540
+ {
1541
+ "epoch": 7.265625,
1542
+ "grad_norm": 1.0,
1543
+ "learning_rate": 1e-05,
1544
+ "loss": 2.5268569946289063,
1545
+ "peak_memory_gb": 36.162281472,
1546
+ "step": 1860
1547
+ },
1548
+ {
1549
+ "epoch": 7.3046875,
1550
+ "grad_norm": 1.0078125,
1551
+ "learning_rate": 1e-05,
1552
+ "loss": 2.5281410217285156,
1553
+ "peak_memory_gb": 36.162281472,
1554
+ "step": 1870
1555
+ },
1556
+ {
1557
+ "epoch": 7.34375,
1558
+ "grad_norm": 1.0,
1559
+ "learning_rate": 1e-05,
1560
+ "loss": 2.527065658569336,
1561
+ "peak_memory_gb": 36.162281472,
1562
+ "step": 1880
1563
+ },
1564
+ {
1565
+ "epoch": 7.3828125,
1566
+ "grad_norm": 1.0,
1567
+ "learning_rate": 1e-05,
1568
+ "loss": 2.5254596710205077,
1569
+ "peak_memory_gb": 36.162281472,
1570
+ "step": 1890
1571
+ },
1572
+ {
1573
+ "epoch": 7.421875,
1574
+ "grad_norm": 0.98046875,
1575
+ "learning_rate": 1e-05,
1576
+ "loss": 2.534819221496582,
1577
+ "peak_memory_gb": 36.162281472,
1578
+ "step": 1900
1579
+ },
1580
+ {
1581
+ "epoch": 7.4609375,
1582
+ "grad_norm": 1.03125,
1583
+ "learning_rate": 1e-05,
1584
+ "loss": 2.5346946716308594,
1585
+ "peak_memory_gb": 36.162281472,
1586
+ "step": 1910
1587
+ },
1588
+ {
1589
+ "epoch": 7.5,
1590
+ "grad_norm": 0.984375,
1591
+ "learning_rate": 1e-05,
1592
+ "loss": 2.53009033203125,
1593
+ "peak_memory_gb": 36.162281472,
1594
+ "step": 1920
1595
+ },
1596
+ {
1597
+ "epoch": 7.5390625,
1598
+ "grad_norm": 0.9921875,
1599
+ "learning_rate": 1e-05,
1600
+ "loss": 2.5360280990600588,
1601
+ "peak_memory_gb": 36.162281472,
1602
+ "step": 1930
1603
+ },
1604
+ {
1605
+ "epoch": 7.578125,
1606
+ "grad_norm": 1.015625,
1607
+ "learning_rate": 1e-05,
1608
+ "loss": 2.532724952697754,
1609
+ "peak_memory_gb": 36.162281472,
1610
+ "step": 1940
1611
+ },
1612
+ {
1613
+ "epoch": 7.6171875,
1614
+ "grad_norm": 0.96484375,
1615
+ "learning_rate": 1e-05,
1616
+ "loss": 2.5413204193115235,
1617
+ "peak_memory_gb": 36.162281472,
1618
+ "step": 1950
1619
+ },
1620
+ {
1621
+ "epoch": 7.65625,
1622
+ "grad_norm": 0.9609375,
1623
+ "learning_rate": 1e-05,
1624
+ "loss": 2.544340896606445,
1625
+ "peak_memory_gb": 36.162281472,
1626
+ "step": 1960
1627
+ },
1628
+ {
1629
+ "epoch": 7.6953125,
1630
+ "grad_norm": 1.0,
1631
+ "learning_rate": 1e-05,
1632
+ "loss": 2.5374500274658205,
1633
+ "peak_memory_gb": 36.162281472,
1634
+ "step": 1970
1635
+ },
1636
+ {
1637
+ "epoch": 7.734375,
1638
+ "grad_norm": 0.94921875,
1639
+ "learning_rate": 1e-05,
1640
+ "loss": 2.531780242919922,
1641
+ "peak_memory_gb": 36.162281472,
1642
+ "step": 1980
1643
+ },
1644
+ {
1645
+ "epoch": 7.7734375,
1646
+ "grad_norm": 0.98046875,
1647
+ "learning_rate": 1e-05,
1648
+ "loss": 2.5461553573608398,
1649
+ "peak_memory_gb": 36.162281472,
1650
+ "step": 1990
1651
+ },
1652
+ {
1653
+ "epoch": 7.8125,
1654
+ "grad_norm": 0.96875,
1655
+ "learning_rate": 1e-05,
1656
+ "loss": 2.535898971557617,
1657
+ "peak_memory_gb": 36.162281472,
1658
+ "step": 2000
1659
+ },
1660
+ {
1661
+ "epoch": 7.8515625,
1662
+ "grad_norm": 0.9921875,
1663
+ "learning_rate": 1e-05,
1664
+ "loss": 2.539328765869141,
1665
+ "peak_memory_gb": 36.162281472,
1666
+ "step": 2010
1667
+ },
1668
+ {
1669
+ "epoch": 7.890625,
1670
+ "grad_norm": 0.96484375,
1671
+ "learning_rate": 1e-05,
1672
+ "loss": 2.537681770324707,
1673
+ "peak_memory_gb": 36.162281472,
1674
+ "step": 2020
1675
+ },
1676
+ {
1677
+ "epoch": 7.9296875,
1678
+ "grad_norm": 0.98046875,
1679
+ "learning_rate": 1e-05,
1680
+ "loss": 2.5407405853271485,
1681
+ "peak_memory_gb": 36.162281472,
1682
+ "step": 2030
1683
+ },
1684
+ {
1685
+ "epoch": 7.96875,
1686
+ "grad_norm": 1.0,
1687
+ "learning_rate": 1e-05,
1688
+ "loss": 2.5407970428466795,
1689
+ "peak_memory_gb": 36.162281472,
1690
+ "step": 2040
1691
+ },
1692
+ {
1693
+ "epoch": 8.0,
1694
+ "eval_loss": 2.735278606414795,
1695
+ "eval_runtime": 5.5512,
1696
+ "eval_samples_per_second": 900.71,
1697
+ "eval_steps_per_second": 56.384,
1698
+ "step": 2048
1699
+ }
1700
+ ],
1701
+ "logging_steps": 10,
1702
+ "max_steps": 2048,
1703
+ "num_input_tokens_seen": 0,
1704
+ "num_train_epochs": 8,
1705
+ "save_steps": 300,
1706
+ "stateful_callbacks": {
1707
+ "TrainerControl": {
1708
+ "args": {
1709
+ "should_epoch_stop": false,
1710
+ "should_evaluate": false,
1711
+ "should_log": false,
1712
+ "should_save": true,
1713
+ "should_training_stop": true
1714
+ },
1715
+ "attributes": {}
1716
+ }
1717
+ },
1718
+ "total_flos": 2.2727316027211776e+16,
1719
+ "train_batch_size": 44,
1720
+ "trial_name": null,
1721
+ "trial_params": null
1722
+ }
stage2/config.json ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dtype": "bfloat16",
3
+ "emotion_scale": 0.07,
4
+ "emotion_transition_end": 0.7,
5
+ "emotion_transition_start": 0.4,
6
+ "estimator_channels": [
7
+ 256
8
+ ],
9
+ "estimator_dropout": 0.0,
10
+ "estimator_ffn_mult": 4,
11
+ "estimator_group_norm_groups": 8,
12
+ "estimator_head_dim": 64,
13
+ "estimator_in_channels": 320,
14
+ "estimator_num_blocks": 4,
15
+ "estimator_num_decoding_left_chunks": -1,
16
+ "estimator_num_heads": 8,
17
+ "estimator_num_mid_blocks": 12,
18
+ "estimator_out_channels": 80,
19
+ "estimator_static_chunk_size": 50,
20
+ "f0_predictor_hidden_size": 512,
21
+ "flow_encoder_attention_dropout": 0.1,
22
+ "flow_encoder_chunk_size": 25,
23
+ "flow_encoder_dropout": 0.1,
24
+ "flow_encoder_ffn_dim": 2048,
25
+ "flow_encoder_hidden_act": "silu",
26
+ "flow_encoder_hidden_size": 512,
27
+ "flow_encoder_num_heads": 8,
28
+ "flow_encoder_num_layers": 6,
29
+ "flow_encoder_positional_dropout": 0.1,
30
+ "flow_encoder_up_num_layers": 4,
31
+ "flow_input_frame_rate": 25,
32
+ "flow_input_size": 512,
33
+ "flow_output_size": 80,
34
+ "hidden_loss_weight": 0.1,
35
+ "inference_cfg_rate": 0.7,
36
+ "initializer_range": 0.02,
37
+ "label_smoothing": 0.0,
38
+ "length_normalized_loss": true,
39
+ "length_regulator_sampling_ratios": [
40
+ 1,
41
+ 1,
42
+ 1,
43
+ 1
44
+ ],
45
+ "lm_attention_dropout": 0.0,
46
+ "lm_chunk_size": 1,
47
+ "lm_dropout": 0.1,
48
+ "lm_ffn_dim": 4096,
49
+ "lm_hidden_act": "relu",
50
+ "lm_hidden_size": 896,
51
+ "lm_input_projection_activation": true,
52
+ "lm_num_heads": 16,
53
+ "lm_num_layers": 14,
54
+ "lm_positional_dropout": 0.1,
55
+ "max_source_positions": 5000,
56
+ "mix_ratio": [
57
+ 5,
58
+ 15
59
+ ],
60
+ "model_type": "emotra_tts",
61
+ "noise_length": 15000,
62
+ "noise_seed": 0,
63
+ "num_flow_inference_steps": 10,
64
+ "num_speech_special_tokens": 3,
65
+ "num_vad_tokens": 5,
66
+ "pre_lookahead_channels": 512,
67
+ "pre_lookahead_len": 3,
68
+ "sample_rate": 24000,
69
+ "sigma_min": 1e-06,
70
+ "speaker_embedding_dim": 192,
71
+ "speaker_encoder_bottleneck_size": 4,
72
+ "speaker_encoder_dilations": [
73
+ 1,
74
+ 2,
75
+ 2
76
+ ],
77
+ "speaker_encoder_front_end_channels": 32,
78
+ "speaker_encoder_front_end_num_blocks": [
79
+ 2,
80
+ 2
81
+ ],
82
+ "speaker_encoder_growth_rate": 32,
83
+ "speaker_encoder_init_channels": 128,
84
+ "speaker_encoder_kernel_sizes": [
85
+ 3,
86
+ 3,
87
+ 3
88
+ ],
89
+ "speaker_encoder_num_layers": [
90
+ 12,
91
+ 24,
92
+ 16
93
+ ],
94
+ "speaker_encoder_num_mel_bins": 80,
95
+ "speaker_encoder_reduction": 2,
96
+ "speaker_encoder_segment_length": 100,
97
+ "speech_tokenizer_conv_stride": 2,
98
+ "speech_tokenizer_ffn_dim": 5120,
99
+ "speech_tokenizer_fsmn_kernel_size": 31,
100
+ "speech_tokenizer_fsq_levels": [
101
+ 3,
102
+ 3,
103
+ 3,
104
+ 3,
105
+ 3,
106
+ 3,
107
+ 3,
108
+ 3
109
+ ],
110
+ "speech_tokenizer_hidden_size": 1280,
111
+ "speech_tokenizer_max_position_embeddings": 2048,
112
+ "speech_tokenizer_max_source_positions": null,
113
+ "speech_tokenizer_num_heads": 20,
114
+ "speech_tokenizer_num_layers": 6,
115
+ "speech_tokenizer_num_mel_bins": 128,
116
+ "speech_tokenizer_rope_theta": 10000.0,
117
+ "speech_vocab_size": 6561,
118
+ "t_scheduler": "cosine",
119
+ "text_config": {
120
+ "architectures": [
121
+ "Qwen2ForCausalLM"
122
+ ],
123
+ "attention_dropout": 0.0,
124
+ "bos_token_id": 151643,
125
+ "dtype": "bfloat16",
126
+ "eos_token_id": 151645,
127
+ "hidden_act": "silu",
128
+ "hidden_size": 896,
129
+ "initializer_range": 0.02,
130
+ "intermediate_size": 4864,
131
+ "layer_types": [
132
+ "full_attention",
133
+ "full_attention",
134
+ "full_attention",
135
+ "full_attention",
136
+ "full_attention",
137
+ "full_attention",
138
+ "full_attention",
139
+ "full_attention",
140
+ "full_attention",
141
+ "full_attention",
142
+ "full_attention",
143
+ "full_attention",
144
+ "full_attention",
145
+ "full_attention",
146
+ "full_attention",
147
+ "full_attention",
148
+ "full_attention",
149
+ "full_attention",
150
+ "full_attention",
151
+ "full_attention",
152
+ "full_attention",
153
+ "full_attention",
154
+ "full_attention",
155
+ "full_attention"
156
+ ],
157
+ "max_position_embeddings": 32768,
158
+ "max_window_layers": 24,
159
+ "model_type": "qwen2",
160
+ "num_attention_heads": 14,
161
+ "num_hidden_layers": 24,
162
+ "num_key_value_heads": 2,
163
+ "pad_token_id": null,
164
+ "rms_norm_eps": 1e-06,
165
+ "rope_parameters": {
166
+ "rope_theta": 1000000.0,
167
+ "rope_type": "default"
168
+ },
169
+ "sliding_window": null,
170
+ "tie_word_embeddings": true,
171
+ "use_cache": true,
172
+ "use_sliding_window": false,
173
+ "vocab_size": 151936
174
+ },
175
+ "text_encoder_attention_dropout": 0.0,
176
+ "text_encoder_chunk_size": 1,
177
+ "text_encoder_dropout": 0.1,
178
+ "text_encoder_ffn_dim": 4096,
179
+ "text_encoder_hidden_act": "silu",
180
+ "text_encoder_hidden_size": 1024,
181
+ "text_encoder_input_size": 512,
182
+ "text_encoder_num_heads": 16,
183
+ "text_encoder_num_layers": 6,
184
+ "text_encoder_positional_dropout": 0.1,
185
+ "text_vocab_size": 51866,
186
+ "token_mel_ratio": 2,
187
+ "training_cfg_rate": 0.2,
188
+ "transformers_version": "5.19.0",
189
+ "use_cache": false,
190
+ "vad_downsample_hidden_size": 256,
191
+ "vad_dropout": 0.1,
192
+ "vad_hidden_state_size": 1024,
193
+ "vad_projection_hidden_size": 256,
194
+ "vad_reconstructor_hidden_size": 512,
195
+ "vocoder_audio_limit": 0.99,
196
+ "vocoder_base_channels": 512,
197
+ "vocoder_in_channels": 80,
198
+ "vocoder_istft_hop_length": 4,
199
+ "vocoder_istft_n_fft": 16,
200
+ "vocoder_leaky_relu_slope": 0.1,
201
+ "vocoder_mel_loss_coeff": 45.0,
202
+ "vocoder_mel_loss_fmax": null,
203
+ "vocoder_mel_loss_fmin": 0.0,
204
+ "vocoder_mel_loss_hop_length": 480,
205
+ "vocoder_mel_loss_n_fft": 1920,
206
+ "vocoder_mel_loss_num_mel_bins": 80,
207
+ "vocoder_mel_loss_win_length": 1920,
208
+ "vocoder_num_harmonics": 8,
209
+ "vocoder_resblock_dilation_sizes": [
210
+ [
211
+ 1,
212
+ 3,
213
+ 5
214
+ ],
215
+ [
216
+ 1,
217
+ 3,
218
+ 5
219
+ ],
220
+ [
221
+ 1,
222
+ 3,
223
+ 5
224
+ ]
225
+ ],
226
+ "vocoder_resblock_kernel_sizes": [
227
+ 3,
228
+ 7,
229
+ 11
230
+ ],
231
+ "vocoder_source_amplitude": 0.1,
232
+ "vocoder_source_noise_std": 0.003,
233
+ "vocoder_source_resblock_dilation_sizes": [
234
+ [
235
+ 1,
236
+ 3,
237
+ 5
238
+ ],
239
+ [
240
+ 1,
241
+ 3,
242
+ 5
243
+ ],
244
+ [
245
+ 1,
246
+ 3,
247
+ 5
248
+ ]
249
+ ],
250
+ "vocoder_source_resblock_kernel_sizes": [
251
+ 7,
252
+ 7,
253
+ 11
254
+ ],
255
+ "vocoder_upsample_kernel_sizes": [
256
+ 16,
257
+ 11,
258
+ 7
259
+ ],
260
+ "vocoder_upsample_rates": [
261
+ 8,
262
+ 5,
263
+ 3
264
+ ],
265
+ "vocoder_voiced_threshold": 10
266
+ }
stage2/trainable.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1169a39e92d09494879f6b3f074068a86374f455d5e5997c5065dd0fce51d4a9
3
+ size 566816
stage2/trainer_state.json ADDED
@@ -0,0 +1,1138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 4.0,
6
+ "eval_steps": 200,
7
+ "global_step": 1316,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.030395136778115502,
14
+ "grad_norm": 1.078125,
15
+ "learning_rate": 5e-05,
16
+ "loss": 0.8506673812866211,
17
+ "peak_memory_gb": 11.392126976,
18
+ "step": 10
19
+ },
20
+ {
21
+ "epoch": 0.060790273556231005,
22
+ "grad_norm": 0.890625,
23
+ "learning_rate": 5e-05,
24
+ "loss": 0.8339740753173828,
25
+ "peak_memory_gb": 11.392126976,
26
+ "step": 20
27
+ },
28
+ {
29
+ "epoch": 0.0911854103343465,
30
+ "grad_norm": 0.322265625,
31
+ "learning_rate": 5e-05,
32
+ "loss": 0.777587604522705,
33
+ "peak_memory_gb": 11.392126976,
34
+ "step": 30
35
+ },
36
+ {
37
+ "epoch": 0.12158054711246201,
38
+ "grad_norm": 0.5625,
39
+ "learning_rate": 5e-05,
40
+ "loss": 0.8202972412109375,
41
+ "peak_memory_gb": 11.392126976,
42
+ "step": 40
43
+ },
44
+ {
45
+ "epoch": 0.1519756838905775,
46
+ "grad_norm": 0.3671875,
47
+ "learning_rate": 5e-05,
48
+ "loss": 0.8009931564331054,
49
+ "peak_memory_gb": 11.392126976,
50
+ "step": 50
51
+ },
52
+ {
53
+ "epoch": 0.182370820668693,
54
+ "grad_norm": 0.3828125,
55
+ "learning_rate": 5e-05,
56
+ "loss": 0.8156126022338868,
57
+ "peak_memory_gb": 11.392126976,
58
+ "step": 60
59
+ },
60
+ {
61
+ "epoch": 0.2127659574468085,
62
+ "grad_norm": 0.484375,
63
+ "learning_rate": 5e-05,
64
+ "loss": 0.8374174118041993,
65
+ "peak_memory_gb": 11.392126976,
66
+ "step": 70
67
+ },
68
+ {
69
+ "epoch": 0.24316109422492402,
70
+ "grad_norm": 0.361328125,
71
+ "learning_rate": 5e-05,
72
+ "loss": 0.8337575912475585,
73
+ "peak_memory_gb": 11.392126976,
74
+ "step": 80
75
+ },
76
+ {
77
+ "epoch": 0.2735562310030395,
78
+ "grad_norm": 0.296875,
79
+ "learning_rate": 5e-05,
80
+ "loss": 0.7992202758789062,
81
+ "peak_memory_gb": 11.392126976,
82
+ "step": 90
83
+ },
84
+ {
85
+ "epoch": 0.303951367781155,
86
+ "grad_norm": 0.353515625,
87
+ "learning_rate": 5e-05,
88
+ "loss": 0.8385377883911133,
89
+ "peak_memory_gb": 11.392126976,
90
+ "step": 100
91
+ },
92
+ {
93
+ "epoch": 0.3343465045592705,
94
+ "grad_norm": 0.1953125,
95
+ "learning_rate": 5e-05,
96
+ "loss": 0.8178864479064941,
97
+ "peak_memory_gb": 11.392126976,
98
+ "step": 110
99
+ },
100
+ {
101
+ "epoch": 0.364741641337386,
102
+ "grad_norm": 0.162109375,
103
+ "learning_rate": 5e-05,
104
+ "loss": 0.8423860549926758,
105
+ "peak_memory_gb": 11.392126976,
106
+ "step": 120
107
+ },
108
+ {
109
+ "epoch": 0.3951367781155015,
110
+ "grad_norm": 0.349609375,
111
+ "learning_rate": 5e-05,
112
+ "loss": 0.8395400047302246,
113
+ "peak_memory_gb": 12.290835456,
114
+ "step": 130
115
+ },
116
+ {
117
+ "epoch": 0.425531914893617,
118
+ "grad_norm": 0.2470703125,
119
+ "learning_rate": 5e-05,
120
+ "loss": 0.779820442199707,
121
+ "peak_memory_gb": 12.290835456,
122
+ "step": 140
123
+ },
124
+ {
125
+ "epoch": 0.45592705167173253,
126
+ "grad_norm": 0.40625,
127
+ "learning_rate": 5e-05,
128
+ "loss": 0.8295249938964844,
129
+ "peak_memory_gb": 12.290835456,
130
+ "step": 150
131
+ },
132
+ {
133
+ "epoch": 0.48632218844984804,
134
+ "grad_norm": 0.359375,
135
+ "learning_rate": 5e-05,
136
+ "loss": 0.8221189498901367,
137
+ "peak_memory_gb": 12.290835456,
138
+ "step": 160
139
+ },
140
+ {
141
+ "epoch": 0.5167173252279635,
142
+ "grad_norm": 0.55078125,
143
+ "learning_rate": 5e-05,
144
+ "loss": 0.8828596115112305,
145
+ "peak_memory_gb": 12.290835456,
146
+ "step": 170
147
+ },
148
+ {
149
+ "epoch": 0.547112462006079,
150
+ "grad_norm": 0.27734375,
151
+ "learning_rate": 5e-05,
152
+ "loss": 0.8440515518188476,
153
+ "peak_memory_gb": 12.290835456,
154
+ "step": 180
155
+ },
156
+ {
157
+ "epoch": 0.5775075987841946,
158
+ "grad_norm": 0.2197265625,
159
+ "learning_rate": 5e-05,
160
+ "loss": 0.8499828338623047,
161
+ "peak_memory_gb": 12.290835456,
162
+ "step": 190
163
+ },
164
+ {
165
+ "epoch": 0.60790273556231,
166
+ "grad_norm": 0.2041015625,
167
+ "learning_rate": 5e-05,
168
+ "loss": 0.8058388710021973,
169
+ "peak_memory_gb": 12.290835456,
170
+ "step": 200
171
+ },
172
+ {
173
+ "epoch": 0.60790273556231,
174
+ "eval_loss": 0.84032142162323,
175
+ "eval_runtime": 18.7325,
176
+ "eval_samples_per_second": 235.473,
177
+ "eval_steps_per_second": 14.734,
178
+ "step": 200
179
+ },
180
+ {
181
+ "epoch": 0.6382978723404256,
182
+ "grad_norm": 0.1875,
183
+ "learning_rate": 5e-05,
184
+ "loss": 0.8288806915283203,
185
+ "peak_memory_gb": 12.290835456,
186
+ "step": 210
187
+ },
188
+ {
189
+ "epoch": 0.668693009118541,
190
+ "grad_norm": 0.302734375,
191
+ "learning_rate": 5e-05,
192
+ "loss": 0.8007297515869141,
193
+ "peak_memory_gb": 12.290835456,
194
+ "step": 220
195
+ },
196
+ {
197
+ "epoch": 0.6990881458966566,
198
+ "grad_norm": 0.2001953125,
199
+ "learning_rate": 5e-05,
200
+ "loss": 0.8257779121398926,
201
+ "peak_memory_gb": 12.290835456,
202
+ "step": 230
203
+ },
204
+ {
205
+ "epoch": 0.729483282674772,
206
+ "grad_norm": 0.431640625,
207
+ "learning_rate": 5e-05,
208
+ "loss": 0.7917570114135742,
209
+ "peak_memory_gb": 12.290835456,
210
+ "step": 240
211
+ },
212
+ {
213
+ "epoch": 0.7598784194528876,
214
+ "grad_norm": 0.279296875,
215
+ "learning_rate": 5e-05,
216
+ "loss": 0.8004946708679199,
217
+ "peak_memory_gb": 12.290835456,
218
+ "step": 250
219
+ },
220
+ {
221
+ "epoch": 0.790273556231003,
222
+ "grad_norm": 0.14453125,
223
+ "learning_rate": 5e-05,
224
+ "loss": 0.8463303565979003,
225
+ "peak_memory_gb": 12.290835456,
226
+ "step": 260
227
+ },
228
+ {
229
+ "epoch": 0.8206686930091185,
230
+ "grad_norm": 0.1689453125,
231
+ "learning_rate": 5e-05,
232
+ "loss": 0.8194509506225586,
233
+ "peak_memory_gb": 12.290835456,
234
+ "step": 270
235
+ },
236
+ {
237
+ "epoch": 0.851063829787234,
238
+ "grad_norm": 0.22265625,
239
+ "learning_rate": 5e-05,
240
+ "loss": 0.8117538452148437,
241
+ "peak_memory_gb": 12.290835456,
242
+ "step": 280
243
+ },
244
+ {
245
+ "epoch": 0.8814589665653495,
246
+ "grad_norm": 0.2333984375,
247
+ "learning_rate": 5e-05,
248
+ "loss": 0.8000720977783203,
249
+ "peak_memory_gb": 12.290835456,
250
+ "step": 290
251
+ },
252
+ {
253
+ "epoch": 0.9118541033434651,
254
+ "grad_norm": 0.34765625,
255
+ "learning_rate": 5e-05,
256
+ "loss": 0.8445416450500488,
257
+ "peak_memory_gb": 12.290835456,
258
+ "step": 300
259
+ },
260
+ {
261
+ "epoch": 0.9422492401215805,
262
+ "grad_norm": 0.82421875,
263
+ "learning_rate": 5e-05,
264
+ "loss": 0.8441438674926758,
265
+ "peak_memory_gb": 12.290835456,
266
+ "step": 310
267
+ },
268
+ {
269
+ "epoch": 0.9726443768996961,
270
+ "grad_norm": 0.2177734375,
271
+ "learning_rate": 5e-05,
272
+ "loss": 0.8477689743041992,
273
+ "peak_memory_gb": 12.290835456,
274
+ "step": 320
275
+ },
276
+ {
277
+ "epoch": 1.0030395136778116,
278
+ "grad_norm": 0.345703125,
279
+ "learning_rate": 5e-05,
280
+ "loss": 0.8435035705566406,
281
+ "peak_memory_gb": 12.290835456,
282
+ "step": 330
283
+ },
284
+ {
285
+ "epoch": 1.033434650455927,
286
+ "grad_norm": 0.287109375,
287
+ "learning_rate": 5e-05,
288
+ "loss": 0.821134090423584,
289
+ "peak_memory_gb": 12.290835456,
290
+ "step": 340
291
+ },
292
+ {
293
+ "epoch": 1.0638297872340425,
294
+ "grad_norm": 0.462890625,
295
+ "learning_rate": 5e-05,
296
+ "loss": 0.829494857788086,
297
+ "peak_memory_gb": 12.290835456,
298
+ "step": 350
299
+ },
300
+ {
301
+ "epoch": 1.094224924012158,
302
+ "grad_norm": 0.21875,
303
+ "learning_rate": 5e-05,
304
+ "loss": 0.832489013671875,
305
+ "peak_memory_gb": 12.290835456,
306
+ "step": 360
307
+ },
308
+ {
309
+ "epoch": 1.1246200607902737,
310
+ "grad_norm": 0.173828125,
311
+ "learning_rate": 5e-05,
312
+ "loss": 0.8220687866210937,
313
+ "peak_memory_gb": 12.290835456,
314
+ "step": 370
315
+ },
316
+ {
317
+ "epoch": 1.155015197568389,
318
+ "grad_norm": 0.1328125,
319
+ "learning_rate": 5e-05,
320
+ "loss": 0.8567506790161132,
321
+ "peak_memory_gb": 12.290835456,
322
+ "step": 380
323
+ },
324
+ {
325
+ "epoch": 1.1854103343465046,
326
+ "grad_norm": 0.2578125,
327
+ "learning_rate": 5e-05,
328
+ "loss": 0.8164398193359375,
329
+ "peak_memory_gb": 12.290835456,
330
+ "step": 390
331
+ },
332
+ {
333
+ "epoch": 1.21580547112462,
334
+ "grad_norm": 0.2890625,
335
+ "learning_rate": 5e-05,
336
+ "loss": 0.85140962600708,
337
+ "peak_memory_gb": 12.290835456,
338
+ "step": 400
339
+ },
340
+ {
341
+ "epoch": 1.21580547112462,
342
+ "eval_loss": 0.8555761575698853,
343
+ "eval_runtime": 17.6759,
344
+ "eval_samples_per_second": 249.549,
345
+ "eval_steps_per_second": 15.614,
346
+ "step": 400
347
+ },
348
+ {
349
+ "epoch": 1.2462006079027357,
350
+ "grad_norm": 0.2060546875,
351
+ "learning_rate": 5e-05,
352
+ "loss": 0.8239400863647461,
353
+ "peak_memory_gb": 12.290835456,
354
+ "step": 410
355
+ },
356
+ {
357
+ "epoch": 1.2765957446808511,
358
+ "grad_norm": 0.234375,
359
+ "learning_rate": 5e-05,
360
+ "loss": 0.8007009506225586,
361
+ "peak_memory_gb": 12.290835456,
362
+ "step": 420
363
+ },
364
+ {
365
+ "epoch": 1.3069908814589666,
366
+ "grad_norm": 0.392578125,
367
+ "learning_rate": 5e-05,
368
+ "loss": 0.8125054359436035,
369
+ "peak_memory_gb": 12.290835456,
370
+ "step": 430
371
+ },
372
+ {
373
+ "epoch": 1.337386018237082,
374
+ "grad_norm": 0.1748046875,
375
+ "learning_rate": 5e-05,
376
+ "loss": 0.8225876808166503,
377
+ "peak_memory_gb": 12.290835456,
378
+ "step": 440
379
+ },
380
+ {
381
+ "epoch": 1.3677811550151975,
382
+ "grad_norm": 0.2080078125,
383
+ "learning_rate": 5e-05,
384
+ "loss": 0.8252336502075195,
385
+ "peak_memory_gb": 12.290835456,
386
+ "step": 450
387
+ },
388
+ {
389
+ "epoch": 1.3981762917933132,
390
+ "grad_norm": 0.279296875,
391
+ "learning_rate": 5e-05,
392
+ "loss": 0.8335677146911621,
393
+ "peak_memory_gb": 12.290835456,
394
+ "step": 460
395
+ },
396
+ {
397
+ "epoch": 1.4285714285714286,
398
+ "grad_norm": 0.1220703125,
399
+ "learning_rate": 5e-05,
400
+ "loss": 0.8358859062194824,
401
+ "peak_memory_gb": 12.291160576,
402
+ "step": 470
403
+ },
404
+ {
405
+ "epoch": 1.458966565349544,
406
+ "grad_norm": 0.28515625,
407
+ "learning_rate": 5e-05,
408
+ "loss": 0.769371509552002,
409
+ "peak_memory_gb": 12.291160576,
410
+ "step": 480
411
+ },
412
+ {
413
+ "epoch": 1.4893617021276595,
414
+ "grad_norm": 0.326171875,
415
+ "learning_rate": 5e-05,
416
+ "loss": 0.8668624877929687,
417
+ "peak_memory_gb": 12.291160576,
418
+ "step": 490
419
+ },
420
+ {
421
+ "epoch": 1.5197568389057752,
422
+ "grad_norm": 0.1962890625,
423
+ "learning_rate": 5e-05,
424
+ "loss": 0.822964859008789,
425
+ "peak_memory_gb": 12.291160576,
426
+ "step": 500
427
+ },
428
+ {
429
+ "epoch": 1.5501519756838906,
430
+ "grad_norm": 0.1845703125,
431
+ "learning_rate": 5e-05,
432
+ "loss": 0.8051273345947265,
433
+ "peak_memory_gb": 12.291160576,
434
+ "step": 510
435
+ },
436
+ {
437
+ "epoch": 1.580547112462006,
438
+ "grad_norm": 0.1572265625,
439
+ "learning_rate": 5e-05,
440
+ "loss": 0.8340553283691406,
441
+ "peak_memory_gb": 12.291160576,
442
+ "step": 520
443
+ },
444
+ {
445
+ "epoch": 1.6109422492401215,
446
+ "grad_norm": 0.3046875,
447
+ "learning_rate": 5e-05,
448
+ "loss": 0.8137052536010743,
449
+ "peak_memory_gb": 12.291160576,
450
+ "step": 530
451
+ },
452
+ {
453
+ "epoch": 1.641337386018237,
454
+ "grad_norm": 0.427734375,
455
+ "learning_rate": 5e-05,
456
+ "loss": 0.8260629653930665,
457
+ "peak_memory_gb": 12.291160576,
458
+ "step": 540
459
+ },
460
+ {
461
+ "epoch": 1.6717325227963524,
462
+ "grad_norm": 0.451171875,
463
+ "learning_rate": 5e-05,
464
+ "loss": 0.8112590789794922,
465
+ "peak_memory_gb": 12.291160576,
466
+ "step": 550
467
+ },
468
+ {
469
+ "epoch": 1.702127659574468,
470
+ "grad_norm": 0.3203125,
471
+ "learning_rate": 5e-05,
472
+ "loss": 0.8116866111755371,
473
+ "peak_memory_gb": 12.291160576,
474
+ "step": 560
475
+ },
476
+ {
477
+ "epoch": 1.7325227963525835,
478
+ "grad_norm": 0.259765625,
479
+ "learning_rate": 5e-05,
480
+ "loss": 0.8534025192260742,
481
+ "peak_memory_gb": 12.291160576,
482
+ "step": 570
483
+ },
484
+ {
485
+ "epoch": 1.7629179331306992,
486
+ "grad_norm": 0.2421875,
487
+ "learning_rate": 5e-05,
488
+ "loss": 0.8095227241516113,
489
+ "peak_memory_gb": 12.291160576,
490
+ "step": 580
491
+ },
492
+ {
493
+ "epoch": 1.7933130699088147,
494
+ "grad_norm": 0.306640625,
495
+ "learning_rate": 5e-05,
496
+ "loss": 0.8268829345703125,
497
+ "peak_memory_gb": 12.291160576,
498
+ "step": 590
499
+ },
500
+ {
501
+ "epoch": 1.8237082066869301,
502
+ "grad_norm": 0.275390625,
503
+ "learning_rate": 5e-05,
504
+ "loss": 0.799107837677002,
505
+ "peak_memory_gb": 12.291160576,
506
+ "step": 600
507
+ },
508
+ {
509
+ "epoch": 1.8237082066869301,
510
+ "eval_loss": 0.8517410755157471,
511
+ "eval_runtime": 17.5033,
512
+ "eval_samples_per_second": 252.009,
513
+ "eval_steps_per_second": 15.768,
514
+ "step": 600
515
+ },
516
+ {
517
+ "epoch": 1.8541033434650456,
518
+ "grad_norm": 0.5546875,
519
+ "learning_rate": 5e-05,
520
+ "loss": 0.8426033020019531,
521
+ "peak_memory_gb": 12.291160576,
522
+ "step": 610
523
+ },
524
+ {
525
+ "epoch": 1.884498480243161,
526
+ "grad_norm": 0.2373046875,
527
+ "learning_rate": 5e-05,
528
+ "loss": 0.8683677673339844,
529
+ "peak_memory_gb": 12.291160576,
530
+ "step": 620
531
+ },
532
+ {
533
+ "epoch": 1.9148936170212765,
534
+ "grad_norm": 0.2265625,
535
+ "learning_rate": 5e-05,
536
+ "loss": 0.8570480346679688,
537
+ "peak_memory_gb": 12.291160576,
538
+ "step": 630
539
+ },
540
+ {
541
+ "epoch": 1.9452887537993921,
542
+ "grad_norm": 0.2392578125,
543
+ "learning_rate": 5e-05,
544
+ "loss": 0.8105743408203125,
545
+ "peak_memory_gb": 12.291160576,
546
+ "step": 640
547
+ },
548
+ {
549
+ "epoch": 1.9756838905775076,
550
+ "grad_norm": 0.19140625,
551
+ "learning_rate": 5e-05,
552
+ "loss": 0.7967374324798584,
553
+ "peak_memory_gb": 12.291160576,
554
+ "step": 650
555
+ },
556
+ {
557
+ "epoch": 2.0060790273556233,
558
+ "grad_norm": 0.2373046875,
559
+ "learning_rate": 5e-05,
560
+ "loss": 0.8381919860839844,
561
+ "peak_memory_gb": 12.291160576,
562
+ "step": 660
563
+ },
564
+ {
565
+ "epoch": 2.0364741641337387,
566
+ "grad_norm": 0.1630859375,
567
+ "learning_rate": 5e-05,
568
+ "loss": 0.8241643905639648,
569
+ "peak_memory_gb": 12.291160576,
570
+ "step": 670
571
+ },
572
+ {
573
+ "epoch": 2.066869300911854,
574
+ "grad_norm": 0.357421875,
575
+ "learning_rate": 5e-05,
576
+ "loss": 0.8248809814453125,
577
+ "peak_memory_gb": 12.291160576,
578
+ "step": 680
579
+ },
580
+ {
581
+ "epoch": 2.0972644376899696,
582
+ "grad_norm": 0.263671875,
583
+ "learning_rate": 5e-05,
584
+ "loss": 0.8149803161621094,
585
+ "peak_memory_gb": 12.291160576,
586
+ "step": 690
587
+ },
588
+ {
589
+ "epoch": 2.127659574468085,
590
+ "grad_norm": 0.1669921875,
591
+ "learning_rate": 5e-05,
592
+ "loss": 0.8410781860351563,
593
+ "peak_memory_gb": 12.291160576,
594
+ "step": 700
595
+ },
596
+ {
597
+ "epoch": 2.1580547112462005,
598
+ "grad_norm": 0.267578125,
599
+ "learning_rate": 5e-05,
600
+ "loss": 0.8229344367980957,
601
+ "peak_memory_gb": 12.751286784,
602
+ "step": 710
603
+ },
604
+ {
605
+ "epoch": 2.188449848024316,
606
+ "grad_norm": 0.1396484375,
607
+ "learning_rate": 5e-05,
608
+ "loss": 0.8392572402954102,
609
+ "peak_memory_gb": 12.751286784,
610
+ "step": 720
611
+ },
612
+ {
613
+ "epoch": 2.2188449848024314,
614
+ "grad_norm": 0.365234375,
615
+ "learning_rate": 5e-05,
616
+ "loss": 0.8548948287963867,
617
+ "peak_memory_gb": 12.751286784,
618
+ "step": 730
619
+ },
620
+ {
621
+ "epoch": 2.2492401215805473,
622
+ "grad_norm": 0.376953125,
623
+ "learning_rate": 5e-05,
624
+ "loss": 0.8341733932495117,
625
+ "peak_memory_gb": 12.751286784,
626
+ "step": 740
627
+ },
628
+ {
629
+ "epoch": 2.2796352583586628,
630
+ "grad_norm": 0.330078125,
631
+ "learning_rate": 5e-05,
632
+ "loss": 0.8456611633300781,
633
+ "peak_memory_gb": 12.751286784,
634
+ "step": 750
635
+ },
636
+ {
637
+ "epoch": 2.310030395136778,
638
+ "grad_norm": 0.1943359375,
639
+ "learning_rate": 5e-05,
640
+ "loss": 0.7936759948730469,
641
+ "peak_memory_gb": 12.751286784,
642
+ "step": 760
643
+ },
644
+ {
645
+ "epoch": 2.3404255319148937,
646
+ "grad_norm": 0.1728515625,
647
+ "learning_rate": 5e-05,
648
+ "loss": 0.8220600128173828,
649
+ "peak_memory_gb": 12.751286784,
650
+ "step": 770
651
+ },
652
+ {
653
+ "epoch": 2.370820668693009,
654
+ "grad_norm": 0.1923828125,
655
+ "learning_rate": 5e-05,
656
+ "loss": 0.7810612678527832,
657
+ "peak_memory_gb": 12.751286784,
658
+ "step": 780
659
+ },
660
+ {
661
+ "epoch": 2.4012158054711246,
662
+ "grad_norm": 0.2314453125,
663
+ "learning_rate": 5e-05,
664
+ "loss": 0.8178634643554688,
665
+ "peak_memory_gb": 12.751286784,
666
+ "step": 790
667
+ },
668
+ {
669
+ "epoch": 2.43161094224924,
670
+ "grad_norm": 0.1923828125,
671
+ "learning_rate": 5e-05,
672
+ "loss": 0.8075672149658203,
673
+ "peak_memory_gb": 12.751286784,
674
+ "step": 800
675
+ },
676
+ {
677
+ "epoch": 2.43161094224924,
678
+ "eval_loss": 0.8188867568969727,
679
+ "eval_runtime": 17.4543,
680
+ "eval_samples_per_second": 252.717,
681
+ "eval_steps_per_second": 15.813,
682
+ "step": 800
683
+ },
684
+ {
685
+ "epoch": 2.4620060790273555,
686
+ "grad_norm": 0.51171875,
687
+ "learning_rate": 5e-05,
688
+ "loss": 0.8298994064331054,
689
+ "peak_memory_gb": 12.751286784,
690
+ "step": 810
691
+ },
692
+ {
693
+ "epoch": 2.4924012158054714,
694
+ "grad_norm": 0.166015625,
695
+ "learning_rate": 5e-05,
696
+ "loss": 0.8390796661376954,
697
+ "peak_memory_gb": 12.751286784,
698
+ "step": 820
699
+ },
700
+ {
701
+ "epoch": 2.522796352583587,
702
+ "grad_norm": 0.5,
703
+ "learning_rate": 5e-05,
704
+ "loss": 0.8386654853820801,
705
+ "peak_memory_gb": 12.751286784,
706
+ "step": 830
707
+ },
708
+ {
709
+ "epoch": 2.5531914893617023,
710
+ "grad_norm": 0.4609375,
711
+ "learning_rate": 5e-05,
712
+ "loss": 0.8712700843811035,
713
+ "peak_memory_gb": 12.751286784,
714
+ "step": 840
715
+ },
716
+ {
717
+ "epoch": 2.5835866261398177,
718
+ "grad_norm": 0.12109375,
719
+ "learning_rate": 5e-05,
720
+ "loss": 0.8246630668640137,
721
+ "peak_memory_gb": 12.751286784,
722
+ "step": 850
723
+ },
724
+ {
725
+ "epoch": 2.613981762917933,
726
+ "grad_norm": 0.166015625,
727
+ "learning_rate": 5e-05,
728
+ "loss": 0.7972818374633789,
729
+ "peak_memory_gb": 12.751286784,
730
+ "step": 860
731
+ },
732
+ {
733
+ "epoch": 2.6443768996960486,
734
+ "grad_norm": 0.1650390625,
735
+ "learning_rate": 5e-05,
736
+ "loss": 0.8640129089355468,
737
+ "peak_memory_gb": 12.751286784,
738
+ "step": 870
739
+ },
740
+ {
741
+ "epoch": 2.674772036474164,
742
+ "grad_norm": 0.1455078125,
743
+ "learning_rate": 5e-05,
744
+ "loss": 0.8084453582763672,
745
+ "peak_memory_gb": 12.751286784,
746
+ "step": 880
747
+ },
748
+ {
749
+ "epoch": 2.7051671732522795,
750
+ "grad_norm": 0.10107421875,
751
+ "learning_rate": 5e-05,
752
+ "loss": 0.8607460021972656,
753
+ "peak_memory_gb": 12.751286784,
754
+ "step": 890
755
+ },
756
+ {
757
+ "epoch": 2.735562310030395,
758
+ "grad_norm": 0.427734375,
759
+ "learning_rate": 5e-05,
760
+ "loss": 0.8540050506591796,
761
+ "peak_memory_gb": 12.751286784,
762
+ "step": 900
763
+ },
764
+ {
765
+ "epoch": 2.7659574468085104,
766
+ "grad_norm": 0.361328125,
767
+ "learning_rate": 5e-05,
768
+ "loss": 0.8457630157470704,
769
+ "peak_memory_gb": 12.751286784,
770
+ "step": 910
771
+ },
772
+ {
773
+ "epoch": 2.7963525835866263,
774
+ "grad_norm": 0.203125,
775
+ "learning_rate": 5e-05,
776
+ "loss": 0.8122754096984863,
777
+ "peak_memory_gb": 12.751286784,
778
+ "step": 920
779
+ },
780
+ {
781
+ "epoch": 2.8267477203647418,
782
+ "grad_norm": 0.26171875,
783
+ "learning_rate": 5e-05,
784
+ "loss": 0.8460748672485352,
785
+ "peak_memory_gb": 12.751286784,
786
+ "step": 930
787
+ },
788
+ {
789
+ "epoch": 2.857142857142857,
790
+ "grad_norm": 0.240234375,
791
+ "learning_rate": 5e-05,
792
+ "loss": 0.8515989303588867,
793
+ "peak_memory_gb": 12.751286784,
794
+ "step": 940
795
+ },
796
+ {
797
+ "epoch": 2.8875379939209727,
798
+ "grad_norm": 0.314453125,
799
+ "learning_rate": 5e-05,
800
+ "loss": 0.8311944961547851,
801
+ "peak_memory_gb": 12.751286784,
802
+ "step": 950
803
+ },
804
+ {
805
+ "epoch": 2.917933130699088,
806
+ "grad_norm": 0.31640625,
807
+ "learning_rate": 5e-05,
808
+ "loss": 0.839780616760254,
809
+ "peak_memory_gb": 12.751286784,
810
+ "step": 960
811
+ },
812
+ {
813
+ "epoch": 2.9483282674772036,
814
+ "grad_norm": 0.392578125,
815
+ "learning_rate": 5e-05,
816
+ "loss": 0.837193489074707,
817
+ "peak_memory_gb": 12.751286784,
818
+ "step": 970
819
+ },
820
+ {
821
+ "epoch": 2.978723404255319,
822
+ "grad_norm": 0.1416015625,
823
+ "learning_rate": 5e-05,
824
+ "loss": 0.8434899330139161,
825
+ "peak_memory_gb": 12.751286784,
826
+ "step": 980
827
+ },
828
+ {
829
+ "epoch": 3.0091185410334345,
830
+ "grad_norm": 0.1640625,
831
+ "learning_rate": 5e-05,
832
+ "loss": 0.855105209350586,
833
+ "peak_memory_gb": 12.751286784,
834
+ "step": 990
835
+ },
836
+ {
837
+ "epoch": 3.0395136778115504,
838
+ "grad_norm": 0.25390625,
839
+ "learning_rate": 5e-05,
840
+ "loss": 0.851835823059082,
841
+ "peak_memory_gb": 12.751286784,
842
+ "step": 1000
843
+ },
844
+ {
845
+ "epoch": 3.0395136778115504,
846
+ "eval_loss": 0.8143728375434875,
847
+ "eval_runtime": 17.5651,
848
+ "eval_samples_per_second": 251.124,
849
+ "eval_steps_per_second": 15.713,
850
+ "step": 1000
851
+ },
852
+ {
853
+ "epoch": 3.069908814589666,
854
+ "grad_norm": 0.1689453125,
855
+ "learning_rate": 5e-05,
856
+ "loss": 0.8214831352233887,
857
+ "peak_memory_gb": 12.751286784,
858
+ "step": 1010
859
+ },
860
+ {
861
+ "epoch": 3.1003039513677813,
862
+ "grad_norm": 0.1298828125,
863
+ "learning_rate": 5e-05,
864
+ "loss": 0.7953415870666504,
865
+ "peak_memory_gb": 12.751286784,
866
+ "step": 1020
867
+ },
868
+ {
869
+ "epoch": 3.1306990881458967,
870
+ "grad_norm": 0.296875,
871
+ "learning_rate": 5e-05,
872
+ "loss": 0.8230077743530273,
873
+ "peak_memory_gb": 12.751286784,
874
+ "step": 1030
875
+ },
876
+ {
877
+ "epoch": 3.161094224924012,
878
+ "grad_norm": 0.13671875,
879
+ "learning_rate": 5e-05,
880
+ "loss": 0.792591667175293,
881
+ "peak_memory_gb": 12.751286784,
882
+ "step": 1040
883
+ },
884
+ {
885
+ "epoch": 3.1914893617021276,
886
+ "grad_norm": 0.2421875,
887
+ "learning_rate": 5e-05,
888
+ "loss": 0.8196142196655274,
889
+ "peak_memory_gb": 12.751286784,
890
+ "step": 1050
891
+ },
892
+ {
893
+ "epoch": 3.221884498480243,
894
+ "grad_norm": 0.1748046875,
895
+ "learning_rate": 5e-05,
896
+ "loss": 0.8279183387756348,
897
+ "peak_memory_gb": 12.751286784,
898
+ "step": 1060
899
+ },
900
+ {
901
+ "epoch": 3.2522796352583585,
902
+ "grad_norm": 0.193359375,
903
+ "learning_rate": 5e-05,
904
+ "loss": 0.8552944183349609,
905
+ "peak_memory_gb": 12.751286784,
906
+ "step": 1070
907
+ },
908
+ {
909
+ "epoch": 3.282674772036474,
910
+ "grad_norm": 0.2060546875,
911
+ "learning_rate": 5e-05,
912
+ "loss": 0.8472248077392578,
913
+ "peak_memory_gb": 12.751286784,
914
+ "step": 1080
915
+ },
916
+ {
917
+ "epoch": 3.31306990881459,
918
+ "grad_norm": 0.26171875,
919
+ "learning_rate": 5e-05,
920
+ "loss": 0.7748371124267578,
921
+ "peak_memory_gb": 12.751286784,
922
+ "step": 1090
923
+ },
924
+ {
925
+ "epoch": 3.3434650455927053,
926
+ "grad_norm": 0.259765625,
927
+ "learning_rate": 5e-05,
928
+ "loss": 0.8276432037353516,
929
+ "peak_memory_gb": 12.751286784,
930
+ "step": 1100
931
+ },
932
+ {
933
+ "epoch": 3.3738601823708207,
934
+ "grad_norm": 0.1337890625,
935
+ "learning_rate": 5e-05,
936
+ "loss": 0.8485677719116211,
937
+ "peak_memory_gb": 12.751286784,
938
+ "step": 1110
939
+ },
940
+ {
941
+ "epoch": 3.404255319148936,
942
+ "grad_norm": 0.337890625,
943
+ "learning_rate": 5e-05,
944
+ "loss": 0.8220198631286622,
945
+ "peak_memory_gb": 12.751286784,
946
+ "step": 1120
947
+ },
948
+ {
949
+ "epoch": 3.4346504559270516,
950
+ "grad_norm": 0.1435546875,
951
+ "learning_rate": 5e-05,
952
+ "loss": 0.8373458862304688,
953
+ "peak_memory_gb": 12.751286784,
954
+ "step": 1130
955
+ },
956
+ {
957
+ "epoch": 3.465045592705167,
958
+ "grad_norm": 0.08837890625,
959
+ "learning_rate": 5e-05,
960
+ "loss": 0.8135047912597656,
961
+ "peak_memory_gb": 12.751286784,
962
+ "step": 1140
963
+ },
964
+ {
965
+ "epoch": 3.4954407294832825,
966
+ "grad_norm": 0.1337890625,
967
+ "learning_rate": 5e-05,
968
+ "loss": 0.7954874038696289,
969
+ "peak_memory_gb": 12.751286784,
970
+ "step": 1150
971
+ },
972
+ {
973
+ "epoch": 3.5258358662613984,
974
+ "grad_norm": 0.2255859375,
975
+ "learning_rate": 5e-05,
976
+ "loss": 0.8478258132934571,
977
+ "peak_memory_gb": 12.751286784,
978
+ "step": 1160
979
+ },
980
+ {
981
+ "epoch": 3.556231003039514,
982
+ "grad_norm": 0.142578125,
983
+ "learning_rate": 5e-05,
984
+ "loss": 0.7790112972259522,
985
+ "peak_memory_gb": 12.751286784,
986
+ "step": 1170
987
+ },
988
+ {
989
+ "epoch": 3.5866261398176293,
990
+ "grad_norm": 0.1669921875,
991
+ "learning_rate": 5e-05,
992
+ "loss": 0.8199026107788085,
993
+ "peak_memory_gb": 12.751286784,
994
+ "step": 1180
995
+ },
996
+ {
997
+ "epoch": 3.617021276595745,
998
+ "grad_norm": 0.123046875,
999
+ "learning_rate": 5e-05,
1000
+ "loss": 0.864778709411621,
1001
+ "peak_memory_gb": 12.751286784,
1002
+ "step": 1190
1003
+ },
1004
+ {
1005
+ "epoch": 3.6474164133738602,
1006
+ "grad_norm": 0.380859375,
1007
+ "learning_rate": 5e-05,
1008
+ "loss": 0.8103488922119141,
1009
+ "peak_memory_gb": 12.751286784,
1010
+ "step": 1200
1011
+ },
1012
+ {
1013
+ "epoch": 3.6474164133738602,
1014
+ "eval_loss": 0.8302319645881653,
1015
+ "eval_runtime": 17.7058,
1016
+ "eval_samples_per_second": 249.128,
1017
+ "eval_steps_per_second": 15.588,
1018
+ "step": 1200
1019
+ },
1020
+ {
1021
+ "epoch": 3.6778115501519757,
1022
+ "grad_norm": 0.1865234375,
1023
+ "learning_rate": 5e-05,
1024
+ "loss": 0.84176025390625,
1025
+ "peak_memory_gb": 12.751286784,
1026
+ "step": 1210
1027
+ },
1028
+ {
1029
+ "epoch": 3.708206686930091,
1030
+ "grad_norm": 0.333984375,
1031
+ "learning_rate": 5e-05,
1032
+ "loss": 0.7894211769104004,
1033
+ "peak_memory_gb": 12.751286784,
1034
+ "step": 1220
1035
+ },
1036
+ {
1037
+ "epoch": 3.7386018237082066,
1038
+ "grad_norm": 0.20703125,
1039
+ "learning_rate": 5e-05,
1040
+ "loss": 0.8175489425659179,
1041
+ "peak_memory_gb": 12.751286784,
1042
+ "step": 1230
1043
+ },
1044
+ {
1045
+ "epoch": 3.768996960486322,
1046
+ "grad_norm": 0.16015625,
1047
+ "learning_rate": 5e-05,
1048
+ "loss": 0.8058491706848144,
1049
+ "peak_memory_gb": 12.751286784,
1050
+ "step": 1240
1051
+ },
1052
+ {
1053
+ "epoch": 3.7993920972644375,
1054
+ "grad_norm": 0.2294921875,
1055
+ "learning_rate": 5e-05,
1056
+ "loss": 0.8182121276855469,
1057
+ "peak_memory_gb": 12.751286784,
1058
+ "step": 1250
1059
+ },
1060
+ {
1061
+ "epoch": 3.829787234042553,
1062
+ "grad_norm": 0.09033203125,
1063
+ "learning_rate": 5e-05,
1064
+ "loss": 0.8203716278076172,
1065
+ "peak_memory_gb": 12.751286784,
1066
+ "step": 1260
1067
+ },
1068
+ {
1069
+ "epoch": 3.860182370820669,
1070
+ "grad_norm": 0.2109375,
1071
+ "learning_rate": 5e-05,
1072
+ "loss": 0.8076398849487305,
1073
+ "peak_memory_gb": 12.751286784,
1074
+ "step": 1270
1075
+ },
1076
+ {
1077
+ "epoch": 3.8905775075987843,
1078
+ "grad_norm": 0.150390625,
1079
+ "learning_rate": 5e-05,
1080
+ "loss": 0.8585376739501953,
1081
+ "peak_memory_gb": 12.751286784,
1082
+ "step": 1280
1083
+ },
1084
+ {
1085
+ "epoch": 3.9209726443768997,
1086
+ "grad_norm": 0.11279296875,
1087
+ "learning_rate": 5e-05,
1088
+ "loss": 0.8176651000976562,
1089
+ "peak_memory_gb": 13.459977728,
1090
+ "step": 1290
1091
+ },
1092
+ {
1093
+ "epoch": 3.951367781155015,
1094
+ "grad_norm": 0.171875,
1095
+ "learning_rate": 5e-05,
1096
+ "loss": 0.7922792911529541,
1097
+ "peak_memory_gb": 13.459977728,
1098
+ "step": 1300
1099
+ },
1100
+ {
1101
+ "epoch": 3.9817629179331306,
1102
+ "grad_norm": 0.193359375,
1103
+ "learning_rate": 5e-05,
1104
+ "loss": 0.7916157722473145,
1105
+ "peak_memory_gb": 13.459977728,
1106
+ "step": 1310
1107
+ },
1108
+ {
1109
+ "epoch": 4.0,
1110
+ "eval_loss": 0.8508836030960083,
1111
+ "eval_runtime": 17.5637,
1112
+ "eval_samples_per_second": 251.144,
1113
+ "eval_steps_per_second": 15.714,
1114
+ "step": 1316
1115
+ }
1116
+ ],
1117
+ "logging_steps": 10,
1118
+ "max_steps": 1316,
1119
+ "num_input_tokens_seen": 0,
1120
+ "num_train_epochs": 4,
1121
+ "save_steps": 200,
1122
+ "stateful_callbacks": {
1123
+ "TrainerControl": {
1124
+ "args": {
1125
+ "should_epoch_stop": false,
1126
+ "should_evaluate": false,
1127
+ "should_log": false,
1128
+ "should_save": true,
1129
+ "should_training_stop": true
1130
+ },
1131
+ "attributes": {}
1132
+ }
1133
+ },
1134
+ "total_flos": 0.0,
1135
+ "train_batch_size": 30,
1136
+ "trial_name": null,
1137
+ "trial_params": null
1138
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df840fcf7d25c655e1b9c6696d22fc0578b68508c5e5d75a8d53eef84804571d
3
+ size 10526802
tokenizer_config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": null,
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|endoftext|>",
7
+ "errors": "replace",
8
+ "extra_special_tokens": [
9
+ "<|im_start|>",
10
+ "<|im_end|>",
11
+ "<|endofprompt|>",
12
+ "[breath]",
13
+ "<strong>",
14
+ "</strong>",
15
+ "[noise]",
16
+ "[laughter]",
17
+ "[cough]",
18
+ "[clucking]",
19
+ "[accent]",
20
+ "[quick_breath]",
21
+ "<laughter>",
22
+ "</laughter>",
23
+ "[hissing]",
24
+ "[sigh]",
25
+ "[vocalized-noise]",
26
+ "[lipsmack]",
27
+ "[mn]"
28
+ ],
29
+ "is_local": true,
30
+ "local_files_only": false,
31
+ "model_max_length": 32768,
32
+ "pad_token": "<|endoftext|>",
33
+ "split_special_tokens": false,
34
+ "tokenizer_class": "Qwen2Tokenizer",
35
+ "unk_token": null
36
+ }
train.py ADDED
@@ -0,0 +1,761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 LightSpeed (Author: Tianchi Liu), Alibaba Inc, TICTAP-11 and b-re-w. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ r"""
15
+ EmoTra-TTS training on CosyVoice2-0.5B: Stage I (the speech token language model) and Stage II (the emotion injection
16
+ of the flow matching model). Port of the upstream recipes `run_EmoTra_sft_LLM.sh`, `run_EmoTra_sft_Flow_Lynorm_fixs.sh`,
17
+ their `conf/*.yaml` and `tools/precompute_llm_tokens_sft_LLM.py` (github.com/Liu-Tianchi/EmoTra-TTS, commit `23fe9e4`).
18
+
19
+ Run it from a copy of this repository (`python train.py ...`); it imports the modeling and processing files next to it.
20
+
21
+ Commands:
22
+
23
+ - `stage1`: starts from the `FunAudioLLM/CosyVoice2-0.5B` backbone ([`load_cosyvoice2_backbone`]) with freshly
24
+ initialized EmoTra-TTS modules and trains the whole language model (`llm.*`). Adam, learning rate $10^{-5}$,
25
+ constant, no weight decay, gradient clipping 5, gradient accumulation 2, 8 epochs.
26
+ - `precompute`: decodes the Stage II speech token inputs with a Stage I checkpoint: for every record with at least
27
+ 100 ground truth speech tokens, between 0.5 and 1.5 times that many tokens; records whose decode is shorter than
28
+ 100 tokens are dropped, the rest are cut or padded with their last token to the ground truth count.
29
+ - `stage2`: copies `llm.vad_projection` and `llm.hidden_reconstructor` of a Stage I checkpoint into the flow
30
+ matching model and trains `flow.vad_downsample` and `flow.emo_layer_norm` only. Adam, learning rate
31
+ $5\times10^{-5}$, constant, eps $10^{-8}$, L2 weight decay $10^{-6}$, gradient clipping 1, gradient accumulation 2,
32
+ 4 epochs. Half of the batches run in streaming mode.
33
+
34
+ Both stages keep the model in BF16, run BF16 autocast, and step FP32 master copies of the trainable parameters
35
+ ([`FP32MasterAdam`]). A checkpoint holds `trainable.safetensors` (the trainable parameters only), `config.json` and
36
+ the trainer state.
37
+
38
+ Data. The released model was trained on `RetentionLabs/emotra-ash-transition-50k`, synthetic emotion transitions of
39
+ the EmoVoice-DB speaker `ash` built as upstream's `step0` to `step2` scripts build them. Its preparation (transition
40
+ synthesis, VAD filtering, w2v2 hidden states, speech tokens, mel features) is not part of this file. `--records`
41
+ is a file `torch.load` reads into `{"train": [...], "held_out": [...]}`, each a list of dicts:
42
+
43
+ | Field | Stage | Shape and content |
44
+ |---|---|---|
45
+ | `key` | both | `str`, unique per record |
46
+ | `input_ids` | I, precompute | `list[int]`, text ids of the processor's tokenizer (`add_special_tokens=False`), at most 200 |
47
+ | `speech_tokens` | I, precompute | `list[int]`, CosyVoice2 speech tokens of the target audio (25 Hz), at least one |
48
+ | `vad_start`, `vad_end` | both | `list[float]` of 3, `[arousal, valence, dominance]` in $[0, 1]$ of utterances A and B |
49
+ | `hidden_states_start`, `hidden_states_end` | I | `torch.Tensor` of shape `(1024,)`, pooled hidden state of the audEERING w2v2 VAD regressor on A and B |
50
+ | `speech_feat` | II | `torch.Tensor` of shape `(num_frames, 80)`, the 24 kHz log mel of the target audio ([`EmoTraTTSProcessor.speech_features`]), 50 frames per second |
51
+
52
+ Stage II also reads `--llm-tokens`, the output of `precompute` (`{"train": {key: tokens}, "held_out": {...}}`), and
53
+ uses the processor's fixed speaker embedding (`speaker_embedding.safetensors`, a CAM++ embedding of one neutral
54
+ recording of the speaker).
55
+ """
56
+
57
+ import argparse
58
+ import importlib
59
+ import os
60
+ import random
61
+ import re
62
+ import sys
63
+ import types
64
+ from collections import defaultdict
65
+ from collections.abc import Callable, Iterable, Mapping, Sequence
66
+ from pathlib import Path
67
+ from typing import Any
68
+
69
+ import torch
70
+ from safetensors.torch import load_file, save_file
71
+ from torch import nn
72
+ from torch.nn.utils.rnn import pad_sequence
73
+ from torch.utils.data import Dataset
74
+ from transformers import Trainer, TrainingArguments
75
+ from transformers.trainer import TRAINING_ARGS_NAME
76
+
77
+
78
+ # The model files use package relative imports, so the folder of this file is loaded as the package `emotra_tts`.
79
+ _package = types.ModuleType("emotra_tts")
80
+ _package.__path__ = [str(Path(__file__).resolve().parent)]
81
+ sys.modules.setdefault("emotra_tts", _package)
82
+ EmoTraTTSConfig = importlib.import_module("emotra_tts.configuration_emotra_tts").EmoTraTTSConfig
83
+ repetition_aware_sampling = importlib.import_module("emotra_tts.generation_emotra_tts").repetition_aware_sampling
84
+ EmoTraTTSForConditionalGeneration = importlib.import_module(
85
+ "emotra_tts.modeling_emotra_tts"
86
+ ).EmoTraTTSForConditionalGeneration
87
+
88
+
89
+ STAGE1_TRAINABLE = "llm."
90
+ """Name prefix of the parameters Stage I trains: the whole language model, as upstream's `train.py --model llm`."""
91
+
92
+ MIN_LLM_TOKENS = 100
93
+ TRAINABLE_WEIGHTS_NAME = "trainable.safetensors"
94
+
95
+ # Key renaming from the released CosyVoice2 files (`llm.pt`, `flow.pt`, `hift.pt`) to this model, applied in order.
96
+ COSYVOICE2_RENAMES = [
97
+ (r"^llm\.llm\.model\.model\.", "llm.model."),
98
+ (r"\.up_embed\.out\.0\.", ".up_input_projection.proj."),
99
+ (r"\.up_embed\.out\.1\.", ".up_input_projection.layer_norm."),
100
+ (r"\.up_encoders\.(\d+)\.self_attn\.", r".up_layers.\1.self_attn."),
101
+ (r"\.up_encoders\.(\d+)\.feed_forward\.", r".up_layers.\1.feed_forward."),
102
+ (r"\.up_encoders\.(\d+)\.norm_mha\.", r".up_layers.\1.self_attn_layer_norm."),
103
+ (r"\.up_encoders\.(\d+)\.norm_ff\.", r".up_layers.\1.final_layer_norm."),
104
+ (r"\.embed\.out\.0\.", ".input_projection.proj."),
105
+ (r"\.embed\.out\.1\.", ".input_projection.layer_norm."),
106
+ (r"\.encoders\.(\d+)\.self_attn\.", r".layers.\1.self_attn."),
107
+ (r"\.encoders\.(\d+)\.feed_forward\.", r".layers.\1.feed_forward."),
108
+ (r"\.encoders\.(\d+)\.norm1\.", r".layers.\1.self_attn_layer_norm."),
109
+ (r"\.encoders\.(\d+)\.norm2\.", r".layers.\1.final_layer_norm."),
110
+ (r"\.encoders\.(\d+)\.norm_mha\.", r".layers.\1.self_attn_layer_norm."),
111
+ (r"\.encoders\.(\d+)\.norm_ff\.", r".layers.\1.final_layer_norm."),
112
+ (r"\.after_norm\.", ".layer_norm."),
113
+ (r"\.weight_g$", ".parametrizations.weight.original0"),
114
+ (r"\.weight_v$", ".parametrizations.weight.original1"),
115
+ ]
116
+ EMOTRA_MODULES = (
117
+ "llm.vad_projection.",
118
+ "llm.hidden_reconstructor.",
119
+ "flow.vad_projection.",
120
+ "flow.vad_hidden_reconstructor.",
121
+ "flow.vad_downsample.",
122
+ "flow.emo_layer_norm.",
123
+ )
124
+
125
+
126
+ def load_cosyvoice2_backbone(model: nn.Module, repo_id: str = "FunAudioLLM/CosyVoice2-0.5B") -> None:
127
+ r"""
128
+ Loads the three released CosyVoice2 networks into an [`EmoTraTTSForConditionalGeneration`], leaving the EmoTra-TTS
129
+ modules as initialized.
130
+
131
+ Args:
132
+ model (`nn.Module`):
133
+ The model.
134
+ repo_id (`str`, *optional*, defaults to `"FunAudioLLM/CosyVoice2-0.5B"`):
135
+ Hub repository or local folder with `llm.pt`, `flow.pt` and `hift.pt`.
136
+
137
+ Raises:
138
+ `ValueError`: If a backbone parameter is missing or a released tensor has no place in the model.
139
+ """
140
+ from huggingface_hub import hf_hub_download
141
+
142
+ state = {}
143
+ for prefix in ("llm", "flow", "hift"):
144
+ path = Path(repo_id) / f"{prefix}.pt"
145
+ path = path if path.is_file() else hf_hub_download(repo_id, f"{prefix}.pt")
146
+ for key, value in torch.load(path, map_location="cpu", weights_only=True).items():
147
+ name = f"{prefix}.{key}"
148
+ for pattern, replacement in COSYVOICE2_RENAMES:
149
+ name = re.sub(pattern, replacement, name)
150
+ state[name] = value
151
+ ignored = re.compile(r"llm\.model\.rotary_emb\.inv_freq|llm\.model\.lm_head\.")
152
+ state = {name: value for name, value in state.items() if not ignored.search(name)}
153
+ missing, unexpected = model.load_state_dict(state, strict=False)
154
+ missing = [name for name in missing if not name.startswith(EMOTRA_MODULES)]
155
+ if missing or unexpected:
156
+ raise ValueError(f"backbone mismatch: missing {missing}, unexpected {unexpected}")
157
+
158
+
159
+ class FP32MasterAdam(torch.optim.Adam):
160
+ r"""
161
+ Constructs Adam on FP32 master copies of BF16 model parameters. The model parameters keep BF16 for forward and
162
+ backward; each step copies their gradients to the masters, updates the masters and writes them back, so updates
163
+ below the BF16 resolution accumulate. `weight_decay` is the L2 term Adam adds to the gradient.
164
+
165
+ Args:
166
+ params (`Iterable[nn.Parameter]`):
167
+ Model parameters in checkpoint order.
168
+ lr (`float`, *optional*, defaults to 0.001):
169
+ Learning rate.
170
+ **kwargs:
171
+ Additional arguments passed to `torch.optim.Adam`.
172
+ """
173
+
174
+ def __init__(self, params: Iterable[nn.Parameter], lr: float = 1e-3, **kwargs: Any):
175
+ self._model_params = list(params)
176
+ masters = [nn.Parameter(parameter.detach().float().clone()) for parameter in self._model_params]
177
+ super().__init__(masters, lr=lr, **kwargs)
178
+
179
+ def zero_grad(self, set_to_none: bool = True) -> None:
180
+ super().zero_grad(set_to_none=set_to_none)
181
+ for parameter in self._model_params:
182
+ if parameter.grad is not None:
183
+ if set_to_none:
184
+ parameter.grad = None
185
+ else:
186
+ parameter.grad.detach_()
187
+ parameter.grad.zero_()
188
+
189
+ @torch.no_grad()
190
+ def step(self, closure: Callable[[], torch.Tensor] | None = None) -> None:
191
+ if closure is not None:
192
+ raise NotImplementedError("FP32 master optimizer does not support a closure; compute and clip model gradients first")
193
+ masters = [parameter for group in self.param_groups for parameter in group["params"]]
194
+ for parameter, master in zip(self._model_params, masters, strict=True):
195
+ master.grad = None if parameter.grad is None else parameter.grad.detach().float()
196
+ super().step()
197
+ for parameter, master in zip(self._model_params, masters, strict=True):
198
+ parameter.copy_(master)
199
+
200
+ def state_dict(self) -> dict[str, Any]:
201
+ state = super().state_dict()
202
+ state["fp32_master_params"] = [
203
+ parameter.detach().clone() for group in self.param_groups for parameter in group["params"]
204
+ ]
205
+ return state
206
+
207
+ def load_state_dict(self, state_dict: dict[str, Any]) -> None:
208
+ state_dict = dict(state_dict)
209
+ masters = state_dict.pop("fp32_master_params", None)
210
+ super().load_state_dict(state_dict)
211
+ with torch.no_grad():
212
+ targets = [parameter for group in self.param_groups for parameter in group["params"]]
213
+ sources = masters if masters is not None else [parameter.float() for parameter in self._model_params]
214
+ for target, source in zip(targets, sources, strict=True):
215
+ target.copy_(source)
216
+
217
+
218
+ class EmoTraTrainer(Trainer):
219
+ r"""
220
+ [`~transformers.Trainer`] that steps [`FP32MasterAdam`] over the trainable parameters, in one group, and saves only
221
+ the trainable parameters (`trainable.safetensors`) in a checkpoint.
222
+ """
223
+
224
+ def create_optimizer(self, model: nn.Module | None = None) -> torch.optim.Optimizer:
225
+ if self.optimizer is None:
226
+ model = self.model if model is None else model
227
+ self.optimizer = FP32MasterAdam(
228
+ [param for param in model.parameters() if param.requires_grad],
229
+ lr=self.args.learning_rate,
230
+ betas=(self.args.adam_beta1, self.args.adam_beta2),
231
+ eps=self.args.adam_epsilon,
232
+ weight_decay=self.args.weight_decay,
233
+ )
234
+ return self.optimizer
235
+
236
+ def _save(self, output_dir: str | None = None, state_dict: dict | None = None) -> None:
237
+ output_dir = output_dir if output_dir is not None else self.args.output_dir
238
+ if not self.args.should_save:
239
+ return
240
+ os.makedirs(output_dir, exist_ok=True)
241
+ model = self.accelerator.unwrap_model(self.model, keep_torch_compile=False)
242
+ trainable = {
243
+ name: param.detach().contiguous().cpu() for name, param in model.named_parameters() if param.requires_grad
244
+ }
245
+ save_file(trainable, os.path.join(output_dir, TRAINABLE_WEIGHTS_NAME), metadata={"format": "pt"})
246
+ model.config.save_pretrained(output_dir)
247
+ torch.save(self.args, os.path.join(output_dir, TRAINING_ARGS_NAME))
248
+
249
+ def _load_from_checkpoint(self, resume_from_checkpoint: str, model: nn.Module | None = None) -> None:
250
+ load_trainable_weights(self.model if model is None else model, resume_from_checkpoint)
251
+
252
+
253
+ def load_trainable_weights(model: nn.Module, checkpoint: str | os.PathLike) -> None:
254
+ r"""
255
+ Loads the trainable parameters a checkpoint holds into `model`.
256
+
257
+ Args:
258
+ model (`nn.Module`):
259
+ The model, already frozen the way the run froze it.
260
+ checkpoint (`str` or `os.PathLike`):
261
+ The checkpoint directory.
262
+
263
+ Raises:
264
+ `ValueError`: If the checkpoint and the trainable parameters of `model` do not name the same tensors.
265
+ """
266
+ state = load_file(os.path.join(checkpoint, TRAINABLE_WEIGHTS_NAME))
267
+ params = dict(model.named_parameters())
268
+ expected = {name for name, param in params.items() if param.requires_grad}
269
+ if set(state) != expected:
270
+ missing, unexpected = sorted(expected - set(state)), sorted(set(state) - expected)
271
+ raise ValueError(
272
+ f"{checkpoint} does not match the trainable parameters: missing {missing}, unexpected {unexpected}"
273
+ )
274
+ with torch.no_grad():
275
+ for name, tensor in state.items():
276
+ params[name].copy_(tensor.to(device=params[name].device, dtype=params[name].dtype))
277
+
278
+
279
+ class EmoTraTransitionDataset(Dataset):
280
+ r"""
281
+ The training items of one stage. Stage I items hold the text ids, the speech tokens, the start and end VAD and the
282
+ hidden states of A and B. Stage II items hold the speech tokens the Stage I model decoded (`llm_tokens`), the mel of
283
+ the audio, the speaker embedding and the VAD. Tokens and mel are cut to a common length of `token_mel_ratio` frames
284
+ per token, as upstream's `compute_fbank` cuts them.
285
+
286
+ Args:
287
+ records (`Sequence[Mapping[str, Any]]`):
288
+ Records in the format of this file's docstring; Stage II records also hold `llm_tokens`.
289
+ stage (`int`):
290
+ 1 or 2.
291
+ speaker_embedding (`torch.Tensor`, *optional*):
292
+ The neutral speaker embedding (192), needed for Stage II.
293
+ token_mel_ratio (`int`, *optional*, defaults to 2):
294
+ Mel frames per speech token.
295
+ """
296
+
297
+ def __init__(
298
+ self,
299
+ records: Sequence[Mapping[str, Any]],
300
+ stage: int,
301
+ speaker_embedding: torch.Tensor | None = None,
302
+ token_mel_ratio: int = 2,
303
+ ):
304
+ if stage not in (1, 2):
305
+ raise ValueError(f"stage must be 1 or 2, got {stage}")
306
+ if stage == 2 and speaker_embedding is None:
307
+ raise ValueError("Stage II needs the speaker embedding")
308
+ self.records = list(records)
309
+ self.stage = stage
310
+ self.speaker_embedding = speaker_embedding
311
+ self.token_mel_ratio = token_mel_ratio
312
+
313
+ def __len__(self) -> int:
314
+ return len(self.records)
315
+
316
+ def __getitem__(self, index: int) -> dict[str, torch.Tensor]:
317
+ record = self.records[index]
318
+ item = {
319
+ "vad_start": torch.tensor(record["vad_start"], dtype=torch.bfloat16),
320
+ "vad_end": torch.tensor(record["vad_end"], dtype=torch.bfloat16),
321
+ }
322
+ if self.stage == 1:
323
+ item["input_ids"] = torch.tensor(record["input_ids"], dtype=torch.long)
324
+ item["speech_token_ids"] = torch.tensor(record["speech_tokens"], dtype=torch.long)
325
+ item["hidden_states_start"] = torch.as_tensor(record["hidden_states_start"], dtype=torch.bfloat16)
326
+ item["hidden_states_end"] = torch.as_tensor(record["hidden_states_end"], dtype=torch.bfloat16)
327
+ return item
328
+ feat = torch.as_tensor(record["speech_feat"])
329
+ tokens = torch.tensor(record["llm_tokens"], dtype=torch.long)
330
+ length = min(feat.shape[0] // self.token_mel_ratio, tokens.shape[0])
331
+ item["speech_token_ids"] = tokens[:length]
332
+ item["speech_feat"] = feat[: length * self.token_mel_ratio].to(torch.bfloat16)
333
+ item["speaker_embedding"] = torch.as_tensor(self.speaker_embedding, dtype=torch.bfloat16).reshape(-1)
334
+ return item
335
+
336
+
337
+ def collate_stage1(items: Sequence[Mapping[str, torch.Tensor]]) -> dict[str, torch.Tensor]:
338
+ """
339
+ Pads Stage I items into the keyword arguments of [`EmoTraTTSForConditionalGeneration.forward`].
340
+
341
+ Args:
342
+ items (`Sequence[Mapping[str, torch.Tensor]]`):
343
+ Items of [`EmoTraTransitionDataset`] for Stage I.
344
+
345
+ Returns:
346
+ `dict[str, torch.Tensor]`: `input_ids`, `input_lengths`, `speech_token_ids`, `speech_token_lengths`,
347
+ `vad_start`, `vad_end`, `hidden_states_start`, `hidden_states_end`.
348
+ """
349
+ return {
350
+ "input_ids": pad_sequence([i["input_ids"] for i in items], batch_first=True),
351
+ "input_lengths": torch.tensor([len(i["input_ids"]) for i in items], dtype=torch.int32),
352
+ "speech_token_ids": pad_sequence([i["speech_token_ids"] for i in items], batch_first=True),
353
+ "speech_token_lengths": torch.tensor([len(i["speech_token_ids"]) for i in items], dtype=torch.int32),
354
+ "vad_start": torch.stack([i["vad_start"] for i in items]),
355
+ "vad_end": torch.stack([i["vad_end"] for i in items]),
356
+ "hidden_states_start": torch.stack([i["hidden_states_start"] for i in items]),
357
+ "hidden_states_end": torch.stack([i["hidden_states_end"] for i in items]),
358
+ }
359
+
360
+
361
+ def collate_stage2(items: Sequence[Mapping[str, torch.Tensor]], streaming_probability: float = 0.5) -> dict[str, Any]:
362
+ """
363
+ Pads Stage II items, and draws whether the batch runs in streaming mode with probability one half, as upstream
364
+ draws it per batch.
365
+
366
+ Args:
367
+ items (`Sequence[Mapping[str, torch.Tensor]]`):
368
+ Items of [`EmoTraTransitionDataset`] for Stage II.
369
+ streaming_probability (`float`, *optional*, defaults to 0.5):
370
+ Probability of streaming mode.
371
+
372
+ Returns:
373
+ `dict[str, Any]`: `speech_token_ids`, `speech_token_lengths`, `speech_feat`, `speech_feat_lengths`,
374
+ `speaker_embedding`, `vad_start`, `vad_end` and `streaming`.
375
+ """
376
+ return {
377
+ "speech_token_ids": pad_sequence([i["speech_token_ids"] for i in items], batch_first=True),
378
+ "speech_token_lengths": torch.tensor([len(i["speech_token_ids"]) for i in items], dtype=torch.int32),
379
+ "speech_feat": pad_sequence([i["speech_feat"] for i in items], batch_first=True),
380
+ "speech_feat_lengths": torch.tensor([len(i["speech_feat"]) for i in items], dtype=torch.int32),
381
+ "speaker_embedding": torch.stack([i["speaker_embedding"] for i in items]),
382
+ "vad_start": torch.stack([i["vad_start"] for i in items]),
383
+ "vad_end": torch.stack([i["vad_end"] for i in items]),
384
+ "streaming": random.random() < streaming_probability,
385
+ }
386
+
387
+
388
+ def prepare_stage1(model: nn.Module) -> list[str]:
389
+ r"""
390
+ Sets up Stage I as upstream does: the whole language model (`llm.*`, the Qwen2 decoder, the text and speech
391
+ embeddings, the speech head and the two VAD modules) trains; the flow model and HiFT are frozen. The model is BF16.
392
+
393
+ Args:
394
+ model (`nn.Module`):
395
+ An [`EmoTraTTSForConditionalGeneration`].
396
+
397
+ Returns:
398
+ `list[str]`: Names of the trainable parameters.
399
+ """
400
+ model.to(dtype=torch.bfloat16)
401
+ for name, param in model.named_parameters():
402
+ param.requires_grad_(name.startswith(STAGE1_TRAINABLE))
403
+ return [name for name, param in model.named_parameters() if param.requires_grad]
404
+
405
+
406
+ def load_stage1_weights_for_flow(model: nn.Module, checkpoint: str | os.PathLike) -> list[str]:
407
+ """
408
+ Loads the `llm.vad_projection` and `llm.hidden_reconstructor` weights of a Stage I checkpoint, which
409
+ [`prepare_stage2`] then copies into the flow model.
410
+
411
+ Args:
412
+ model (`nn.Module`):
413
+ An [`EmoTraTTSForConditionalGeneration`].
414
+ checkpoint (`str` or `os.PathLike`):
415
+ The Stage I checkpoint directory.
416
+
417
+ Returns:
418
+ `list[str]`: The loaded parameter names.
419
+
420
+ Raises:
421
+ ValueError: If the checkpoint lacks a parameter of the two modules.
422
+ """
423
+ state = load_file(os.path.join(checkpoint, TRAINABLE_WEIGHTS_NAME))
424
+ wanted = {
425
+ name: param
426
+ for name, param in model.named_parameters()
427
+ if name.startswith(("llm.vad_projection.", "llm.hidden_reconstructor."))
428
+ }
429
+ missing = sorted(set(wanted) - set(state))
430
+ if missing:
431
+ raise ValueError(f"{checkpoint} lacks {missing}")
432
+ with torch.no_grad():
433
+ for name, param in wanted.items():
434
+ param.copy_(state[name].to(param.device, param.dtype))
435
+ return sorted(wanted)
436
+
437
+
438
+ def prepare_stage2(model: nn.Module) -> list[str]:
439
+ """
440
+ Sets up Stage II with [`EmoTraTTSForConditionalGeneration.prepare_flow_stage`]: the VAD modules copied into the
441
+ flow model, everything frozen except `flow.vad_downsample` and `flow.emo_layer_norm`.
442
+
443
+ Args:
444
+ model (`nn.Module`):
445
+ The model, with the Stage I VAD modules loaded.
446
+
447
+ Returns:
448
+ `list[str]`: Names of the trainable parameters.
449
+ """
450
+ model.to(dtype=torch.bfloat16)
451
+ model.prepare_flow_stage()
452
+ return [name for name, param in model.named_parameters() if param.requires_grad]
453
+
454
+
455
+ def load_for_generation(
456
+ model: nn.Module, stage1_checkpoint: str | os.PathLike, stage2_checkpoint: str | os.PathLike
457
+ ) -> nn.Module:
458
+ r"""
459
+ Assembles the generating model as upstream's inference does: the Stage I language model, with the flow model's VAD
460
+ modules copied from it, and the Stage II flow emotion modules. This is how the weights of this repository were
461
+ assembled from `stage1/` and `stage2/`.
462
+
463
+ Args:
464
+ model (`nn.Module`):
465
+ An [`EmoTraTTSForConditionalGeneration`] holding the CosyVoice2 backbone.
466
+ stage1_checkpoint (`str` or `os.PathLike`):
467
+ The Stage I checkpoint directory.
468
+ stage2_checkpoint (`str` or `os.PathLike`):
469
+ The Stage II checkpoint directory.
470
+
471
+ Returns:
472
+ `nn.Module`: The model, frozen and in evaluation mode.
473
+ """
474
+ prepare_stage1(model)
475
+ load_trainable_weights(model, stage1_checkpoint)
476
+ prepare_stage2(model)
477
+ load_trainable_weights(model, stage2_checkpoint)
478
+ model.requires_grad_(False)
479
+ return model.eval()
480
+
481
+
482
+ def decode_llm_tokens_batch(
483
+ model: nn.Module,
484
+ input_ids: torch.Tensor,
485
+ vad_start: torch.Tensor,
486
+ vad_end: torch.Tensor,
487
+ min_lengths: Sequence[int],
488
+ max_lengths: Sequence[int],
489
+ top_p: float = 0.8,
490
+ top_k: int = 25,
491
+ window_size: int = 10,
492
+ repetition_threshold: float = 0.1,
493
+ ) -> list[list[int]]:
494
+ r"""
495
+ Decodes equal-length text prefixes as independent autoregressive token sequences.
496
+
497
+ Args:
498
+ model (`nn.Module`):
499
+ The Stage I model.
500
+ input_ids (`torch.Tensor` of shape `(batch_size, text_length)`):
501
+ Equal-length text ids.
502
+ vad_start (`torch.Tensor` of shape `(batch_size, 3)`):
503
+ Start VAD.
504
+ vad_end (`torch.Tensor` of shape `(batch_size, 3)`):
505
+ End VAD.
506
+ min_lengths (`Sequence[int]`):
507
+ Fewest tokens per sequence.
508
+ max_lengths (`Sequence[int]`):
509
+ Most tokens per sequence.
510
+ top_p (`float`, *optional*, defaults to 0.8):
511
+ Nucleus probability.
512
+ top_k (`int`, *optional*, defaults to 25):
513
+ Candidates.
514
+ window_size (`int`, *optional*, defaults to 10):
515
+ Repetition window.
516
+ repetition_threshold (`float`, *optional*, defaults to 0.1):
517
+ Repetition limit.
518
+
519
+ Returns:
520
+ `list[list[int]]`: Decoded tokens in input order.
521
+ """
522
+ batch_size = input_ids.shape[0]
523
+ llm = model.llm
524
+ sos = llm.llm_embedding.weight[llm.sos_index].reshape(1, 1, -1).expand(batch_size, -1, -1)
525
+ task_id = llm.llm_embedding.weight[llm.task_id_index].reshape(1, 1, -1).expand(batch_size, -1, -1)
526
+ vad = llm.embed_vad(vad_start.to(sos.dtype), vad_end.to(sos.dtype)).to(sos.dtype)
527
+ hidden_states = torch.concat([sos, vad, llm.embed_text(input_ids), task_id], dim=1)
528
+ tokens = [[] for _ in range(batch_size)]
529
+ active = list(range(batch_size))
530
+ past_key_values = None
531
+ while active:
532
+ logits, past_key_values = llm(hidden_states, past_key_values=past_key_values, use_cache=True)
533
+ next_active = []
534
+ next_embeddings = []
535
+ for active_index, original_index in enumerate(active):
536
+ log_probs = logits[active_index, -1].float().log_softmax(dim=-1)
537
+ if len(tokens[original_index]) < min_lengths[original_index]:
538
+ log_probs[llm.eos_token_id] = -float("inf")
539
+ token = repetition_aware_sampling(
540
+ log_probs, tokens[original_index], top_p, top_k, window_size, repetition_threshold
541
+ )
542
+ if token not in llm.stop_token_ids:
543
+ tokens[original_index].append(token)
544
+ if token not in llm.stop_token_ids and len(tokens[original_index]) < max_lengths[original_index]:
545
+ next_active.append(original_index)
546
+ next_embeddings.append(llm.speech_embedding.weight[token])
547
+ if not next_active:
548
+ break
549
+ indices = torch.tensor([active.index(index) for index in next_active], device=hidden_states.device)
550
+ past_key_values.batch_select_indices(indices)
551
+ active = next_active
552
+ hidden_states = torch.stack(next_embeddings).unsqueeze(1)
553
+ return tokens
554
+
555
+
556
+ def truncate_or_pad_tokens(generated: Sequence[int], length: int) -> list[int]:
557
+ """
558
+ Cuts decoded tokens to `length`, or pads them with their last token (0 when there is none).
559
+
560
+ Args:
561
+ generated (`Sequence[int]`):
562
+ Decoded tokens.
563
+ length (`int`):
564
+ The ground truth token count.
565
+
566
+ Returns:
567
+ `list[int]`: Exactly `length` tokens.
568
+ """
569
+ generated = list(generated)
570
+ if len(generated) >= length:
571
+ return generated[:length]
572
+ return generated + [generated[-1] if generated else 0] * (length - len(generated))
573
+
574
+
575
+ @torch.inference_mode()
576
+ def precompute_llm_tokens(
577
+ model: nn.Module,
578
+ records: Sequence[Mapping[str, Any]],
579
+ min_token_len: int = MIN_LLM_TOKENS,
580
+ decode_batch_size: int = 32,
581
+ ) -> dict[str, list[int]]:
582
+ r"""
583
+ The Stage II inputs (`precompute_llm_tokens_sft_LLM.py`): for every record with at least `min_token_len` ground
584
+ truth tokens, the Stage I model decodes between half and one and a half times that many tokens; records whose
585
+ decode is shorter than `min_token_len` are dropped, the rest are cut or padded to the ground truth count.
586
+
587
+ Args:
588
+ model (`nn.Module`):
589
+ The Stage I model, in evaluation mode.
590
+ records (`Sequence[Mapping[str, Any]]`):
591
+ Records with `key`, `input_ids`, `speech_tokens`, `vad_start` and `vad_end`.
592
+ min_token_len (`int`, *optional*, defaults to 100):
593
+ Fewest tokens kept (4 s at 25 Hz).
594
+ decode_batch_size (`int`, *optional*, defaults to 32):
595
+ Equal text-length records decoded per model call.
596
+
597
+ Returns:
598
+ `dict[str, list[int]]`: Tokens per kept record key.
599
+ """
600
+ device = next(model.parameters()).device
601
+ buckets = defaultdict(list)
602
+ for record in records:
603
+ if len(record["speech_tokens"]) >= min_token_len:
604
+ buckets[len(record["input_ids"])].append(record)
605
+ result = {}
606
+ for bucket in buckets.values():
607
+ for start in range(0, len(bucket), decode_batch_size):
608
+ batch = bucket[start : start + decode_batch_size]
609
+ generated = decode_llm_tokens_batch(
610
+ model,
611
+ torch.tensor([record["input_ids"] for record in batch], device=device),
612
+ torch.tensor([record["vad_start"] for record in batch], device=device),
613
+ torch.tensor([record["vad_end"] for record in batch], device=device),
614
+ [max(1, int(len(record["speech_tokens"]) * 0.5)) for record in batch],
615
+ [int(len(record["speech_tokens"]) * 1.5) for record in batch],
616
+ )
617
+ for record, tokens in zip(batch, generated, strict=True):
618
+ if len(tokens) >= min_token_len:
619
+ result[record["key"]] = truncate_or_pad_tokens(tokens, len(record["speech_tokens"]))
620
+ return result
621
+
622
+
623
+ def stage_training_arguments(stage: int, output_dir: str, **overrides: Any) -> TrainingArguments:
624
+ r"""
625
+ The training arguments of a stage, with upstream's recipe: Stage I Adam at $10^{-5}$, constant, no weight decay,
626
+ clipping 5, accumulation 2, 8 epochs; Stage II Adam at $5\times10^{-5}$, constant, eps $10^{-8}$, L2 weight decay
627
+ $10^{-6}$, clipping 1, accumulation 2, 4 epochs. Both run BF16 autocast.
628
+
629
+ Args:
630
+ stage (`int`):
631
+ 1 or 2.
632
+ output_dir (`str`):
633
+ Run directory.
634
+ **overrides:
635
+ Fields of [`~transformers.TrainingArguments`] that replace the defaults.
636
+
637
+ Returns:
638
+ [`~transformers.TrainingArguments`]: The arguments.
639
+ """
640
+ common = dict(
641
+ output_dir=output_dir,
642
+ lr_scheduler_type="constant",
643
+ gradient_accumulation_steps=2,
644
+ eval_strategy="steps",
645
+ save_strategy="steps",
646
+ logging_steps=10,
647
+ report_to="none",
648
+ remove_unused_columns=False,
649
+ dataloader_num_workers=0,
650
+ seed=0,
651
+ bf16=True,
652
+ )
653
+ if stage == 1:
654
+ recipe = dict(
655
+ learning_rate=1e-5, weight_decay=0.0, max_grad_norm=5.0, num_train_epochs=8, eval_steps=300,
656
+ save_steps=300, label_names=["speech_token_ids"],
657
+ ) # fmt: skip
658
+ else:
659
+ recipe = dict(
660
+ learning_rate=5e-5, adam_epsilon=1e-8, weight_decay=1e-6, max_grad_norm=1.0, num_train_epochs=4,
661
+ eval_steps=200, save_steps=200, label_names=["speech_feat"],
662
+ ) # fmt: skip
663
+ return TrainingArguments(**{**common, **recipe, **overrides})
664
+
665
+
666
+ def build_model(release: str, cosyvoice: str) -> nn.Module:
667
+ """
668
+ Builds an [`EmoTraTTSForConditionalGeneration`] with the configuration of this repository, the CosyVoice2 backbone
669
+ and freshly initialized EmoTra-TTS modules, in BF16.
670
+
671
+ Args:
672
+ release (`str`):
673
+ Folder or Hub id of this repository, for `config.json`.
674
+ cosyvoice (`str`):
675
+ Folder or Hub id of the released CosyVoice2 checkpoint.
676
+
677
+ Returns:
678
+ `nn.Module`: The model.
679
+ """
680
+ model = EmoTraTTSForConditionalGeneration(EmoTraTTSConfig.from_pretrained(release))
681
+ load_cosyvoice2_backbone(model, cosyvoice)
682
+ return model.to(torch.bfloat16)
683
+
684
+
685
+ def main(argv: Sequence[str] | None = None) -> None:
686
+ """
687
+ Command line entry point, see the module docstring.
688
+
689
+ Args:
690
+ argv (`Sequence[str]`, *optional*):
691
+ Arguments, defaults to `sys.argv[1:]`.
692
+ """
693
+ parser = argparse.ArgumentParser(prog="python train.py")
694
+ parser.add_argument("--records", required=True, help="torch file with {'train': [...], 'held_out': [...]}")
695
+ parser.add_argument("--release", default=str(Path(__file__).resolve().parent), help="this repository")
696
+ parser.add_argument("--cosyvoice", default="FunAudioLLM/CosyVoice2-0.5B")
697
+ parser.add_argument("--device", default=None)
698
+ commands = parser.add_subparsers(dest="command", required=True)
699
+ for name in ("stage1", "stage2"):
700
+ stage = commands.add_parser(name)
701
+ stage.add_argument("--output-dir", required=True)
702
+ stage.add_argument("--per-device-train-batch-size", type=int, default=16)
703
+ stage.add_argument("--max-steps", type=int, default=-1)
704
+ if name == "stage2":
705
+ stage.add_argument("--stage1-checkpoint", required=True)
706
+ stage.add_argument("--llm-tokens", required=True)
707
+ precompute = commands.add_parser("precompute")
708
+ precompute.add_argument("--stage1-checkpoint", required=True)
709
+ precompute.add_argument("--output", required=True)
710
+ precompute.add_argument("--min-token-len", type=int, default=MIN_LLM_TOKENS)
711
+ precompute.add_argument("--decode-batch-size", type=int, default=32)
712
+ args = parser.parse_args(argv)
713
+
714
+ device = args.device or ("cuda" if torch.cuda.is_available() else "cpu")
715
+ records = torch.load(args.records, weights_only=False)
716
+ train_records, eval_records = records["train"], records["held_out"]
717
+ model = build_model(args.release, args.cosyvoice)
718
+
719
+ if args.command == "precompute":
720
+ prepare_stage1(model)
721
+ load_trainable_weights(model, args.stage1_checkpoint)
722
+ model.to(device).eval()
723
+ tokens = {
724
+ split: precompute_llm_tokens(model, part, args.min_token_len, args.decode_batch_size)
725
+ for split, part in (("train", train_records), ("held_out", eval_records))
726
+ }
727
+ torch.save(tokens, args.output)
728
+ print(f"{len(tokens['train'])} train and {len(tokens['held_out'])} held-out records kept for Stage II")
729
+ return
730
+
731
+ if args.command == "stage1":
732
+ prepare_stage1(model)
733
+ train_set, eval_set = EmoTraTransitionDataset(train_records, 1), EmoTraTransitionDataset(eval_records, 1)
734
+ collator = collate_stage1
735
+ else:
736
+ load_stage1_weights_for_flow(model, args.stage1_checkpoint)
737
+ prepare_stage2(model)
738
+ llm_tokens = torch.load(args.llm_tokens)
739
+ from safetensors.torch import load_file as load_safetensors
740
+ from transformers.utils.hub import cached_file
741
+
742
+ speaker = load_safetensors(cached_file(args.release, "speaker_embedding.safetensors"))["speaker_embedding"]
743
+ parts = []
744
+ for split, part in (("train", train_records), ("held_out", eval_records)):
745
+ kept = llm_tokens[split]
746
+ parts.append([{**record, "llm_tokens": kept[record["key"]]} for record in part if record["key"] in kept])
747
+ train_set = EmoTraTransitionDataset(parts[0], 2, speaker_embedding=speaker)
748
+ eval_set = EmoTraTransitionDataset(parts[1], 2, speaker_embedding=speaker)
749
+ collator = collate_stage2
750
+ stage = 1 if args.command == "stage1" else 2
751
+ training_args = stage_training_arguments(
752
+ stage, args.output_dir, per_device_train_batch_size=args.per_device_train_batch_size, max_steps=args.max_steps
753
+ )
754
+ trainer = EmoTraTrainer(
755
+ model=model, args=training_args, train_dataset=train_set, eval_dataset=eval_set, data_collator=collator
756
+ )
757
+ trainer.train(resume_from_checkpoint=any(Path(args.output_dir).glob("checkpoint-*")) or None)
758
+
759
+
760
+ if __name__ == "__main__":
761
+ main()