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
|
|
1 |
+
import os
|
2 |
+
import gc
|
3 |
+
|
4 |
+
from trainer import Trainer, TrainerArgs
|
5 |
+
|
6 |
+
from TTS.config.shared_configs import BaseDatasetConfig
|
7 |
+
from TTS.tts.datasets import load_tts_samples
|
8 |
+
from TTS.tts.layers.xtts.trainer.gpt_trainer import GPTArgs, GPTTrainer, GPTTrainerConfig, XttsAudioConfig
|
9 |
+
from TTS.utils.manage import ModelManager
|
10 |
+
|
11 |
+
from dataclasses import dataclass, field
|
12 |
+
from typing import Optional
|
13 |
+
from transformers import HfArgumentParser
|
14 |
+
|
15 |
+
import argparse
|
16 |
+
|
17 |
+
def create_xtts_trainer_parser():
|
18 |
+
parser = argparse.ArgumentParser(description="Arguments for XTTS Trainer")
|
19 |
+
|
20 |
+
parser.add_argument("--output_path", type=str, required=True,
|
21 |
+
help="Path to pretrained + checkpoint model")
|
22 |
+
parser.add_argument("--metadatas", nargs='+', type=str, required=True,
|
23 |
+
help="train_csv_path,eval_csv_path,language")
|
24 |
+
parser.add_argument("--num_epochs", type=int, default=1,
|
25 |
+
help="Number of epochs")
|
26 |
+
parser.add_argument("--batch_size", type=int, default=1,
|
27 |
+
help="Mini batch size")
|
28 |
+
parser.add_argument("--grad_acumm", type=int, default=1,
|
29 |
+
help="Grad accumulation steps")
|
30 |
+
parser.add_argument("--max_audio_length", type=int, default=255995,
|
31 |
+
help="Max audio length")
|
32 |
+
parser.add_argument("--max_text_length", type=int, default=200,
|
33 |
+
help="Max text length")
|
34 |
+
parser.add_argument("--weight_decay", type=float, default=1e-2,
|
35 |
+
help="Weight decay")
|
36 |
+
parser.add_argument("--lr", type=float, default=5e-6,
|
37 |
+
help="Learning rate")
|
38 |
+
parser.add_argument("--save_step", type=int, default=5000,
|
39 |
+
help="Save step")
|
40 |
+
|
41 |
+
return parser
|
42 |
+
|
43 |
+
|
44 |
+
|
45 |
+
def train_gpt(metadatas, num_epochs, batch_size, grad_acumm, output_path, max_audio_length, max_text_length, lr, weight_decay, save_step):
|
46 |
+
# Logging parameters
|
47 |
+
RUN_NAME = "GPT_XTTS_FT"
|
48 |
+
PROJECT_NAME = "XTTS_trainer"
|
49 |
+
DASHBOARD_LOGGER = "tensorboard"
|
50 |
+
LOGGER_URI = None
|
51 |
+
|
52 |
+
# Set here the path that the checkpoints will be saved. Default: ./run/training/
|
53 |
+
# OUT_PATH = os.path.join(output_path, "run", "training")
|
54 |
+
OUT_PATH = output_path
|
55 |
+
|
56 |
+
# Training Parameters
|
57 |
+
OPTIMIZER_WD_ONLY_ON_WEIGHTS = True # for multi-gpu training please make it False
|
58 |
+
START_WITH_EVAL = False # if True it will star with evaluation
|
59 |
+
BATCH_SIZE = batch_size # set here the batch size
|
60 |
+
GRAD_ACUMM_STEPS = grad_acumm # set here the grad accumulation steps
|
61 |
+
|
62 |
+
|
63 |
+
# Define here the dataset that you want to use for the fine-tuning on.
|
64 |
+
DATASETS_CONFIG_LIST = []
|
65 |
+
for metadata in metadatas:
|
66 |
+
train_csv, eval_csv, language = metadata.split(",")
|
67 |
+
print(train_csv, eval_csv, language)
|
68 |
+
|
69 |
+
config_dataset = BaseDatasetConfig(
|
70 |
+
formatter="coqui",
|
71 |
+
dataset_name="ft_dataset",
|
72 |
+
path=os.path.dirname(train_csv),
|
73 |
+
meta_file_train=os.path.basename(train_csv),
|
74 |
+
meta_file_val=os.path.basename(eval_csv),
|
75 |
+
language=language,
|
76 |
+
)
|
77 |
+
|
78 |
+
DATASETS_CONFIG_LIST.append(config_dataset)
|
79 |
+
|
80 |
+
# Define the path where XTTS v2.0.1 files will be downloaded
|
81 |
+
CHECKPOINTS_OUT_PATH = os.path.join(OUT_PATH, "XTTS_v2.0_original_model_files/")
|
82 |
+
os.makedirs(CHECKPOINTS_OUT_PATH, exist_ok=True)
|
83 |
+
|
84 |
+
|
85 |
+
# DVAE files
|
86 |
+
DVAE_CHECKPOINT_LINK = "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/dvae.pth"
|
87 |
+
MEL_NORM_LINK = "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/mel_stats.pth"
|
88 |
+
|
89 |
+
# Set the path to the downloaded files
|
90 |
+
DVAE_CHECKPOINT = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(DVAE_CHECKPOINT_LINK))
|
91 |
+
MEL_NORM_FILE = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(MEL_NORM_LINK))
|
92 |
+
|
93 |
+
# download DVAE files if needed
|
94 |
+
if not os.path.isfile(DVAE_CHECKPOINT) or not os.path.isfile(MEL_NORM_FILE):
|
95 |
+
print(" > Downloading DVAE files!")
|
96 |
+
ModelManager._download_model_files([MEL_NORM_LINK, DVAE_CHECKPOINT_LINK], CHECKPOINTS_OUT_PATH, progress_bar=True)
|
97 |
+
|
98 |
+
|
99 |
+
# Download XTTS v2.0 checkpoint if needed
|
100 |
+
TOKENIZER_FILE_LINK = "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/vocab.json"
|
101 |
+
XTTS_CHECKPOINT_LINK = "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/model.pth"
|
102 |
+
XTTS_CONFIG_LINK = "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/config.json"
|
103 |
+
|
104 |
+
# XTTS transfer learning parameters: You we need to provide the paths of XTTS model checkpoint that you want to do the fine tuning.
|
105 |
+
TOKENIZER_FILE = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(TOKENIZER_FILE_LINK)) # vocab.json file
|
106 |
+
XTTS_CHECKPOINT = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(XTTS_CHECKPOINT_LINK)) # model.pth file
|
107 |
+
XTTS_CONFIG_FILE = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(XTTS_CONFIG_LINK)) # config.json file
|
108 |
+
|
109 |
+
# download XTTS v2.0 files if needed
|
110 |
+
if not os.path.isfile(TOKENIZER_FILE):
|
111 |
+
print(" > Downloading XTTS v2.0 tokenizer!")
|
112 |
+
ModelManager._download_model_files(
|
113 |
+
[TOKENIZER_FILE_LINK], CHECKPOINTS_OUT_PATH, progress_bar=True
|
114 |
+
)
|
115 |
+
if not os.path.isfile(XTTS_CHECKPOINT):
|
116 |
+
print(" > Downloading XTTS v2.0 checkpoint!")
|
117 |
+
ModelManager._download_model_files(
|
118 |
+
[XTTS_CHECKPOINT_LINK], CHECKPOINTS_OUT_PATH, progress_bar=True
|
119 |
+
)
|
120 |
+
if not os.path.isfile(XTTS_CONFIG_FILE):
|
121 |
+
print(" > Downloading XTTS v2.0 config!")
|
122 |
+
ModelManager._download_model_files(
|
123 |
+
[XTTS_CONFIG_LINK], CHECKPOINTS_OUT_PATH, progress_bar=True
|
124 |
+
)
|
125 |
+
|
126 |
+
# init args and config
|
127 |
+
model_args = GPTArgs(
|
128 |
+
max_conditioning_length=132300, # 6 secs
|
129 |
+
min_conditioning_length=11025, # 0.5 secs
|
130 |
+
debug_loading_failures=False,
|
131 |
+
max_wav_length=max_audio_length, # ~11.6 seconds
|
132 |
+
max_text_length=max_text_length,
|
133 |
+
mel_norm_file=MEL_NORM_FILE,
|
134 |
+
dvae_checkpoint=DVAE_CHECKPOINT,
|
135 |
+
xtts_checkpoint=XTTS_CHECKPOINT, # checkpoint path of the model that you want to fine-tune
|
136 |
+
tokenizer_file=TOKENIZER_FILE,
|
137 |
+
gpt_num_audio_tokens=1026,
|
138 |
+
gpt_start_audio_token=1024,
|
139 |
+
gpt_stop_audio_token=1025,
|
140 |
+
gpt_use_masking_gt_prompt_approach=True,
|
141 |
+
gpt_use_perceiver_resampler=True,
|
142 |
+
)
|
143 |
+
# define audio config
|
144 |
+
audio_config = XttsAudioConfig(sample_rate=22050, dvae_sample_rate=22050, output_sample_rate=24000)
|
145 |
+
# training parameters config
|
146 |
+
|
147 |
+
config = GPTTrainerConfig()
|
148 |
+
|
149 |
+
config.load_json(XTTS_CONFIG_FILE)
|
150 |
+
|
151 |
+
config.epochs = num_epochs
|
152 |
+
config.output_path = OUT_PATH
|
153 |
+
config.model_args = model_args
|
154 |
+
config.run_name = RUN_NAME
|
155 |
+
config.project_name = PROJECT_NAME
|
156 |
+
config.run_description = """
|
157 |
+
GPT XTTS training
|
158 |
+
""",
|
159 |
+
config.dashboard_logger = DASHBOARD_LOGGER
|
160 |
+
config.logger_uri = LOGGER_URI
|
161 |
+
config.audio = audio_config
|
162 |
+
config.batch_size = BATCH_SIZE
|
163 |
+
config.num_loader_workers = 8
|
164 |
+
config.eval_split_max_size = 256
|
165 |
+
config.print_step = 50
|
166 |
+
config.plot_step = 100
|
167 |
+
config.log_model_step = 100
|
168 |
+
config.save_n_checkpoints = 1
|
169 |
+
config.save_checkpoints = False
|
170 |
+
config.print_eval = False
|
171 |
+
config.optimizer = "AdamW"
|
172 |
+
config.optimizer_wd_only_on_weights = OPTIMIZER_WD_ONLY_ON_WEIGHTS
|
173 |
+
config.optimizer_params = {"betas": [0.9, 0.96], "eps": 1e-8, "weight_decay": weight_decay}
|
174 |
+
config.lr = lr
|
175 |
+
config.lr_scheduler = "MultiStepLR"
|
176 |
+
config.lr_scheduler_params = {"milestones": [50000 * 18, 150000 * 18, 300000 * 18], "gamma": 0.5, "last_epoch": -1}
|
177 |
+
config.test_sentences = []
|
178 |
+
config.save_step = 9999999999
|
179 |
+
|
180 |
+
|
181 |
+
# init the model from config
|
182 |
+
model = GPTTrainer.init_from_config(config)
|
183 |
+
|
184 |
+
# load training samples
|
185 |
+
train_samples, eval_samples = load_tts_samples(
|
186 |
+
DATASETS_CONFIG_LIST,
|
187 |
+
eval_split=True,
|
188 |
+
eval_split_max_size=config.eval_split_max_size,
|
189 |
+
eval_split_size=config.eval_split_size,
|
190 |
+
)
|
191 |
+
|
192 |
+
# init the trainer and 🚀
|
193 |
+
trainer = Trainer(
|
194 |
+
TrainerArgs(
|
195 |
+
restore_path=None, # xtts checkpoint is restored via xtts_checkpoint key so no need of restore it using Trainer restore_path parameter
|
196 |
+
skip_train_epoch=False,
|
197 |
+
start_with_eval=START_WITH_EVAL,
|
198 |
+
grad_accum_steps=GRAD_ACUMM_STEPS
|
199 |
+
),
|
200 |
+
config,
|
201 |
+
output_path=os.path.join(output_path, "run", "training"),
|
202 |
+
model=model,
|
203 |
+
train_samples=train_samples,
|
204 |
+
eval_samples=eval_samples,
|
205 |
+
)
|
206 |
+
trainer.fit()
|
207 |
+
trainer_out_path = trainer.output_path
|
208 |
+
|
209 |
+
# deallocate VRAM and RAM
|
210 |
+
del model, trainer, train_samples, eval_samples
|
211 |
+
gc.collect()
|
212 |
+
|
213 |
+
return trainer_out_path
|
214 |
+
|
215 |
+
if __name__ == "__main__":
|
216 |
+
parser = create_xtts_trainer_parser()
|
217 |
+
args = parser.parse_args()
|
218 |
+
|
219 |
+
trainer_out_path = train_gpt(
|
220 |
+
metadatas=args.metadatas,
|
221 |
+
output_path=args.output_path,
|
222 |
+
num_epochs=args.num_epochs,
|
223 |
+
batch_size=args.batch_size,
|
224 |
+
grad_acumm=args.grad_acumm,
|
225 |
+
weight_decay=args.weight_decay,
|
226 |
+
lr=args.lr,
|
227 |
+
max_text_length=args.max_text_length,
|
228 |
+
max_audio_length=args.max_audio_length,
|
229 |
+
save_step=args.save_step
|
230 |
+
)
|
231 |
+
|
232 |
+
print(f"Checkpoint saved in dir: {trainer_out_path}")
|