Spaces:
Running
on
Zero
Running
on
Zero
mrfakename
commited on
Commit
•
fededd1
1
Parent(s):
b0bca14
Sync from GitHub repo
Browse filesThis Space is synced from the GitHub repo: https://github.com/SWivid/F5-TTS. Please submit contributions to the Space there
- .gitmodules +3 -0
- README_REPO.md +7 -0
- src/f5_tts/api.py +22 -14
- src/f5_tts/eval/eval_infer_batch.py +39 -29
- src/f5_tts/eval/utils_eval.py +11 -3
- src/f5_tts/infer/README.md +4 -0
- src/f5_tts/infer/infer_cli.py +32 -16
- src/f5_tts/infer/speech_edit.py +36 -36
- src/f5_tts/infer/utils_infer.py +78 -30
- src/f5_tts/model/cfm.py +6 -8
- src/f5_tts/model/dataset.py +23 -5
- src/f5_tts/model/modules.py +106 -29
- src/f5_tts/model/trainer.py +12 -13
- src/f5_tts/train/train.py +11 -5
.gitmodules
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
[submodule "src/third_party/BigVGAN"]
|
2 |
+
path = src/third_party/BigVGAN
|
3 |
+
url = https://github.com/NVIDIA/BigVGAN.git
|
README_REPO.md
CHANGED
@@ -43,8 +43,15 @@ pip install git+https://github.com/SWivid/F5-TTS.git
|
|
43 |
```bash
|
44 |
git clone https://github.com/SWivid/F5-TTS.git
|
45 |
cd F5-TTS
|
|
|
46 |
pip install -e .
|
47 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
|
49 |
### 3. Docker usage
|
50 |
```bash
|
|
|
43 |
```bash
|
44 |
git clone https://github.com/SWivid/F5-TTS.git
|
45 |
cd F5-TTS
|
46 |
+
# git submodule update --init --recursive # (optional, if need bigvgan)
|
47 |
pip install -e .
|
48 |
```
|
49 |
+
If initialize submodule, you should add the following code at the beginning of `src/third_party/BigVGAN/bigvgan.py`.
|
50 |
+
```python
|
51 |
+
import os
|
52 |
+
import sys
|
53 |
+
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
54 |
+
```
|
55 |
|
56 |
### 3. Docker usage
|
57 |
```bash
|
src/f5_tts/api.py
CHANGED
@@ -1,24 +1,24 @@
|
|
1 |
import random
|
2 |
import sys
|
3 |
-
import tqdm
|
4 |
from importlib.resources import files
|
5 |
|
6 |
import soundfile as sf
|
7 |
import torch
|
|
|
8 |
from cached_path import cached_path
|
9 |
|
10 |
-
from f5_tts.model import DiT, UNetT
|
11 |
-
from f5_tts.model.utils import seed_everything
|
12 |
from f5_tts.infer.utils_infer import (
|
13 |
-
|
14 |
-
load_model,
|
15 |
infer_process,
|
|
|
|
|
|
|
16 |
remove_silence_for_generated_wav,
|
17 |
save_spectrogram,
|
18 |
-
preprocess_ref_audio_text,
|
19 |
target_sample_rate,
|
20 |
-
hop_length,
|
21 |
)
|
|
|
|
|
22 |
|
23 |
|
24 |
class F5TTS:
|
@@ -29,6 +29,7 @@ class F5TTS:
|
|
29 |
vocab_file="",
|
30 |
ode_method="euler",
|
31 |
use_ema=True,
|
|
|
32 |
local_path=None,
|
33 |
device=None,
|
34 |
):
|
@@ -37,6 +38,7 @@ class F5TTS:
|
|
37 |
self.target_sample_rate = target_sample_rate
|
38 |
self.hop_length = hop_length
|
39 |
self.seed = -1
|
|
|
40 |
|
41 |
# Set device
|
42 |
self.device = device or (
|
@@ -44,16 +46,19 @@ class F5TTS:
|
|
44 |
)
|
45 |
|
46 |
# Load models
|
47 |
-
self.load_vocoder_model(local_path)
|
48 |
-
self.load_ema_model(model_type, ckpt_file, vocab_file, ode_method, use_ema)
|
49 |
|
50 |
-
def load_vocoder_model(self, local_path):
|
51 |
-
self.vocoder = load_vocoder(local_path is not None, local_path, self.device)
|
52 |
|
53 |
-
def load_ema_model(self, model_type, ckpt_file, vocab_file, ode_method, use_ema):
|
54 |
if model_type == "F5-TTS":
|
55 |
if not ckpt_file:
|
56 |
-
|
|
|
|
|
|
|
57 |
model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
58 |
model_cls = DiT
|
59 |
elif model_type == "E2-TTS":
|
@@ -64,7 +69,9 @@ class F5TTS:
|
|
64 |
else:
|
65 |
raise ValueError(f"Unknown model type: {model_type}")
|
66 |
|
67 |
-
self.ema_model = load_model(
|
|
|
|
|
68 |
|
69 |
def export_wav(self, wav, file_wave, remove_silence=False):
|
70 |
sf.write(file_wave, wav, self.target_sample_rate)
|
@@ -107,6 +114,7 @@ class F5TTS:
|
|
107 |
gen_text,
|
108 |
self.ema_model,
|
109 |
self.vocoder,
|
|
|
110 |
show_info=show_info,
|
111 |
progress=progress,
|
112 |
target_rms=target_rms,
|
|
|
1 |
import random
|
2 |
import sys
|
|
|
3 |
from importlib.resources import files
|
4 |
|
5 |
import soundfile as sf
|
6 |
import torch
|
7 |
+
import tqdm
|
8 |
from cached_path import cached_path
|
9 |
|
|
|
|
|
10 |
from f5_tts.infer.utils_infer import (
|
11 |
+
hop_length,
|
|
|
12 |
infer_process,
|
13 |
+
load_model,
|
14 |
+
load_vocoder,
|
15 |
+
preprocess_ref_audio_text,
|
16 |
remove_silence_for_generated_wav,
|
17 |
save_spectrogram,
|
|
|
18 |
target_sample_rate,
|
|
|
19 |
)
|
20 |
+
from f5_tts.model import DiT, UNetT
|
21 |
+
from f5_tts.model.utils import seed_everything
|
22 |
|
23 |
|
24 |
class F5TTS:
|
|
|
29 |
vocab_file="",
|
30 |
ode_method="euler",
|
31 |
use_ema=True,
|
32 |
+
vocoder_name="vocos",
|
33 |
local_path=None,
|
34 |
device=None,
|
35 |
):
|
|
|
38 |
self.target_sample_rate = target_sample_rate
|
39 |
self.hop_length = hop_length
|
40 |
self.seed = -1
|
41 |
+
self.mel_spec_type = vocoder_name
|
42 |
|
43 |
# Set device
|
44 |
self.device = device or (
|
|
|
46 |
)
|
47 |
|
48 |
# Load models
|
49 |
+
self.load_vocoder_model(vocoder_name, local_path)
|
50 |
+
self.load_ema_model(model_type, ckpt_file, vocoder_name, vocab_file, ode_method, use_ema)
|
51 |
|
52 |
+
def load_vocoder_model(self, vocoder_name, local_path):
|
53 |
+
self.vocoder = load_vocoder(vocoder_name, local_path is not None, local_path, self.device)
|
54 |
|
55 |
+
def load_ema_model(self, model_type, ckpt_file, mel_spec_type, vocab_file, ode_method, use_ema):
|
56 |
if model_type == "F5-TTS":
|
57 |
if not ckpt_file:
|
58 |
+
if mel_spec_type == "vocos":
|
59 |
+
ckpt_file = str(cached_path("hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors"))
|
60 |
+
elif mel_spec_type == "bigvgan":
|
61 |
+
ckpt_file = str(cached_path("hf://SWivid/F5-TTS/F5TTS_Base_bigvgan/model_1250000.pt"))
|
62 |
model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
63 |
model_cls = DiT
|
64 |
elif model_type == "E2-TTS":
|
|
|
69 |
else:
|
70 |
raise ValueError(f"Unknown model type: {model_type}")
|
71 |
|
72 |
+
self.ema_model = load_model(
|
73 |
+
model_cls, model_cfg, ckpt_file, mel_spec_type, vocab_file, ode_method, use_ema, self.device
|
74 |
+
)
|
75 |
|
76 |
def export_wav(self, wav, file_wave, remove_silence=False):
|
77 |
sf.write(file_wave, wav, self.target_sample_rate)
|
|
|
114 |
gen_text,
|
115 |
self.ema_model,
|
116 |
self.vocoder,
|
117 |
+
self.mel_spec_type,
|
118 |
show_info=show_info,
|
119 |
progress=progress,
|
120 |
target_rms=target_rms,
|
src/f5_tts/eval/eval_infer_batch.py
CHANGED
@@ -1,26 +1,25 @@
|
|
1 |
-
import sys
|
2 |
import os
|
|
|
3 |
|
4 |
sys.path.append(os.getcwd())
|
5 |
|
6 |
-
import time
|
7 |
-
from tqdm import tqdm
|
8 |
import argparse
|
|
|
9 |
from importlib.resources import files
|
10 |
|
11 |
import torch
|
12 |
import torchaudio
|
13 |
from accelerate import Accelerator
|
14 |
-
from
|
15 |
|
16 |
-
from f5_tts.model import CFM, UNetT, DiT
|
17 |
-
from f5_tts.model.utils import get_tokenizer
|
18 |
-
from f5_tts.infer.utils_infer import load_checkpoint
|
19 |
from f5_tts.eval.utils_eval import (
|
20 |
-
get_seedtts_testset_metainfo,
|
21 |
-
get_librispeech_test_clean_metainfo,
|
22 |
get_inference_prompt,
|
|
|
|
|
23 |
)
|
|
|
|
|
|
|
24 |
|
25 |
accelerator = Accelerator()
|
26 |
device = f"cuda:{accelerator.process_index}"
|
@@ -31,8 +30,11 @@ device = f"cuda:{accelerator.process_index}"
|
|
31 |
target_sample_rate = 24000
|
32 |
n_mel_channels = 100
|
33 |
hop_length = 256
|
|
|
|
|
34 |
target_rms = 0.1
|
35 |
|
|
|
36 |
tokenizer = "pinyin"
|
37 |
rel_path = str(files("f5_tts").joinpath("../../"))
|
38 |
|
@@ -46,6 +48,7 @@ def main():
|
|
46 |
parser.add_argument("-d", "--dataset", default="Emilia_ZH_EN")
|
47 |
parser.add_argument("-n", "--expname", required=True)
|
48 |
parser.add_argument("-c", "--ckptstep", default=1200000, type=int)
|
|
|
49 |
|
50 |
parser.add_argument("-nfe", "--nfestep", default=32, type=int)
|
51 |
parser.add_argument("-o", "--odemethod", default="euler")
|
@@ -60,6 +63,7 @@ def main():
|
|
60 |
exp_name = args.expname
|
61 |
ckpt_step = args.ckptstep
|
62 |
ckpt_path = rel_path + f"/ckpts/{exp_name}/model_{ckpt_step}.pt"
|
|
|
63 |
|
64 |
nfe_step = args.nfestep
|
65 |
ode_method = args.odemethod
|
@@ -98,7 +102,7 @@ def main():
|
|
98 |
output_dir = (
|
99 |
f"{rel_path}/"
|
100 |
f"results/{exp_name}_{ckpt_step}/{testset}/"
|
101 |
-
f"seed{seed}_{ode_method}_nfe{nfe_step}"
|
102 |
f"{f'_ss{sway_sampling_coef}' if sway_sampling_coef else ''}"
|
103 |
f"_cfg{cfg_strength}_speed{speed}"
|
104 |
f"{'_gt-dur' if use_truth_duration else ''}"
|
@@ -116,6 +120,7 @@ def main():
|
|
116 |
target_sample_rate=target_sample_rate,
|
117 |
n_mel_channels=n_mel_channels,
|
118 |
hop_length=hop_length,
|
|
|
119 |
target_rms=target_rms,
|
120 |
use_truth_duration=use_truth_duration,
|
121 |
infer_batch_size=infer_batch_size,
|
@@ -123,14 +128,11 @@ def main():
|
|
123 |
|
124 |
# Vocoder model
|
125 |
local = False
|
126 |
-
if
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
vocos.eval()
|
132 |
-
else:
|
133 |
-
vocos = Vocos.from_pretrained("charactr/vocos-mel-24khz")
|
134 |
|
135 |
# Tokenizer
|
136 |
vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
|
@@ -139,9 +141,12 @@ def main():
|
|
139 |
model = CFM(
|
140 |
transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
|
141 |
mel_spec_kwargs=dict(
|
142 |
-
|
143 |
-
n_mel_channels=n_mel_channels,
|
144 |
hop_length=hop_length,
|
|
|
|
|
|
|
|
|
145 |
),
|
146 |
odeint_kwargs=dict(
|
147 |
method=ode_method,
|
@@ -149,7 +154,8 @@ def main():
|
|
149 |
vocab_char_map=vocab_char_map,
|
150 |
).to(device)
|
151 |
|
152 |
-
|
|
|
153 |
|
154 |
if not os.path.exists(output_dir) and accelerator.is_main_process:
|
155 |
os.makedirs(output_dir)
|
@@ -178,14 +184,18 @@ def main():
|
|
178 |
no_ref_audio=no_ref_audio,
|
179 |
seed=seed,
|
180 |
)
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
|
|
|
|
|
|
|
|
189 |
|
190 |
accelerator.wait_for_everyone()
|
191 |
if accelerator.is_main_process:
|
|
|
|
|
1 |
import os
|
2 |
+
import sys
|
3 |
|
4 |
sys.path.append(os.getcwd())
|
5 |
|
|
|
|
|
6 |
import argparse
|
7 |
+
import time
|
8 |
from importlib.resources import files
|
9 |
|
10 |
import torch
|
11 |
import torchaudio
|
12 |
from accelerate import Accelerator
|
13 |
+
from tqdm import tqdm
|
14 |
|
|
|
|
|
|
|
15 |
from f5_tts.eval.utils_eval import (
|
|
|
|
|
16 |
get_inference_prompt,
|
17 |
+
get_librispeech_test_clean_metainfo,
|
18 |
+
get_seedtts_testset_metainfo,
|
19 |
)
|
20 |
+
from f5_tts.infer.utils_infer import load_checkpoint, load_vocoder
|
21 |
+
from f5_tts.model import CFM, DiT, UNetT
|
22 |
+
from f5_tts.model.utils import get_tokenizer
|
23 |
|
24 |
accelerator = Accelerator()
|
25 |
device = f"cuda:{accelerator.process_index}"
|
|
|
30 |
target_sample_rate = 24000
|
31 |
n_mel_channels = 100
|
32 |
hop_length = 256
|
33 |
+
win_length = 1024
|
34 |
+
n_fft = 1024
|
35 |
target_rms = 0.1
|
36 |
|
37 |
+
|
38 |
tokenizer = "pinyin"
|
39 |
rel_path = str(files("f5_tts").joinpath("../../"))
|
40 |
|
|
|
48 |
parser.add_argument("-d", "--dataset", default="Emilia_ZH_EN")
|
49 |
parser.add_argument("-n", "--expname", required=True)
|
50 |
parser.add_argument("-c", "--ckptstep", default=1200000, type=int)
|
51 |
+
parser.add_argument("-m", "--mel_spec_type", default="vocos", type=str, choices=["bigvgan", "vocos"])
|
52 |
|
53 |
parser.add_argument("-nfe", "--nfestep", default=32, type=int)
|
54 |
parser.add_argument("-o", "--odemethod", default="euler")
|
|
|
63 |
exp_name = args.expname
|
64 |
ckpt_step = args.ckptstep
|
65 |
ckpt_path = rel_path + f"/ckpts/{exp_name}/model_{ckpt_step}.pt"
|
66 |
+
mel_spec_type = args.mel_spec_type
|
67 |
|
68 |
nfe_step = args.nfestep
|
69 |
ode_method = args.odemethod
|
|
|
102 |
output_dir = (
|
103 |
f"{rel_path}/"
|
104 |
f"results/{exp_name}_{ckpt_step}/{testset}/"
|
105 |
+
f"seed{seed}_{ode_method}_nfe{nfe_step}_{mel_spec_type}"
|
106 |
f"{f'_ss{sway_sampling_coef}' if sway_sampling_coef else ''}"
|
107 |
f"_cfg{cfg_strength}_speed{speed}"
|
108 |
f"{'_gt-dur' if use_truth_duration else ''}"
|
|
|
120 |
target_sample_rate=target_sample_rate,
|
121 |
n_mel_channels=n_mel_channels,
|
122 |
hop_length=hop_length,
|
123 |
+
mel_spec_type=mel_spec_type,
|
124 |
target_rms=target_rms,
|
125 |
use_truth_duration=use_truth_duration,
|
126 |
infer_batch_size=infer_batch_size,
|
|
|
128 |
|
129 |
# Vocoder model
|
130 |
local = False
|
131 |
+
if mel_spec_type == "vocos":
|
132 |
+
vocoder_local_path = "../checkpoints/charactr/vocos-mel-24khz"
|
133 |
+
elif mel_spec_type == "bigvgan":
|
134 |
+
vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
|
135 |
+
vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=local, local_path=vocoder_local_path)
|
|
|
|
|
|
|
136 |
|
137 |
# Tokenizer
|
138 |
vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
|
|
|
141 |
model = CFM(
|
142 |
transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
|
143 |
mel_spec_kwargs=dict(
|
144 |
+
n_fft=n_fft,
|
|
|
145 |
hop_length=hop_length,
|
146 |
+
win_length=win_length,
|
147 |
+
n_mel_channels=n_mel_channels,
|
148 |
+
target_sample_rate=target_sample_rate,
|
149 |
+
mel_spec_type=mel_spec_type,
|
150 |
),
|
151 |
odeint_kwargs=dict(
|
152 |
method=ode_method,
|
|
|
154 |
vocab_char_map=vocab_char_map,
|
155 |
).to(device)
|
156 |
|
157 |
+
dtype = torch.float32 if mel_spec_type == "bigvgan" else None
|
158 |
+
model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
|
159 |
|
160 |
if not os.path.exists(output_dir) and accelerator.is_main_process:
|
161 |
os.makedirs(output_dir)
|
|
|
184 |
no_ref_audio=no_ref_audio,
|
185 |
seed=seed,
|
186 |
)
|
187 |
+
# Final result
|
188 |
+
for i, gen in enumerate(generated):
|
189 |
+
gen = gen[ref_mel_lens[i] : total_mel_lens[i], :].unsqueeze(0)
|
190 |
+
gen_mel_spec = gen.permute(0, 2, 1)
|
191 |
+
if mel_spec_type == "vocos":
|
192 |
+
generated_wave = vocoder.decode(gen_mel_spec)
|
193 |
+
elif mel_spec_type == "bigvgan":
|
194 |
+
generated_wave = vocoder(gen_mel_spec)
|
195 |
+
|
196 |
+
if ref_rms_list[i] < target_rms:
|
197 |
+
generated_wave = generated_wave * ref_rms_list[i] / target_rms
|
198 |
+
torchaudio.save(f"{output_dir}/{utts[i]}.wav", generated_wave.squeeze(0).cpu(), target_sample_rate)
|
199 |
|
200 |
accelerator.wait_for_everyone()
|
201 |
if accelerator.is_main_process:
|
src/f5_tts/eval/utils_eval.py
CHANGED
@@ -2,15 +2,15 @@ import math
|
|
2 |
import os
|
3 |
import random
|
4 |
import string
|
5 |
-
from tqdm import tqdm
|
6 |
|
7 |
import torch
|
8 |
import torch.nn.functional as F
|
9 |
import torchaudio
|
|
|
10 |
|
|
|
11 |
from f5_tts.model.modules import MelSpec
|
12 |
from f5_tts.model.utils import convert_char_to_pinyin
|
13 |
-
from f5_tts.eval.ecapa_tdnn import ECAPA_TDNN_SMALL
|
14 |
|
15 |
|
16 |
# seedtts testset metainfo: utt, prompt_text, prompt_wav, gt_text, gt_wav
|
@@ -74,8 +74,11 @@ def get_inference_prompt(
|
|
74 |
tokenizer="pinyin",
|
75 |
polyphone=True,
|
76 |
target_sample_rate=24000,
|
|
|
|
|
77 |
n_mel_channels=100,
|
78 |
hop_length=256,
|
|
|
79 |
target_rms=0.1,
|
80 |
use_truth_duration=False,
|
81 |
infer_batch_size=1,
|
@@ -94,7 +97,12 @@ def get_inference_prompt(
|
|
94 |
)
|
95 |
|
96 |
mel_spectrogram = MelSpec(
|
97 |
-
|
|
|
|
|
|
|
|
|
|
|
98 |
)
|
99 |
|
100 |
for utt, prompt_text, prompt_wav, gt_text, gt_wav in tqdm(metainfo, desc="Processing prompts..."):
|
|
|
2 |
import os
|
3 |
import random
|
4 |
import string
|
|
|
5 |
|
6 |
import torch
|
7 |
import torch.nn.functional as F
|
8 |
import torchaudio
|
9 |
+
from tqdm import tqdm
|
10 |
|
11 |
+
from f5_tts.eval.ecapa_tdnn import ECAPA_TDNN_SMALL
|
12 |
from f5_tts.model.modules import MelSpec
|
13 |
from f5_tts.model.utils import convert_char_to_pinyin
|
|
|
14 |
|
15 |
|
16 |
# seedtts testset metainfo: utt, prompt_text, prompt_wav, gt_text, gt_wav
|
|
|
74 |
tokenizer="pinyin",
|
75 |
polyphone=True,
|
76 |
target_sample_rate=24000,
|
77 |
+
n_fft=1024,
|
78 |
+
win_length=1024,
|
79 |
n_mel_channels=100,
|
80 |
hop_length=256,
|
81 |
+
mel_spec_type="vocos",
|
82 |
target_rms=0.1,
|
83 |
use_truth_duration=False,
|
84 |
infer_batch_size=1,
|
|
|
97 |
)
|
98 |
|
99 |
mel_spectrogram = MelSpec(
|
100 |
+
n_fft=n_fft,
|
101 |
+
hop_length=hop_length,
|
102 |
+
win_length=win_length,
|
103 |
+
n_mel_channels=n_mel_channels,
|
104 |
+
target_sample_rate=target_sample_rate,
|
105 |
+
mel_spec_type=mel_spec_type,
|
106 |
)
|
107 |
|
108 |
for utt, prompt_text, prompt_wav, gt_text, gt_wav in tqdm(metainfo, desc="Processing prompts..."):
|
src/f5_tts/infer/README.md
CHANGED
@@ -56,6 +56,10 @@ f5-tts_infer-cli \
|
|
56 |
--ref_audio "ref_audio.wav" \
|
57 |
--ref_text "The content, subtitle or transcription of reference audio." \
|
58 |
--gen_text "Some text you want TTS model generate for you."
|
|
|
|
|
|
|
|
|
59 |
```
|
60 |
|
61 |
And a `.toml` file would help with more flexible usage.
|
|
|
56 |
--ref_audio "ref_audio.wav" \
|
57 |
--ref_text "The content, subtitle or transcription of reference audio." \
|
58 |
--gen_text "Some text you want TTS model generate for you."
|
59 |
+
|
60 |
+
# Choose Vocoder
|
61 |
+
f5-tts_infer-cli --vocoder_name bigvgan --load_vocoder_from_local --ckpt_file <YOUR_CKPT_PATH, eg:ckpts/F5TTS_Base_bigvgan/model_1250000.pt>
|
62 |
+
f5-tts_infer-cli --vocoder_name vocos --load_vocoder_from_local --ckpt_file <YOUR_CKPT_PATH, eg:ckpts/F5TTS_Base/model_1200000.safetensors>
|
63 |
```
|
64 |
|
65 |
And a `.toml` file would help with more flexible usage.
|
src/f5_tts/infer/infer_cli.py
CHANGED
@@ -2,23 +2,22 @@ import argparse
|
|
2 |
import codecs
|
3 |
import os
|
4 |
import re
|
5 |
-
from pathlib import Path
|
6 |
from importlib.resources import files
|
|
|
7 |
|
8 |
import numpy as np
|
9 |
import soundfile as sf
|
10 |
import tomli
|
11 |
from cached_path import cached_path
|
12 |
|
13 |
-
from f5_tts.model import DiT, UNetT
|
14 |
from f5_tts.infer.utils_infer import (
|
15 |
-
|
16 |
load_model,
|
|
|
17 |
preprocess_ref_audio_text,
|
18 |
-
infer_process,
|
19 |
remove_silence_for_generated_wav,
|
20 |
)
|
21 |
-
|
22 |
|
23 |
parser = argparse.ArgumentParser(
|
24 |
prog="python3 infer-cli.py",
|
@@ -70,6 +69,7 @@ parser.add_argument(
|
|
70 |
"--remove_silence",
|
71 |
help="Remove silence.",
|
72 |
)
|
|
|
73 |
parser.add_argument(
|
74 |
"--load_vocoder_from_local",
|
75 |
action="store_true",
|
@@ -111,9 +111,13 @@ remove_silence = args.remove_silence if args.remove_silence else config["remove_
|
|
111 |
speed = args.speed
|
112 |
wave_path = Path(output_dir) / "infer_cli_out.wav"
|
113 |
# spectrogram_path = Path(output_dir) / "infer_cli_out.png"
|
114 |
-
|
|
|
|
|
|
|
|
|
115 |
|
116 |
-
vocoder = load_vocoder(is_local=args.load_vocoder_from_local, local_path=
|
117 |
|
118 |
|
119 |
# load models
|
@@ -121,11 +125,17 @@ if model == "F5-TTS":
|
|
121 |
model_cls = DiT
|
122 |
model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
123 |
if ckpt_file == "":
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
|
130 |
elif model == "E2-TTS":
|
131 |
model_cls = UNetT
|
@@ -136,12 +146,18 @@ elif model == "E2-TTS":
|
|
136 |
ckpt_step = 1200000
|
137 |
ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
|
138 |
# ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
|
140 |
print(f"Using {model}...")
|
141 |
-
ema_model = load_model(model_cls, model_cfg, ckpt_file, vocab_file)
|
142 |
|
143 |
|
144 |
-
def main_process(ref_audio, ref_text, text_gen, model_obj, remove_silence, speed):
|
145 |
main_voice = {"ref_audio": ref_audio, "ref_text": ref_text}
|
146 |
if "voices" not in config:
|
147 |
voices = {"main": main_voice}
|
@@ -178,7 +194,7 @@ def main_process(ref_audio, ref_text, text_gen, model_obj, remove_silence, speed
|
|
178 |
ref_text = voices[voice]["ref_text"]
|
179 |
print(f"Voice: {voice}")
|
180 |
audio, final_sample_rate, spectragram = infer_process(
|
181 |
-
ref_audio, ref_text, gen_text, model_obj, vocoder, speed=speed
|
182 |
)
|
183 |
generated_audio_segments.append(audio)
|
184 |
|
@@ -197,7 +213,7 @@ def main_process(ref_audio, ref_text, text_gen, model_obj, remove_silence, speed
|
|
197 |
|
198 |
|
199 |
def main():
|
200 |
-
main_process(ref_audio, ref_text, gen_text, ema_model, remove_silence, speed)
|
201 |
|
202 |
|
203 |
if __name__ == "__main__":
|
|
|
2 |
import codecs
|
3 |
import os
|
4 |
import re
|
|
|
5 |
from importlib.resources import files
|
6 |
+
from pathlib import Path
|
7 |
|
8 |
import numpy as np
|
9 |
import soundfile as sf
|
10 |
import tomli
|
11 |
from cached_path import cached_path
|
12 |
|
|
|
13 |
from f5_tts.infer.utils_infer import (
|
14 |
+
infer_process,
|
15 |
load_model,
|
16 |
+
load_vocoder,
|
17 |
preprocess_ref_audio_text,
|
|
|
18 |
remove_silence_for_generated_wav,
|
19 |
)
|
20 |
+
from f5_tts.model import DiT, UNetT
|
21 |
|
22 |
parser = argparse.ArgumentParser(
|
23 |
prog="python3 infer-cli.py",
|
|
|
69 |
"--remove_silence",
|
70 |
help="Remove silence.",
|
71 |
)
|
72 |
+
parser.add_argument("--vocoder_name", type=str, default="vocos", choices=["vocos", "bigvgan"], help="vocoder name")
|
73 |
parser.add_argument(
|
74 |
"--load_vocoder_from_local",
|
75 |
action="store_true",
|
|
|
111 |
speed = args.speed
|
112 |
wave_path = Path(output_dir) / "infer_cli_out.wav"
|
113 |
# spectrogram_path = Path(output_dir) / "infer_cli_out.png"
|
114 |
+
if args.vocoder_name == "vocos":
|
115 |
+
vocoder_local_path = "../checkpoints/vocos-mel-24khz"
|
116 |
+
elif args.vocoder_name == "bigvgan":
|
117 |
+
vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
|
118 |
+
mel_spec_type = args.vocoder_name
|
119 |
|
120 |
+
vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=args.load_vocoder_from_local, local_path=vocoder_local_path)
|
121 |
|
122 |
|
123 |
# load models
|
|
|
125 |
model_cls = DiT
|
126 |
model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
127 |
if ckpt_file == "":
|
128 |
+
if args.vocoder_name == "vocos":
|
129 |
+
repo_name = "F5-TTS"
|
130 |
+
exp_name = "F5TTS_Base"
|
131 |
+
ckpt_step = 1200000
|
132 |
+
ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
|
133 |
+
# ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path
|
134 |
+
elif args.vocoder_name == "bigvgan":
|
135 |
+
repo_name = "F5-TTS"
|
136 |
+
exp_name = "F5TTS_Base_bigvgan"
|
137 |
+
ckpt_step = 1250000
|
138 |
+
ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.pt"))
|
139 |
|
140 |
elif model == "E2-TTS":
|
141 |
model_cls = UNetT
|
|
|
146 |
ckpt_step = 1200000
|
147 |
ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
|
148 |
# ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path
|
149 |
+
elif args.vocoder_name == "bigvgan": # TODO: need to test
|
150 |
+
repo_name = "F5-TTS"
|
151 |
+
exp_name = "F5TTS_Base_bigvgan"
|
152 |
+
ckpt_step = 1250000
|
153 |
+
ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.pt"))
|
154 |
+
|
155 |
|
156 |
print(f"Using {model}...")
|
157 |
+
ema_model = load_model(model_cls, model_cfg, ckpt_file, mel_spec_type=args.vocoder_name, vocab_file=vocab_file)
|
158 |
|
159 |
|
160 |
+
def main_process(ref_audio, ref_text, text_gen, model_obj, mel_spec_type, remove_silence, speed):
|
161 |
main_voice = {"ref_audio": ref_audio, "ref_text": ref_text}
|
162 |
if "voices" not in config:
|
163 |
voices = {"main": main_voice}
|
|
|
194 |
ref_text = voices[voice]["ref_text"]
|
195 |
print(f"Voice: {voice}")
|
196 |
audio, final_sample_rate, spectragram = infer_process(
|
197 |
+
ref_audio, ref_text, gen_text, model_obj, vocoder, mel_spec_type=mel_spec_type, speed=speed
|
198 |
)
|
199 |
generated_audio_segments.append(audio)
|
200 |
|
|
|
213 |
|
214 |
|
215 |
def main():
|
216 |
+
main_process(ref_audio, ref_text, gen_text, ema_model, mel_spec_type, remove_silence, speed)
|
217 |
|
218 |
|
219 |
if __name__ == "__main__":
|
src/f5_tts/infer/speech_edit.py
CHANGED
@@ -3,17 +3,10 @@ import os
|
|
3 |
import torch
|
4 |
import torch.nn.functional as F
|
5 |
import torchaudio
|
6 |
-
|
7 |
-
|
8 |
-
from f5_tts.model import CFM,
|
9 |
-
from f5_tts.model.utils import
|
10 |
-
get_tokenizer,
|
11 |
-
convert_char_to_pinyin,
|
12 |
-
)
|
13 |
-
from f5_tts.infer.utils_infer import (
|
14 |
-
load_checkpoint,
|
15 |
-
save_spectrogram,
|
16 |
-
)
|
17 |
|
18 |
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
19 |
|
@@ -23,6 +16,9 @@ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is
|
|
23 |
target_sample_rate = 24000
|
24 |
n_mel_channels = 100
|
25 |
hop_length = 256
|
|
|
|
|
|
|
26 |
target_rms = 0.1
|
27 |
|
28 |
tokenizer = "pinyin"
|
@@ -89,15 +85,11 @@ if not os.path.exists(output_dir):
|
|
89 |
|
90 |
# Vocoder model
|
91 |
local = False
|
92 |
-
if
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
vocos.eval()
|
99 |
-
else:
|
100 |
-
vocos = Vocos.from_pretrained("charactr/vocos-mel-24khz")
|
101 |
|
102 |
# Tokenizer
|
103 |
vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
|
@@ -106,9 +98,12 @@ vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
|
|
106 |
model = CFM(
|
107 |
transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
|
108 |
mel_spec_kwargs=dict(
|
109 |
-
|
110 |
-
n_mel_channels=n_mel_channels,
|
111 |
hop_length=hop_length,
|
|
|
|
|
|
|
|
|
112 |
),
|
113 |
odeint_kwargs=dict(
|
114 |
method=ode_method,
|
@@ -116,7 +111,8 @@ model = CFM(
|
|
116 |
vocab_char_map=vocab_char_map,
|
117 |
).to(device)
|
118 |
|
119 |
-
|
|
|
120 |
|
121 |
# Audio
|
122 |
audio, sr = torchaudio.load(audio_to_edit)
|
@@ -176,16 +172,20 @@ with torch.inference_mode():
|
|
176 |
seed=seed,
|
177 |
edit_mask=edit_mask,
|
178 |
)
|
179 |
-
print(f"Generated mel: {generated.shape}")
|
180 |
-
|
181 |
-
# Final result
|
182 |
-
generated = generated.to(torch.float32)
|
183 |
-
generated = generated[:, ref_audio_len:, :]
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
|
|
|
|
|
|
|
|
|
3 |
import torch
|
4 |
import torch.nn.functional as F
|
5 |
import torchaudio
|
6 |
+
|
7 |
+
from f5_tts.infer.utils_infer import load_checkpoint, load_vocoder, save_spectrogram
|
8 |
+
from f5_tts.model import CFM, DiT, UNetT
|
9 |
+
from f5_tts.model.utils import convert_char_to_pinyin, get_tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
12 |
|
|
|
16 |
target_sample_rate = 24000
|
17 |
n_mel_channels = 100
|
18 |
hop_length = 256
|
19 |
+
win_length = 1024
|
20 |
+
n_fft = 1024
|
21 |
+
mel_spec_type = "vocos" # 'vocos' or 'bigvgan'
|
22 |
target_rms = 0.1
|
23 |
|
24 |
tokenizer = "pinyin"
|
|
|
85 |
|
86 |
# Vocoder model
|
87 |
local = False
|
88 |
+
if mel_spec_type == "vocos":
|
89 |
+
vocoder_local_path = "../checkpoints/charactr/vocos-mel-24khz"
|
90 |
+
elif mel_spec_type == "bigvgan":
|
91 |
+
vocoder_local_path = "../checkpoints/bigvgan_v2_24khz_100band_256x"
|
92 |
+
vocoder = load_vocoder(vocoder_name=mel_spec_type, is_local=local, local_path=vocoder_local_path)
|
|
|
|
|
|
|
|
|
93 |
|
94 |
# Tokenizer
|
95 |
vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
|
|
|
98 |
model = CFM(
|
99 |
transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
|
100 |
mel_spec_kwargs=dict(
|
101 |
+
n_fft=n_fft,
|
|
|
102 |
hop_length=hop_length,
|
103 |
+
win_length=win_length,
|
104 |
+
n_mel_channels=n_mel_channels,
|
105 |
+
target_sample_rate=target_sample_rate,
|
106 |
+
mel_spec_type=mel_spec_type,
|
107 |
),
|
108 |
odeint_kwargs=dict(
|
109 |
method=ode_method,
|
|
|
111 |
vocab_char_map=vocab_char_map,
|
112 |
).to(device)
|
113 |
|
114 |
+
dtype = torch.float32 if mel_spec_type == "bigvgan" else None
|
115 |
+
model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
|
116 |
|
117 |
# Audio
|
118 |
audio, sr = torchaudio.load(audio_to_edit)
|
|
|
172 |
seed=seed,
|
173 |
edit_mask=edit_mask,
|
174 |
)
|
175 |
+
print(f"Generated mel: {generated.shape}")
|
176 |
+
|
177 |
+
# Final result
|
178 |
+
generated = generated.to(torch.float32)
|
179 |
+
generated = generated[:, ref_audio_len:, :]
|
180 |
+
gen_mel_spec = generated.permute(0, 2, 1)
|
181 |
+
if mel_spec_type == "vocos":
|
182 |
+
generated_wave = vocoder.decode(gen_mel_spec)
|
183 |
+
elif mel_spec_type == "bigvgan":
|
184 |
+
generated_wave = vocoder(gen_mel_spec)
|
185 |
+
|
186 |
+
if rms < target_rms:
|
187 |
+
generated_wave = generated_wave * rms / target_rms
|
188 |
+
|
189 |
+
save_spectrogram(gen_mel_spec[0].cpu().numpy(), f"{output_dir}/speech_edit_out.png")
|
190 |
+
torchaudio.save(f"{output_dir}/speech_edit_out.wav", generated_wave.squeeze(0).cpu(), target_sample_rate)
|
191 |
+
print(f"Generated wav: {generated_wave.shape}")
|
src/f5_tts/infer/utils_infer.py
CHANGED
@@ -1,5 +1,9 @@
|
|
1 |
# A unified script for inference process
|
2 |
# Make adjustments inside functions, and consider both gradio and cli scripts if need to change func output format
|
|
|
|
|
|
|
|
|
3 |
|
4 |
import hashlib
|
5 |
import re
|
@@ -34,6 +38,9 @@ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is
|
|
34 |
target_sample_rate = 24000
|
35 |
n_mel_channels = 100
|
36 |
hop_length = 256
|
|
|
|
|
|
|
37 |
target_rms = 0.1
|
38 |
cross_fade_duration = 0.15
|
39 |
ode_method = "euler"
|
@@ -80,17 +87,31 @@ def chunk_text(text, max_chars=135):
|
|
80 |
|
81 |
|
82 |
# load vocoder
|
83 |
-
def load_vocoder(is_local=False, local_path="", device=device):
|
84 |
-
if
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
|
95 |
|
96 |
# load asr pipeline
|
@@ -111,9 +132,12 @@ def initialize_asr_pipeline(device=device):
|
|
111 |
# load model checkpoint for inference
|
112 |
|
113 |
|
114 |
-
def load_checkpoint(model, ckpt_path, device, use_ema=True):
|
115 |
-
if
|
116 |
-
|
|
|
|
|
|
|
117 |
|
118 |
ckpt_type = ckpt_path.split(".")[-1]
|
119 |
if ckpt_type == "safetensors":
|
@@ -131,6 +155,11 @@ def load_checkpoint(model, ckpt_path, device, use_ema=True):
|
|
131 |
for k, v in checkpoint["ema_model_state_dict"].items()
|
132 |
if k not in ["initted", "step"]
|
133 |
}
|
|
|
|
|
|
|
|
|
|
|
134 |
model.load_state_dict(checkpoint["model_state_dict"])
|
135 |
else:
|
136 |
if ckpt_type == "safetensors":
|
@@ -143,7 +172,16 @@ def load_checkpoint(model, ckpt_path, device, use_ema=True):
|
|
143 |
# load model for inference
|
144 |
|
145 |
|
146 |
-
def load_model(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
147 |
if vocab_file == "":
|
148 |
vocab_file = str(files("f5_tts").joinpath("infer/examples/vocab.txt"))
|
149 |
tokenizer = "custom"
|
@@ -156,9 +194,12 @@ def load_model(model_cls, model_cfg, ckpt_path, vocab_file="", ode_method=ode_me
|
|
156 |
model = CFM(
|
157 |
transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
|
158 |
mel_spec_kwargs=dict(
|
159 |
-
|
160 |
-
n_mel_channels=n_mel_channels,
|
161 |
hop_length=hop_length,
|
|
|
|
|
|
|
|
|
162 |
),
|
163 |
odeint_kwargs=dict(
|
164 |
method=ode_method,
|
@@ -166,7 +207,8 @@ def load_model(model_cls, model_cfg, ckpt_path, vocab_file="", ode_method=ode_me
|
|
166 |
vocab_char_map=vocab_char_map,
|
167 |
).to(device)
|
168 |
|
169 |
-
|
|
|
170 |
|
171 |
return model
|
172 |
|
@@ -261,6 +303,7 @@ def infer_process(
|
|
261 |
gen_text,
|
262 |
model_obj,
|
263 |
vocoder,
|
|
|
264 |
show_info=print,
|
265 |
progress=tqdm,
|
266 |
target_rms=target_rms,
|
@@ -286,6 +329,7 @@ def infer_process(
|
|
286 |
gen_text_batches,
|
287 |
model_obj,
|
288 |
vocoder,
|
|
|
289 |
progress=progress,
|
290 |
target_rms=target_rms,
|
291 |
cross_fade_duration=cross_fade_duration,
|
@@ -307,6 +351,7 @@ def infer_batch_process(
|
|
307 |
gen_text_batches,
|
308 |
model_obj,
|
309 |
vocoder,
|
|
|
310 |
progress=tqdm,
|
311 |
target_rms=0.1,
|
312 |
cross_fade_duration=0.15,
|
@@ -359,18 +404,21 @@ def infer_batch_process(
|
|
359 |
sway_sampling_coef=sway_sampling_coef,
|
360 |
)
|
361 |
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
|
|
|
|
|
|
374 |
|
375 |
# Combine all generated waves with cross-fading
|
376 |
if cross_fade_duration <= 0:
|
|
|
1 |
# A unified script for inference process
|
2 |
# Make adjustments inside functions, and consider both gradio and cli scripts if need to change func output format
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
|
6 |
+
sys.path.append(f"../../{os.path.dirname(os.path.abspath(__file__))}/third_party/BigVGAN/")
|
7 |
|
8 |
import hashlib
|
9 |
import re
|
|
|
38 |
target_sample_rate = 24000
|
39 |
n_mel_channels = 100
|
40 |
hop_length = 256
|
41 |
+
win_length = 1024
|
42 |
+
n_fft = 1024
|
43 |
+
mel_spec_type = "vocos"
|
44 |
target_rms = 0.1
|
45 |
cross_fade_duration = 0.15
|
46 |
ode_method = "euler"
|
|
|
87 |
|
88 |
|
89 |
# load vocoder
|
90 |
+
def load_vocoder(vocoder_name="vocos", is_local=False, local_path="", device=device):
|
91 |
+
if vocoder_name == "vocos":
|
92 |
+
if is_local:
|
93 |
+
print(f"Load vocos from local path {local_path}")
|
94 |
+
vocoder = Vocos.from_hparams(f"{local_path}/config.yaml")
|
95 |
+
state_dict = torch.load(f"{local_path}/pytorch_model.bin", map_location="cpu")
|
96 |
+
vocoder.load_state_dict(state_dict)
|
97 |
+
vocoder = vocoder.eval().to(device)
|
98 |
+
else:
|
99 |
+
print("Download Vocos from huggingface charactr/vocos-mel-24khz")
|
100 |
+
vocoder = Vocos.from_pretrained("charactr/vocos-mel-24khz").to(device)
|
101 |
+
elif vocoder_name == "bigvgan":
|
102 |
+
try:
|
103 |
+
from third_party.BigVGAN import bigvgan
|
104 |
+
except ImportError:
|
105 |
+
print("You need to follow the README to init submodule and change the BigVGAN source code.")
|
106 |
+
if is_local:
|
107 |
+
"""download from https://huggingface.co/nvidia/bigvgan_v2_24khz_100band_256x/tree/main"""
|
108 |
+
vocoder = bigvgan.BigVGAN.from_pretrained(local_path, use_cuda_kernel=False)
|
109 |
+
else:
|
110 |
+
vocoder = bigvgan.BigVGAN.from_pretrained("nvidia/bigvgan_v2_24khz_100band_256x", use_cuda_kernel=False)
|
111 |
+
|
112 |
+
vocoder.remove_weight_norm()
|
113 |
+
vocoder = vocoder.eval().to(device)
|
114 |
+
return vocoder
|
115 |
|
116 |
|
117 |
# load asr pipeline
|
|
|
132 |
# load model checkpoint for inference
|
133 |
|
134 |
|
135 |
+
def load_checkpoint(model, ckpt_path, device, dtype=None, use_ema=True):
|
136 |
+
if dtype is None:
|
137 |
+
dtype = (
|
138 |
+
torch.float16 if device == "cuda" and torch.cuda.get_device_properties(device).major >= 6 else torch.float32
|
139 |
+
)
|
140 |
+
model = model.to(dtype)
|
141 |
|
142 |
ckpt_type = ckpt_path.split(".")[-1]
|
143 |
if ckpt_type == "safetensors":
|
|
|
155 |
for k, v in checkpoint["ema_model_state_dict"].items()
|
156 |
if k not in ["initted", "step"]
|
157 |
}
|
158 |
+
|
159 |
+
for key in ["mel_spec.mel_stft.mel_scale.fb", "mel_spec.mel_stft.spectrogram.window"]:
|
160 |
+
if key in checkpoint["model_state_dict"]:
|
161 |
+
del checkpoint["model_state_dict"][key]
|
162 |
+
|
163 |
model.load_state_dict(checkpoint["model_state_dict"])
|
164 |
else:
|
165 |
if ckpt_type == "safetensors":
|
|
|
172 |
# load model for inference
|
173 |
|
174 |
|
175 |
+
def load_model(
|
176 |
+
model_cls,
|
177 |
+
model_cfg,
|
178 |
+
ckpt_path,
|
179 |
+
mel_spec_type=mel_spec_type,
|
180 |
+
vocab_file="",
|
181 |
+
ode_method=ode_method,
|
182 |
+
use_ema=True,
|
183 |
+
device=device,
|
184 |
+
):
|
185 |
if vocab_file == "":
|
186 |
vocab_file = str(files("f5_tts").joinpath("infer/examples/vocab.txt"))
|
187 |
tokenizer = "custom"
|
|
|
194 |
model = CFM(
|
195 |
transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
|
196 |
mel_spec_kwargs=dict(
|
197 |
+
n_fft=n_fft,
|
|
|
198 |
hop_length=hop_length,
|
199 |
+
win_length=win_length,
|
200 |
+
n_mel_channels=n_mel_channels,
|
201 |
+
target_sample_rate=target_sample_rate,
|
202 |
+
mel_spec_type=mel_spec_type,
|
203 |
),
|
204 |
odeint_kwargs=dict(
|
205 |
method=ode_method,
|
|
|
207 |
vocab_char_map=vocab_char_map,
|
208 |
).to(device)
|
209 |
|
210 |
+
dtype = torch.float32 if mel_spec_type == "bigvgan" else None
|
211 |
+
model = load_checkpoint(model, ckpt_path, device, dtype=dtype, use_ema=use_ema)
|
212 |
|
213 |
return model
|
214 |
|
|
|
303 |
gen_text,
|
304 |
model_obj,
|
305 |
vocoder,
|
306 |
+
mel_spec_type=mel_spec_type,
|
307 |
show_info=print,
|
308 |
progress=tqdm,
|
309 |
target_rms=target_rms,
|
|
|
329 |
gen_text_batches,
|
330 |
model_obj,
|
331 |
vocoder,
|
332 |
+
mel_spec_type=mel_spec_type,
|
333 |
progress=progress,
|
334 |
target_rms=target_rms,
|
335 |
cross_fade_duration=cross_fade_duration,
|
|
|
351 |
gen_text_batches,
|
352 |
model_obj,
|
353 |
vocoder,
|
354 |
+
mel_spec_type="vocos",
|
355 |
progress=tqdm,
|
356 |
target_rms=0.1,
|
357 |
cross_fade_duration=0.15,
|
|
|
404 |
sway_sampling_coef=sway_sampling_coef,
|
405 |
)
|
406 |
|
407 |
+
generated = generated.to(torch.float32)
|
408 |
+
generated = generated[:, ref_audio_len:, :]
|
409 |
+
generated_mel_spec = generated.permute(0, 2, 1)
|
410 |
+
if mel_spec_type == "vocos":
|
411 |
+
generated_wave = vocoder.decode(generated_mel_spec)
|
412 |
+
elif mel_spec_type == "bigvgan":
|
413 |
+
generated_wave = vocoder(generated_mel_spec)
|
414 |
+
if rms < target_rms:
|
415 |
+
generated_wave = generated_wave * rms / target_rms
|
416 |
+
|
417 |
+
# wav -> numpy
|
418 |
+
generated_wave = generated_wave.squeeze().cpu().numpy()
|
419 |
+
|
420 |
+
generated_waves.append(generated_wave)
|
421 |
+
spectrograms.append(generated_mel_spec[0].cpu().numpy())
|
422 |
|
423 |
# Combine all generated waves with cross-fading
|
424 |
if cross_fade_duration <= 0:
|
src/f5_tts/model/cfm.py
CHANGED
@@ -8,23 +8,23 @@ d - dimension
|
|
8 |
"""
|
9 |
|
10 |
from __future__ import annotations
|
11 |
-
|
12 |
from random import random
|
|
|
13 |
|
14 |
import torch
|
15 |
-
from torch import nn
|
16 |
import torch.nn.functional as F
|
|
|
17 |
from torch.nn.utils.rnn import pad_sequence
|
18 |
-
|
19 |
from torchdiffeq import odeint
|
20 |
|
21 |
from f5_tts.model.modules import MelSpec
|
22 |
from f5_tts.model.utils import (
|
23 |
default,
|
24 |
exists,
|
|
|
25 |
list_str_to_idx,
|
26 |
list_str_to_tensor,
|
27 |
-
lens_to_mask,
|
28 |
mask_from_frac_lengths,
|
29 |
)
|
30 |
|
@@ -98,10 +98,6 @@ class CFM(nn.Module):
|
|
98 |
edit_mask=None,
|
99 |
):
|
100 |
self.eval()
|
101 |
-
|
102 |
-
if next(self.parameters()).dtype == torch.float16:
|
103 |
-
cond = cond.half()
|
104 |
-
|
105 |
# raw wave
|
106 |
|
107 |
if cond.ndim == 2:
|
@@ -109,6 +105,8 @@ class CFM(nn.Module):
|
|
109 |
cond = cond.permute(0, 2, 1)
|
110 |
assert cond.shape[-1] == self.num_channels
|
111 |
|
|
|
|
|
112 |
batch, cond_seq_len, device = *cond.shape[:2], cond.device
|
113 |
if not exists(lens):
|
114 |
lens = torch.full((batch,), cond_seq_len, device=device, dtype=torch.long)
|
|
|
8 |
"""
|
9 |
|
10 |
from __future__ import annotations
|
11 |
+
|
12 |
from random import random
|
13 |
+
from typing import Callable
|
14 |
|
15 |
import torch
|
|
|
16 |
import torch.nn.functional as F
|
17 |
+
from torch import nn
|
18 |
from torch.nn.utils.rnn import pad_sequence
|
|
|
19 |
from torchdiffeq import odeint
|
20 |
|
21 |
from f5_tts.model.modules import MelSpec
|
22 |
from f5_tts.model.utils import (
|
23 |
default,
|
24 |
exists,
|
25 |
+
lens_to_mask,
|
26 |
list_str_to_idx,
|
27 |
list_str_to_tensor,
|
|
|
28 |
mask_from_frac_lengths,
|
29 |
)
|
30 |
|
|
|
98 |
edit_mask=None,
|
99 |
):
|
100 |
self.eval()
|
|
|
|
|
|
|
|
|
101 |
# raw wave
|
102 |
|
103 |
if cond.ndim == 2:
|
|
|
105 |
cond = cond.permute(0, 2, 1)
|
106 |
assert cond.shape[-1] == self.num_channels
|
107 |
|
108 |
+
cond = cond.to(next(self.parameters()).dtype)
|
109 |
+
|
110 |
batch, cond_seq_len, device = *cond.shape[:2], cond.device
|
111 |
if not exists(lens):
|
112 |
lens = torch.full((batch,), cond_seq_len, device=device, dtype=torch.long)
|
src/f5_tts/model/dataset.py
CHANGED
@@ -1,15 +1,15 @@
|
|
1 |
import json
|
2 |
import random
|
3 |
from importlib.resources import files
|
4 |
-
from tqdm import tqdm
|
5 |
|
6 |
import torch
|
7 |
import torch.nn.functional as F
|
8 |
import torchaudio
|
|
|
|
|
9 |
from torch import nn
|
10 |
from torch.utils.data import Dataset, Sampler
|
11 |
-
from
|
12 |
-
from datasets import Dataset as Dataset_
|
13 |
|
14 |
from f5_tts.model.modules import MelSpec
|
15 |
from f5_tts.model.utils import default
|
@@ -22,12 +22,21 @@ class HFDataset(Dataset):
|
|
22 |
target_sample_rate=24_000,
|
23 |
n_mel_channels=100,
|
24 |
hop_length=256,
|
|
|
|
|
|
|
25 |
):
|
26 |
self.data = hf_dataset
|
27 |
self.target_sample_rate = target_sample_rate
|
28 |
self.hop_length = hop_length
|
|
|
29 |
self.mel_spectrogram = MelSpec(
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
31 |
)
|
32 |
|
33 |
def get_frame_len(self, index):
|
@@ -79,6 +88,9 @@ class CustomDataset(Dataset):
|
|
79 |
target_sample_rate=24_000,
|
80 |
hop_length=256,
|
81 |
n_mel_channels=100,
|
|
|
|
|
|
|
82 |
preprocessed_mel=False,
|
83 |
mel_spec_module: nn.Module | None = None,
|
84 |
):
|
@@ -86,15 +98,21 @@ class CustomDataset(Dataset):
|
|
86 |
self.durations = durations
|
87 |
self.target_sample_rate = target_sample_rate
|
88 |
self.hop_length = hop_length
|
|
|
|
|
|
|
89 |
self.preprocessed_mel = preprocessed_mel
|
90 |
|
91 |
if not preprocessed_mel:
|
92 |
self.mel_spectrogram = default(
|
93 |
mel_spec_module,
|
94 |
MelSpec(
|
95 |
-
|
96 |
hop_length=hop_length,
|
|
|
97 |
n_mel_channels=n_mel_channels,
|
|
|
|
|
98 |
),
|
99 |
)
|
100 |
|
|
|
1 |
import json
|
2 |
import random
|
3 |
from importlib.resources import files
|
|
|
4 |
|
5 |
import torch
|
6 |
import torch.nn.functional as F
|
7 |
import torchaudio
|
8 |
+
from datasets import Dataset as Dataset_
|
9 |
+
from datasets import load_from_disk
|
10 |
from torch import nn
|
11 |
from torch.utils.data import Dataset, Sampler
|
12 |
+
from tqdm import tqdm
|
|
|
13 |
|
14 |
from f5_tts.model.modules import MelSpec
|
15 |
from f5_tts.model.utils import default
|
|
|
22 |
target_sample_rate=24_000,
|
23 |
n_mel_channels=100,
|
24 |
hop_length=256,
|
25 |
+
n_fft=1024,
|
26 |
+
win_length=1024,
|
27 |
+
mel_spec_type="vocos",
|
28 |
):
|
29 |
self.data = hf_dataset
|
30 |
self.target_sample_rate = target_sample_rate
|
31 |
self.hop_length = hop_length
|
32 |
+
|
33 |
self.mel_spectrogram = MelSpec(
|
34 |
+
n_fft=n_fft,
|
35 |
+
hop_length=hop_length,
|
36 |
+
win_length=win_length,
|
37 |
+
n_mel_channels=n_mel_channels,
|
38 |
+
target_sample_rate=target_sample_rate,
|
39 |
+
mel_spec_type=mel_spec_type,
|
40 |
)
|
41 |
|
42 |
def get_frame_len(self, index):
|
|
|
88 |
target_sample_rate=24_000,
|
89 |
hop_length=256,
|
90 |
n_mel_channels=100,
|
91 |
+
n_fft=1024,
|
92 |
+
win_length=1024,
|
93 |
+
mel_spec_type="vocos",
|
94 |
preprocessed_mel=False,
|
95 |
mel_spec_module: nn.Module | None = None,
|
96 |
):
|
|
|
98 |
self.durations = durations
|
99 |
self.target_sample_rate = target_sample_rate
|
100 |
self.hop_length = hop_length
|
101 |
+
self.n_fft = n_fft
|
102 |
+
self.win_length = win_length
|
103 |
+
self.mel_spec_type = mel_spec_type
|
104 |
self.preprocessed_mel = preprocessed_mel
|
105 |
|
106 |
if not preprocessed_mel:
|
107 |
self.mel_spectrogram = default(
|
108 |
mel_spec_module,
|
109 |
MelSpec(
|
110 |
+
n_fft=n_fft,
|
111 |
hop_length=hop_length,
|
112 |
+
win_length=win_length,
|
113 |
n_mel_channels=n_mel_channels,
|
114 |
+
target_sample_rate=target_sample_rate,
|
115 |
+
mel_spec_type=mel_spec_type,
|
116 |
),
|
117 |
)
|
118 |
|
src/f5_tts/model/modules.py
CHANGED
@@ -8,61 +8,138 @@ d - dimension
|
|
8 |
"""
|
9 |
|
10 |
from __future__ import annotations
|
11 |
-
|
12 |
import math
|
|
|
13 |
|
14 |
import torch
|
15 |
-
from torch import nn
|
16 |
import torch.nn.functional as F
|
17 |
import torchaudio
|
18 |
-
|
|
|
19 |
from x_transformers.x_transformers import apply_rotary_pos_emb
|
20 |
|
21 |
|
22 |
# raw wav to mel spec
|
23 |
|
24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
class MelSpec(nn.Module):
|
26 |
def __init__(
|
27 |
self,
|
28 |
-
|
29 |
hop_length=256,
|
30 |
win_length=1024,
|
31 |
n_mel_channels=100,
|
32 |
target_sample_rate=24_000,
|
33 |
-
|
34 |
-
power=1,
|
35 |
-
norm=None,
|
36 |
-
center=True,
|
37 |
):
|
38 |
super().__init__()
|
|
|
|
|
|
|
|
|
|
|
39 |
self.n_mel_channels = n_mel_channels
|
|
|
40 |
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
hop_length=hop_length,
|
46 |
-
n_mels=n_mel_channels,
|
47 |
-
power=power,
|
48 |
-
center=center,
|
49 |
-
normalized=normalize,
|
50 |
-
norm=norm,
|
51 |
-
)
|
52 |
|
53 |
self.register_buffer("dummy", torch.tensor(0), persistent=False)
|
54 |
|
55 |
-
def forward(self,
|
56 |
-
if
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
self.
|
|
|
|
|
|
|
|
|
63 |
|
64 |
-
mel = self.mel_stft(inp)
|
65 |
-
mel = mel.clamp(min=1e-5).log()
|
66 |
return mel
|
67 |
|
68 |
|
|
|
8 |
"""
|
9 |
|
10 |
from __future__ import annotations
|
11 |
+
|
12 |
import math
|
13 |
+
from typing import Optional
|
14 |
|
15 |
import torch
|
|
|
16 |
import torch.nn.functional as F
|
17 |
import torchaudio
|
18 |
+
from librosa.filters import mel as librosa_mel_fn
|
19 |
+
from torch import nn
|
20 |
from x_transformers.x_transformers import apply_rotary_pos_emb
|
21 |
|
22 |
|
23 |
# raw wav to mel spec
|
24 |
|
25 |
|
26 |
+
mel_basis_cache = {}
|
27 |
+
hann_window_cache = {}
|
28 |
+
|
29 |
+
|
30 |
+
def get_bigvgan_mel_spectrogram(
|
31 |
+
waveform,
|
32 |
+
n_fft=1024,
|
33 |
+
n_mel_channels=100,
|
34 |
+
target_sample_rate=24000,
|
35 |
+
hop_length=256,
|
36 |
+
win_length=1024,
|
37 |
+
fmin=0,
|
38 |
+
fmax=None,
|
39 |
+
center=False,
|
40 |
+
): # Copy from https://github.com/NVIDIA/BigVGAN/tree/main
|
41 |
+
device = waveform.device
|
42 |
+
key = f"{n_fft}_{n_mel_channels}_{target_sample_rate}_{hop_length}_{win_length}_{fmin}_{fmax}_{device}"
|
43 |
+
|
44 |
+
if key not in mel_basis_cache:
|
45 |
+
mel = librosa_mel_fn(sr=target_sample_rate, n_fft=n_fft, n_mels=n_mel_channels, fmin=fmin, fmax=fmax)
|
46 |
+
mel_basis_cache[key] = torch.from_numpy(mel).float().to(device) # TODO: why they need .float()?
|
47 |
+
hann_window_cache[key] = torch.hann_window(win_length).to(device)
|
48 |
+
|
49 |
+
mel_basis = mel_basis_cache[key]
|
50 |
+
hann_window = hann_window_cache[key]
|
51 |
+
|
52 |
+
padding = (n_fft - hop_length) // 2
|
53 |
+
waveform = torch.nn.functional.pad(waveform.unsqueeze(1), (padding, padding), mode="reflect").squeeze(1)
|
54 |
+
|
55 |
+
spec = torch.stft(
|
56 |
+
waveform,
|
57 |
+
n_fft,
|
58 |
+
hop_length=hop_length,
|
59 |
+
win_length=win_length,
|
60 |
+
window=hann_window,
|
61 |
+
center=center,
|
62 |
+
pad_mode="reflect",
|
63 |
+
normalized=False,
|
64 |
+
onesided=True,
|
65 |
+
return_complex=True,
|
66 |
+
)
|
67 |
+
spec = torch.sqrt(torch.view_as_real(spec).pow(2).sum(-1) + 1e-9)
|
68 |
+
|
69 |
+
mel_spec = torch.matmul(mel_basis, spec)
|
70 |
+
mel_spec = torch.log(torch.clamp(mel_spec, min=1e-5))
|
71 |
+
|
72 |
+
return mel_spec
|
73 |
+
|
74 |
+
|
75 |
+
def get_vocos_mel_spectrogram(
|
76 |
+
waveform,
|
77 |
+
n_fft=1024,
|
78 |
+
n_mel_channels=100,
|
79 |
+
target_sample_rate=24000,
|
80 |
+
hop_length=256,
|
81 |
+
win_length=1024,
|
82 |
+
):
|
83 |
+
mel_stft = torchaudio.transforms.MelSpectrogram(
|
84 |
+
sample_rate=target_sample_rate,
|
85 |
+
n_fft=n_fft,
|
86 |
+
win_length=win_length,
|
87 |
+
hop_length=hop_length,
|
88 |
+
n_mels=n_mel_channels,
|
89 |
+
power=1,
|
90 |
+
center=True,
|
91 |
+
normalized=False,
|
92 |
+
norm=None,
|
93 |
+
).to(waveform.device)
|
94 |
+
if len(waveform.shape) == 3:
|
95 |
+
waveform = waveform.squeeze(1) # 'b 1 nw -> b nw'
|
96 |
+
|
97 |
+
assert len(waveform.shape) == 2
|
98 |
+
|
99 |
+
mel = mel_stft(waveform)
|
100 |
+
mel = mel.clamp(min=1e-5).log()
|
101 |
+
return mel
|
102 |
+
|
103 |
+
|
104 |
class MelSpec(nn.Module):
|
105 |
def __init__(
|
106 |
self,
|
107 |
+
n_fft=1024,
|
108 |
hop_length=256,
|
109 |
win_length=1024,
|
110 |
n_mel_channels=100,
|
111 |
target_sample_rate=24_000,
|
112 |
+
mel_spec_type="vocos",
|
|
|
|
|
|
|
113 |
):
|
114 |
super().__init__()
|
115 |
+
assert mel_spec_type in ["vocos", "bigvgan"], print("We only support two extract mel backend: vocos or bigvgan")
|
116 |
+
|
117 |
+
self.n_fft = n_fft
|
118 |
+
self.hop_length = hop_length
|
119 |
+
self.win_length = win_length
|
120 |
self.n_mel_channels = n_mel_channels
|
121 |
+
self.target_sample_rate = target_sample_rate
|
122 |
|
123 |
+
if mel_spec_type == "vocos":
|
124 |
+
self.extractor = get_vocos_mel_spectrogram
|
125 |
+
elif mel_spec_type == "bigvgan":
|
126 |
+
self.extractor = get_bigvgan_mel_spectrogram
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
|
128 |
self.register_buffer("dummy", torch.tensor(0), persistent=False)
|
129 |
|
130 |
+
def forward(self, wav):
|
131 |
+
if self.dummy.device != wav.device:
|
132 |
+
self.to(wav.device)
|
133 |
+
|
134 |
+
mel = self.extractor(
|
135 |
+
waveform=wav,
|
136 |
+
n_fft=self.n_fft,
|
137 |
+
n_mel_channels=self.n_mel_channels,
|
138 |
+
target_sample_rate=self.target_sample_rate,
|
139 |
+
hop_length=self.hop_length,
|
140 |
+
win_length=self.win_length,
|
141 |
+
)
|
142 |
|
|
|
|
|
143 |
return mel
|
144 |
|
145 |
|
src/f5_tts/model/trainer.py
CHANGED
@@ -1,25 +1,22 @@
|
|
1 |
from __future__ import annotations
|
2 |
|
3 |
-
import os
|
4 |
import gc
|
5 |
-
|
6 |
-
import wandb
|
7 |
|
8 |
import torch
|
9 |
import torchaudio
|
10 |
-
|
11 |
-
from torch.utils.data import DataLoader, Dataset, SequentialSampler
|
12 |
-
from torch.optim.lr_scheduler import LinearLR, SequentialLR
|
13 |
-
|
14 |
from accelerate import Accelerator
|
15 |
from accelerate.utils import DistributedDataParallelKwargs
|
16 |
-
|
17 |
from ema_pytorch import EMA
|
|
|
|
|
|
|
|
|
18 |
|
19 |
from f5_tts.model import CFM
|
20 |
-
from f5_tts.model.utils import exists, default
|
21 |
from f5_tts.model.dataset import DynamicBatchSampler, collate_fn
|
22 |
-
|
23 |
|
24 |
# trainer
|
25 |
|
@@ -49,6 +46,7 @@ class Trainer:
|
|
49 |
accelerate_kwargs: dict = dict(),
|
50 |
ema_kwargs: dict = dict(),
|
51 |
bnb_optimizer: bool = False,
|
|
|
52 |
):
|
53 |
ddp_kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
|
54 |
|
@@ -110,6 +108,7 @@ class Trainer:
|
|
110 |
self.max_samples = max_samples
|
111 |
self.grad_accumulation_steps = grad_accumulation_steps
|
112 |
self.max_grad_norm = max_grad_norm
|
|
|
113 |
|
114 |
self.noise_scheduler = noise_scheduler
|
115 |
|
@@ -188,9 +187,9 @@ class Trainer:
|
|
188 |
|
189 |
def train(self, train_dataset: Dataset, num_workers=16, resumable_with_seed: int = None):
|
190 |
if self.log_samples:
|
191 |
-
from f5_tts.infer.utils_infer import load_vocoder, nfe_step,
|
192 |
|
193 |
-
vocoder = load_vocoder()
|
194 |
target_sample_rate = self.accelerator.unwrap_model(self.model).mel_spec.mel_stft.sample_rate
|
195 |
log_samples_path = f"{self.checkpoint_path}/samples"
|
196 |
os.makedirs(log_samples_path, exist_ok=True)
|
@@ -315,7 +314,7 @@ class Trainer:
|
|
315 |
self.save_checkpoint(global_step)
|
316 |
|
317 |
if self.log_samples and self.accelerator.is_local_main_process:
|
318 |
-
ref_audio, ref_audio_len = vocoder.decode(batch["mel"][0].unsqueeze(0)
|
319 |
torchaudio.save(f"{log_samples_path}/step_{global_step}_ref.wav", ref_audio, target_sample_rate)
|
320 |
with torch.inference_mode():
|
321 |
generated, _ = self.accelerator.unwrap_model(self.model).sample(
|
|
|
1 |
from __future__ import annotations
|
2 |
|
|
|
3 |
import gc
|
4 |
+
import os
|
|
|
5 |
|
6 |
import torch
|
7 |
import torchaudio
|
8 |
+
import wandb
|
|
|
|
|
|
|
9 |
from accelerate import Accelerator
|
10 |
from accelerate.utils import DistributedDataParallelKwargs
|
|
|
11 |
from ema_pytorch import EMA
|
12 |
+
from torch.optim import AdamW
|
13 |
+
from torch.optim.lr_scheduler import LinearLR, SequentialLR
|
14 |
+
from torch.utils.data import DataLoader, Dataset, SequentialSampler
|
15 |
+
from tqdm import tqdm
|
16 |
|
17 |
from f5_tts.model import CFM
|
|
|
18 |
from f5_tts.model.dataset import DynamicBatchSampler, collate_fn
|
19 |
+
from f5_tts.model.utils import default, exists
|
20 |
|
21 |
# trainer
|
22 |
|
|
|
46 |
accelerate_kwargs: dict = dict(),
|
47 |
ema_kwargs: dict = dict(),
|
48 |
bnb_optimizer: bool = False,
|
49 |
+
mel_spec_type: str = "vocos", # "vocos" | "bigvgan"
|
50 |
):
|
51 |
ddp_kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
|
52 |
|
|
|
108 |
self.max_samples = max_samples
|
109 |
self.grad_accumulation_steps = grad_accumulation_steps
|
110 |
self.max_grad_norm = max_grad_norm
|
111 |
+
self.vocoder_name = mel_spec_type
|
112 |
|
113 |
self.noise_scheduler = noise_scheduler
|
114 |
|
|
|
187 |
|
188 |
def train(self, train_dataset: Dataset, num_workers=16, resumable_with_seed: int = None):
|
189 |
if self.log_samples:
|
190 |
+
from f5_tts.infer.utils_infer import cfg_strength, load_vocoder, nfe_step, sway_sampling_coef
|
191 |
|
192 |
+
vocoder = load_vocoder(vocoder_name=self.vocoder_name)
|
193 |
target_sample_rate = self.accelerator.unwrap_model(self.model).mel_spec.mel_stft.sample_rate
|
194 |
log_samples_path = f"{self.checkpoint_path}/samples"
|
195 |
os.makedirs(log_samples_path, exist_ok=True)
|
|
|
314 |
self.save_checkpoint(global_step)
|
315 |
|
316 |
if self.log_samples and self.accelerator.is_local_main_process:
|
317 |
+
ref_audio, ref_audio_len = vocoder.decode(batch["mel"][0].unsqueeze(0)), mel_lengths[0]
|
318 |
torchaudio.save(f"{log_samples_path}/step_{global_step}_ref.wav", ref_audio, target_sample_rate)
|
319 |
with torch.inference_mode():
|
320 |
generated, _ = self.accelerator.unwrap_model(self.model).sample(
|
src/f5_tts/train/train.py
CHANGED
@@ -2,16 +2,18 @@
|
|
2 |
|
3 |
from importlib.resources import files
|
4 |
|
5 |
-
from f5_tts.model import CFM,
|
6 |
-
from f5_tts.model.utils import get_tokenizer
|
7 |
from f5_tts.model.dataset import load_dataset
|
8 |
-
|
9 |
|
10 |
# -------------------------- Dataset Settings --------------------------- #
|
11 |
|
12 |
target_sample_rate = 24000
|
13 |
n_mel_channels = 100
|
14 |
hop_length = 256
|
|
|
|
|
|
|
15 |
|
16 |
tokenizer = "pinyin" # 'pinyin', 'char', or 'custom'
|
17 |
tokenizer_path = None # if tokenizer = 'custom', define the path to the tokenizer you want to use (should be vocab.txt)
|
@@ -56,9 +58,12 @@ def main():
|
|
56 |
vocab_char_map, vocab_size = get_tokenizer(tokenizer_path, tokenizer)
|
57 |
|
58 |
mel_spec_kwargs = dict(
|
59 |
-
|
60 |
-
n_mel_channels=n_mel_channels,
|
61 |
hop_length=hop_length,
|
|
|
|
|
|
|
|
|
62 |
)
|
63 |
|
64 |
model = CFM(
|
@@ -84,6 +89,7 @@ def main():
|
|
84 |
wandb_resume_id=wandb_resume_id,
|
85 |
last_per_steps=last_per_steps,
|
86 |
log_samples=True,
|
|
|
87 |
)
|
88 |
|
89 |
train_dataset = load_dataset(dataset_name, tokenizer, mel_spec_kwargs=mel_spec_kwargs)
|
|
|
2 |
|
3 |
from importlib.resources import files
|
4 |
|
5 |
+
from f5_tts.model import CFM, DiT, Trainer, UNetT
|
|
|
6 |
from f5_tts.model.dataset import load_dataset
|
7 |
+
from f5_tts.model.utils import get_tokenizer
|
8 |
|
9 |
# -------------------------- Dataset Settings --------------------------- #
|
10 |
|
11 |
target_sample_rate = 24000
|
12 |
n_mel_channels = 100
|
13 |
hop_length = 256
|
14 |
+
win_length = 1024
|
15 |
+
n_fft = 1024
|
16 |
+
mel_spec_type = "vocos" # 'vocos' or 'bigvgan'
|
17 |
|
18 |
tokenizer = "pinyin" # 'pinyin', 'char', or 'custom'
|
19 |
tokenizer_path = None # if tokenizer = 'custom', define the path to the tokenizer you want to use (should be vocab.txt)
|
|
|
58 |
vocab_char_map, vocab_size = get_tokenizer(tokenizer_path, tokenizer)
|
59 |
|
60 |
mel_spec_kwargs = dict(
|
61 |
+
n_fft=n_fft,
|
|
|
62 |
hop_length=hop_length,
|
63 |
+
win_length=win_length,
|
64 |
+
n_mel_channels=n_mel_channels,
|
65 |
+
target_sample_rate=target_sample_rate,
|
66 |
+
mel_spec_type=mel_spec_type,
|
67 |
)
|
68 |
|
69 |
model = CFM(
|
|
|
89 |
wandb_resume_id=wandb_resume_id,
|
90 |
last_per_steps=last_per_steps,
|
91 |
log_samples=True,
|
92 |
+
mel_spec_type=mel_spec_type,
|
93 |
)
|
94 |
|
95 |
train_dataset = load_dataset(dataset_name, tokenizer, mel_spec_kwargs=mel_spec_kwargs)
|