litagin commited on
Commit
78b6bf0
1 Parent(s): a5a8526
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +1 -0
  2. LICENSE +661 -0
  3. README.md +4 -4
  4. app.py +540 -0
  5. attentions.py +462 -0
  6. bert/bert_models.json +14 -0
  7. bert/chinese-roberta-wwm-ext-large/.gitattributes +9 -0
  8. bert/chinese-roberta-wwm-ext-large/README.md +57 -0
  9. bert/chinese-roberta-wwm-ext-large/added_tokens.json +1 -0
  10. bert/chinese-roberta-wwm-ext-large/config.json +28 -0
  11. bert/chinese-roberta-wwm-ext-large/pytorch_model.bin +3 -0
  12. bert/chinese-roberta-wwm-ext-large/special_tokens_map.json +1 -0
  13. bert/chinese-roberta-wwm-ext-large/tokenizer.json +0 -0
  14. bert/chinese-roberta-wwm-ext-large/tokenizer_config.json +1 -0
  15. bert/chinese-roberta-wwm-ext-large/vocab.txt +0 -0
  16. bert/deberta-v2-large-japanese-char-wwm/.gitattributes +34 -0
  17. bert/deberta-v2-large-japanese-char-wwm/README.md +89 -0
  18. bert/deberta-v2-large-japanese-char-wwm/config.json +37 -0
  19. bert/deberta-v2-large-japanese-char-wwm/pytorch_model.bin +3 -0
  20. bert/deberta-v2-large-japanese-char-wwm/special_tokens_map.json +7 -0
  21. bert/deberta-v2-large-japanese-char-wwm/tokenizer_config.json +19 -0
  22. bert/deberta-v2-large-japanese-char-wwm/vocab.txt +0 -0
  23. bert/deberta-v3-large/.gitattributes +27 -0
  24. bert/deberta-v3-large/README.md +93 -0
  25. bert/deberta-v3-large/config.json +22 -0
  26. bert/deberta-v3-large/generator_config.json +22 -0
  27. bert/deberta-v3-large/pytorch_model.bin +3 -0
  28. bert/deberta-v3-large/pytorch_model.bin.bin +3 -0
  29. bert/deberta-v3-large/spm.model +3 -0
  30. bert/deberta-v3-large/tokenizer_config.json +4 -0
  31. bert_gen.py +84 -0
  32. commons.py +152 -0
  33. config.py +254 -0
  34. config.yml +58 -0
  35. configs/config.json +70 -0
  36. data_utils.py +425 -0
  37. default_config.yml +81 -0
  38. infer.py +263 -0
  39. losses.py +153 -0
  40. mel_processing.py +146 -0
  41. model_assets/jvnv-F1/config.json +76 -0
  42. model_assets/jvnv-F1/jvnv-F1.safetensors +3 -0
  43. model_assets/jvnv-F1/style_vectors.npy +3 -0
  44. model_assets/jvnv-F2/config.json +79 -0
  45. model_assets/jvnv-F2/jvnv-F2.safetensors +3 -0
  46. model_assets/jvnv-F2/style_vectors.npy +3 -0
  47. model_assets/jvnv-M1/config.json +79 -0
  48. model_assets/jvnv-M1/jvnv-M1.safetensors +3 -0
  49. model_assets/jvnv-M1/style_vectors.npy +3 -0
  50. model_assets/jvnv-M2/config.json +79 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__/
LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
README.md CHANGED
@@ -1,13 +1,13 @@
1
  ---
2
  title: Style Bert VITS2 JVNV
3
- emoji: 📉
4
- colorFrom: yellow
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 4.12.0
8
  app_file: app.py
9
  pinned: false
10
- license: cc-by-4.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: Style Bert VITS2 JVNV
3
+ emoji: 🎙️😡😊😱😫🎙️
4
+ colorFrom: blue
5
+ colorTo: red
6
  sdk: gradio
7
  sdk_version: 4.12.0
8
  app_file: app.py
9
  pinned: false
10
+ license: agpl-3.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import datetime
3
+ import os
4
+ import sys
5
+ import warnings
6
+
7
+ import gradio as gr
8
+ import numpy as np
9
+ import torch
10
+ from gradio.processing_utils import convert_to_16_bit_wav
11
+
12
+ import utils
13
+ from config import config
14
+ from infer import get_net_g, infer
15
+ from tools.log import logger
16
+
17
+ is_hf_spaces = os.getenv("SYSTEM") == "spaces"
18
+ limit = 100
19
+
20
+
21
+ class Model:
22
+ def __init__(self, model_path, config_path, style_vec_path, device):
23
+ self.model_path = model_path
24
+ self.config_path = config_path
25
+ self.device = device
26
+ self.style_vec_path = style_vec_path
27
+ self.load()
28
+
29
+ def load(self):
30
+ self.hps = utils.get_hparams_from_file(self.config_path)
31
+ self.spk2id = self.hps.data.spk2id
32
+ self.num_styles = self.hps.data.num_styles
33
+ if hasattr(self.hps.data, "style2id"):
34
+ self.style2id = self.hps.data.style2id
35
+ else:
36
+ self.style2id = {str(i): i for i in range(self.num_styles)}
37
+
38
+ self.style_vectors = np.load(self.style_vec_path)
39
+ self.net_g = None
40
+
41
+ def load_net_g(self):
42
+ self.net_g = get_net_g(
43
+ model_path=self.model_path,
44
+ version=self.hps.version,
45
+ device=self.device,
46
+ hps=self.hps,
47
+ )
48
+
49
+ def get_style_vector(self, style_id, weight=1.0):
50
+ mean = self.style_vectors[0]
51
+ style_vec = self.style_vectors[style_id]
52
+ style_vec = mean + (style_vec - mean) * weight
53
+ return style_vec
54
+
55
+ def get_style_vector_from_audio(self, audio_path, weight=1.0):
56
+ from style_gen import extract_style_vector
57
+
58
+ xvec = extract_style_vector(audio_path)
59
+ mean = self.style_vectors[0]
60
+ xvec = mean + (xvec - mean) * weight
61
+ return xvec
62
+
63
+ def infer(
64
+ self,
65
+ text,
66
+ language="JP",
67
+ sid=0,
68
+ reference_audio_path=None,
69
+ sdp_ratio=0.2,
70
+ noise=0.6,
71
+ noisew=0.8,
72
+ length=1.0,
73
+ line_split=True,
74
+ split_interval=0.2,
75
+ style_text="",
76
+ style_weight=0.7,
77
+ use_style_text=False,
78
+ style="0",
79
+ emotion_weight=1.0,
80
+ ):
81
+ if reference_audio_path == "":
82
+ reference_audio_path = None
83
+ if style_text == "" or not use_style_text:
84
+ style_text = None
85
+
86
+ if self.net_g is None:
87
+ self.load_net_g()
88
+ if reference_audio_path is None:
89
+ style_id = self.style2id[style]
90
+ style_vector = self.get_style_vector(style_id, emotion_weight)
91
+ else:
92
+ style_vector = self.get_style_vector_from_audio(
93
+ reference_audio_path, emotion_weight
94
+ )
95
+ if not line_split:
96
+ with torch.no_grad():
97
+ audio = infer(
98
+ text=text,
99
+ sdp_ratio=sdp_ratio,
100
+ noise_scale=noise,
101
+ noise_scale_w=noisew,
102
+ length_scale=length,
103
+ sid=sid,
104
+ language=language,
105
+ hps=self.hps,
106
+ net_g=self.net_g,
107
+ device=self.device,
108
+ style_text=style_text,
109
+ style_weight=style_weight,
110
+ style_vec=style_vector,
111
+ )
112
+ else:
113
+ texts = text.split("\n")
114
+ texts = [t for t in texts if t != ""]
115
+ audios = []
116
+ with torch.no_grad():
117
+ for i, t in enumerate(texts):
118
+ audios.append(
119
+ infer(
120
+ text=t,
121
+ sdp_ratio=sdp_ratio,
122
+ noise_scale=noise,
123
+ noise_scale_w=noisew,
124
+ length_scale=length,
125
+ sid=sid,
126
+ language=language,
127
+ hps=self.hps,
128
+ net_g=self.net_g,
129
+ device=self.device,
130
+ style_text=style_text,
131
+ style_weight=style_weight,
132
+ style_vec=style_vector,
133
+ )
134
+ )
135
+ if i != len(texts) - 1:
136
+ audios.append(np.zeros(int(44100 * split_interval)))
137
+ audio = np.concatenate(audios)
138
+ with warnings.catch_warnings():
139
+ warnings.simplefilter("ignore")
140
+ audio = convert_to_16_bit_wav(audio)
141
+ return (self.hps.data.sampling_rate, audio)
142
+
143
+
144
+ class ModelHolder:
145
+ def __init__(self, root_dir, device):
146
+ self.root_dir = root_dir
147
+ self.device = device
148
+ self.model_files_dict = {}
149
+ self.current_model = None
150
+ self.model_names = []
151
+ self.models = []
152
+ self.refresh()
153
+
154
+ def refresh(self):
155
+ self.model_files_dict = {}
156
+ self.model_names = []
157
+ self.current_model = None
158
+ model_dirs = [
159
+ d
160
+ for d in os.listdir(self.root_dir)
161
+ if os.path.isdir(os.path.join(self.root_dir, d))
162
+ ]
163
+ for model_name in model_dirs:
164
+ model_dir = os.path.join(self.root_dir, model_name)
165
+ model_files = [
166
+ os.path.join(model_dir, f)
167
+ for f in os.listdir(model_dir)
168
+ if f.endswith(".pth") or f.endswith(".pt") or f.endswith(".safetensors")
169
+ ]
170
+ if len(model_files) == 0:
171
+ logger.info(
172
+ f"No model files found in {self.root_dir}/{model_name}, so skip it"
173
+ )
174
+ self.model_files_dict[model_name] = model_files
175
+ self.model_names.append(model_name)
176
+
177
+ def load_model(self, model_name, model_path):
178
+ if model_name not in self.model_files_dict:
179
+ raise Exception(f"モデル名{model_name}は存在しません")
180
+ if model_path not in self.model_files_dict[model_name]:
181
+ raise Exception(f"pthファイル{model_path}は存在しません")
182
+ self.current_model = Model(
183
+ model_path=model_path,
184
+ config_path=os.path.join(self.root_dir, model_name, "config.json"),
185
+ style_vec_path=os.path.join(self.root_dir, model_name, "style_vectors.npy"),
186
+ device=self.device,
187
+ )
188
+ styles = list(self.current_model.style2id.keys())
189
+ return (
190
+ gr.Dropdown(choices=styles, value=styles[0]),
191
+ gr.update(interactive=True, value="音声合成"),
192
+ )
193
+
194
+ def update_model_files_dropdown(self, model_name):
195
+ model_files = self.model_files_dict[model_name]
196
+ return gr.Dropdown(choices=model_files, value=model_files[0])
197
+
198
+ def update_model_names_dropdown(self):
199
+ self.refresh()
200
+ initial_model_name = self.model_names[0]
201
+ initial_model_files = self.model_files_dict[initial_model_name]
202
+ return (
203
+ gr.Dropdown(choices=self.model_names, value=initial_model_name),
204
+ gr.Dropdown(choices=initial_model_files, value=initial_model_files[0]),
205
+ gr.update(interactive=False), # For tts_button
206
+ )
207
+
208
+
209
+ def tts_fn(
210
+ text,
211
+ language,
212
+ reference_audio_path,
213
+ sdp_ratio,
214
+ noise_scale,
215
+ noise_scale_w,
216
+ length_scale,
217
+ line_split,
218
+ split_interval,
219
+ style_text,
220
+ style_weight,
221
+ use_style_text,
222
+ emotion,
223
+ emotion_weight,
224
+ ):
225
+ if is_hf_spaces and len(text) > limit:
226
+ raise Exception(f"文字数が{limit}文字を超えています")
227
+
228
+ assert model_holder.current_model is not None
229
+
230
+ start_time = datetime.datetime.now()
231
+
232
+ sr, audio = model_holder.current_model.infer(
233
+ text=text,
234
+ language=language,
235
+ reference_audio_path=reference_audio_path,
236
+ sdp_ratio=sdp_ratio,
237
+ noise=noise_scale,
238
+ noisew=noise_scale_w,
239
+ length=length_scale,
240
+ line_split=line_split,
241
+ split_interval=split_interval,
242
+ style_text=style_text,
243
+ style_weight=style_weight,
244
+ use_style_text=use_style_text,
245
+ style=emotion,
246
+ emotion_weight=emotion_weight,
247
+ )
248
+
249
+ end_time = datetime.datetime.now()
250
+ duration = (end_time - start_time).total_seconds()
251
+ return f"Success, time: {duration} seconds.", (sr, audio)
252
+
253
+
254
+ initial_text = "こんにちは、初めまして。あなたの名前はなんていうの?"
255
+
256
+ example_local = [
257
+ [initial_text, "JP"],
258
+ [
259
+ """あなたがそんなこと言うなんて、私はとっても嬉しい。
260
+ あなたがそんなこと言うなんて、私はとっても怒ってる。
261
+ あなたがそんなこと言うなんて、私はとっても驚いてる。
262
+ あなたがそんなこと言うなんて、私はとっても辛い。""",
263
+ "JP",
264
+ ],
265
+ [ # ChatGPTに考えてもらった告白セリフ
266
+ """私、ずっと前からあなたのことを見てきました。あなたの笑顔、優しさ、強さに、心惹かれていたんです。
267
+ 友達として過ごす中で、あなたのことがだんだんと特別な存在になっていくのがわかりました。
268
+ えっと、私、あなたのことが好きです!もしよければ、私と付き合ってくれませんか?""",
269
+ "JP",
270
+ ],
271
+ [ # 夏目漱石『吾輩は猫である』
272
+ """吾輩は猫である。名前はまだ無い。
273
+ どこで生れたかとんと見当がつかぬ。なんでも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。
274
+ 吾輩はここで始めて人間というものを見た。しかもあとで聞くと、それは書生という、人間中で一番獰悪な種族であったそうだ。
275
+ この書生というのは時々我々を捕まえて煮て食うという話である。""",
276
+ "JP",
277
+ ],
278
+ [ # 梶井基次郎『桜の樹の下には』
279
+ """桜の樹の下には屍体が埋まっている!これは信じていいことなんだよ。
280
+ 何故って、桜の花があんなにも見事に咲くなんて信じられないことじゃないか。俺はあの美しさが信じられないので、このにさんにち不安だった。
281
+ しかしいま、やっとわかるときが来た。桜の樹の下には屍体が埋まっている。これは信じていいことだ。""",
282
+ "JP",
283
+ ],
284
+ [ # ChatGPTと考えた、感情を表すセリフ
285
+ """やったー!テストで満点取れた!私とっても嬉しいな!
286
+ どうして私の意見を無視するの?許せない!ムカつく!あんたなんか死ねばいいのに。
287
+ あはははっ!この漫画めっちゃ笑える、見てよこれ、ふふふ、あはは。
288
+ あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しい。""",
289
+ "JP",
290
+ ],
291
+ [ # 上の丁寧語バージョン
292
+ """やりました!テストで満点取れましたよ!私とっても嬉しいです!
293
+ どうして私の意見を無視するんですか?許せません!ムカつきます!あんたなんか死んでください。
294
+ あはははっ!この漫画めっちゃ笑えます、見てくださいこれ、ふふふ、あはは。
295
+ あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しいです。""",
296
+ "JP",
297
+ ],
298
+ [ # ChatGPTに考えてもらった音声合成の説明文章
299
+ """音声合成は、機械学習を活用して、テキストから人の声を再現する技術です。この技術は、言語の構造を解析し、それに基づいて音声を生成します。
300
+ この分野の最新の研究成果を使うと、より自然で表現豊かな音声の生成が可能である。深層学習の応用により、感情やアクセントを含む声質の微妙な変化も再現することが出来る。""",
301
+ "JP",
302
+ ],
303
+ [
304
+ "Speech synthesis is the artificial production of human speech. A computer system used for this purpose is called a speech synthesizer, and can be implemented in software or hardware products.",
305
+ "EN",
306
+ ],
307
+ ["语音合成是人工制造人类语音。用于此目的的计算机系统称为语音合成器,可以通过软件或硬件产品实现。", "ZH"],
308
+ ]
309
+
310
+ example_hf_spaces = [
311
+ [initial_text, "JP"],
312
+ ["えっと、私、あなたのことが好きです!もしよければ付き合ってくれませんか?", "JP"],
313
+ ["吾輩は猫である。名前はまだ無い。", "JP"],
314
+ ["どこで生れたかとんと見当がつかぬ。なんでも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。", "JP"],
315
+ ["やったー!テストで満点取れたよ!私とっても嬉しいな!", "JP"],
316
+ ["どうして私の意見を無視するの?許せない!ムカつく!あんたなんか死ねばいいのに。", "JP"],
317
+ ["あはははっ!この漫画めっちゃ笑える、見てよこれ、ふふふ、あはは。", "JP"],
318
+ ["あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しい。", "JP"],
319
+ ["深層学習の応用により、感情やアクセントを含む声質の微妙な変化も再現されている。", "JP"],
320
+ ]
321
+
322
+ initial_md = """
323
+ # Style-Bert-VITS2 音声合成
324
+
325
+ 注意: 初期からある[jvnvのモデル](https://huggingface.co/litagin/style_bert_vits2_jvnv)は、[JVNVコーパス(言語音声と非言語音声を持つ日本語感情音声コーパス)](https://sites.google.com/site/shinnosuketakamichi/research-topics/jvnv_corpus)で学習されたモデルです。ライセンスは[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.ja)です。
326
+ """
327
+
328
+ how_to_md = """
329
+ 下のように`model_assets`ディレクトリの中にモデルファイルたちを置いてください。
330
+ ```
331
+ model_assets
332
+ ├── your_model
333
+ │ ├── config.json
334
+ │ ├── your_model_file1.safetensors
335
+ │ ├── your_model_file2.safetensors
336
+ │ ├── ...
337
+ │ └── style_vectors.npy
338
+ └── another_model
339
+ ├── ...
340
+ ```
341
+ 各モデルにはファイルたちが必要です:
342
+ - `config.json`:学習時の設定ファイル
343
+ - `*.safetensors`:学習済みモデルファイル(1つ以上が必要、複数可)
344
+ - `style_vectors.npy`:スタイルベクトルファイル
345
+
346
+ 上2つは`Train.bat`による学習で自動的に正しい位置に保存されます。`style_vectors.npy`は`Style.bat`を実行して指示に従って生成してください。
347
+
348
+ TODO: 現在のところはspeaker_id = 0に固定しており複数話者の合成には対応していません。
349
+ """
350
+
351
+ style_md = """
352
+ - プリセットまたは音声ファイルから読み上げの声音・感情・スタイルのようなものを制御できます。
353
+ - デフォルトのNeutralでも、十分に読み上げる文に応じた感情で感���豊かに読み上げられます。このスタイル制御は、それを重み付きで上書きするような感じです。
354
+ - 強さを大きくしすぎると発音が変になったり声にならなかったりと崩壊することがあります。
355
+ - どのくらいに強さがいいかはモデルやスタイルによって異なるようです。
356
+ - 音声ファイルを入力する場合は、学習データと似た声音の話者(特に同じ性別)でないとよい効果が出ないかもしれません。
357
+ """
358
+
359
+
360
+ def make_interactive():
361
+ return gr.update(interactive=True, value="音声合成")
362
+
363
+
364
+ def make_non_interactive():
365
+ return gr.update(interactive=False, value="音声合成(モデルをロードしてください)")
366
+
367
+
368
+ def gr_util(item):
369
+ if item == "プリセットから選ぶ":
370
+ return (gr.update(visible=True), gr.Audio(visible=False, value=None))
371
+ else:
372
+ return (gr.update(visible=False), gr.update(visible=True))
373
+
374
+
375
+ if __name__ == "__main__":
376
+ parser = argparse.ArgumentParser()
377
+ parser.add_argument("--cpu", action="store_true", help="Use CPU instead of GPU")
378
+ parser.add_argument(
379
+ "--dir", "-d", type=str, help="Model directory", default=config.out_dir
380
+ )
381
+ args = parser.parse_args()
382
+ model_dir = args.dir
383
+
384
+ if args.cpu:
385
+ device = "cpu"
386
+ else:
387
+ device = "cuda" if torch.cuda.is_available() else "cpu"
388
+
389
+ model_holder = ModelHolder(model_dir, device)
390
+
391
+ languages = ["JP", "EN", "ZH"]
392
+ examples = example_hf_spaces if is_hf_spaces else example_local
393
+
394
+ model_names = model_holder.model_names
395
+ if len(model_names) == 0:
396
+ logger.error(f"モデルが見つかりませんでした。{model_dir}にモデルを置いてください。")
397
+ sys.exit(1)
398
+ initial_id = 1 if is_hf_spaces else 0
399
+ initial_pth_files = model_holder.model_files_dict[model_names[initial_id]]
400
+
401
+ with gr.Blocks(theme="NoCrypt/miku") as app:
402
+ gr.Markdown(initial_md)
403
+ with gr.Accordion(label="使い方", open=False):
404
+ gr.Markdown(how_to_md)
405
+ with gr.Row():
406
+ with gr.Column():
407
+ with gr.Row():
408
+ with gr.Column(scale=3):
409
+ model_name = gr.Dropdown(
410
+ label="モデル一覧",
411
+ choices=model_names,
412
+ value=model_names[initial_id],
413
+ )
414
+ model_path = gr.Dropdown(
415
+ label="モデルファイル",
416
+ choices=initial_pth_files,
417
+ value=initial_pth_files[0],
418
+ )
419
+ refresh_button = gr.Button("更新", scale=1, visible=not is_hf_spaces)
420
+ load_button = gr.Button("ロード", scale=1, variant="primary")
421
+ text_input = gr.TextArea(label="テキスト", value=initial_text)
422
+
423
+ line_split = gr.Checkbox(label="改行で分けて生成", value=True)
424
+ split_interval = gr.Slider(
425
+ minimum=0.0,
426
+ maximum=2,
427
+ value=0.5,
428
+ step=0.1,
429
+ label="分けた場合に挟む無音の長さ(秒)",
430
+ )
431
+ language = gr.Dropdown(choices=languages, value="JP", label="Language")
432
+ with gr.Accordion(label="詳細設定", open=False):
433
+ sdp_ratio = gr.Slider(
434
+ minimum=0, maximum=1, value=0.2, step=0.1, label="SDP Ratio"
435
+ )
436
+ noise_scale = gr.Slider(
437
+ minimum=0.1, maximum=2, value=0.6, step=0.1, label="Noise"
438
+ )
439
+ noise_scale_w = gr.Slider(
440
+ minimum=0.1, maximum=2, value=0.8, step=0.1, label="Noise_W"
441
+ )
442
+ length_scale = gr.Slider(
443
+ minimum=0.1, maximum=2, value=1.0, step=0.1, label="Length"
444
+ )
445
+ use_style_text = gr.Checkbox(label="Style textを使う", value=False)
446
+ style_text = gr.Textbox(
447
+ label="Style text",
448
+ placeholder="どうして私の意見を無視するの?許せない、ムカつく!死ねばいいのに。",
449
+ info="このテキストの読み上げと似た声音・感情になりやすくなります。ただ抑揚やテンポ等が犠牲になる傾向があります。",
450
+ visible=False,
451
+ )
452
+ style_text_weight = gr.Slider(
453
+ minimum=0,
454
+ maximum=1,
455
+ value=0.7,
456
+ step=0.1,
457
+ label="Style textの強さ",
458
+ visible=False,
459
+ )
460
+ use_style_text.change(
461
+ lambda x: (gr.Textbox(visible=x), gr.Slider(visible=x)),
462
+ inputs=[use_style_text],
463
+ outputs=[style_text, style_text_weight],
464
+ )
465
+ with gr.Column():
466
+ with gr.Accordion("スタイルについて詳細", open=False):
467
+ gr.Markdown(style_md)
468
+ style_mode = gr.Radio(
469
+ ["プリセットから選ぶ", "音声ファイルを入力"],
470
+ label="スタイルの指定方法",
471
+ value="プリセットから選ぶ",
472
+ )
473
+ style = gr.Dropdown(
474
+ label="スタイル(Neutralが平均スタイル)",
475
+ choices=["モデルをロードしてください"],
476
+ value="モデルをロードしてください",
477
+ )
478
+ style_weight = gr.Slider(
479
+ minimum=0,
480
+ maximum=50,
481
+ value=1,
482
+ step=0.1,
483
+ label="スタイルの強さ",
484
+ )
485
+ ref_audio_path = gr.Audio(label="参照音声", type="filepath", visible=False)
486
+ tts_button = gr.Button(
487
+ "音声合成(モデルをロードしてください)", variant="primary", interactive=False
488
+ )
489
+ text_output = gr.Textbox(label="情報")
490
+ audio_output = gr.Audio(label="結果")
491
+ with gr.Accordion("テキスト例", open=False):
492
+ gr.Examples(examples, inputs=[text_input, language])
493
+
494
+ tts_button.click(
495
+ tts_fn,
496
+ inputs=[
497
+ text_input,
498
+ language,
499
+ ref_audio_path,
500
+ sdp_ratio,
501
+ noise_scale,
502
+ noise_scale_w,
503
+ length_scale,
504
+ line_split,
505
+ split_interval,
506
+ style_text,
507
+ style_text_weight,
508
+ use_style_text,
509
+ style,
510
+ style_weight,
511
+ ],
512
+ outputs=[text_output, audio_output],
513
+ )
514
+
515
+ model_name.change(
516
+ model_holder.update_model_files_dropdown,
517
+ inputs=[model_name],
518
+ outputs=[model_path],
519
+ )
520
+
521
+ model_path.change(make_non_interactive, outputs=[tts_button])
522
+
523
+ refresh_button.click(
524
+ model_holder.update_model_names_dropdown,
525
+ outputs=[model_name, model_path, tts_button],
526
+ )
527
+
528
+ load_button.click(
529
+ model_holder.load_model,
530
+ inputs=[model_name, model_path],
531
+ outputs=[style, tts_button],
532
+ )
533
+
534
+ style_mode.change(
535
+ gr_util,
536
+ inputs=[style_mode],
537
+ outputs=[style, ref_audio_path],
538
+ )
539
+
540
+ app.launch(inbrowser=True)
attentions.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ import commons
7
+ from tools.log import logger as logging
8
+
9
+
10
+ class LayerNorm(nn.Module):
11
+ def __init__(self, channels, eps=1e-5):
12
+ super().__init__()
13
+ self.channels = channels
14
+ self.eps = eps
15
+
16
+ self.gamma = nn.Parameter(torch.ones(channels))
17
+ self.beta = nn.Parameter(torch.zeros(channels))
18
+
19
+ def forward(self, x):
20
+ x = x.transpose(1, -1)
21
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
22
+ return x.transpose(1, -1)
23
+
24
+
25
+ @torch.jit.script
26
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
27
+ n_channels_int = n_channels[0]
28
+ in_act = input_a + input_b
29
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
30
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
31
+ acts = t_act * s_act
32
+ return acts
33
+
34
+
35
+ class Encoder(nn.Module):
36
+ def __init__(
37
+ self,
38
+ hidden_channels,
39
+ filter_channels,
40
+ n_heads,
41
+ n_layers,
42
+ kernel_size=1,
43
+ p_dropout=0.0,
44
+ window_size=4,
45
+ isflow=True,
46
+ **kwargs
47
+ ):
48
+ super().__init__()
49
+ self.hidden_channels = hidden_channels
50
+ self.filter_channels = filter_channels
51
+ self.n_heads = n_heads
52
+ self.n_layers = n_layers
53
+ self.kernel_size = kernel_size
54
+ self.p_dropout = p_dropout
55
+ self.window_size = window_size
56
+ # if isflow:
57
+ # cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
58
+ # self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
59
+ # self.cond_layer = weight_norm(cond_layer, name='weight')
60
+ # self.gin_channels = 256
61
+ self.cond_layer_idx = self.n_layers
62
+ if "gin_channels" in kwargs:
63
+ self.gin_channels = kwargs["gin_channels"]
64
+ if self.gin_channels != 0:
65
+ self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
66
+ # vits2 says 3rd block, so idx is 2 by default
67
+ self.cond_layer_idx = (
68
+ kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
69
+ )
70
+ # logging.debug(self.gin_channels, self.cond_layer_idx)
71
+ assert (
72
+ self.cond_layer_idx < self.n_layers
73
+ ), "cond_layer_idx should be less than n_layers"
74
+ self.drop = nn.Dropout(p_dropout)
75
+ self.attn_layers = nn.ModuleList()
76
+ self.norm_layers_1 = nn.ModuleList()
77
+ self.ffn_layers = nn.ModuleList()
78
+ self.norm_layers_2 = nn.ModuleList()
79
+ for i in range(self.n_layers):
80
+ self.attn_layers.append(
81
+ MultiHeadAttention(
82
+ hidden_channels,
83
+ hidden_channels,
84
+ n_heads,
85
+ p_dropout=p_dropout,
86
+ window_size=window_size,
87
+ )
88
+ )
89
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
90
+ self.ffn_layers.append(
91
+ FFN(
92
+ hidden_channels,
93
+ hidden_channels,
94
+ filter_channels,
95
+ kernel_size,
96
+ p_dropout=p_dropout,
97
+ )
98
+ )
99
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
100
+
101
+ def forward(self, x, x_mask, g=None):
102
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
103
+ x = x * x_mask
104
+ for i in range(self.n_layers):
105
+ if i == self.cond_layer_idx and g is not None:
106
+ g = self.spk_emb_linear(g.transpose(1, 2))
107
+ g = g.transpose(1, 2)
108
+ x = x + g
109
+ x = x * x_mask
110
+ y = self.attn_layers[i](x, x, attn_mask)
111
+ y = self.drop(y)
112
+ x = self.norm_layers_1[i](x + y)
113
+
114
+ y = self.ffn_layers[i](x, x_mask)
115
+ y = self.drop(y)
116
+ x = self.norm_layers_2[i](x + y)
117
+ x = x * x_mask
118
+ return x
119
+
120
+
121
+ class Decoder(nn.Module):
122
+ def __init__(
123
+ self,
124
+ hidden_channels,
125
+ filter_channels,
126
+ n_heads,
127
+ n_layers,
128
+ kernel_size=1,
129
+ p_dropout=0.0,
130
+ proximal_bias=False,
131
+ proximal_init=True,
132
+ **kwargs
133
+ ):
134
+ super().__init__()
135
+ self.hidden_channels = hidden_channels
136
+ self.filter_channels = filter_channels
137
+ self.n_heads = n_heads
138
+ self.n_layers = n_layers
139
+ self.kernel_size = kernel_size
140
+ self.p_dropout = p_dropout
141
+ self.proximal_bias = proximal_bias
142
+ self.proximal_init = proximal_init
143
+
144
+ self.drop = nn.Dropout(p_dropout)
145
+ self.self_attn_layers = nn.ModuleList()
146
+ self.norm_layers_0 = nn.ModuleList()
147
+ self.encdec_attn_layers = nn.ModuleList()
148
+ self.norm_layers_1 = nn.ModuleList()
149
+ self.ffn_layers = nn.ModuleList()
150
+ self.norm_layers_2 = nn.ModuleList()
151
+ for i in range(self.n_layers):
152
+ self.self_attn_layers.append(
153
+ MultiHeadAttention(
154
+ hidden_channels,
155
+ hidden_channels,
156
+ n_heads,
157
+ p_dropout=p_dropout,
158
+ proximal_bias=proximal_bias,
159
+ proximal_init=proximal_init,
160
+ )
161
+ )
162
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
163
+ self.encdec_attn_layers.append(
164
+ MultiHeadAttention(
165
+ hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
166
+ )
167
+ )
168
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
169
+ self.ffn_layers.append(
170
+ FFN(
171
+ hidden_channels,
172
+ hidden_channels,
173
+ filter_channels,
174
+ kernel_size,
175
+ p_dropout=p_dropout,
176
+ causal=True,
177
+ )
178
+ )
179
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
180
+
181
+ def forward(self, x, x_mask, h, h_mask):
182
+ """
183
+ x: decoder input
184
+ h: encoder output
185
+ """
186
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
187
+ device=x.device, dtype=x.dtype
188
+ )
189
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
190
+ x = x * x_mask
191
+ for i in range(self.n_layers):
192
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
193
+ y = self.drop(y)
194
+ x = self.norm_layers_0[i](x + y)
195
+
196
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
197
+ y = self.drop(y)
198
+ x = self.norm_layers_1[i](x + y)
199
+
200
+ y = self.ffn_layers[i](x, x_mask)
201
+ y = self.drop(y)
202
+ x = self.norm_layers_2[i](x + y)
203
+ x = x * x_mask
204
+ return x
205
+
206
+
207
+ class MultiHeadAttention(nn.Module):
208
+ def __init__(
209
+ self,
210
+ channels,
211
+ out_channels,
212
+ n_heads,
213
+ p_dropout=0.0,
214
+ window_size=None,
215
+ heads_share=True,
216
+ block_length=None,
217
+ proximal_bias=False,
218
+ proximal_init=False,
219
+ ):
220
+ super().__init__()
221
+ assert channels % n_heads == 0
222
+
223
+ self.channels = channels
224
+ self.out_channels = out_channels
225
+ self.n_heads = n_heads
226
+ self.p_dropout = p_dropout
227
+ self.window_size = window_size
228
+ self.heads_share = heads_share
229
+ self.block_length = block_length
230
+ self.proximal_bias = proximal_bias
231
+ self.proximal_init = proximal_init
232
+ self.attn = None
233
+
234
+ self.k_channels = channels // n_heads
235
+ self.conv_q = nn.Conv1d(channels, channels, 1)
236
+ self.conv_k = nn.Conv1d(channels, channels, 1)
237
+ self.conv_v = nn.Conv1d(channels, channels, 1)
238
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
239
+ self.drop = nn.Dropout(p_dropout)
240
+
241
+ if window_size is not None:
242
+ n_heads_rel = 1 if heads_share else n_heads
243
+ rel_stddev = self.k_channels**-0.5
244
+ self.emb_rel_k = nn.Parameter(
245
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
246
+ * rel_stddev
247
+ )
248
+ self.emb_rel_v = nn.Parameter(
249
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
250
+ * rel_stddev
251
+ )
252
+
253
+ nn.init.xavier_uniform_(self.conv_q.weight)
254
+ nn.init.xavier_uniform_(self.conv_k.weight)
255
+ nn.init.xavier_uniform_(self.conv_v.weight)
256
+ if proximal_init:
257
+ with torch.no_grad():
258
+ self.conv_k.weight.copy_(self.conv_q.weight)
259
+ self.conv_k.bias.copy_(self.conv_q.bias)
260
+
261
+ def forward(self, x, c, attn_mask=None):
262
+ q = self.conv_q(x)
263
+ k = self.conv_k(c)
264
+ v = self.conv_v(c)
265
+
266
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
267
+
268
+ x = self.conv_o(x)
269
+ return x
270
+
271
+ def attention(self, query, key, value, mask=None):
272
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
273
+ b, d, t_s, t_t = (*key.size(), query.size(2))
274
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
275
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
276
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
277
+
278
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
279
+ if self.window_size is not None:
280
+ assert (
281
+ t_s == t_t
282
+ ), "Relative attention is only available for self-attention."
283
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
284
+ rel_logits = self._matmul_with_relative_keys(
285
+ query / math.sqrt(self.k_channels), key_relative_embeddings
286
+ )
287
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
288
+ scores = scores + scores_local
289
+ if self.proximal_bias:
290
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
291
+ scores = scores + self._attention_bias_proximal(t_s).to(
292
+ device=scores.device, dtype=scores.dtype
293
+ )
294
+ if mask is not None:
295
+ scores = scores.masked_fill(mask == 0, -1e4)
296
+ if self.block_length is not None:
297
+ assert (
298
+ t_s == t_t
299
+ ), "Local attention is only available for self-attention."
300
+ block_mask = (
301
+ torch.ones_like(scores)
302
+ .triu(-self.block_length)
303
+ .tril(self.block_length)
304
+ )
305
+ scores = scores.masked_fill(block_mask == 0, -1e4)
306
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
307
+ p_attn = self.drop(p_attn)
308
+ output = torch.matmul(p_attn, value)
309
+ if self.window_size is not None:
310
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
311
+ value_relative_embeddings = self._get_relative_embeddings(
312
+ self.emb_rel_v, t_s
313
+ )
314
+ output = output + self._matmul_with_relative_values(
315
+ relative_weights, value_relative_embeddings
316
+ )
317
+ output = (
318
+ output.transpose(2, 3).contiguous().view(b, d, t_t)
319
+ ) # [b, n_h, t_t, d_k] -> [b, d, t_t]
320
+ return output, p_attn
321
+
322
+ def _matmul_with_relative_values(self, x, y):
323
+ """
324
+ x: [b, h, l, m]
325
+ y: [h or 1, m, d]
326
+ ret: [b, h, l, d]
327
+ """
328
+ ret = torch.matmul(x, y.unsqueeze(0))
329
+ return ret
330
+
331
+ def _matmul_with_relative_keys(self, x, y):
332
+ """
333
+ x: [b, h, l, d]
334
+ y: [h or 1, m, d]
335
+ ret: [b, h, l, m]
336
+ """
337
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
338
+ return ret
339
+
340
+ def _get_relative_embeddings(self, relative_embeddings, length):
341
+ 2 * self.window_size + 1
342
+ # Pad first before slice to avoid using cond ops.
343
+ pad_length = max(length - (self.window_size + 1), 0)
344
+ slice_start_position = max((self.window_size + 1) - length, 0)
345
+ slice_end_position = slice_start_position + 2 * length - 1
346
+ if pad_length > 0:
347
+ padded_relative_embeddings = F.pad(
348
+ relative_embeddings,
349
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
350
+ )
351
+ else:
352
+ padded_relative_embeddings = relative_embeddings
353
+ used_relative_embeddings = padded_relative_embeddings[
354
+ :, slice_start_position:slice_end_position
355
+ ]
356
+ return used_relative_embeddings
357
+
358
+ def _relative_position_to_absolute_position(self, x):
359
+ """
360
+ x: [b, h, l, 2*l-1]
361
+ ret: [b, h, l, l]
362
+ """
363
+ batch, heads, length, _ = x.size()
364
+ # Concat columns of pad to shift from relative to absolute indexing.
365
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
366
+
367
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
368
+ x_flat = x.view([batch, heads, length * 2 * length])
369
+ x_flat = F.pad(
370
+ x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
371
+ )
372
+
373
+ # Reshape and slice out the padded elements.
374
+ x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
375
+ :, :, :length, length - 1 :
376
+ ]
377
+ return x_final
378
+
379
+ def _absolute_position_to_relative_position(self, x):
380
+ """
381
+ x: [b, h, l, l]
382
+ ret: [b, h, l, 2*l-1]
383
+ """
384
+ batch, heads, length, _ = x.size()
385
+ # pad along column
386
+ x = F.pad(
387
+ x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
388
+ )
389
+ x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
390
+ # add 0's in the beginning that will skew the elements after reshape
391
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
392
+ x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
393
+ return x_final
394
+
395
+ def _attention_bias_proximal(self, length):
396
+ """Bias for self-attention to encourage attention to close positions.
397
+ Args:
398
+ length: an integer scalar.
399
+ Returns:
400
+ a Tensor with shape [1, 1, length, length]
401
+ """
402
+ r = torch.arange(length, dtype=torch.float32)
403
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
404
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
405
+
406
+
407
+ class FFN(nn.Module):
408
+ def __init__(
409
+ self,
410
+ in_channels,
411
+ out_channels,
412
+ filter_channels,
413
+ kernel_size,
414
+ p_dropout=0.0,
415
+ activation=None,
416
+ causal=False,
417
+ ):
418
+ super().__init__()
419
+ self.in_channels = in_channels
420
+ self.out_channels = out_channels
421
+ self.filter_channels = filter_channels
422
+ self.kernel_size = kernel_size
423
+ self.p_dropout = p_dropout
424
+ self.activation = activation
425
+ self.causal = causal
426
+
427
+ if causal:
428
+ self.padding = self._causal_padding
429
+ else:
430
+ self.padding = self._same_padding
431
+
432
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
433
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
434
+ self.drop = nn.Dropout(p_dropout)
435
+
436
+ def forward(self, x, x_mask):
437
+ x = self.conv_1(self.padding(x * x_mask))
438
+ if self.activation == "gelu":
439
+ x = x * torch.sigmoid(1.702 * x)
440
+ else:
441
+ x = torch.relu(x)
442
+ x = self.drop(x)
443
+ x = self.conv_2(self.padding(x * x_mask))
444
+ return x * x_mask
445
+
446
+ def _causal_padding(self, x):
447
+ if self.kernel_size == 1:
448
+ return x
449
+ pad_l = self.kernel_size - 1
450
+ pad_r = 0
451
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
452
+ x = F.pad(x, commons.convert_pad_shape(padding))
453
+ return x
454
+
455
+ def _same_padding(self, x):
456
+ if self.kernel_size == 1:
457
+ return x
458
+ pad_l = (self.kernel_size - 1) // 2
459
+ pad_r = self.kernel_size // 2
460
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
461
+ x = F.pad(x, commons.convert_pad_shape(padding))
462
+ return x
bert/bert_models.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "deberta-v2-large-japanese-char-wwm": {
3
+ "repo_id": "ku-nlp/deberta-v2-large-japanese-char-wwm",
4
+ "files": ["pytorch_model.bin"]
5
+ },
6
+ "chinese-roberta-wwm-ext-large": {
7
+ "repo_id": "hfl/chinese-roberta-wwm-ext-large",
8
+ "files": ["pytorch_model.bin"]
9
+ },
10
+ "deberta-v3-large": {
11
+ "repo_id": "microsoft/deberta-v3-large",
12
+ "files": ["spm.model", "pytorch_model.bin"]
13
+ }
14
+ }
bert/chinese-roberta-wwm-ext-large/.gitattributes ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
2
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.h5 filter=lfs diff=lfs merge=lfs -text
5
+ *.tflite filter=lfs diff=lfs merge=lfs -text
6
+ *.tar.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.ot filter=lfs diff=lfs merge=lfs -text
8
+ *.onnx filter=lfs diff=lfs merge=lfs -text
9
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
bert/chinese-roberta-wwm-ext-large/README.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - zh
4
+ tags:
5
+ - bert
6
+ license: "apache-2.0"
7
+ ---
8
+
9
+ # Please use 'Bert' related functions to load this model!
10
+
11
+ ## Chinese BERT with Whole Word Masking
12
+ For further accelerating Chinese natural language processing, we provide **Chinese pre-trained BERT with Whole Word Masking**.
13
+
14
+ **[Pre-Training with Whole Word Masking for Chinese BERT](https://arxiv.org/abs/1906.08101)**
15
+ Yiming Cui, Wanxiang Che, Ting Liu, Bing Qin, Ziqing Yang, Shijin Wang, Guoping Hu
16
+
17
+ This repository is developed based on:https://github.com/google-research/bert
18
+
19
+ You may also interested in,
20
+ - Chinese BERT series: https://github.com/ymcui/Chinese-BERT-wwm
21
+ - Chinese MacBERT: https://github.com/ymcui/MacBERT
22
+ - Chinese ELECTRA: https://github.com/ymcui/Chinese-ELECTRA
23
+ - Chinese XLNet: https://github.com/ymcui/Chinese-XLNet
24
+ - Knowledge Distillation Toolkit - TextBrewer: https://github.com/airaria/TextBrewer
25
+
26
+ More resources by HFL: https://github.com/ymcui/HFL-Anthology
27
+
28
+ ## Citation
29
+ If you find the technical report or resource is useful, please cite the following technical report in your paper.
30
+ - Primary: https://arxiv.org/abs/2004.13922
31
+ ```
32
+ @inproceedings{cui-etal-2020-revisiting,
33
+ title = "Revisiting Pre-Trained Models for {C}hinese Natural Language Processing",
34
+ author = "Cui, Yiming and
35
+ Che, Wanxiang and
36
+ Liu, Ting and
37
+ Qin, Bing and
38
+ Wang, Shijin and
39
+ Hu, Guoping",
40
+ booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings",
41
+ month = nov,
42
+ year = "2020",
43
+ address = "Online",
44
+ publisher = "Association for Computational Linguistics",
45
+ url = "https://www.aclweb.org/anthology/2020.findings-emnlp.58",
46
+ pages = "657--668",
47
+ }
48
+ ```
49
+ - Secondary: https://arxiv.org/abs/1906.08101
50
+ ```
51
+ @article{chinese-bert-wwm,
52
+ title={Pre-Training with Whole Word Masking for Chinese BERT},
53
+ author={Cui, Yiming and Che, Wanxiang and Liu, Ting and Qin, Bing and Yang, Ziqing and Wang, Shijin and Hu, Guoping},
54
+ journal={arXiv preprint arXiv:1906.08101},
55
+ year={2019}
56
+ }
57
+ ```
bert/chinese-roberta-wwm-ext-large/added_tokens.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
bert/chinese-roberta-wwm-ext-large/config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForMaskedLM"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "bos_token_id": 0,
7
+ "directionality": "bidi",
8
+ "eos_token_id": 2,
9
+ "hidden_act": "gelu",
10
+ "hidden_dropout_prob": 0.1,
11
+ "hidden_size": 1024,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 4096,
14
+ "layer_norm_eps": 1e-12,
15
+ "max_position_embeddings": 512,
16
+ "model_type": "bert",
17
+ "num_attention_heads": 16,
18
+ "num_hidden_layers": 24,
19
+ "output_past": true,
20
+ "pad_token_id": 0,
21
+ "pooler_fc_size": 768,
22
+ "pooler_num_attention_heads": 12,
23
+ "pooler_num_fc_layers": 3,
24
+ "pooler_size_per_head": 128,
25
+ "pooler_type": "first_token_transform",
26
+ "type_vocab_size": 2,
27
+ "vocab_size": 21128
28
+ }
bert/chinese-roberta-wwm-ext-large/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ac62d49144d770c5ca9a5d1d3039c4995665a080febe63198189857c6bd11cd
3
+ size 1306484351
bert/chinese-roberta-wwm-ext-large/special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}
bert/chinese-roberta-wwm-ext-large/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
bert/chinese-roberta-wwm-ext-large/tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"init_inputs": []}
bert/chinese-roberta-wwm-ext-large/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
bert/deberta-v2-large-japanese-char-wwm/.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
bert/deberta-v2-large-japanese-char-wwm/README.md ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: ja
3
+ license: cc-by-sa-4.0
4
+ library_name: transformers
5
+ tags:
6
+ - deberta
7
+ - deberta-v2
8
+ - fill-mask
9
+ - character
10
+ - wwm
11
+ datasets:
12
+ - wikipedia
13
+ - cc100
14
+ - oscar
15
+ metrics:
16
+ - accuracy
17
+ mask_token: "[MASK]"
18
+ widget:
19
+ - text: "京都大学で自然言語処理を[MASK][MASK]する。"
20
+ ---
21
+
22
+ # Model Card for Japanese character-level DeBERTa V2 large
23
+
24
+ ## Model description
25
+
26
+ This is a Japanese DeBERTa V2 large model pre-trained on Japanese Wikipedia, the Japanese portion of CC-100, and the Japanese portion of OSCAR.
27
+ This model is trained with character-level tokenization and whole word masking.
28
+
29
+ ## How to use
30
+
31
+ You can use this model for masked language modeling as follows:
32
+
33
+ ```python
34
+ from transformers import AutoTokenizer, AutoModelForMaskedLM
35
+ tokenizer = AutoTokenizer.from_pretrained('ku-nlp/deberta-v2-large-japanese-char-wwm')
36
+ model = AutoModelForMaskedLM.from_pretrained('ku-nlp/deberta-v2-large-japanese-char-wwm')
37
+
38
+ sentence = '京都大学で自然言語処理を[MASK][MASK]する。'
39
+ encoding = tokenizer(sentence, return_tensors='pt')
40
+ ...
41
+ ```
42
+
43
+ You can also fine-tune this model on downstream tasks.
44
+
45
+ ## Tokenization
46
+
47
+ There is no need to tokenize texts in advance, and you can give raw texts to the tokenizer.
48
+ The texts are tokenized into character-level tokens by [sentencepiece](https://github.com/google/sentencepiece).
49
+
50
+ ## Training data
51
+
52
+ We used the following corpora for pre-training:
53
+
54
+ - Japanese Wikipedia (as of 20221020, 3.2GB, 27M sentences, 1.3M documents)
55
+ - Japanese portion of CC-100 (85GB, 619M sentences, 66M documents)
56
+ - Japanese portion of OSCAR (54GB, 326M sentences, 25M documents)
57
+
58
+ Note that we filtered out documents annotated with "header", "footer", or "noisy" tags in OSCAR.
59
+ Also note that Japanese Wikipedia was duplicated 10 times to make the total size of the corpus comparable to that of CC-100 and OSCAR. As a result, the total size of the training data is 171GB.
60
+
61
+ ## Training procedure
62
+
63
+ We first segmented texts in the corpora into words using [Juman++ 2.0.0-rc3](https://github.com/ku-nlp/jumanpp/releases/tag/v2.0.0-rc3) for whole word masking.
64
+ Then, we built a sentencepiece model with 22,012 tokens including all characters that appear in the training corpus.
65
+
66
+ We tokenized raw corpora into character-level subwords using the sentencepiece model and trained the Japanese DeBERTa model using [transformers](https://github.com/huggingface/transformers) library.
67
+ The training took 26 days using 16 NVIDIA A100-SXM4-40GB GPUs.
68
+
69
+ The following hyperparameters were used during pre-training:
70
+
71
+ - learning_rate: 1e-4
72
+ - per_device_train_batch_size: 26
73
+ - distributed_type: multi-GPU
74
+ - num_devices: 16
75
+ - gradient_accumulation_steps: 8
76
+ - total_train_batch_size: 3,328
77
+ - max_seq_length: 512
78
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-06
79
+ - lr_scheduler_type: linear schedule with warmup (lr = 0 at 300k steps)
80
+ - training_steps: 260,000
81
+ - warmup_steps: 10,000
82
+
83
+ The accuracy of the trained model on the masked language modeling task was 0.795.
84
+ The evaluation set consists of 5,000 randomly sampled documents from each of the training corpora.
85
+
86
+ ## Acknowledgments
87
+
88
+ This work was supported by Joint Usage/Research Center for Interdisciplinary Large-scale Information Infrastructures (JHPCN) through General Collaboration Project no. jh221004, "Developing a Platform for Constructing and Sharing of Large-Scale Japanese Language Models".
89
+ For training models, we used the mdx: a platform for the data-driven future.
bert/deberta-v2-large-japanese-char-wwm/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DebertaV2ForMaskedLM"
4
+ ],
5
+ "attention_head_size": 64,
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "conv_act": "gelu",
8
+ "conv_kernel_size": 3,
9
+ "hidden_act": "gelu",
10
+ "hidden_dropout_prob": 0.1,
11
+ "hidden_size": 1024,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 4096,
14
+ "layer_norm_eps": 1e-07,
15
+ "max_position_embeddings": 512,
16
+ "max_relative_positions": -1,
17
+ "model_type": "deberta-v2",
18
+ "norm_rel_ebd": "layer_norm",
19
+ "num_attention_heads": 16,
20
+ "num_hidden_layers": 24,
21
+ "pad_token_id": 0,
22
+ "pooler_dropout": 0,
23
+ "pooler_hidden_act": "gelu",
24
+ "pooler_hidden_size": 1024,
25
+ "pos_att_type": [
26
+ "p2c",
27
+ "c2p"
28
+ ],
29
+ "position_biased_input": false,
30
+ "position_buckets": 256,
31
+ "relative_attention": true,
32
+ "share_att_key": true,
33
+ "torch_dtype": "float16",
34
+ "transformers_version": "4.25.1",
35
+ "type_vocab_size": 0,
36
+ "vocab_size": 22012
37
+ }
bert/deberta-v2-large-japanese-char-wwm/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf0dab8ad87bd7c22e85ec71e04f2240804fda6d33196157d6b5923af6ea1201
3
+ size 1318456639
bert/deberta-v2-large-japanese-char-wwm/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
bert/deberta-v2-large-japanese-char-wwm/tokenizer_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "do_lower_case": false,
4
+ "do_subword_tokenize": true,
5
+ "do_word_tokenize": true,
6
+ "jumanpp_kwargs": null,
7
+ "mask_token": "[MASK]",
8
+ "mecab_kwargs": null,
9
+ "model_max_length": 1000000000000000019884624838656,
10
+ "never_split": null,
11
+ "pad_token": "[PAD]",
12
+ "sep_token": "[SEP]",
13
+ "special_tokens_map_file": null,
14
+ "subword_tokenizer_type": "character",
15
+ "sudachi_kwargs": null,
16
+ "tokenizer_class": "BertJapaneseTokenizer",
17
+ "unk_token": "[UNK]",
18
+ "word_tokenizer_type": "basic"
19
+ }
bert/deberta-v2-large-japanese-char-wwm/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
bert/deberta-v3-large/.gitattributes ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.model filter=lfs diff=lfs merge=lfs -text
12
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
13
+ *.onnx filter=lfs diff=lfs merge=lfs -text
14
+ *.ot filter=lfs diff=lfs merge=lfs -text
15
+ *.parquet filter=lfs diff=lfs merge=lfs -text
16
+ *.pb filter=lfs diff=lfs merge=lfs -text
17
+ *.pt filter=lfs diff=lfs merge=lfs -text
18
+ *.pth filter=lfs diff=lfs merge=lfs -text
19
+ *.rar filter=lfs diff=lfs merge=lfs -text
20
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
21
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
22
+ *.tflite filter=lfs diff=lfs merge=lfs -text
23
+ *.tgz filter=lfs diff=lfs merge=lfs -text
24
+ *.xz filter=lfs diff=lfs merge=lfs -text
25
+ *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
bert/deberta-v3-large/README.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: en
3
+ tags:
4
+ - deberta
5
+ - deberta-v3
6
+ - fill-mask
7
+ thumbnail: https://huggingface.co/front/thumbnails/microsoft.png
8
+ license: mit
9
+ ---
10
+
11
+ ## DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing
12
+
13
+ [DeBERTa](https://arxiv.org/abs/2006.03654) improves the BERT and RoBERTa models using disentangled attention and enhanced mask decoder. With those two improvements, DeBERTa out perform RoBERTa on a majority of NLU tasks with 80GB training data.
14
+
15
+ In [DeBERTa V3](https://arxiv.org/abs/2111.09543), we further improved the efficiency of DeBERTa using ELECTRA-Style pre-training with Gradient Disentangled Embedding Sharing. Compared to DeBERTa, our V3 version significantly improves the model performance on downstream tasks. You can find more technique details about the new model from our [paper](https://arxiv.org/abs/2111.09543).
16
+
17
+ Please check the [official repository](https://github.com/microsoft/DeBERTa) for more implementation details and updates.
18
+
19
+ The DeBERTa V3 large model comes with 24 layers and a hidden size of 1024. It has 304M backbone parameters with a vocabulary containing 128K tokens which introduces 131M parameters in the Embedding layer. This model was trained using the 160GB data as DeBERTa V2.
20
+
21
+
22
+ #### Fine-tuning on NLU tasks
23
+
24
+ We present the dev results on SQuAD 2.0 and MNLI tasks.
25
+
26
+ | Model |Vocabulary(K)|Backbone #Params(M)| SQuAD 2.0(F1/EM) | MNLI-m/mm(ACC)|
27
+ |-------------------|----------|-------------------|-----------|----------|
28
+ | RoBERTa-large |50 |304 | 89.4/86.5 | 90.2 |
29
+ | XLNet-large |32 |- | 90.6/87.9 | 90.8 |
30
+ | DeBERTa-large |50 |- | 90.7/88.0 | 91.3 |
31
+ | **DeBERTa-v3-large**|128|304 | **91.5/89.0**| **91.8/91.9**|
32
+
33
+
34
+ #### Fine-tuning with HF transformers
35
+
36
+ ```bash
37
+ #!/bin/bash
38
+
39
+ cd transformers/examples/pytorch/text-classification/
40
+
41
+ pip install datasets
42
+ export TASK_NAME=mnli
43
+
44
+ output_dir="ds_results"
45
+
46
+ num_gpus=8
47
+
48
+ batch_size=8
49
+
50
+ python -m torch.distributed.launch --nproc_per_node=${num_gpus} \
51
+ run_glue.py \
52
+ --model_name_or_path microsoft/deberta-v3-large \
53
+ --task_name $TASK_NAME \
54
+ --do_train \
55
+ --do_eval \
56
+ --evaluation_strategy steps \
57
+ --max_seq_length 256 \
58
+ --warmup_steps 50 \
59
+ --per_device_train_batch_size ${batch_size} \
60
+ --learning_rate 6e-6 \
61
+ --num_train_epochs 2 \
62
+ --output_dir $output_dir \
63
+ --overwrite_output_dir \
64
+ --logging_steps 1000 \
65
+ --logging_dir $output_dir
66
+
67
+ ```
68
+
69
+ ### Citation
70
+
71
+ If you find DeBERTa useful for your work, please cite the following papers:
72
+
73
+ ``` latex
74
+ @misc{he2021debertav3,
75
+ title={DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing},
76
+ author={Pengcheng He and Jianfeng Gao and Weizhu Chen},
77
+ year={2021},
78
+ eprint={2111.09543},
79
+ archivePrefix={arXiv},
80
+ primaryClass={cs.CL}
81
+ }
82
+ ```
83
+
84
+ ``` latex
85
+ @inproceedings{
86
+ he2021deberta,
87
+ title={DEBERTA: DECODING-ENHANCED BERT WITH DISENTANGLED ATTENTION},
88
+ author={Pengcheng He and Xiaodong Liu and Jianfeng Gao and Weizhu Chen},
89
+ booktitle={International Conference on Learning Representations},
90
+ year={2021},
91
+ url={https://openreview.net/forum?id=XPZIaotutsD}
92
+ }
93
+ ```
bert/deberta-v3-large/config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "deberta-v2",
3
+ "attention_probs_dropout_prob": 0.1,
4
+ "hidden_act": "gelu",
5
+ "hidden_dropout_prob": 0.1,
6
+ "hidden_size": 1024,
7
+ "initializer_range": 0.02,
8
+ "intermediate_size": 4096,
9
+ "max_position_embeddings": 512,
10
+ "relative_attention": true,
11
+ "position_buckets": 256,
12
+ "norm_rel_ebd": "layer_norm",
13
+ "share_att_key": true,
14
+ "pos_att_type": "p2c|c2p",
15
+ "layer_norm_eps": 1e-7,
16
+ "max_relative_positions": -1,
17
+ "position_biased_input": false,
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 24,
20
+ "type_vocab_size": 0,
21
+ "vocab_size": 128100
22
+ }
bert/deberta-v3-large/generator_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "deberta-v2",
3
+ "attention_probs_dropout_prob": 0.1,
4
+ "hidden_act": "gelu",
5
+ "hidden_dropout_prob": 0.1,
6
+ "hidden_size": 1024,
7
+ "initializer_range": 0.02,
8
+ "intermediate_size": 4096,
9
+ "max_position_embeddings": 512,
10
+ "relative_attention": true,
11
+ "position_buckets": 256,
12
+ "norm_rel_ebd": "layer_norm",
13
+ "share_att_key": true,
14
+ "pos_att_type": "p2c|c2p",
15
+ "layer_norm_eps": 1e-7,
16
+ "max_relative_positions": -1,
17
+ "position_biased_input": false,
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 12,
20
+ "type_vocab_size": 0,
21
+ "vocab_size": 128100
22
+ }
bert/deberta-v3-large/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd5b5d93e2db101aaf281df0ea1216c07ad73620ff59c5b42dccac4bf2eef5b5
3
+ size 873673253
bert/deberta-v3-large/pytorch_model.bin.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd5b5d93e2db101aaf281df0ea1216c07ad73620ff59c5b42dccac4bf2eef5b5
3
+ size 873673253
bert/deberta-v3-large/spm.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c679fbf93643d19aab7ee10c0b99e460bdbc02fedf34b92b05af343b4af586fd
3
+ size 2464616
bert/deberta-v3-large/tokenizer_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "do_lower_case": false,
3
+ "vocab_type": "spm"
4
+ }
bert_gen.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import sys
3
+ from multiprocessing import Pool
4
+
5
+ import torch
6
+ import torch.multiprocessing as mp
7
+ from tqdm import tqdm
8
+
9
+ import commons
10
+ import utils
11
+ from config import config
12
+ from text import cleaned_text_to_sequence, get_bert
13
+
14
+
15
+ def process_line(x):
16
+ line, add_blank = x
17
+ device = config.bert_gen_config.device
18
+ if config.bert_gen_config.use_multi_device:
19
+ rank = mp.current_process()._identity
20
+ rank = rank[0] if len(rank) > 0 else 0
21
+ if torch.cuda.is_available():
22
+ gpu_id = rank % torch.cuda.device_count()
23
+ device = torch.device(f"cuda:{gpu_id}")
24
+ else:
25
+ device = torch.device("cpu")
26
+ wav_path, _, language_str, text, phones, tone, word2ph = line.strip().split("|")
27
+ phone = phones.split(" ")
28
+ tone = [int(i) for i in tone.split(" ")]
29
+ word2ph = [int(i) for i in word2ph.split(" ")]
30
+ word2ph = [i for i in word2ph]
31
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
32
+
33
+ if add_blank:
34
+ phone = commons.intersperse(phone, 0)
35
+ tone = commons.intersperse(tone, 0)
36
+ language = commons.intersperse(language, 0)
37
+ for i in range(len(word2ph)):
38
+ word2ph[i] = word2ph[i] * 2
39
+ word2ph[0] += 1
40
+
41
+ bert_path = wav_path.replace(".WAV", ".wav").replace(".wav", ".bert.pt")
42
+
43
+ try:
44
+ bert = torch.load(bert_path)
45
+ assert bert.shape[-1] == len(phone)
46
+ except Exception:
47
+ bert = get_bert(text, word2ph, language_str, device)
48
+ assert bert.shape[-1] == len(phone)
49
+ torch.save(bert, bert_path)
50
+
51
+
52
+ preprocess_text_config = config.preprocess_text_config
53
+
54
+ if __name__ == "__main__":
55
+ parser = argparse.ArgumentParser()
56
+ parser.add_argument(
57
+ "-c", "--config", type=str, default=config.bert_gen_config.config_path
58
+ )
59
+ parser.add_argument(
60
+ "--num_processes", type=int, default=config.bert_gen_config.num_processes
61
+ )
62
+ args, _ = parser.parse_known_args()
63
+ config_path = args.config
64
+ hps = utils.get_hparams_from_file(config_path)
65
+ lines = []
66
+ with open(hps.data.training_files, encoding="utf-8") as f:
67
+ lines.extend(f.readlines())
68
+
69
+ with open(hps.data.validation_files, encoding="utf-8") as f:
70
+ lines.extend(f.readlines())
71
+ add_blank = [hps.data.add_blank] * len(lines)
72
+
73
+ if len(lines) != 0:
74
+ num_processes = args.num_processes
75
+ with Pool(processes=num_processes) as pool:
76
+ for _ in tqdm(
77
+ pool.imap_unordered(process_line, zip(lines, add_blank)),
78
+ total=len(lines),
79
+ file=sys.stdout,
80
+ ):
81
+ # 这里是缩进的代码块,表示循环体
82
+ pass # 使用pass语句作为占位符
83
+
84
+ print(f"bert.pt is generated! total: {len(lines)} bert.pt files.")
commons.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch.nn import functional as F
4
+
5
+
6
+ def init_weights(m, mean=0.0, std=0.01):
7
+ classname = m.__class__.__name__
8
+ if classname.find("Conv") != -1:
9
+ m.weight.data.normal_(mean, std)
10
+
11
+
12
+ def get_padding(kernel_size, dilation=1):
13
+ return int((kernel_size * dilation - dilation) / 2)
14
+
15
+
16
+ def convert_pad_shape(pad_shape):
17
+ layer = pad_shape[::-1]
18
+ pad_shape = [item for sublist in layer for item in sublist]
19
+ return pad_shape
20
+
21
+
22
+ def intersperse(lst, item):
23
+ result = [item] * (len(lst) * 2 + 1)
24
+ result[1::2] = lst
25
+ return result
26
+
27
+
28
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
29
+ """KL(P||Q)"""
30
+ kl = (logs_q - logs_p) - 0.5
31
+ kl += (
32
+ 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
33
+ )
34
+ return kl
35
+
36
+
37
+ def rand_gumbel(shape):
38
+ """Sample from the Gumbel distribution, protect from overflows."""
39
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
40
+ return -torch.log(-torch.log(uniform_samples))
41
+
42
+
43
+ def rand_gumbel_like(x):
44
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
45
+ return g
46
+
47
+
48
+ def slice_segments(x, ids_str, segment_size=4):
49
+ gather_indices = ids_str.view(x.size(0), 1, 1).repeat(
50
+ 1, x.size(1), 1
51
+ ) + torch.arange(segment_size, device=x.device)
52
+ return torch.gather(x, 2, gather_indices)
53
+
54
+
55
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
56
+ b, d, t = x.size()
57
+ if x_lengths is None:
58
+ x_lengths = t
59
+ ids_str_max = torch.clamp(x_lengths - segment_size + 1, min=0)
60
+ ids_str = (torch.rand([b], device=x.device) * ids_str_max).to(dtype=torch.long)
61
+ ret = slice_segments(x, ids_str, segment_size)
62
+ return ret, ids_str
63
+
64
+
65
+ def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
66
+ position = torch.arange(length, dtype=torch.float)
67
+ num_timescales = channels // 2
68
+ log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
69
+ num_timescales - 1
70
+ )
71
+ inv_timescales = min_timescale * torch.exp(
72
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
73
+ )
74
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
75
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
76
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
77
+ signal = signal.view(1, channels, length)
78
+ return signal
79
+
80
+
81
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
82
+ b, channels, length = x.size()
83
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
84
+ return x + signal.to(dtype=x.dtype, device=x.device)
85
+
86
+
87
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
88
+ b, channels, length = x.size()
89
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
90
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
91
+
92
+
93
+ def subsequent_mask(length):
94
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
95
+ return mask
96
+
97
+
98
+ @torch.jit.script
99
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
100
+ n_channels_int = n_channels[0]
101
+ in_act = input_a + input_b
102
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
103
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
104
+ acts = t_act * s_act
105
+ return acts
106
+
107
+
108
+ def shift_1d(x):
109
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
110
+ return x
111
+
112
+
113
+ def sequence_mask(length, max_length=None):
114
+ if max_length is None:
115
+ max_length = length.max()
116
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
117
+ return x.unsqueeze(0) < length.unsqueeze(1)
118
+
119
+
120
+ def generate_path(duration, mask):
121
+ """
122
+ duration: [b, 1, t_x]
123
+ mask: [b, 1, t_y, t_x]
124
+ """
125
+
126
+ b, _, t_y, t_x = mask.shape
127
+ cum_duration = torch.cumsum(duration, -1)
128
+
129
+ cum_duration_flat = cum_duration.view(b * t_x)
130
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
131
+ path = path.view(b, t_x, t_y)
132
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
133
+ path = path.unsqueeze(1).transpose(2, 3) * mask
134
+ return path
135
+
136
+
137
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
138
+ if isinstance(parameters, torch.Tensor):
139
+ parameters = [parameters]
140
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
141
+ norm_type = float(norm_type)
142
+ if clip_value is not None:
143
+ clip_value = float(clip_value)
144
+
145
+ total_norm = 0
146
+ for p in parameters:
147
+ param_norm = p.grad.data.norm(norm_type)
148
+ total_norm += param_norm.item() ** norm_type
149
+ if clip_value is not None:
150
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
151
+ total_norm = total_norm ** (1.0 / norm_type)
152
+ return total_norm
config.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ @Desc: 全局配置文件读取
3
+ """
4
+ import argparse
5
+ import yaml
6
+ from typing import Dict, List
7
+ import os
8
+ import shutil
9
+ import sys
10
+
11
+
12
+ class Resample_config:
13
+ """重采样配置"""
14
+
15
+ def __init__(self, in_dir: str, out_dir: str, sampling_rate: int = 44100):
16
+ self.sampling_rate: int = sampling_rate # 目标采样率
17
+ self.in_dir: str = in_dir # 待处理音频目录路径
18
+ self.out_dir: str = out_dir # 重采样输出路径
19
+
20
+ @classmethod
21
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
22
+ """从字典中生成实例"""
23
+
24
+ # 不检查路径是否有效,此逻辑在resample.py中处理
25
+ data["in_dir"] = os.path.join(dataset_path, data["in_dir"])
26
+ data["out_dir"] = os.path.join(dataset_path, data["out_dir"])
27
+
28
+ return cls(**data)
29
+
30
+
31
+ class Preprocess_text_config:
32
+ """数据预处理配置"""
33
+
34
+ def __init__(
35
+ self,
36
+ transcription_path: str,
37
+ cleaned_path: str,
38
+ train_path: str,
39
+ val_path: str,
40
+ config_path: str,
41
+ val_per_lang: int = 5,
42
+ max_val_total: int = 10000,
43
+ clean: bool = True,
44
+ ):
45
+ self.transcription_path: str = transcription_path # 原始文本文件路径,文本格式应为{wav_path}|{speaker_name}|{language}|{text}。
46
+ self.cleaned_path: str = cleaned_path # 数据清洗后文本路径,可以不填。不填则将在原始文本目录生成
47
+ self.train_path: str = train_path # 训练集路径,可以不填。不填则将在原始文本目录生成
48
+ self.val_path: str = val_path # 验证集路径,可以不填。不填则将在原始文本目录生成
49
+ self.config_path: str = config_path # 配置文件路径
50
+ self.val_per_lang: int = val_per_lang # 每个speaker的验证集条数
51
+ self.max_val_total: int = max_val_total # 验证集最大条数,多于的会被截断并放到训练集中
52
+ self.clean: bool = clean # 是否进行数据清洗
53
+
54
+ @classmethod
55
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
56
+ """从字典中生成实例"""
57
+
58
+ data["transcription_path"] = os.path.join(
59
+ dataset_path, data["transcription_path"]
60
+ )
61
+ if data["cleaned_path"] == "" or data["cleaned_path"] is None:
62
+ data["cleaned_path"] = None
63
+ else:
64
+ data["cleaned_path"] = os.path.join(dataset_path, data["cleaned_path"])
65
+ data["train_path"] = os.path.join(dataset_path, data["train_path"])
66
+ data["val_path"] = os.path.join(dataset_path, data["val_path"])
67
+ data["config_path"] = os.path.join(dataset_path, data["config_path"])
68
+
69
+ return cls(**data)
70
+
71
+
72
+ class Bert_gen_config:
73
+ """bert_gen 配置"""
74
+
75
+ def __init__(
76
+ self,
77
+ config_path: str,
78
+ num_processes: int = 2,
79
+ device: str = "cuda",
80
+ use_multi_device: bool = False,
81
+ ):
82
+ self.config_path = config_path
83
+ self.num_processes = num_processes
84
+ self.device = device
85
+ self.use_multi_device = use_multi_device
86
+
87
+ @classmethod
88
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
89
+ data["config_path"] = os.path.join(dataset_path, data["config_path"])
90
+
91
+ return cls(**data)
92
+
93
+
94
+ class Style_gen_config:
95
+ """style_gen 配置"""
96
+
97
+ def __init__(
98
+ self,
99
+ config_path: str,
100
+ num_processes: int = 2,
101
+ device: str = "cuda",
102
+ ):
103
+ self.config_path = config_path
104
+ self.num_processes = num_processes
105
+ self.device = device
106
+
107
+ @classmethod
108
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
109
+ data["config_path"] = os.path.join(dataset_path, data["config_path"])
110
+
111
+ return cls(**data)
112
+
113
+
114
+ class Train_ms_config:
115
+ """训练配置"""
116
+
117
+ def __init__(
118
+ self,
119
+ config_path: str,
120
+ env: Dict[str, any],
121
+ # base: Dict[str, any],
122
+ model: str,
123
+ num_workers: int,
124
+ spec_cache: bool,
125
+ keep_ckpts: int,
126
+ ):
127
+ self.env = env # 需要加载的环境变量
128
+ # self.base = base # 底模配置
129
+ self.model = model # 训练模型存储目录,该路径为相对于dataset_path的路径,而非项目根目录
130
+ self.config_path = config_path # 配置文件路径
131
+ self.num_workers = num_workers # worker数量
132
+ self.spec_cache = spec_cache # 是否启用spec缓存
133
+ self.keep_ckpts = keep_ckpts # ckpt数量
134
+
135
+ @classmethod
136
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
137
+ # data["model"] = os.path.join(dataset_path, data["model"])
138
+ data["config_path"] = os.path.join(dataset_path, data["config_path"])
139
+
140
+ return cls(**data)
141
+
142
+
143
+ class Webui_config:
144
+ """webui 配置"""
145
+
146
+ def __init__(
147
+ self,
148
+ device: str,
149
+ model: str,
150
+ config_path: str,
151
+ language_identification_library: str,
152
+ port: int = 7860,
153
+ share: bool = False,
154
+ debug: bool = False,
155
+ ):
156
+ self.device: str = device
157
+ self.model: str = model # 端口号
158
+ self.config_path: str = config_path # 是否公开部署,对外网开放
159
+ self.port: int = port # 是否开启debug模式
160
+ self.share: bool = share # 模型路径
161
+ self.debug: bool = debug # 配置文件路径
162
+ self.language_identification_library: str = (
163
+ language_identification_library # 语种识别库
164
+ )
165
+
166
+ @classmethod
167
+ def from_dict(cls, dataset_path: str, data: Dict[str, any]):
168
+ data["config_path"] = os.path.join(dataset_path, data["config_path"])
169
+ data["model"] = os.path.join(dataset_path, data["model"])
170
+ return cls(**data)
171
+
172
+
173
+ class Server_config:
174
+ def __init__(
175
+ self, models: List[Dict[str, any]], port: int = 5000, device: str = "cuda"
176
+ ):
177
+ self.models: List[Dict[str, any]] = models # 需要加载的所有模型的配置
178
+ self.port: int = port # 端口号
179
+ self.device: str = device # 模型默认使用设备
180
+
181
+ @classmethod
182
+ def from_dict(cls, data: Dict[str, any]):
183
+ return cls(**data)
184
+
185
+
186
+ class Translate_config:
187
+ """翻译api配置"""
188
+
189
+ def __init__(self, app_key: str, secret_key: str):
190
+ self.app_key = app_key
191
+ self.secret_key = secret_key
192
+
193
+ @classmethod
194
+ def from_dict(cls, data: Dict[str, any]):
195
+ return cls(**data)
196
+
197
+
198
+ class Config:
199
+ def __init__(self, config_path: str):
200
+ if not os.path.isfile(config_path) and os.path.isfile("default_config.yml"):
201
+ shutil.copy(src="default_config.yml", dst=config_path)
202
+ print(
203
+ f"A configuration file {config_path} has been generated based on the default configuration file default_config.yml."
204
+ )
205
+ print(
206
+ "If you have no special needs, please do not modify default_config.yml."
207
+ )
208
+ # sys.exit(0)
209
+ with open(file=config_path, mode="r", encoding="utf-8") as file:
210
+ yaml_config: Dict[str, any] = yaml.safe_load(file.read())
211
+ model_name: str = yaml_config["model_name"]
212
+ self.model_name: str = model_name
213
+ if "dataset_path" in yaml_config:
214
+ dataset_path = yaml_config["dataset_path"]
215
+ else:
216
+ dataset_path = f"Data/{model_name}"
217
+ self.out_dir = yaml_config["out_dir"]
218
+ # openi_token: str = yaml_config["openi_token"]
219
+ self.dataset_path: str = dataset_path
220
+ # self.mirror: str = yaml_config["mirror"]
221
+ # self.openi_token: str = openi_token
222
+ self.resample_config: Resample_config = Resample_config.from_dict(
223
+ dataset_path, yaml_config["resample"]
224
+ )
225
+ self.preprocess_text_config: Preprocess_text_config = (
226
+ Preprocess_text_config.from_dict(
227
+ dataset_path, yaml_config["preprocess_text"]
228
+ )
229
+ )
230
+ self.bert_gen_config: Bert_gen_config = Bert_gen_config.from_dict(
231
+ dataset_path, yaml_config["bert_gen"]
232
+ )
233
+ self.style_gen_config: Style_gen_config = Style_gen_config.from_dict(
234
+ dataset_path, yaml_config["style_gen"]
235
+ )
236
+ self.train_ms_config: Train_ms_config = Train_ms_config.from_dict(
237
+ dataset_path, yaml_config["train_ms"]
238
+ )
239
+ self.webui_config: Webui_config = Webui_config.from_dict(
240
+ dataset_path, yaml_config["webui"]
241
+ )
242
+ self.server_config: Server_config = Server_config.from_dict(
243
+ yaml_config["server"]
244
+ )
245
+ # self.translate_config: Translate_config = Translate_config.from_dict(
246
+ # yaml_config["translate"]
247
+ # )
248
+
249
+
250
+ parser = argparse.ArgumentParser()
251
+ # 为避免与以前的config.json起冲突,将其更名如下
252
+ parser.add_argument("-y", "--yml_config", type=str, default="config.yml")
253
+ args, _ = parser.parse_known_args()
254
+ config = Config(args.yml_config)
config.yml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ bert_gen:
2
+ config_path: config.json
3
+ device: cuda
4
+ num_processes: 4
5
+ use_multi_device: false
6
+ dataset_path: Data\jvnv-M2
7
+ model_name: jvnv-M2
8
+ out_dir: model_assets
9
+ preprocess_text:
10
+ clean: true
11
+ cleaned_path: ''
12
+ config_path: config.json
13
+ max_val_total: 12
14
+ train_path: filelists/train.list
15
+ transcription_path: filelists/text.list
16
+ val_path: filelists/val.list
17
+ val_per_lang: 4
18
+ resample:
19
+ in_dir: audios/raw
20
+ out_dir: audios/wavs
21
+ sampling_rate: 44100
22
+ server:
23
+ device: cuda
24
+ models:
25
+ - config: ''
26
+ device: cuda
27
+ language: ZH
28
+ model: ''
29
+ - config: ''
30
+ device: cpu
31
+ language: JP
32
+ model: ''
33
+ speakers: []
34
+ port: 5000
35
+ style_gen:
36
+ config_path: config.json
37
+ device: cuda
38
+ num_processes: 4
39
+ train_ms:
40
+ config_path: config.json
41
+ env:
42
+ LOCAL_RANK: 0
43
+ MASTER_ADDR: localhost
44
+ MASTER_PORT: 10086
45
+ RANK: 0
46
+ WORLD_SIZE: 1
47
+ keep_ckpts: 1
48
+ model: models
49
+ num_workers: 16
50
+ spec_cache: true
51
+ webui:
52
+ config_path: config.json
53
+ debug: false
54
+ device: cuda
55
+ language_identification_library: langid
56
+ model: models/G_8000.pth
57
+ port: 7860
58
+ share: false
configs/config.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "your_model_name",
3
+ "train": {
4
+ "log_interval": 200,
5
+ "eval_interval": 1000,
6
+ "seed": 42,
7
+ "epochs": 1000,
8
+ "learning_rate": 0.0002,
9
+ "betas": [0.8, 0.99],
10
+ "eps": 1e-9,
11
+ "batch_size": 4,
12
+ "bf16_run": true,
13
+ "lr_decay": 0.99995,
14
+ "segment_size": 16384,
15
+ "init_lr_ratio": 1,
16
+ "warmup_epochs": 0,
17
+ "c_mel": 45,
18
+ "c_kl": 1.0,
19
+ "skip_optimizer": false,
20
+ "freeze_ZH_bert": false,
21
+ "freeze_JP_bert": false,
22
+ "freeze_EN_bert": false
23
+ },
24
+ "data": {
25
+ "training_files": "Data/your_model_name/filelists/train.list",
26
+ "validation_files": "Data/your_model_name/filelists/val.list",
27
+ "max_wav_value": 32768.0,
28
+ "sampling_rate": 44100,
29
+ "filter_length": 2048,
30
+ "hop_length": 512,
31
+ "win_length": 2048,
32
+ "n_mel_channels": 128,
33
+ "mel_fmin": 0.0,
34
+ "mel_fmax": null,
35
+ "add_blank": true,
36
+ "n_speakers": 1,
37
+ "cleaned_text": true,
38
+ "num_styles": 1,
39
+ "style2id": {
40
+ "Neutral": 0
41
+ }
42
+ },
43
+ "model": {
44
+ "use_spk_conditioned_encoder": true,
45
+ "use_noise_scaled_mas": true,
46
+ "use_mel_posterior_encoder": false,
47
+ "use_duration_discriminator": true,
48
+ "inter_channels": 192,
49
+ "hidden_channels": 192,
50
+ "filter_channels": 768,
51
+ "n_heads": 2,
52
+ "n_layers": 6,
53
+ "kernel_size": 3,
54
+ "p_dropout": 0.1,
55
+ "resblock": "1",
56
+ "resblock_kernel_sizes": [3, 7, 11],
57
+ "resblock_dilation_sizes": [
58
+ [1, 3, 5],
59
+ [1, 3, 5],
60
+ [1, 3, 5]
61
+ ],
62
+ "upsample_rates": [8, 8, 2, 2, 2],
63
+ "upsample_initial_channel": 512,
64
+ "upsample_kernel_sizes": [16, 16, 8, 2, 2],
65
+ "n_layers_q": 3,
66
+ "use_spectral_norm": false,
67
+ "gin_channels": 256
68
+ },
69
+ "version": "1.0"
70
+ }
data_utils.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import torch
4
+ import torch.utils.data
5
+ from tqdm import tqdm
6
+ import numpy as np
7
+ from tools.log import logger
8
+ import commons
9
+ from mel_processing import spectrogram_torch, mel_spectrogram_torch
10
+ from utils import load_wav_to_torch, load_filepaths_and_text
11
+ from text import cleaned_text_to_sequence
12
+ from config import config
13
+
14
+ """Multi speaker version"""
15
+
16
+
17
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
18
+ """
19
+ 1) loads audio, speaker_id, text pairs
20
+ 2) normalizes text and converts them to sequences of integers
21
+ 3) computes spectrograms from audio files.
22
+ """
23
+
24
+ def __init__(self, audiopaths_sid_text, hparams):
25
+ self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
26
+ self.max_wav_value = hparams.max_wav_value
27
+ self.sampling_rate = hparams.sampling_rate
28
+ self.filter_length = hparams.filter_length
29
+ self.hop_length = hparams.hop_length
30
+ self.win_length = hparams.win_length
31
+ self.sampling_rate = hparams.sampling_rate
32
+ self.spk_map = hparams.spk2id
33
+ self.hparams = hparams
34
+
35
+ self.use_mel_spec_posterior = getattr(
36
+ hparams, "use_mel_posterior_encoder", False
37
+ )
38
+ if self.use_mel_spec_posterior:
39
+ self.n_mel_channels = getattr(hparams, "n_mel_channels", 80)
40
+
41
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
42
+
43
+ self.add_blank = hparams.add_blank
44
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
45
+ self.max_text_len = getattr(hparams, "max_text_len", 384)
46
+
47
+ random.seed(1234)
48
+ random.shuffle(self.audiopaths_sid_text)
49
+ self._filter()
50
+
51
+ def _filter(self):
52
+ """
53
+ Filter text & store spec lengths
54
+ """
55
+ # Store spectrogram lengths for Bucketing
56
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
57
+ # spec_length = wav_length // hop_length
58
+
59
+ audiopaths_sid_text_new = []
60
+ lengths = []
61
+ skipped = 0
62
+ logger.info("Init dataset...")
63
+ for _id, spk, language, text, phones, tone, word2ph in tqdm(
64
+ self.audiopaths_sid_text
65
+ ):
66
+ audiopath = f"{_id}"
67
+ if self.min_text_len <= len(phones) and len(phones) <= self.max_text_len:
68
+ phones = phones.split(" ")
69
+ tone = [int(i) for i in tone.split(" ")]
70
+ word2ph = [int(i) for i in word2ph.split(" ")]
71
+ audiopaths_sid_text_new.append(
72
+ [audiopath, spk, language, text, phones, tone, word2ph]
73
+ )
74
+ lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
75
+ else:
76
+ skipped += 1
77
+ logger.info(
78
+ "skipped: "
79
+ + str(skipped)
80
+ + ", total: "
81
+ + str(len(self.audiopaths_sid_text))
82
+ )
83
+ self.audiopaths_sid_text = audiopaths_sid_text_new
84
+ self.lengths = lengths
85
+
86
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
87
+ # separate filename, speaker_id and text
88
+ audiopath, sid, language, text, phones, tone, word2ph = audiopath_sid_text
89
+
90
+ bert, ja_bert, en_bert, phones, tone, language = self.get_text(
91
+ text, word2ph, phones, tone, language, audiopath
92
+ )
93
+
94
+ spec, wav = self.get_audio(audiopath)
95
+ sid = torch.LongTensor([int(self.spk_map[sid])])
96
+ style_vec = torch.FloatTensor(np.load(f"{audiopath}.npy"))
97
+ return (
98
+ phones,
99
+ spec,
100
+ wav,
101
+ sid,
102
+ tone,
103
+ language,
104
+ bert,
105
+ ja_bert,
106
+ en_bert,
107
+ style_vec,
108
+ )
109
+
110
+ def get_audio(self, filename):
111
+ audio, sampling_rate = load_wav_to_torch(filename)
112
+ if sampling_rate != self.sampling_rate:
113
+ raise ValueError(
114
+ "{} {} SR doesn't match target {} SR".format(
115
+ filename, sampling_rate, self.sampling_rate
116
+ )
117
+ )
118
+ audio_norm = audio / self.max_wav_value
119
+ audio_norm = audio_norm.unsqueeze(0)
120
+ spec_filename = filename.replace(".wav", ".spec.pt")
121
+ if self.use_mel_spec_posterior:
122
+ spec_filename = spec_filename.replace(".spec.pt", ".mel.pt")
123
+ try:
124
+ spec = torch.load(spec_filename)
125
+ except:
126
+ if self.use_mel_spec_posterior:
127
+ spec = mel_spectrogram_torch(
128
+ audio_norm,
129
+ self.filter_length,
130
+ self.n_mel_channels,
131
+ self.sampling_rate,
132
+ self.hop_length,
133
+ self.win_length,
134
+ self.hparams.mel_fmin,
135
+ self.hparams.mel_fmax,
136
+ center=False,
137
+ )
138
+ else:
139
+ spec = spectrogram_torch(
140
+ audio_norm,
141
+ self.filter_length,
142
+ self.sampling_rate,
143
+ self.hop_length,
144
+ self.win_length,
145
+ center=False,
146
+ )
147
+ spec = torch.squeeze(spec, 0)
148
+ if config.train_ms_config.spec_cache:
149
+ torch.save(spec, spec_filename)
150
+ return spec, audio_norm
151
+
152
+ def get_text(self, text, word2ph, phone, tone, language_str, wav_path):
153
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
154
+ if self.add_blank:
155
+ phone = commons.intersperse(phone, 0)
156
+ tone = commons.intersperse(tone, 0)
157
+ language = commons.intersperse(language, 0)
158
+ for i in range(len(word2ph)):
159
+ word2ph[i] = word2ph[i] * 2
160
+ word2ph[0] += 1
161
+ bert_path = wav_path.replace(".wav", ".bert.pt")
162
+ try:
163
+ bert_ori = torch.load(bert_path)
164
+ assert bert_ori.shape[-1] == len(phone)
165
+ except Exception as e:
166
+ logger.warning("Bert load Failed")
167
+ logger.warning(e)
168
+
169
+ if language_str == "ZH":
170
+ bert = bert_ori
171
+ ja_bert = torch.zeros(1024, len(phone))
172
+ en_bert = torch.zeros(1024, len(phone))
173
+ elif language_str == "JP":
174
+ bert = torch.zeros(1024, len(phone))
175
+ ja_bert = bert_ori
176
+ en_bert = torch.zeros(1024, len(phone))
177
+ elif language_str == "EN":
178
+ bert = torch.zeros(1024, len(phone))
179
+ ja_bert = torch.zeros(1024, len(phone))
180
+ en_bert = bert_ori
181
+ phone = torch.LongTensor(phone)
182
+ tone = torch.LongTensor(tone)
183
+ language = torch.LongTensor(language)
184
+ return bert, ja_bert, en_bert, phone, tone, language
185
+
186
+ def get_sid(self, sid):
187
+ sid = torch.LongTensor([int(sid)])
188
+ return sid
189
+
190
+ def __getitem__(self, index):
191
+ return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
192
+
193
+ def __len__(self):
194
+ return len(self.audiopaths_sid_text)
195
+
196
+
197
+ class TextAudioSpeakerCollate:
198
+ """Zero-pads model inputs and targets"""
199
+
200
+ def __init__(self, return_ids=False):
201
+ self.return_ids = return_ids
202
+
203
+ def __call__(self, batch):
204
+ """Collate's training batch from normalized text, audio and speaker identities
205
+ PARAMS
206
+ ------
207
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
208
+ """
209
+ # Right zero-pad all one-hot text sequences to max input length
210
+ _, ids_sorted_decreasing = torch.sort(
211
+ torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True
212
+ )
213
+
214
+ max_text_len = max([len(x[0]) for x in batch])
215
+ max_spec_len = max([x[1].size(1) for x in batch])
216
+ max_wav_len = max([x[2].size(1) for x in batch])
217
+
218
+ text_lengths = torch.LongTensor(len(batch))
219
+ spec_lengths = torch.LongTensor(len(batch))
220
+ wav_lengths = torch.LongTensor(len(batch))
221
+ sid = torch.LongTensor(len(batch))
222
+
223
+ text_padded = torch.LongTensor(len(batch), max_text_len)
224
+ tone_padded = torch.LongTensor(len(batch), max_text_len)
225
+ language_padded = torch.LongTensor(len(batch), max_text_len)
226
+ bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
227
+ ja_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
228
+ en_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
229
+ style_vec = torch.FloatTensor(len(batch), 256)
230
+
231
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
232
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
233
+ text_padded.zero_()
234
+ tone_padded.zero_()
235
+ language_padded.zero_()
236
+ spec_padded.zero_()
237
+ wav_padded.zero_()
238
+ bert_padded.zero_()
239
+ ja_bert_padded.zero_()
240
+ en_bert_padded.zero_()
241
+ style_vec.zero_()
242
+
243
+ for i in range(len(ids_sorted_decreasing)):
244
+ row = batch[ids_sorted_decreasing[i]]
245
+
246
+ text = row[0]
247
+ text_padded[i, : text.size(0)] = text
248
+ text_lengths[i] = text.size(0)
249
+
250
+ spec = row[1]
251
+ spec_padded[i, :, : spec.size(1)] = spec
252
+ spec_lengths[i] = spec.size(1)
253
+
254
+ wav = row[2]
255
+ wav_padded[i, :, : wav.size(1)] = wav
256
+ wav_lengths[i] = wav.size(1)
257
+
258
+ sid[i] = row[3]
259
+
260
+ tone = row[4]
261
+ tone_padded[i, : tone.size(0)] = tone
262
+
263
+ language = row[5]
264
+ language_padded[i, : language.size(0)] = language
265
+
266
+ bert = row[6]
267
+ bert_padded[i, :, : bert.size(1)] = bert
268
+
269
+ ja_bert = row[7]
270
+ ja_bert_padded[i, :, : ja_bert.size(1)] = ja_bert
271
+
272
+ en_bert = row[8]
273
+ en_bert_padded[i, :, : en_bert.size(1)] = en_bert
274
+
275
+ style_vec[i, :] = row[9]
276
+
277
+ return (
278
+ text_padded,
279
+ text_lengths,
280
+ spec_padded,
281
+ spec_lengths,
282
+ wav_padded,
283
+ wav_lengths,
284
+ sid,
285
+ tone_padded,
286
+ language_padded,
287
+ bert_padded,
288
+ ja_bert_padded,
289
+ en_bert_padded,
290
+ style_vec,
291
+ )
292
+
293
+
294
+ class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
295
+ """
296
+ Maintain similar input lengths in a batch.
297
+ Length groups are specified by boundaries.
298
+ Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
299
+
300
+ It removes samples which are not included in the boundaries.
301
+ Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
302
+ """
303
+
304
+ def __init__(
305
+ self,
306
+ dataset,
307
+ batch_size,
308
+ boundaries,
309
+ num_replicas=None,
310
+ rank=None,
311
+ shuffle=True,
312
+ ):
313
+ super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
314
+ self.lengths = dataset.lengths
315
+ self.batch_size = batch_size
316
+ self.boundaries = boundaries
317
+
318
+ self.buckets, self.num_samples_per_bucket = self._create_buckets()
319
+ logger.info(f"Bucket info: {self.num_samples_per_bucket}")
320
+ logger.info(
321
+ f"Unused samples: {len(self.lengths) - sum(self.num_samples_per_bucket)}"
322
+ )
323
+ self.total_size = sum(self.num_samples_per_bucket)
324
+ self.num_samples = self.total_size // self.num_replicas
325
+
326
+ def _create_buckets(self):
327
+ buckets = [[] for _ in range(len(self.boundaries) - 1)]
328
+ for i in range(len(self.lengths)):
329
+ length = self.lengths[i]
330
+ idx_bucket = self._bisect(length)
331
+ if idx_bucket != -1:
332
+ buckets[idx_bucket].append(i)
333
+
334
+ try:
335
+ for i in range(len(buckets) - 1, 0, -1):
336
+ if len(buckets[i]) == 0:
337
+ buckets.pop(i)
338
+ self.boundaries.pop(i + 1)
339
+ assert all(len(bucket) > 0 for bucket in buckets)
340
+ # When one bucket is not traversed
341
+ except Exception as e:
342
+ print("Bucket warning ", e)
343
+ for i in range(len(buckets) - 1, -1, -1):
344
+ if len(buckets[i]) == 0:
345
+ buckets.pop(i)
346
+ self.boundaries.pop(i + 1)
347
+
348
+ num_samples_per_bucket = []
349
+ for i in range(len(buckets)):
350
+ len_bucket = len(buckets[i])
351
+ total_batch_size = self.num_replicas * self.batch_size
352
+ rem = (
353
+ total_batch_size - (len_bucket % total_batch_size)
354
+ ) % total_batch_size
355
+ num_samples_per_bucket.append(len_bucket + rem)
356
+ return buckets, num_samples_per_bucket
357
+
358
+ def __iter__(self):
359
+ # deterministically shuffle based on epoch
360
+ g = torch.Generator()
361
+ g.manual_seed(self.epoch)
362
+
363
+ indices = []
364
+ if self.shuffle:
365
+ for bucket in self.buckets:
366
+ indices.append(torch.randperm(len(bucket), generator=g).tolist())
367
+ else:
368
+ for bucket in self.buckets:
369
+ indices.append(list(range(len(bucket))))
370
+
371
+ batches = []
372
+ for i in range(len(self.buckets)):
373
+ bucket = self.buckets[i]
374
+ len_bucket = len(bucket)
375
+ if len_bucket == 0:
376
+ continue
377
+ ids_bucket = indices[i]
378
+ num_samples_bucket = self.num_samples_per_bucket[i]
379
+
380
+ # add extra samples to make it evenly divisible
381
+ rem = num_samples_bucket - len_bucket
382
+ ids_bucket = (
383
+ ids_bucket
384
+ + ids_bucket * (rem // len_bucket)
385
+ + ids_bucket[: (rem % len_bucket)]
386
+ )
387
+
388
+ # subsample
389
+ ids_bucket = ids_bucket[self.rank :: self.num_replicas]
390
+
391
+ # batching
392
+ for j in range(len(ids_bucket) // self.batch_size):
393
+ batch = [
394
+ bucket[idx]
395
+ for idx in ids_bucket[
396
+ j * self.batch_size : (j + 1) * self.batch_size
397
+ ]
398
+ ]
399
+ batches.append(batch)
400
+
401
+ if self.shuffle:
402
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
403
+ batches = [batches[i] for i in batch_ids]
404
+ self.batches = batches
405
+
406
+ assert len(self.batches) * self.batch_size == self.num_samples
407
+ return iter(self.batches)
408
+
409
+ def _bisect(self, x, lo=0, hi=None):
410
+ if hi is None:
411
+ hi = len(self.boundaries) - 1
412
+
413
+ if hi > lo:
414
+ mid = (hi + lo) // 2
415
+ if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
416
+ return mid
417
+ elif x <= self.boundaries[mid]:
418
+ return self._bisect(x, lo, mid)
419
+ else:
420
+ return self._bisect(x, mid + 1, hi)
421
+ else:
422
+ return -1
423
+
424
+ def __len__(self):
425
+ return self.num_samples // self.batch_size
default_config.yml ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Global configuration file for Bert-VITS2
2
+
3
+ model_name: "model_name"
4
+
5
+ out_dir: "model_assets"
6
+
7
+ # If you want to use a specific dataset path, uncomment the following line.
8
+ # Otherwise, the dataset path is `Data/{model_name}`.
9
+
10
+ # dataset_path: "your/dataset/path"
11
+
12
+ resample:
13
+ sampling_rate: 44100
14
+ in_dir: "audios/raw"
15
+ out_dir: "audios/wavs"
16
+
17
+ preprocess_text:
18
+ transcription_path: "filelists/esd.list"
19
+ cleaned_path: ""
20
+ train_path: "filelists/train.list"
21
+ val_path: "filelists/val.list"
22
+ config_path: "config.json"
23
+ val_per_lang: 4
24
+ max_val_total: 12
25
+ clean: true
26
+
27
+ bert_gen:
28
+ config_path: "config.json"
29
+ num_processes: 4
30
+ device: "cuda"
31
+ use_multi_device: false
32
+
33
+ style_gen:
34
+ config_path: "config.json"
35
+ num_processes: 4
36
+ device: "cuda"
37
+
38
+ train_ms:
39
+ env:
40
+ MASTER_ADDR: "localhost"
41
+ MASTER_PORT: 10086
42
+ WORLD_SIZE: 1
43
+ LOCAL_RANK: 0
44
+ RANK: 0
45
+ model: "models"
46
+ config_path: "config.json"
47
+ num_workers: 16
48
+ spec_cache: True
49
+ keep_ckpts: 1 # Set this to 0 to keep all checkpoints
50
+
51
+ webui:
52
+ # 推理设备
53
+ device: "cuda"
54
+ # 模型路径
55
+ model: "models/G_8000.pth"
56
+ # 配置文件路径
57
+ config_path: "config.json"
58
+ # 端口号
59
+ port: 7860
60
+ # 是否公开部署,对外网开放
61
+ share: false
62
+ # 是否开启debug模式
63
+ debug: false
64
+ # 语种识别库,可选langid, fastlid
65
+ language_identification_library: "langid"
66
+
67
+ # server_fastapi's config
68
+ # TODO: `server_fastapi.py` is not implemented yet for this version
69
+ server:
70
+ port: 5000
71
+ device: "cuda"
72
+ models:
73
+ - model: ""
74
+ config: ""
75
+ device: "cuda"
76
+ language: "ZH"
77
+ - model: ""
78
+ config: ""
79
+ device: "cpu"
80
+ language: "JP"
81
+ speakers: []
infer.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ import commons
4
+ import utils
5
+ from models import SynthesizerTrn
6
+ from text import cleaned_text_to_sequence, get_bert
7
+ from text.cleaner import clean_text
8
+ from text.symbols import symbols
9
+
10
+ # latest_version = "1.0"
11
+
12
+
13
+ def get_net_g(model_path: str, version: str, device: str, hps):
14
+ net_g = SynthesizerTrn(
15
+ len(symbols),
16
+ hps.data.filter_length // 2 + 1,
17
+ hps.train.segment_size // hps.data.hop_length,
18
+ n_speakers=hps.data.n_speakers,
19
+ **hps.model,
20
+ ).to(device)
21
+ net_g.state_dict()
22
+ _ = net_g.eval()
23
+ if model_path.endswith(".pth") or model_path.endswith(".pt"):
24
+ _ = utils.load_checkpoint(model_path, net_g, None, skip_optimizer=True)
25
+ elif model_path.endswith(".safetensors"):
26
+ _ = utils.load_safetensors(model_path, net_g, device)
27
+ else:
28
+ raise ValueError(f"Unknown model format: {model_path}")
29
+ return net_g
30
+
31
+
32
+ def get_text(text, language_str, hps, device, style_text=None, style_weight=0.7):
33
+ # 在此处实现当前版本的get_text
34
+ norm_text, phone, tone, word2ph = clean_text(text, language_str)
35
+ phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
36
+
37
+ if hps.data.add_blank:
38
+ phone = commons.intersperse(phone, 0)
39
+ tone = commons.intersperse(tone, 0)
40
+ language = commons.intersperse(language, 0)
41
+ for i in range(len(word2ph)):
42
+ word2ph[i] = word2ph[i] * 2
43
+ word2ph[0] += 1
44
+ bert_ori = get_bert(
45
+ norm_text, word2ph, language_str, device, style_text, style_weight
46
+ )
47
+ del word2ph
48
+ assert bert_ori.shape[-1] == len(phone), phone
49
+
50
+ if language_str == "ZH":
51
+ bert = bert_ori
52
+ ja_bert = torch.zeros(1024, len(phone))
53
+ en_bert = torch.zeros(1024, len(phone))
54
+ elif language_str == "JP":
55
+ bert = torch.zeros(1024, len(phone))
56
+ ja_bert = bert_ori
57
+ en_bert = torch.zeros(1024, len(phone))
58
+ elif language_str == "EN":
59
+ bert = torch.zeros(1024, len(phone))
60
+ ja_bert = torch.zeros(1024, len(phone))
61
+ en_bert = bert_ori
62
+ else:
63
+ raise ValueError("language_str should be ZH, JP or EN")
64
+
65
+ assert bert.shape[-1] == len(
66
+ phone
67
+ ), f"Bert seq len {bert.shape[-1]} != {len(phone)}"
68
+
69
+ phone = torch.LongTensor(phone)
70
+ tone = torch.LongTensor(tone)
71
+ language = torch.LongTensor(language)
72
+ return bert, ja_bert, en_bert, phone, tone, language
73
+
74
+
75
+ def infer(
76
+ text,
77
+ style_vec,
78
+ sdp_ratio,
79
+ noise_scale,
80
+ noise_scale_w,
81
+ length_scale,
82
+ sid: int, # In the original Bert-VITS2, its speaker_name: str, but here it's id
83
+ language,
84
+ hps,
85
+ net_g,
86
+ device,
87
+ skip_start=False,
88
+ skip_end=False,
89
+ style_text=None,
90
+ style_weight=0.7,
91
+ ):
92
+ bert, ja_bert, en_bert, phones, tones, lang_ids = get_text(
93
+ text,
94
+ language,
95
+ hps,
96
+ device,
97
+ style_text=style_text,
98
+ style_weight=style_weight,
99
+ )
100
+ if skip_start:
101
+ phones = phones[3:]
102
+ tones = tones[3:]
103
+ lang_ids = lang_ids[3:]
104
+ bert = bert[:, 3:]
105
+ ja_bert = ja_bert[:, 3:]
106
+ en_bert = en_bert[:, 3:]
107
+ if skip_end:
108
+ phones = phones[:-2]
109
+ tones = tones[:-2]
110
+ lang_ids = lang_ids[:-2]
111
+ bert = bert[:, :-2]
112
+ ja_bert = ja_bert[:, :-2]
113
+ en_bert = en_bert[:, :-2]
114
+ with torch.no_grad():
115
+ x_tst = phones.to(device).unsqueeze(0)
116
+ tones = tones.to(device).unsqueeze(0)
117
+ lang_ids = lang_ids.to(device).unsqueeze(0)
118
+ bert = bert.to(device).unsqueeze(0)
119
+ ja_bert = ja_bert.to(device).unsqueeze(0)
120
+ en_bert = en_bert.to(device).unsqueeze(0)
121
+ x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
122
+ style_vec = torch.from_numpy(style_vec).to(device).unsqueeze(0)
123
+ del phones
124
+ sid_tensor = torch.LongTensor([sid]).to(device)
125
+ audio = (
126
+ net_g.infer(
127
+ x_tst,
128
+ x_tst_lengths,
129
+ sid_tensor,
130
+ tones,
131
+ lang_ids,
132
+ bert,
133
+ ja_bert,
134
+ en_bert,
135
+ style_vec=style_vec,
136
+ sdp_ratio=sdp_ratio,
137
+ noise_scale=noise_scale,
138
+ noise_scale_w=noise_scale_w,
139
+ length_scale=length_scale,
140
+ )[0][0, 0]
141
+ .data.cpu()
142
+ .float()
143
+ .numpy()
144
+ )
145
+ del (
146
+ x_tst,
147
+ tones,
148
+ lang_ids,
149
+ bert,
150
+ x_tst_lengths,
151
+ sid_tensor,
152
+ ja_bert,
153
+ en_bert,
154
+ style_vec,
155
+ ) # , emo
156
+ if torch.cuda.is_available():
157
+ torch.cuda.empty_cache()
158
+ return audio
159
+
160
+
161
+ def infer_multilang(
162
+ text,
163
+ style_vec,
164
+ sdp_ratio,
165
+ noise_scale,
166
+ noise_scale_w,
167
+ length_scale,
168
+ sid,
169
+ language,
170
+ hps,
171
+ net_g,
172
+ device,
173
+ skip_start=False,
174
+ skip_end=False,
175
+ ):
176
+ bert, ja_bert, en_bert, phones, tones, lang_ids = [], [], [], [], [], []
177
+ # emo = get_emo_(reference_audio, emotion, sid)
178
+ # if isinstance(reference_audio, np.ndarray):
179
+ # emo = get_clap_audio_feature(reference_audio, device)
180
+ # else:
181
+ # emo = get_clap_text_feature(emotion, device)
182
+ # emo = torch.squeeze(emo, dim=1)
183
+ for idx, (txt, lang) in enumerate(zip(text, language)):
184
+ _skip_start = (idx != 0) or (skip_start and idx == 0)
185
+ _skip_end = (idx != len(language) - 1) or skip_end
186
+ (
187
+ temp_bert,
188
+ temp_ja_bert,
189
+ temp_en_bert,
190
+ temp_phones,
191
+ temp_tones,
192
+ temp_lang_ids,
193
+ ) = get_text(txt, lang, hps, device)
194
+ if _skip_start:
195
+ temp_bert = temp_bert[:, 3:]
196
+ temp_ja_bert = temp_ja_bert[:, 3:]
197
+ temp_en_bert = temp_en_bert[:, 3:]
198
+ temp_phones = temp_phones[3:]
199
+ temp_tones = temp_tones[3:]
200
+ temp_lang_ids = temp_lang_ids[3:]
201
+ if _skip_end:
202
+ temp_bert = temp_bert[:, :-2]
203
+ temp_ja_bert = temp_ja_bert[:, :-2]
204
+ temp_en_bert = temp_en_bert[:, :-2]
205
+ temp_phones = temp_phones[:-2]
206
+ temp_tones = temp_tones[:-2]
207
+ temp_lang_ids = temp_lang_ids[:-2]
208
+ bert.append(temp_bert)
209
+ ja_bert.append(temp_ja_bert)
210
+ en_bert.append(temp_en_bert)
211
+ phones.append(temp_phones)
212
+ tones.append(temp_tones)
213
+ lang_ids.append(temp_lang_ids)
214
+ bert = torch.concatenate(bert, dim=1)
215
+ ja_bert = torch.concatenate(ja_bert, dim=1)
216
+ en_bert = torch.concatenate(en_bert, dim=1)
217
+ phones = torch.concatenate(phones, dim=0)
218
+ tones = torch.concatenate(tones, dim=0)
219
+ lang_ids = torch.concatenate(lang_ids, dim=0)
220
+ with torch.no_grad():
221
+ x_tst = phones.to(device).unsqueeze(0)
222
+ tones = tones.to(device).unsqueeze(0)
223
+ lang_ids = lang_ids.to(device).unsqueeze(0)
224
+ bert = bert.to(device).unsqueeze(0)
225
+ ja_bert = ja_bert.to(device).unsqueeze(0)
226
+ en_bert = en_bert.to(device).unsqueeze(0)
227
+ # emo = emo.to(device).unsqueeze(0)
228
+ x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device)
229
+ del phones
230
+ speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(device)
231
+ audio = (
232
+ net_g.infer(
233
+ x_tst,
234
+ x_tst_lengths,
235
+ speakers,
236
+ tones,
237
+ lang_ids,
238
+ bert,
239
+ ja_bert,
240
+ en_bert,
241
+ style_vec=style_vec,
242
+ sdp_ratio=sdp_ratio,
243
+ noise_scale=noise_scale,
244
+ noise_scale_w=noise_scale_w,
245
+ length_scale=length_scale,
246
+ )[0][0, 0]
247
+ .data.cpu()
248
+ .float()
249
+ .numpy()
250
+ )
251
+ del (
252
+ x_tst,
253
+ tones,
254
+ lang_ids,
255
+ bert,
256
+ x_tst_lengths,
257
+ speakers,
258
+ ja_bert,
259
+ en_bert,
260
+ ) # , emo
261
+ if torch.cuda.is_available():
262
+ torch.cuda.empty_cache()
263
+ return audio
losses.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchaudio
3
+ from transformers import AutoModel
4
+
5
+
6
+ def feature_loss(fmap_r, fmap_g):
7
+ loss = 0
8
+ for dr, dg in zip(fmap_r, fmap_g):
9
+ for rl, gl in zip(dr, dg):
10
+ rl = rl.float().detach()
11
+ gl = gl.float()
12
+ loss += torch.mean(torch.abs(rl - gl))
13
+
14
+ return loss * 2
15
+
16
+
17
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
18
+ loss = 0
19
+ r_losses = []
20
+ g_losses = []
21
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
22
+ dr = dr.float()
23
+ dg = dg.float()
24
+ r_loss = torch.mean((1 - dr) ** 2)
25
+ g_loss = torch.mean(dg**2)
26
+ loss += r_loss + g_loss
27
+ r_losses.append(r_loss.item())
28
+ g_losses.append(g_loss.item())
29
+
30
+ return loss, r_losses, g_losses
31
+
32
+
33
+ def generator_loss(disc_outputs):
34
+ loss = 0
35
+ gen_losses = []
36
+ for dg in disc_outputs:
37
+ dg = dg.float()
38
+ l = torch.mean((1 - dg) ** 2)
39
+ gen_losses.append(l)
40
+ loss += l
41
+
42
+ return loss, gen_losses
43
+
44
+
45
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
46
+ """
47
+ z_p, logs_q: [b, h, t_t]
48
+ m_p, logs_p: [b, h, t_t]
49
+ """
50
+ z_p = z_p.float()
51
+ logs_q = logs_q.float()
52
+ m_p = m_p.float()
53
+ logs_p = logs_p.float()
54
+ z_mask = z_mask.float()
55
+
56
+ kl = logs_p - logs_q - 0.5
57
+ kl += 0.5 * ((z_p - m_p) ** 2) * torch.exp(-2.0 * logs_p)
58
+ kl = torch.sum(kl * z_mask)
59
+ l = kl / torch.sum(z_mask)
60
+ return l
61
+
62
+
63
+ class WavLMLoss(torch.nn.Module):
64
+ def __init__(self, model, wd, model_sr, slm_sr=16000):
65
+ super(WavLMLoss, self).__init__()
66
+ self.wavlm = AutoModel.from_pretrained(model)
67
+ self.wd = wd
68
+ self.resample = torchaudio.transforms.Resample(model_sr, slm_sr)
69
+ self.wavlm.eval()
70
+ for param in self.wavlm.parameters():
71
+ param.requires_grad = False
72
+
73
+ def forward(self, wav, y_rec):
74
+ with torch.no_grad():
75
+ wav_16 = self.resample(wav)
76
+ wav_embeddings = self.wavlm(
77
+ input_values=wav_16, output_hidden_states=True
78
+ ).hidden_states
79
+ y_rec_16 = self.resample(y_rec)
80
+ y_rec_embeddings = self.wavlm(
81
+ input_values=y_rec_16.squeeze(), output_hidden_states=True
82
+ ).hidden_states
83
+
84
+ floss = 0
85
+ for er, eg in zip(wav_embeddings, y_rec_embeddings):
86
+ floss += torch.mean(torch.abs(er - eg))
87
+
88
+ return floss.mean()
89
+
90
+ def generator(self, y_rec):
91
+ y_rec_16 = self.resample(y_rec)
92
+ y_rec_embeddings = self.wavlm(
93
+ input_values=y_rec_16, output_hidden_states=True
94
+ ).hidden_states
95
+ y_rec_embeddings = (
96
+ torch.stack(y_rec_embeddings, dim=1)
97
+ .transpose(-1, -2)
98
+ .flatten(start_dim=1, end_dim=2)
99
+ )
100
+ y_df_hat_g = self.wd(y_rec_embeddings)
101
+ loss_gen = torch.mean((1 - y_df_hat_g) ** 2)
102
+
103
+ return loss_gen
104
+
105
+ def discriminator(self, wav, y_rec):
106
+ with torch.no_grad():
107
+ wav_16 = self.resample(wav)
108
+ wav_embeddings = self.wavlm(
109
+ input_values=wav_16, output_hidden_states=True
110
+ ).hidden_states
111
+ y_rec_16 = self.resample(y_rec)
112
+ y_rec_embeddings = self.wavlm(
113
+ input_values=y_rec_16, output_hidden_states=True
114
+ ).hidden_states
115
+
116
+ y_embeddings = (
117
+ torch.stack(wav_embeddings, dim=1)
118
+ .transpose(-1, -2)
119
+ .flatten(start_dim=1, end_dim=2)
120
+ )
121
+ y_rec_embeddings = (
122
+ torch.stack(y_rec_embeddings, dim=1)
123
+ .transpose(-1, -2)
124
+ .flatten(start_dim=1, end_dim=2)
125
+ )
126
+
127
+ y_d_rs = self.wd(y_embeddings)
128
+ y_d_gs = self.wd(y_rec_embeddings)
129
+
130
+ y_df_hat_r, y_df_hat_g = y_d_rs, y_d_gs
131
+
132
+ r_loss = torch.mean((1 - y_df_hat_r) ** 2)
133
+ g_loss = torch.mean((y_df_hat_g) ** 2)
134
+
135
+ loss_disc_f = r_loss + g_loss
136
+
137
+ return loss_disc_f.mean()
138
+
139
+ def discriminator_forward(self, wav):
140
+ with torch.no_grad():
141
+ wav_16 = self.resample(wav)
142
+ wav_embeddings = self.wavlm(
143
+ input_values=wav_16, output_hidden_states=True
144
+ ).hidden_states
145
+ y_embeddings = (
146
+ torch.stack(wav_embeddings, dim=1)
147
+ .transpose(-1, -2)
148
+ .flatten(start_dim=1, end_dim=2)
149
+ )
150
+
151
+ y_d_rs = self.wd(y_embeddings)
152
+
153
+ return y_d_rs
mel_processing.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.utils.data
3
+ from librosa.filters import mel as librosa_mel_fn
4
+ import warnings
5
+
6
+ # warnings.simplefilter(action='ignore', category=FutureWarning)
7
+ warnings.filterwarnings(action="ignore")
8
+ MAX_WAV_VALUE = 32768.0
9
+
10
+
11
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
12
+ """
13
+ PARAMS
14
+ ------
15
+ C: compression factor
16
+ """
17
+ return torch.log(torch.clamp(x, min=clip_val) * C)
18
+
19
+
20
+ def dynamic_range_decompression_torch(x, C=1):
21
+ """
22
+ PARAMS
23
+ ------
24
+ C: compression factor used to compress
25
+ """
26
+ return torch.exp(x) / C
27
+
28
+
29
+ def spectral_normalize_torch(magnitudes):
30
+ output = dynamic_range_compression_torch(magnitudes)
31
+ return output
32
+
33
+
34
+ def spectral_de_normalize_torch(magnitudes):
35
+ output = dynamic_range_decompression_torch(magnitudes)
36
+ return output
37
+
38
+
39
+ mel_basis = {}
40
+ hann_window = {}
41
+
42
+
43
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
44
+ if torch.min(y) < -1.0:
45
+ print("min value is ", torch.min(y))
46
+ if torch.max(y) > 1.0:
47
+ print("max value is ", torch.max(y))
48
+
49
+ global hann_window
50
+ dtype_device = str(y.dtype) + "_" + str(y.device)
51
+ wnsize_dtype_device = str(win_size) + "_" + dtype_device
52
+ if wnsize_dtype_device not in hann_window:
53
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
54
+ dtype=y.dtype, device=y.device
55
+ )
56
+
57
+ y = torch.nn.functional.pad(
58
+ y.unsqueeze(1),
59
+ (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
60
+ mode="reflect",
61
+ )
62
+ y = y.squeeze(1)
63
+
64
+ spec = torch.stft(
65
+ y,
66
+ n_fft,
67
+ hop_length=hop_size,
68
+ win_length=win_size,
69
+ window=hann_window[wnsize_dtype_device],
70
+ center=center,
71
+ pad_mode="reflect",
72
+ normalized=False,
73
+ onesided=True,
74
+ return_complex=False,
75
+ )
76
+
77
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
78
+ return spec
79
+
80
+
81
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
82
+ global mel_basis
83
+ dtype_device = str(spec.dtype) + "_" + str(spec.device)
84
+ fmax_dtype_device = str(fmax) + "_" + dtype_device
85
+ if fmax_dtype_device not in mel_basis:
86
+ mel = librosa_mel_fn(
87
+ sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
88
+ )
89
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
90
+ dtype=spec.dtype, device=spec.device
91
+ )
92
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
93
+ spec = spectral_normalize_torch(spec)
94
+ return spec
95
+
96
+
97
+ def mel_spectrogram_torch(
98
+ y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False
99
+ ):
100
+ if torch.min(y) < -1.0:
101
+ print("min value is ", torch.min(y))
102
+ if torch.max(y) > 1.0:
103
+ print("max value is ", torch.max(y))
104
+
105
+ global mel_basis, hann_window
106
+ dtype_device = str(y.dtype) + "_" + str(y.device)
107
+ fmax_dtype_device = str(fmax) + "_" + dtype_device
108
+ wnsize_dtype_device = str(win_size) + "_" + dtype_device
109
+ if fmax_dtype_device not in mel_basis:
110
+ mel = librosa_mel_fn(
111
+ sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
112
+ )
113
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
114
+ dtype=y.dtype, device=y.device
115
+ )
116
+ if wnsize_dtype_device not in hann_window:
117
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
118
+ dtype=y.dtype, device=y.device
119
+ )
120
+
121
+ y = torch.nn.functional.pad(
122
+ y.unsqueeze(1),
123
+ (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
124
+ mode="reflect",
125
+ )
126
+ y = y.squeeze(1)
127
+
128
+ spec = torch.stft(
129
+ y,
130
+ n_fft,
131
+ hop_length=hop_size,
132
+ win_length=win_size,
133
+ window=hann_window[wnsize_dtype_device],
134
+ center=center,
135
+ pad_mode="reflect",
136
+ normalized=False,
137
+ onesided=True,
138
+ return_complex=False,
139
+ )
140
+
141
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
142
+
143
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
144
+ spec = spectral_normalize_torch(spec)
145
+
146
+ return spec
model_assets/jvnv-F1/config.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 50,
4
+ "eval_interval": 1000,
5
+ "save_compressed_models": true,
6
+ "seed": 42,
7
+ "epochs": 100,
8
+ "learning_rate": 0.0002,
9
+ "betas": [0.8, 0.99],
10
+ "eps": 1e-9,
11
+ "batch_size": 4,
12
+ "fp16_run": false,
13
+ "lr_decay": 0.99995,
14
+ "segment_size": 16384,
15
+ "init_lr_ratio": 1,
16
+ "warmup_epochs": 0,
17
+ "c_mel": 45,
18
+ "c_kl": 1.0,
19
+ "skip_optimizer": true
20
+ },
21
+ "data": {
22
+ "training_files": "Data/jvnv-F1/filelists/train.list",
23
+ "validation_files": "Data/jvnv-F1/filelists/val.list",
24
+ "max_wav_value": 32768.0,
25
+ "sampling_rate": 44100,
26
+ "filter_length": 2048,
27
+ "hop_length": 512,
28
+ "win_length": 2048,
29
+ "n_mel_channels": 128,
30
+ "mel_fmin": 0.0,
31
+ "mel_fmax": null,
32
+ "add_blank": true,
33
+ "n_speakers": 1,
34
+ "cleaned_text": true,
35
+ "spk2id": {
36
+ "jvnv-F1": 0
37
+ },
38
+ "num_styles": 7,
39
+ "style2id": {
40
+ "Neutral": 0,
41
+ "Angry": 1,
42
+ "Disgust": 2,
43
+ "Fear": 3,
44
+ "Happy": 4,
45
+ "Sad": 5,
46
+ "Surprise": 6
47
+ }
48
+ },
49
+ "model": {
50
+ "use_spk_conditioned_encoder": true,
51
+ "use_noise_scaled_mas": true,
52
+ "use_mel_posterior_encoder": false,
53
+ "use_duration_discriminator": true,
54
+ "inter_channels": 192,
55
+ "hidden_channels": 192,
56
+ "filter_channels": 768,
57
+ "n_heads": 2,
58
+ "n_layers": 6,
59
+ "kernel_size": 3,
60
+ "p_dropout": 0.1,
61
+ "resblock": "1",
62
+ "resblock_kernel_sizes": [3, 7, 11],
63
+ "resblock_dilation_sizes": [
64
+ [1, 3, 5],
65
+ [1, 3, 5],
66
+ [1, 3, 5]
67
+ ],
68
+ "upsample_rates": [8, 8, 2, 2, 2],
69
+ "upsample_initial_channel": 512,
70
+ "upsample_kernel_sizes": [16, 16, 8, 2, 2],
71
+ "n_layers_q": 3,
72
+ "use_spectral_norm": false,
73
+ "gin_channels": 256
74
+ },
75
+ "version": "1.0"
76
+ }
model_assets/jvnv-F1/jvnv-F1.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f831d5df6a286f844621391df498388b98a681f930d24478cb36c619d74d3596
3
+ size 198768188
model_assets/jvnv-F1/style_vectors.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0cfa1c1dc94d65c69dd5a855e8d93a06603bdde1e7a39474104f16274e819ef
3
+ size 7296
model_assets/jvnv-F2/config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "save_compressed_models": true,
6
+ "seed": 42,
7
+ "epochs": 1000,
8
+ "learning_rate": 0.0002,
9
+ "betas": [0.8, 0.99],
10
+ "eps": 1e-9,
11
+ "batch_size": 4,
12
+ "bf16_run": false,
13
+ "lr_decay": 0.99995,
14
+ "segment_size": 16384,
15
+ "init_lr_ratio": 1,
16
+ "warmup_epochs": 0,
17
+ "c_mel": 45,
18
+ "c_kl": 1.0,
19
+ "skip_optimizer": true,
20
+ "freeze_ZH_bert": false,
21
+ "freeze_JP_bert": false,
22
+ "freeze_EN_bert": false
23
+ },
24
+ "data": {
25
+ "training_files": "Data/jvnv-F2/filelists/train.list",
26
+ "validation_files": "Data/jvnv-F2/filelists/val.list",
27
+ "max_wav_value": 32768.0,
28
+ "sampling_rate": 44100,
29
+ "filter_length": 2048,
30
+ "hop_length": 512,
31
+ "win_length": 2048,
32
+ "n_mel_channels": 128,
33
+ "mel_fmin": 0.0,
34
+ "mel_fmax": null,
35
+ "add_blank": true,
36
+ "n_speakers": 1,
37
+ "cleaned_text": true,
38
+ "spk2id": {
39
+ "jvnv-F2": 0
40
+ },
41
+ "num_styles": 7,
42
+ "style2id": {
43
+ "Neutral": 0,
44
+ "Anger": 1,
45
+ "Disgust": 2,
46
+ "Fear": 3,
47
+ "Happy": 4,
48
+ "Sad": 5,
49
+ "Surprise": 6
50
+ }
51
+ },
52
+ "model": {
53
+ "use_spk_conditioned_encoder": true,
54
+ "use_noise_scaled_mas": true,
55
+ "use_mel_posterior_encoder": false,
56
+ "use_duration_discriminator": true,
57
+ "inter_channels": 192,
58
+ "hidden_channels": 192,
59
+ "filter_channels": 768,
60
+ "n_heads": 2,
61
+ "n_layers": 6,
62
+ "kernel_size": 3,
63
+ "p_dropout": 0.1,
64
+ "resblock": "1",
65
+ "resblock_kernel_sizes": [3, 7, 11],
66
+ "resblock_dilation_sizes": [
67
+ [1, 3, 5],
68
+ [1, 3, 5],
69
+ [1, 3, 5]
70
+ ],
71
+ "upsample_rates": [8, 8, 2, 2, 2],
72
+ "upsample_initial_channel": 512,
73
+ "upsample_kernel_sizes": [16, 16, 8, 2, 2],
74
+ "n_layers_q": 3,
75
+ "use_spectral_norm": false,
76
+ "gin_channels": 256
77
+ },
78
+ "version": "1.0"
79
+ }
model_assets/jvnv-F2/jvnv-F2.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:423535bd82e29dd1509c69fd57843f0608d0684423f2266ca1bc7eb09965fd2a
3
+ size 198768188
model_assets/jvnv-F2/style_vectors.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c4a80802dee330b425d7941a1af5d6f8025d7bf6d57002ccdf6d8c4f14e85b3
3
+ size 7296
model_assets/jvnv-M1/config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "jvnv-M1",
3
+ "train": {
4
+ "log_interval": 200,
5
+ "eval_interval": 1000,
6
+ "seed": 42,
7
+ "epochs": 1000,
8
+ "learning_rate": 0.0002,
9
+ "betas": [0.8, 0.99],
10
+ "eps": 1e-9,
11
+ "batch_size": 4,
12
+ "bf16_run": true,
13
+ "lr_decay": 0.99995,
14
+ "segment_size": 16384,
15
+ "init_lr_ratio": 1,
16
+ "warmup_epochs": 0,
17
+ "c_mel": 45,
18
+ "c_kl": 1.0,
19
+ "skip_optimizer": true,
20
+ "freeze_ZH_bert": false,
21
+ "freeze_JP_bert": false,
22
+ "freeze_EN_bert": false
23
+ },
24
+ "data": {
25
+ "training_files": "Data/jvnv-M1/train.list",
26
+ "validation_files": "Data/jvnv-M1/val.list",
27
+ "max_wav_value": 32768.0,
28
+ "sampling_rate": 44100,
29
+ "filter_length": 2048,
30
+ "hop_length": 512,
31
+ "win_length": 2048,
32
+ "n_mel_channels": 128,
33
+ "mel_fmin": 0.0,
34
+ "mel_fmax": null,
35
+ "add_blank": true,
36
+ "n_speakers": 1,
37
+ "cleaned_text": true,
38
+ "spk2id": {
39
+ "jvnv-F2": 0
40
+ },
41
+ "num_styles": 7,
42
+ "style2id": {
43
+ "Neutral": 0,
44
+ "Angry": 1,
45
+ "Disgust": 2,
46
+ "Fear": 3,
47
+ "Happy": 4,
48
+ "Sad": 5,
49
+ "Surprise": 6
50
+ }
51
+ },
52
+ "model": {
53
+ "use_spk_conditioned_encoder": true,
54
+ "use_noise_scaled_mas": true,
55
+ "use_mel_posterior_encoder": false,
56
+ "use_duration_discriminator": true,
57
+ "inter_channels": 192,
58
+ "hidden_channels": 192,
59
+ "filter_channels": 768,
60
+ "n_heads": 2,
61
+ "n_layers": 6,
62
+ "kernel_size": 3,
63
+ "p_dropout": 0.1,
64
+ "resblock": "1",
65
+ "resblock_kernel_sizes": [3, 7, 11],
66
+ "resblock_dilation_sizes": [
67
+ [1, 3, 5],
68
+ [1, 3, 5],
69
+ [1, 3, 5]
70
+ ],
71
+ "upsample_rates": [8, 8, 2, 2, 2],
72
+ "upsample_initial_channel": 512,
73
+ "upsample_kernel_sizes": [16, 16, 8, 2, 2],
74
+ "n_layers_q": 3,
75
+ "use_spectral_norm": false,
76
+ "gin_channels": 256
77
+ },
78
+ "version": "1.0"
79
+ }
model_assets/jvnv-M1/jvnv-M1.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9cbf823fcef37b98b307047f34b235c3ff5c48eaaf5c3fde313b37bdb79f2e71
3
+ size 198768188
model_assets/jvnv-M1/style_vectors.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30586c87133de056ce61557bcebd4e69f0ebae19cc9eb0cce52582714eabbe8e
3
+ size 7296
model_assets/jvnv-M2/config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "jvnv-M2",
3
+ "train": {
4
+ "log_interval": 200,
5
+ "eval_interval": 1000,
6
+ "seed": 42,
7
+ "epochs": 100,
8
+ "learning_rate": 0.0002,
9
+ "betas": [0.8, 0.99],
10
+ "eps": 1e-9,
11
+ "batch_size": 4,
12
+ "bf16_run": true,
13
+ "lr_decay": 0.99995,
14
+ "segment_size": 16384,
15
+ "init_lr_ratio": 1,
16
+ "warmup_epochs": 0,
17
+ "c_mel": 45,
18
+ "c_kl": 1.0,
19
+ "skip_optimizer": false,
20
+ "freeze_ZH_bert": false,
21
+ "freeze_JP_bert": false,
22
+ "freeze_EN_bert": false
23
+ },
24
+ "data": {
25
+ "training_files": "Data/jvnv-M2/train.list",
26
+ "validation_files": "Data/jvnv-M2/val.list",
27
+ "max_wav_value": 32768.0,
28
+ "sampling_rate": 44100,
29
+ "filter_length": 2048,
30
+ "hop_length": 512,
31
+ "win_length": 2048,
32
+ "n_mel_channels": 128,
33
+ "mel_fmin": 0.0,
34
+ "mel_fmax": null,
35
+ "add_blank": true,
36
+ "n_speakers": 1,
37
+ "cleaned_text": true,
38
+ "num_styles": 7,
39
+ "style2id": {
40
+ "Neutral": 0,
41
+ "Angry": 1,
42
+ "Disgust": 2,
43
+ "Fear": 3,
44
+ "Happy": 4,
45
+ "Sad": 5,
46
+ "Surprise": 6
47
+ },
48
+ "spk2id": {
49
+ "jvnv-F2": 0
50
+ }
51
+ },
52
+ "model": {
53
+ "use_spk_conditioned_encoder": true,
54
+ "use_noise_scaled_mas": true,
55
+ "use_mel_posterior_encoder": false,
56
+ "use_duration_discriminator": true,
57
+ "inter_channels": 192,
58
+ "hidden_channels": 192,
59
+ "filter_channels": 768,
60
+ "n_heads": 2,
61
+ "n_layers": 6,
62
+ "kernel_size": 3,
63
+ "p_dropout": 0.1,
64
+ "resblock": "1",
65
+ "resblock_kernel_sizes": [3, 7, 11],
66
+ "resblock_dilation_sizes": [
67
+ [1, 3, 5],
68
+ [1, 3, 5],
69
+ [1, 3, 5]
70
+ ],
71
+ "upsample_rates": [8, 8, 2, 2, 2],
72
+ "upsample_initial_channel": 512,
73
+ "upsample_kernel_sizes": [16, 16, 8, 2, 2],
74
+ "n_layers_q": 3,
75
+ "use_spectral_norm": false,
76
+ "gin_channels": 256
77
+ },
78
+ "version": "1.0"
79
+ }