Banaxi-Tech commited on
Commit
9364e9f
·
verified ·
1 Parent(s): 3b2af5a

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ logo.png filter=lfs diff=lfs merge=lfs -text
FP32/vocoder.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c504b332bc90f11560a3810ba033b239fc91d4643dc1a0acd6b2fb031a4c9441
3
+ size 14237380
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Banaxi-Tech
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,3 +1,138 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - text-to-speech
7
+ - tts
8
+ - speech
9
+ - tacotron
10
+ - hifigan
11
+ - ljspeech
12
+ library_name: pytorch
13
+ pipeline_tag: text-to-speech
14
+ datasets:
15
+ - lj_speech
16
  ---
17
+
18
+ # BananaMind TTS V2
19
+
20
+ ![BananaMind TTS V2 logo](logo.png)
21
+
22
+ BananaMind TTS V2 is a small from-scratch English single-speaker text-to-speech model trained on LJSpeech. It combines the Tacotron-lite acoustic model with a self-trained HiFi-GAN vocoder, so it no longer depends on the Griffin-Lim fallback used in V1.
23
+
24
+ This release is named V2 for packaging and release purposes. In the local training code, the HiFi-GAN work was sometimes called V3.
25
+
26
+ Training code: https://github.com/Banaxi-Tech/bananamind-tts-v1-training-code
27
+
28
+ ## What This Model Is
29
+
30
+ - English-only TTS
31
+ - Single speaker
32
+ - Character-input Tacotron-lite acoustic model
33
+ - Self-trained HiFi-GAN neural vocoder
34
+ - Trained from scratch on LJSpeech
35
+ - 22.05 kHz audio output
36
+ - Weights provided as `safetensors` for inference
37
+
38
+ ## What This Model Is Not
39
+
40
+ - Not voice cloning
41
+ - No speaker embeddings
42
+ - No reference audio conditioning
43
+ - No multi-speaker support
44
+ - No pretrained TTS checkpoint was used
45
+
46
+ ## Files
47
+
48
+ - `model.safetensors`: Tacotron-lite acoustic model weights
49
+ - `vocoder.safetensors`: default BF16 HiFi-GAN generator-only vocoder
50
+ - `FP32/vocoder.safetensors`: FP32 HiFi-GAN generator-only vocoder
51
+ - `full_vocoder/vocoder.pt`: full epoch twenty eight vocoder training checkpoint with generator, discriminators, optimizers, config, epoch, and step
52
+ - `config.json`: Hugging Face custom model config for `AutoModel`
53
+ - `configuration_bananamind_tts.py`: custom `AutoConfig` implementation
54
+ - `modeling_bananamind_tts.py`: custom `AutoModel` implementation with HiFi-GAN loading
55
+ - `model_config.json`: sidecar metadata with acoustic config, tokenizer, vocoder metadata, epoch, and step
56
+ - `generate.py`: local generation example
57
+
58
+ ## Usage
59
+
60
+ Install runtime dependencies:
61
+
62
+ ```bash
63
+ pip install torch numpy safetensors transformers huggingface_hub
64
+ ```
65
+
66
+ Use with Transformers remote code:
67
+
68
+ ```python
69
+ import torch
70
+ from transformers import AutoModel
71
+
72
+ model = AutoModel.from_pretrained(
73
+ "Banaxi-Tech/BananaMind-TTS-V2",
74
+ trust_remote_code=True,
75
+ )
76
+ model.eval()
77
+
78
+ with torch.inference_mode():
79
+ out = model.tts(
80
+ "Hello from BananaMind TTS version two.",
81
+ normalize_wav=True,
82
+ )
83
+
84
+ model.save_wav("sample.wav", out.waveform, out.sample_rate)
85
+ ```
86
+
87
+ From this folder, you can also run:
88
+
89
+ ```bash
90
+ python generate.py
91
+ ```
92
+
93
+ ## Vocoder Options
94
+
95
+ The default vocoder is `vocoder.safetensors`, a BF16 generator-only HiFi-GAN export. It is small and intended for normal inference.
96
+
97
+ To switch to the FP32 generator-only vocoder:
98
+
99
+ ```python
100
+ model.reload_vocoder("FP32/vocoder.safetensors", dtype="float32")
101
+ ```
102
+
103
+ The full training vocoder checkpoint is included at `full_vocoder/vocoder.pt`. It is much larger because it includes the discriminators and optimizer states needed for training resume. It is not needed for normal text-to-speech generation.
104
+
105
+ ## Text Normalization Note
106
+
107
+ The tokenizer is character based and strips unsupported characters, including digits. Write numbers as words:
108
+
109
+ - Use `one plus one is two`
110
+ - Not `1 plus 1 is 2`
111
+
112
+ ## Training Summary
113
+
114
+ - Acoustic model type: Tacotron-lite
115
+ - Vocoder type: HiFi-GAN generator
116
+ - Dataset: LJSpeech
117
+ - Sample rate: 22050 Hz
118
+ - Acoustic epoch: 80
119
+ - Acoustic step: 64529
120
+ - Vocoder epoch: 28
121
+ - Vocoder step: 42000
122
+ - Approximate acoustic parameters: 9.49M
123
+ - Approximate vocoder generator parameters: 3.56M
124
+
125
+ ## Current Limitations
126
+
127
+ - Character input is less robust than phoneme input for English pronunciation.
128
+ - Numbers and unusual symbols must be normalized before synthesis.
129
+ - Quality is limited by LJSpeech-only training and a small single-speaker architecture.
130
+ - This is a fixed-voice research/demo model, not a production voice system.
131
+
132
+ ## Intended Use
133
+
134
+ This model is intended for English single-speaker text-to-speech generation with the included custom Transformers model code.
135
+
136
+ ## Out-of-Scope Use
137
+
138
+ Do not present this model as a voice cloning model or use it to impersonate any person. It has no voice-cloning capability.
config.json ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "bananamind_tts",
3
+ "architectures": [
4
+ "BananaMindTTSModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_bananamind_tts.BananaMindTTSConfig",
8
+ "AutoModel": "modeling_bananamind_tts.BananaMindTTSModel"
9
+ },
10
+ "banana_config": {
11
+ "project": {
12
+ "name": "BananaTTS-20M-Tacotron",
13
+ "seed": 1337
14
+ },
15
+ "dataset": {
16
+ "name": "MikhailT/lj-speech",
17
+ "fallback_name": "keithito/lj_speech",
18
+ "split": "train",
19
+ "cache_dir": "data/cache/ljspeech_22050",
20
+ "validation_ratio": 0.02,
21
+ "limit": null,
22
+ "percent": null,
23
+ "min_audio_seconds": 0.25,
24
+ "max_audio_seconds": 20.0
25
+ },
26
+ "text": {
27
+ "use_phonemes": false,
28
+ "keep_punctuation": true,
29
+ "max_tokens": 256
30
+ },
31
+ "audio": {
32
+ "sample_rate": 22050,
33
+ "n_fft": 1024,
34
+ "hop_length": 256,
35
+ "win_length": 1024,
36
+ "n_mels": 80,
37
+ "f_min": 0.0,
38
+ "f_max": 8000.0,
39
+ "power": 1.0,
40
+ "griffin_lim_iters": 32,
41
+ "mel_stats": {
42
+ "mean": -1.2497830139289026,
43
+ "std": 1.9540364596741207,
44
+ "min": -11.512925148010254,
45
+ "max": 6.246073246002197,
46
+ "count": 593805760,
47
+ "normalized_training": true
48
+ }
49
+ },
50
+ "model": {
51
+ "type": "tacotron_lite",
52
+ "hidden_size": 256,
53
+ "reduction_factor": 4,
54
+ "encoder_conv_layers": 3,
55
+ "encoder_dropout": 0.15,
56
+ "prenet_sizes": [
57
+ 256,
58
+ 128
59
+ ],
60
+ "attention_dim": 128,
61
+ "decoder_dim": 512,
62
+ "location_channels": 32,
63
+ "location_kernel_size": 31,
64
+ "postnet_channels": 512,
65
+ "postnet_layers": 5,
66
+ "dropout": 0.5,
67
+ "postnet_dropout": 0.5,
68
+ "max_decoder_steps": 1200,
69
+ "stop_threshold": 0.55,
70
+ "attention_window": 12
71
+ },
72
+ "training": {
73
+ "batch_size": 16,
74
+ "epochs": 80,
75
+ "learning_rate": 0.001,
76
+ "weight_decay": 1e-06,
77
+ "grad_clip": 1.0,
78
+ "log_interval": 20,
79
+ "val_interval": 500,
80
+ "save_interval": 1000,
81
+ "num_workers": 4,
82
+ "checkpoints_dir": "checkpoints_tacotron",
83
+ "runs_dir": "runs",
84
+ "resume": null,
85
+ "mel_loss_weight": 1.0,
86
+ "stop_loss_weight": 0.5,
87
+ "guided_attention_weight": 1.0,
88
+ "guided_attention_sigma": 0.4
89
+ }
90
+ },
91
+ "tokenizer": {
92
+ "symbols": [
93
+ "<pad>",
94
+ "<unk>",
95
+ "<bos>",
96
+ "<eos>",
97
+ "a",
98
+ "b",
99
+ "c",
100
+ "d",
101
+ "e",
102
+ "f",
103
+ "g",
104
+ "h",
105
+ "i",
106
+ "j",
107
+ "k",
108
+ "l",
109
+ "m",
110
+ "n",
111
+ "o",
112
+ "p",
113
+ "q",
114
+ "r",
115
+ "s",
116
+ "t",
117
+ "u",
118
+ "v",
119
+ "w",
120
+ "x",
121
+ "y",
122
+ "z",
123
+ " ",
124
+ "'",
125
+ ".",
126
+ ",",
127
+ "!",
128
+ "?",
129
+ ";",
130
+ ":",
131
+ "-"
132
+ ],
133
+ "use_phonemes": false,
134
+ "keep_punctuation": true
135
+ },
136
+ "vocoder": {
137
+ "enabled": true,
138
+ "type": "hifigan",
139
+ "default_weights": "vocoder.safetensors",
140
+ "default_dtype": "bfloat16",
141
+ "fp32_weights": "FP32/vocoder.safetensors",
142
+ "full_checkpoint": "full_vocoder/vocoder.pt",
143
+ "epoch": 28,
144
+ "step": 42000,
145
+ "generator_parameters": 3555649,
146
+ "config": {
147
+ "type": "hifigan",
148
+ "checkpoint": "checkpoints_vocoder/vocoder_latest.pt",
149
+ "initial_channels": 256,
150
+ "upsample_rates": [
151
+ 8,
152
+ 8,
153
+ 2,
154
+ 2
155
+ ],
156
+ "upsample_kernel_sizes": [
157
+ 16,
158
+ 16,
159
+ 4,
160
+ 4
161
+ ],
162
+ "resblock_kernel_sizes": [
163
+ 3,
164
+ 7,
165
+ 11
166
+ ],
167
+ "resblock_dilation_sizes": [
168
+ [
169
+ 1,
170
+ 3,
171
+ 5
172
+ ],
173
+ [
174
+ 1,
175
+ 3,
176
+ 5
177
+ ],
178
+ [
179
+ 1,
180
+ 3,
181
+ 5
182
+ ]
183
+ ],
184
+ "leaky_relu_slope": 0.1
185
+ }
186
+ },
187
+ "epoch": 80,
188
+ "step": 64529,
189
+ "torch_dtype": "float32",
190
+ "library_name": "transformers"
191
+ }
configuration_bananamind_tts.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from transformers import PretrainedConfig
4
+
5
+
6
+ class BananaMindTTSConfig(PretrainedConfig):
7
+ model_type = "bananamind_tts"
8
+
9
+ def __init__(
10
+ self,
11
+ banana_config: dict | None = None,
12
+ tokenizer: dict | None = None,
13
+ vocoder: dict | None = None,
14
+ epoch: int | None = None,
15
+ step: int | None = None,
16
+ **kwargs,
17
+ ):
18
+ super().__init__(**kwargs)
19
+ self.banana_config = banana_config or {}
20
+ self.tokenizer = tokenizer or {}
21
+ self.vocoder = vocoder or {}
22
+ self.epoch = epoch
23
+ self.step = step
full_vocoder/vocoder.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30da70d18fb0b057d8c2947dfb54a0ca88c03ae6bb232de103580ba8a366a683
3
+ size 1218226409
generate.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import torch
6
+ from transformers import AutoModel
7
+
8
+
9
+ MODEL_DIR = Path(__file__).resolve().parent
10
+
11
+
12
+ def main() -> None:
13
+ model = AutoModel.from_pretrained(MODEL_DIR, trust_remote_code=True)
14
+ model.eval()
15
+ with torch.inference_mode():
16
+ out = model.tts(
17
+ "This is BananaMind TTS version two with a HiFi GAN vocoder.",
18
+ normalize_wav=True,
19
+ )
20
+ model.save_wav(MODEL_DIR / "sample.wav", out.waveform, out.sample_rate)
21
+ print(f"Saved {MODEL_DIR / 'sample.wav'}")
22
+
23
+
24
+ if __name__ == "__main__":
25
+ main()
logo.png ADDED

Git LFS Details

  • SHA256: 9e90fe4640592f70a089ba3df42778b7885fe37d27a63f86071547c4bc9b72bb
  • Pointer size: 131 Bytes
  • Size of remote file: 343 kB
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdfd95b7c769eaeec3e06dd30f4a557495e3f02fe20376b576702a44a6d0e15d
3
+ size 38009396
model_config.json ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "tacotron_lite",
3
+ "step": 64529,
4
+ "epoch": 80,
5
+ "config": {
6
+ "project": {
7
+ "name": "BananaTTS-20M-Tacotron",
8
+ "seed": 1337
9
+ },
10
+ "dataset": {
11
+ "name": "MikhailT/lj-speech",
12
+ "fallback_name": "keithito/lj_speech",
13
+ "split": "train",
14
+ "cache_dir": "data/cache/ljspeech_22050",
15
+ "validation_ratio": 0.02,
16
+ "limit": null,
17
+ "percent": null,
18
+ "min_audio_seconds": 0.25,
19
+ "max_audio_seconds": 20.0
20
+ },
21
+ "text": {
22
+ "use_phonemes": false,
23
+ "keep_punctuation": true,
24
+ "max_tokens": 256
25
+ },
26
+ "audio": {
27
+ "sample_rate": 22050,
28
+ "n_fft": 1024,
29
+ "hop_length": 256,
30
+ "win_length": 1024,
31
+ "n_mels": 80,
32
+ "f_min": 0.0,
33
+ "f_max": 8000.0,
34
+ "power": 1.0,
35
+ "griffin_lim_iters": 32,
36
+ "mel_stats": {
37
+ "mean": -1.2497830139289026,
38
+ "std": 1.9540364596741207,
39
+ "min": -11.512925148010254,
40
+ "max": 6.246073246002197,
41
+ "count": 593805760,
42
+ "normalized_training": true
43
+ }
44
+ },
45
+ "model": {
46
+ "type": "tacotron_lite",
47
+ "hidden_size": 256,
48
+ "reduction_factor": 4,
49
+ "encoder_conv_layers": 3,
50
+ "encoder_dropout": 0.15,
51
+ "prenet_sizes": [
52
+ 256,
53
+ 128
54
+ ],
55
+ "attention_dim": 128,
56
+ "decoder_dim": 512,
57
+ "location_channels": 32,
58
+ "location_kernel_size": 31,
59
+ "postnet_channels": 512,
60
+ "postnet_layers": 5,
61
+ "dropout": 0.5,
62
+ "postnet_dropout": 0.5,
63
+ "max_decoder_steps": 1200,
64
+ "stop_threshold": 0.55,
65
+ "attention_window": 12
66
+ },
67
+ "training": {
68
+ "batch_size": 16,
69
+ "epochs": 80,
70
+ "learning_rate": 0.001,
71
+ "weight_decay": 1e-06,
72
+ "grad_clip": 1.0,
73
+ "log_interval": 20,
74
+ "val_interval": 500,
75
+ "save_interval": 1000,
76
+ "num_workers": 4,
77
+ "checkpoints_dir": "checkpoints_tacotron",
78
+ "runs_dir": "runs",
79
+ "resume": null,
80
+ "mel_loss_weight": 1.0,
81
+ "stop_loss_weight": 0.5,
82
+ "guided_attention_weight": 1.0,
83
+ "guided_attention_sigma": 0.4
84
+ }
85
+ },
86
+ "tokenizer": {
87
+ "symbols": [
88
+ "<pad>",
89
+ "<unk>",
90
+ "<bos>",
91
+ "<eos>",
92
+ "a",
93
+ "b",
94
+ "c",
95
+ "d",
96
+ "e",
97
+ "f",
98
+ "g",
99
+ "h",
100
+ "i",
101
+ "j",
102
+ "k",
103
+ "l",
104
+ "m",
105
+ "n",
106
+ "o",
107
+ "p",
108
+ "q",
109
+ "r",
110
+ "s",
111
+ "t",
112
+ "u",
113
+ "v",
114
+ "w",
115
+ "x",
116
+ "y",
117
+ "z",
118
+ " ",
119
+ "'",
120
+ ".",
121
+ ",",
122
+ "!",
123
+ "?",
124
+ ";",
125
+ ":",
126
+ "-"
127
+ ],
128
+ "use_phonemes": false,
129
+ "keep_punctuation": true
130
+ },
131
+ "weights": "model.safetensors",
132
+ "vocoder": {
133
+ "enabled": true,
134
+ "type": "hifigan",
135
+ "default_weights": "vocoder.safetensors",
136
+ "default_dtype": "bfloat16",
137
+ "fp32_weights": "FP32/vocoder.safetensors",
138
+ "full_checkpoint": "full_vocoder/vocoder.pt",
139
+ "epoch": 28,
140
+ "step": 42000,
141
+ "generator_parameters": 3555649,
142
+ "config": {
143
+ "type": "hifigan",
144
+ "checkpoint": "checkpoints_vocoder/vocoder_latest.pt",
145
+ "initial_channels": 256,
146
+ "upsample_rates": [
147
+ 8,
148
+ 8,
149
+ 2,
150
+ 2
151
+ ],
152
+ "upsample_kernel_sizes": [
153
+ 16,
154
+ 16,
155
+ 4,
156
+ 4
157
+ ],
158
+ "resblock_kernel_sizes": [
159
+ 3,
160
+ 7,
161
+ 11
162
+ ],
163
+ "resblock_dilation_sizes": [
164
+ [
165
+ 1,
166
+ 3,
167
+ 5
168
+ ],
169
+ [
170
+ 1,
171
+ 3,
172
+ 5
173
+ ],
174
+ [
175
+ 1,
176
+ 3,
177
+ 5
178
+ ]
179
+ ],
180
+ "leaky_relu_slope": 0.1
181
+ }
182
+ }
183
+ }
modeling_bananamind_tts.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import re
5
+ import string
6
+ import wave
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ import torch
13
+ from torch import nn
14
+ import torch.nn.functional as F
15
+ from transformers import PreTrainedModel
16
+
17
+ from .configuration_bananamind_tts import BananaMindTTSConfig
18
+
19
+
20
+ PAD = "<pad>"
21
+ UNK = "<unk>"
22
+ BOS = "<bos>"
23
+ EOS = "<eos>"
24
+ ALLOWED = set(string.ascii_lowercase + " '.,!?;:-")
25
+
26
+
27
+ def normalize_text(text: str, keep_punctuation: bool = True) -> str:
28
+ text = text.lower()
29
+ text = text.replace("\u2019", "'").replace("\u2018", "'")
30
+ text = text.replace("\u201c", '"').replace("\u201d", '"')
31
+ text = text.replace("&", " and ")
32
+ allowed = ALLOWED if keep_punctuation else set(string.ascii_lowercase + " '")
33
+ text = "".join(ch if ch in allowed else " " for ch in text)
34
+ return re.sub(r"\s+", " ", text).strip()
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class TextTokenizer:
39
+ symbols: list[str]
40
+ keep_punctuation: bool = True
41
+
42
+ @property
43
+ def symbol_to_id(self) -> dict[str, int]:
44
+ return {s: i for i, s in enumerate(self.symbols)}
45
+
46
+ @property
47
+ def pad_id(self) -> int:
48
+ return self.symbol_to_id[PAD]
49
+
50
+ @property
51
+ def bos_id(self) -> int:
52
+ return self.symbol_to_id[BOS]
53
+
54
+ @property
55
+ def eos_id(self) -> int:
56
+ return self.symbol_to_id[EOS]
57
+
58
+ @property
59
+ def vocab_size(self) -> int:
60
+ return len(self.symbols)
61
+
62
+ def encode(self, text: str) -> list[int]:
63
+ normalized = normalize_text(text, keep_punctuation=self.keep_punctuation)
64
+ stoi = self.symbol_to_id
65
+ ids = [stoi.get(ch, stoi[UNK]) for ch in normalized]
66
+ return [self.bos_id] + ids + [self.eos_id]
67
+
68
+
69
+ def tokenizer_from_config(config: BananaMindTTSConfig) -> TextTokenizer:
70
+ data = config.tokenizer
71
+ return TextTokenizer(symbols=list(data["symbols"]), keep_punctuation=bool(data.get("keep_punctuation", True)))
72
+
73
+
74
+ def make_padding_mask(lengths: torch.Tensor, max_len: int | None = None) -> torch.Tensor:
75
+ max_len = int(max_len or lengths.max().item())
76
+ return torch.arange(max_len, device=lengths.device).unsqueeze(0) >= lengths.unsqueeze(1)
77
+
78
+
79
+ class Prenet(nn.Module):
80
+ def __init__(self, in_dim: int, sizes: list[int], dropout: float):
81
+ super().__init__()
82
+ layers: list[nn.Module] = []
83
+ last = in_dim
84
+ for size in sizes:
85
+ layers.extend([nn.Linear(last, size), nn.ReLU(), nn.Dropout(dropout)])
86
+ last = size
87
+ self.net = nn.Sequential(*layers)
88
+
89
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
90
+ return self.net(x)
91
+
92
+
93
+ class ConvBlock(nn.Module):
94
+ def __init__(self, channels: int, kernel_size: int, dropout: float):
95
+ super().__init__()
96
+ self.conv = nn.Conv1d(channels, channels, kernel_size, padding=kernel_size // 2)
97
+ self.bn = nn.BatchNorm1d(channels)
98
+ self.dropout = nn.Dropout(dropout)
99
+
100
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
101
+ return self.dropout(F.relu(self.bn(self.conv(x))))
102
+
103
+
104
+ class Encoder(nn.Module):
105
+ def __init__(self, vocab_size: int, hidden_size: int, pad_id: int, dropout: float, conv_layers: int):
106
+ super().__init__()
107
+ self.embedding = nn.Embedding(vocab_size, hidden_size, padding_idx=pad_id)
108
+ self.convs = nn.ModuleList([ConvBlock(hidden_size, 5, dropout) for _ in range(conv_layers)])
109
+ self.lstm = nn.LSTM(hidden_size, hidden_size // 2, num_layers=1, batch_first=True, bidirectional=True)
110
+
111
+ def forward(self, tokens: torch.Tensor) -> torch.Tensor:
112
+ x = self.embedding(tokens).transpose(1, 2)
113
+ for conv in self.convs:
114
+ x = conv(x)
115
+ self.lstm.flatten_parameters()
116
+ out, _ = self.lstm(x.transpose(1, 2))
117
+ return out
118
+
119
+
120
+ class LocationSensitiveAttention(nn.Module):
121
+ def __init__(self, query_dim: int, memory_dim: int, attention_dim: int, location_channels: int, location_kernel: int):
122
+ super().__init__()
123
+ self.query_layer = nn.Linear(query_dim, attention_dim, bias=False)
124
+ self.memory_layer = nn.Linear(memory_dim, attention_dim, bias=False)
125
+ self.location_conv = nn.Conv1d(2, location_channels, location_kernel, padding=location_kernel // 2, bias=False)
126
+ self.location_layer = nn.Linear(location_channels, attention_dim, bias=False)
127
+ self.v = nn.Linear(attention_dim, 1, bias=True)
128
+
129
+ def forward(
130
+ self,
131
+ query: torch.Tensor,
132
+ memory: torch.Tensor,
133
+ processed_memory: torch.Tensor,
134
+ attention_weights: torch.Tensor,
135
+ attention_cum: torch.Tensor,
136
+ mask: torch.Tensor,
137
+ window_mask: torch.Tensor | None = None,
138
+ ) -> tuple[torch.Tensor, torch.Tensor]:
139
+ location = torch.stack([attention_weights, attention_cum], dim=1)
140
+ location = self.location_conv(location).transpose(1, 2)
141
+ energies = self.v(
142
+ torch.tanh(self.query_layer(query).unsqueeze(1) + processed_memory + self.location_layer(location))
143
+ ).squeeze(-1)
144
+ energies = energies.masked_fill(mask, -1e4)
145
+ if window_mask is not None:
146
+ energies = energies.masked_fill(window_mask, -1e4)
147
+ weights = F.softmax(energies, dim=-1)
148
+ context = torch.bmm(weights.unsqueeze(1), memory).squeeze(1)
149
+ return context, weights
150
+
151
+
152
+ class Postnet(nn.Module):
153
+ def __init__(self, n_mels: int, channels: int, layers: int, dropout: float):
154
+ super().__init__()
155
+ modules: list[nn.Module] = []
156
+ in_channels = n_mels
157
+ for idx in range(layers):
158
+ out_channels = n_mels if idx == layers - 1 else channels
159
+ modules.extend([nn.Conv1d(in_channels, out_channels, 5, padding=2), nn.BatchNorm1d(out_channels)])
160
+ if idx < layers - 1:
161
+ modules.append(nn.Tanh())
162
+ modules.append(nn.Dropout(dropout))
163
+ in_channels = out_channels
164
+ self.net = nn.Sequential(*modules)
165
+
166
+ def forward(self, mel: torch.Tensor) -> torch.Tensor:
167
+ return self.net(mel.transpose(1, 2)).transpose(1, 2)
168
+
169
+
170
+ class HiFiGANResBlock(nn.Module):
171
+ def __init__(self, channels: int, kernel_size: int, dilations: list[int], slope: float = 0.1):
172
+ super().__init__()
173
+ self.slope = slope
174
+ self.convs1 = nn.ModuleList(
175
+ [
176
+ nn.Conv1d(
177
+ channels,
178
+ channels,
179
+ kernel_size,
180
+ padding=(kernel_size * dilation - dilation) // 2,
181
+ dilation=dilation,
182
+ )
183
+ for dilation in dilations
184
+ ]
185
+ )
186
+ self.convs2 = nn.ModuleList(
187
+ [nn.Conv1d(channels, channels, kernel_size, padding=(kernel_size - 1) // 2) for _ in dilations]
188
+ )
189
+
190
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
191
+ for conv1, conv2 in zip(self.convs1, self.convs2, strict=True):
192
+ residual = x
193
+ y = F.leaky_relu(x, self.slope)
194
+ y = conv1(y)
195
+ y = F.leaky_relu(y, self.slope)
196
+ y = conv2(y)
197
+ x = y + residual
198
+ return x
199
+
200
+
201
+ class HiFiGANGenerator(nn.Module):
202
+ def __init__(self, n_mels: int, config: dict[str, Any]):
203
+ super().__init__()
204
+ channels = int(config.get("initial_channels", 256))
205
+ upsample_rates = [int(x) for x in config.get("upsample_rates", [8, 8, 2, 2])]
206
+ upsample_kernels = [int(x) for x in config.get("upsample_kernel_sizes", [16, 16, 4, 4])]
207
+ resblock_kernels = [int(x) for x in config.get("resblock_kernel_sizes", [3, 7, 11])]
208
+ resblock_dilations = config.get("resblock_dilation_sizes", [[1, 3, 5], [1, 3, 5], [1, 3, 5]])
209
+ self.slope = float(config.get("leaky_relu_slope", 0.1))
210
+ self.conv_pre = nn.Conv1d(n_mels, channels, kernel_size=7, padding=3)
211
+ self.ups = nn.ModuleList()
212
+ self.resblocks = nn.ModuleList()
213
+ current_channels = channels
214
+ for rate, kernel in zip(upsample_rates, upsample_kernels, strict=True):
215
+ next_channels = current_channels // 2
216
+ self.ups.append(
217
+ nn.ConvTranspose1d(
218
+ current_channels,
219
+ next_channels,
220
+ kernel_size=kernel,
221
+ stride=rate,
222
+ padding=(kernel - rate) // 2,
223
+ )
224
+ )
225
+ for kernel_size, dilations in zip(resblock_kernels, resblock_dilations, strict=True):
226
+ self.resblocks.append(HiFiGANResBlock(next_channels, int(kernel_size), [int(d) for d in dilations], self.slope))
227
+ current_channels = next_channels
228
+ self.num_resblocks = len(resblock_kernels)
229
+ self.conv_post = nn.Conv1d(current_channels, 1, kernel_size=7, padding=3)
230
+
231
+ def forward(self, mel: torch.Tensor) -> torch.Tensor:
232
+ x = self.conv_pre(mel)
233
+ for idx, upsample in enumerate(self.ups):
234
+ x = F.leaky_relu(x, self.slope)
235
+ x = upsample(x)
236
+ block_offset = idx * self.num_resblocks
237
+ xs = [self.resblocks[block_offset + block_idx](x) for block_idx in range(self.num_resblocks)]
238
+ x = torch.stack(xs, dim=0).mean(dim=0)
239
+ x = F.leaky_relu(x, self.slope)
240
+ return torch.tanh(self.conv_post(x)).squeeze(1)
241
+
242
+
243
+ @dataclass
244
+ class TTSOutput:
245
+ waveform: torch.Tensor
246
+ sample_rate: int
247
+ mel: torch.Tensor
248
+ alignments: torch.Tensor
249
+ stop_logits: torch.Tensor
250
+
251
+
252
+ def _resolve_asset(config: BananaMindTTSConfig, filename: str) -> Path:
253
+ model_id = getattr(config, "_name_or_path", "") or ""
254
+ if model_id and Path(model_id).exists():
255
+ return Path(model_id) / filename
256
+ local = Path(filename)
257
+ if local.exists():
258
+ return local
259
+ try:
260
+ from huggingface_hub import hf_hub_download
261
+
262
+ return Path(hf_hub_download(repo_id=model_id, filename=filename))
263
+ except Exception as exc:
264
+ raise FileNotFoundError(f"Could not resolve model asset {filename!r} for {model_id!r}") from exc
265
+
266
+
267
+ class BananaMindTTSModel(PreTrainedModel):
268
+ config_class = BananaMindTTSConfig
269
+ base_model_prefix = ""
270
+ main_input_name = "tokens"
271
+ _tied_weights_keys: list[str] = []
272
+ all_tied_weights_keys: dict[str, str] = {}
273
+ _keys_to_ignore_on_load_missing = [r"vocoder_generator\..*"]
274
+
275
+ def __init__(self, config: BananaMindTTSConfig):
276
+ super().__init__(config)
277
+ self.tokenizer = tokenizer_from_config(config)
278
+ banana_config = config.banana_config
279
+ model_config = banana_config["model"]
280
+ audio_config = banana_config["audio"]
281
+ hidden = int(model_config.get("hidden_size", 256))
282
+ dropout = float(model_config.get("dropout", 0.5))
283
+ prenet_sizes = list(model_config.get("prenet_sizes", [256, 128]))
284
+ attention_dim = int(model_config.get("attention_dim", 128))
285
+ decoder_dim = int(model_config.get("decoder_dim", 512))
286
+ n_mels = int(audio_config["n_mels"])
287
+
288
+ self.n_mels = n_mels
289
+ self.reduction_factor = int(model_config.get("reduction_factor", 4))
290
+ self.encoder = Encoder(
291
+ self.tokenizer.vocab_size,
292
+ hidden,
293
+ self.tokenizer.pad_id,
294
+ float(model_config.get("encoder_dropout", 0.15)),
295
+ int(model_config.get("encoder_conv_layers", 3)),
296
+ )
297
+ self.prenet = Prenet(n_mels, prenet_sizes, dropout)
298
+ self.attention_rnn = nn.GRUCell(prenet_sizes[-1] + hidden, decoder_dim)
299
+ self.attention = LocationSensitiveAttention(
300
+ decoder_dim,
301
+ hidden,
302
+ attention_dim,
303
+ int(model_config.get("location_channels", 32)),
304
+ int(model_config.get("location_kernel_size", 31)),
305
+ )
306
+ self.decoder_rnn = nn.GRUCell(decoder_dim + hidden, decoder_dim)
307
+ proj_dim = decoder_dim + hidden
308
+ self.mel_proj = nn.Linear(proj_dim, n_mels * self.reduction_factor)
309
+ self.stop_proj = nn.Linear(proj_dim, self.reduction_factor)
310
+ self.postnet = Postnet(
311
+ n_mels,
312
+ int(model_config.get("postnet_channels", 512)),
313
+ int(model_config.get("postnet_layers", 5)),
314
+ float(model_config.get("postnet_dropout", 0.5)),
315
+ )
316
+ self.vocoder_generator: HiFiGANGenerator | None = None
317
+ self.vocoder_dtype = torch.float32
318
+ self._vocoder_loaded = False
319
+
320
+ def ensure_default_vocoder(self) -> None:
321
+ if self._vocoder_loaded:
322
+ return
323
+ self._vocoder_loaded = True
324
+ vocoder_info = getattr(self.config, "vocoder", {}) or {}
325
+ if not vocoder_info.get("enabled", True):
326
+ return
327
+ filename = str(vocoder_info.get("default_weights", "vocoder.safetensors"))
328
+ dtype_name = str(vocoder_info.get("default_dtype", "bfloat16")).lower()
329
+ self.vocoder_dtype = torch.bfloat16 if dtype_name in {"bf16", "bfloat16"} else torch.float16 if dtype_name in {"fp16", "float16"} else torch.float32
330
+ banana_config = self.config.banana_config
331
+ audio_config = banana_config["audio"]
332
+ vocoder_config = vocoder_info.get("config") or banana_config.get("vocoder") or {}
333
+ model_device = next(self.parameters()).device
334
+ self.vocoder_generator = HiFiGANGenerator(int(audio_config["n_mels"]), vocoder_config).to(
335
+ device=model_device,
336
+ dtype=self.vocoder_dtype,
337
+ )
338
+ try:
339
+ from safetensors.torch import load_file
340
+
341
+ state = load_file(str(_resolve_asset(self.config, filename)), device="cpu")
342
+ self.vocoder_generator.load_state_dict(state)
343
+ self.vocoder_generator.eval()
344
+ except Exception:
345
+ self.vocoder_generator = None
346
+ raise
347
+
348
+ def reload_vocoder(self, weights: str = "vocoder.safetensors", dtype: str = "bfloat16"):
349
+ self.config.vocoder["default_weights"] = weights
350
+ self.config.vocoder["default_dtype"] = dtype
351
+ self.vocoder_generator = None
352
+ self._vocoder_loaded = False
353
+ self.ensure_default_vocoder()
354
+ return self
355
+
356
+ def initialize_decoder_states(self, memory: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
357
+ batch, text_len, hidden = memory.shape
358
+ attention_hidden = memory.new_zeros(batch, self.attention_rnn.hidden_size)
359
+ decoder_hidden = memory.new_zeros(batch, self.decoder_rnn.hidden_size)
360
+ context = memory.new_zeros(batch, hidden)
361
+ attention_weights = memory.new_zeros(batch, text_len)
362
+ attention_weights[:, 0] = 1.0
363
+ attention_cum = memory.new_zeros(batch, text_len)
364
+ attention_cum[:, 0] = 1.0
365
+ return attention_hidden, decoder_hidden, context, attention_weights, attention_cum
366
+
367
+ def decode_step(
368
+ self,
369
+ decoder_input: torch.Tensor,
370
+ memory: torch.Tensor,
371
+ processed_memory: torch.Tensor,
372
+ mask: torch.Tensor,
373
+ attention_hidden: torch.Tensor,
374
+ decoder_hidden: torch.Tensor,
375
+ context: torch.Tensor,
376
+ attention_weights: torch.Tensor,
377
+ attention_cum: torch.Tensor,
378
+ window_mask: torch.Tensor | None = None,
379
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
380
+ prenet_out = self.prenet(decoder_input)
381
+ attention_hidden = self.attention_rnn(torch.cat([prenet_out, context], dim=-1), attention_hidden)
382
+ context, attention_weights = self.attention(attention_hidden, memory, processed_memory, attention_weights, attention_cum, mask, window_mask)
383
+ attention_cum = attention_cum + attention_weights
384
+ decoder_hidden = self.decoder_rnn(torch.cat([attention_hidden, context], dim=-1), decoder_hidden)
385
+ proj_input = torch.cat([decoder_hidden, context], dim=-1)
386
+ mel = self.mel_proj(proj_input).view(proj_input.shape[0], self.reduction_factor, self.n_mels)
387
+ stop = self.stop_proj(proj_input)
388
+ return mel, stop, attention_hidden, decoder_hidden, context, attention_weights, attention_cum
389
+
390
+ @torch.no_grad()
391
+ def infer(
392
+ self,
393
+ tokens: torch.Tensor,
394
+ token_lens: torch.Tensor,
395
+ max_steps: int = 1200,
396
+ stop_threshold: float = 0.55,
397
+ min_steps: int = 30,
398
+ attention_window: int = 12,
399
+ ):
400
+ memory = self.encoder(tokens)
401
+ mask = make_padding_mask(token_lens, tokens.shape[1])
402
+ processed_memory = self.attention.memory_layer(memory)
403
+ states = self.initialize_decoder_states(memory)
404
+ decoder_input = memory.new_zeros(tokens.shape[0], self.n_mels)
405
+ mel_outputs: list[torch.Tensor] = []
406
+ stop_outputs: list[torch.Tensor] = []
407
+ alignments: list[torch.Tensor] = []
408
+ max_decoder_steps = max(1, max_steps // self.reduction_factor)
409
+ min_decoder_steps = max(1, min_steps // self.reduction_factor)
410
+ prev_attention_index = torch.zeros(tokens.shape[0], dtype=torch.long, device=tokens.device)
411
+ for step in range(max_decoder_steps):
412
+ window_mask = None
413
+ if attention_window > 0:
414
+ positions = torch.arange(tokens.shape[1], device=tokens.device).unsqueeze(0)
415
+ left = (prev_attention_index - 1).clamp_min(0).unsqueeze(1)
416
+ right = (prev_attention_index + attention_window).clamp_max(tokens.shape[1] - 1).unsqueeze(1)
417
+ window_mask = (positions < left) | (positions > right) | mask
418
+ mel, stop, *states = self.decode_step(decoder_input, memory, processed_memory, mask, *states, window_mask=window_mask)
419
+ mel_outputs.append(mel)
420
+ stop_outputs.append(stop)
421
+ alignments.append(states[-2])
422
+ prev_attention_index = states[-2].argmax(dim=-1).clamp_min(prev_attention_index)
423
+ decoder_input = mel[:, -1]
424
+ if step >= min_decoder_steps and torch.sigmoid(stop[:, -1]).min().item() > stop_threshold:
425
+ break
426
+ mel = torch.stack(mel_outputs, dim=1).reshape(tokens.shape[0], -1, self.n_mels)
427
+ stop_logits = torch.stack(stop_outputs, dim=1).reshape(tokens.shape[0], -1)
428
+ align = torch.stack(alignments, dim=1)
429
+ mel_postnet = mel + self.postnet(mel)
430
+ return mel_postnet, align, stop_logits
431
+
432
+ def denormalize_mel(self, mel: torch.Tensor) -> torch.Tensor:
433
+ stats = self.config.banana_config.get("audio", {}).get("mel_stats")
434
+ if not stats or not stats.get("normalized_training", False):
435
+ return mel
436
+ mel = mel * max(float(stats["std"]), 1e-5) + float(stats["mean"])
437
+ return mel.clamp(float(stats.get("min", -12.0)), float(stats.get("max", 8.0)))
438
+
439
+ @torch.no_grad()
440
+ def vocode(self, mel: torch.Tensor) -> torch.Tensor:
441
+ audio_config = self.config.banana_config["audio"]
442
+ self.ensure_default_vocoder()
443
+ if self.vocoder_generator is None:
444
+ return griffin_lim(mel.detach().cpu(), audio_config)
445
+ vocoder_device = next(self.vocoder_generator.parameters()).device
446
+ mel_batch = mel.to(device=vocoder_device, dtype=self.vocoder_dtype).transpose(0, 1).unsqueeze(0)
447
+ wav = self.vocoder_generator(mel_batch).float()
448
+ target_samples = max(1, (mel.shape[0] - 1) * int(audio_config["hop_length"]))
449
+ if wav.shape[-1] < target_samples:
450
+ wav = F.pad(wav, (0, target_samples - wav.shape[-1]))
451
+ return wav[..., :target_samples].squeeze(0).detach().cpu()
452
+
453
+ @torch.no_grad()
454
+ def tts(
455
+ self,
456
+ text: str,
457
+ max_steps: int | None = None,
458
+ stop_threshold: float | None = None,
459
+ attention_window: int | None = None,
460
+ normalize_wav: bool = True,
461
+ ) -> TTSOutput:
462
+ device = next(self.parameters()).device
463
+ model_config = self.config.banana_config["model"]
464
+ audio_config = self.config.banana_config["audio"]
465
+ token_ids = self.tokenizer.encode(text)
466
+ tokens = torch.tensor(token_ids, dtype=torch.long, device=device).unsqueeze(0)
467
+ token_lens = torch.tensor([len(token_ids)], dtype=torch.long, device=device)
468
+ mel, alignments, stop_logits = self.infer(
469
+ tokens,
470
+ token_lens,
471
+ max_steps=int(max_steps or model_config.get("max_decoder_steps", 1200)),
472
+ stop_threshold=float(stop_threshold or model_config.get("stop_threshold", 0.55)),
473
+ min_steps=max(20, len(token_ids) * 3),
474
+ attention_window=int(attention_window if attention_window is not None else model_config.get("attention_window", 12)),
475
+ )
476
+ mel = self.denormalize_mel(mel[0].detach())
477
+ wav = self.vocode(mel)
478
+ if normalize_wav:
479
+ peak = wav.abs().max()
480
+ if peak > 0:
481
+ wav = wav / peak * 0.95
482
+ return TTSOutput(
483
+ waveform=wav,
484
+ sample_rate=int(audio_config["sample_rate"]),
485
+ mel=mel.detach().cpu(),
486
+ alignments=alignments.detach().cpu(),
487
+ stop_logits=stop_logits.detach().cpu(),
488
+ )
489
+
490
+ def forward(self, tokens: torch.Tensor, token_lens: torch.Tensor, **kwargs):
491
+ return self.infer(tokens, token_lens, **kwargs)
492
+
493
+ @staticmethod
494
+ def save_wav(path: str | Path, waveform: torch.Tensor, sample_rate: int) -> None:
495
+ path = Path(path)
496
+ path.parent.mkdir(parents=True, exist_ok=True)
497
+ wav_np = waveform.detach().cpu().clamp(-1.0, 1.0).numpy()
498
+ wav_i16 = np.clip(wav_np * 32767.0, -32768, 32767).astype(np.int16)
499
+ with wave.open(str(path), "wb") as f:
500
+ f.setnchannels(1)
501
+ f.setsampwidth(2)
502
+ f.setframerate(sample_rate)
503
+ f.writeframes(wav_i16.tobytes())
504
+
505
+
506
+ def hz_to_mel(freq: torch.Tensor) -> torch.Tensor:
507
+ return 2595.0 * torch.log10(1.0 + freq / 700.0)
508
+
509
+
510
+ def mel_to_hz(mel: torch.Tensor) -> torch.Tensor:
511
+ return 700.0 * (10.0 ** (mel / 2595.0) - 1.0)
512
+
513
+
514
+ def mel_filterbank(sample_rate: int, n_fft: int, n_mels: int, f_min: float, f_max: float) -> torch.Tensor:
515
+ f_max = min(float(f_max), sample_rate / 2)
516
+ m_min = hz_to_mel(torch.tensor(float(f_min)))
517
+ m_max = hz_to_mel(torch.tensor(float(f_max)))
518
+ m_points = torch.linspace(m_min, m_max, n_mels + 2)
519
+ f_points = mel_to_hz(m_points)
520
+ bins = torch.floor((n_fft + 1) * f_points / sample_rate).long()
521
+ fb = torch.zeros(n_mels, n_fft // 2 + 1)
522
+ for i in range(n_mels):
523
+ left, center, right = bins[i].item(), bins[i + 1].item(), bins[i + 2].item()
524
+ center = max(center, left + 1)
525
+ right = max(right, center + 1)
526
+ for j in range(left, min(center, fb.shape[1])):
527
+ fb[i, j] = (j - left) / max(1, center - left)
528
+ for j in range(center, min(right, fb.shape[1])):
529
+ fb[i, j] = (right - j) / max(1, right - center)
530
+ return fb
531
+
532
+
533
+ def griffin_lim(mel: torch.Tensor, config: dict[str, Any]) -> torch.Tensor:
534
+ n_fft = int(config["n_fft"])
535
+ hop_length = int(config["hop_length"])
536
+ win_length = int(config["win_length"])
537
+ n_iters = int(config.get("griffin_lim_iters", 32))
538
+ window = torch.hann_window(win_length)
539
+ fb = mel_filterbank(int(config["sample_rate"]), n_fft, int(config["n_mels"]), float(config.get("f_min", 0.0)), float(config.get("f_max", 8000.0)))
540
+ mag = torch.linalg.pinv(fb) @ torch.exp(mel.float()).transpose(0, 1)
541
+ mag = mag.clamp_min(1e-6)
542
+ spec = torch.polar(mag, 2 * math.pi * torch.rand_like(mag))
543
+ wav_len = max(1, (mel.shape[0] - 1) * hop_length)
544
+ wav = torch.istft(spec, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window=window, length=wav_len)
545
+ for _ in range(n_iters):
546
+ rebuilt = torch.stft(wav, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window=window, return_complex=True)
547
+ spec = mag * torch.exp(1j * rebuilt.angle())
548
+ wav = torch.istft(spec, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window=window, length=wav_len)
549
+ wav = torch.nan_to_num(wav.detach().cpu())
550
+ peak = wav.abs().max()
551
+ return wav / peak if peak > 1.0 else wav.clamp(-1.0, 1.0)
vocoder.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e9af7774f0c093c2b893d31a9d060c82edcc9e079d1bd177cba9adc56710ce2c
3
+ size 7126090