返回 F5-TTS
dataset.py
根目录 / src / f5_tts / model / dataset.py
1 import json
2 from importlib.resources import files
3
4 import torch
5 import torch.nn.functional as F
6 import torchaudio
7 from datasets import Dataset as Dataset_
8 from datasets import load_dataset as load_hf_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
16
17
18 class HFDataset(Dataset):
19 def __init__(
20 self,
21 hf_dataset: Dataset,
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 mel_spec_module: nn.Module | None = None,
29 ):
30 self.data = hf_dataset
31 self.target_sample_rate = target_sample_rate
32 self.hop_length = hop_length
33
34 self.mel_spectrogram = (
35 mel_spec_module
36 if mel_spec_module is not None
37 else MelSpec(
38 n_fft=n_fft,
39 hop_length=hop_length,
40 win_length=win_length,
41 n_mel_channels=n_mel_channels,
42 target_sample_rate=target_sample_rate,
43 mel_spec_type=mel_spec_type,
44 )
45 )
46 self._resamplers = {}
47
48 def get_frame_len(self, index):
49 row = self.data[index]
50 audio = row["audio"]["array"]
51 sample_rate = row["audio"]["sampling_rate"]
52 return audio.shape[-1] / sample_rate * self.target_sample_rate / self.hop_length
53
54 def __len__(self):
55 return len(self.data)
56
57 def __getitem__(self, index):
58 row = self.data[index]
59 audio = row["audio"]["array"]
60
61 sample_rate = row["audio"]["sampling_rate"]
62 duration = audio.shape[-1] / sample_rate
63
64 if duration > 30 or duration < 0.3:
65 return self.__getitem__((index + 1) % len(self.data))
66
67 audio_tensor = torch.from_numpy(audio).float()
68
69 if sample_rate != self.target_sample_rate:
70 if sample_rate not in self._resamplers:
71 self._resamplers[sample_rate] = torchaudio.transforms.Resample(sample_rate, self.target_sample_rate)
72 audio_tensor = self._resamplers[sample_rate](audio_tensor)
73
74 audio_tensor = audio_tensor.unsqueeze(0) # 't -> 1 t')
75
76 mel_spec = self.mel_spectrogram(audio_tensor)
77
78 mel_spec = mel_spec.squeeze(0) # '1 d t -> d t'
79
80 text = row["text"]
81
82 return dict(
83 mel_spec=mel_spec,
84 text=text,
85 )
86
87
88 class CustomDataset(Dataset):
89 def __init__(
90 self,
91 custom_dataset: Dataset,
92 durations=None,
93 target_sample_rate=24_000,
94 hop_length=256,
95 n_mel_channels=100,
96 n_fft=1024,
97 win_length=1024,
98 mel_spec_type="vocos",
99 preprocessed_mel=False,
100 mel_spec_module: nn.Module | None = None,
101 ):
102 self.data = custom_dataset
103 self.durations = durations
104 self.target_sample_rate = target_sample_rate
105 self.hop_length = hop_length
106 self.n_fft = n_fft
107 self.win_length = win_length
108 self.mel_spec_type = mel_spec_type
109 self.preprocessed_mel = preprocessed_mel
110
111 if not preprocessed_mel:
112 self.mel_spectrogram = default(
113 mel_spec_module,
114 MelSpec(
115 n_fft=n_fft,
116 hop_length=hop_length,
117 win_length=win_length,
118 n_mel_channels=n_mel_channels,
119 target_sample_rate=target_sample_rate,
120 mel_spec_type=mel_spec_type,
121 ),
122 )
123 self._resamplers = {}
124
125 def get_frame_len(self, index):
126 if (
127 self.durations is not None
128 ): # Please make sure the separately provided durations are correct, otherwise 99.99% OOM
129 return self.durations[index] * self.target_sample_rate / self.hop_length
130 return self.data[index]["duration"] * self.target_sample_rate / self.hop_length
131
132 def __len__(self):
133 return len(self.data)
134
135 def __getitem__(self, index):
136 while True:
137 row = self.data[index]
138 text = row["text"]
139 duration = row["duration"]
140
141 # filter by given length
142 if 0.3 <= duration <= 30:
143 break # valid
144
145 index = (index + 1) % len(self.data)
146
147 if self.preprocessed_mel:
148 mel_spec = torch.tensor(row["mel_spec"])
149 else:
150 audio, source_sample_rate = torchaudio.load(row["audio_path"])
151
152 # make sure mono input
153 if audio.shape[0] > 1:
154 audio = torch.mean(audio, dim=0, keepdim=True)
155
156 # resample if necessary
157 if source_sample_rate != self.target_sample_rate:
158 if source_sample_rate not in self._resamplers:
159 self._resamplers[source_sample_rate] = torchaudio.transforms.Resample(
160 source_sample_rate, self.target_sample_rate
161 )
162 audio = self._resamplers[source_sample_rate](audio)
163
164 # to mel spectrogram
165 mel_spec = self.mel_spectrogram(audio)
166 mel_spec = mel_spec.squeeze(0) # '1 d t -> d t'
167
168 return {
169 "mel_spec": mel_spec,
170 "text": text,
171 }
172
173
174 # Dynamic Batch Sampler
175 class DynamicBatchSampler(Sampler[list[int]]):
176 """Extension of Sampler that will do the following:
177 1. Change the batch size (essentially number of sequences)
178 in a batch to ensure that the total number of frames are less
179 than a certain threshold.
180 2. Make sure the padding efficiency in the batch is high.
181 3. Shuffle batches each epoch while maintaining reproducibility.
182 """
183
184 def __init__(
185 self, sampler: Sampler[int], frames_threshold: int, max_samples=0, random_seed=None, drop_residual: bool = False
186 ):
187 self.sampler = sampler
188 self.frames_threshold = frames_threshold
189 self.max_samples = max_samples
190 self.random_seed = random_seed
191 self.epoch = 0
192
193 indices, batches = [], []
194 data_source = self.sampler.data_source
195
196 for idx in tqdm(
197 self.sampler, desc="Sorting with sampler... if slow, check whether dataset is provided with duration"
198 ):
199 indices.append((idx, data_source.get_frame_len(idx)))
200 indices.sort(key=lambda elem: elem[1])
201
202 batch = []
203 batch_frames = 0
204 for idx, frame_len in tqdm(
205 indices, desc=f"Creating dynamic batches with {frames_threshold} audio frames per gpu"
206 ):
207 if batch_frames + frame_len <= self.frames_threshold and (max_samples == 0 or len(batch) < max_samples):
208 batch.append(idx)
209 batch_frames += frame_len
210 else:
211 if len(batch) > 0:
212 batches.append(batch)
213 if frame_len <= self.frames_threshold:
214 batch = [idx]
215 batch_frames = frame_len
216 else:
217 batch = []
218 batch_frames = 0
219
220 if not drop_residual and len(batch) > 0:
221 batches.append(batch)
222
223 del indices
224 self.batches = batches
225
226 # Ensure even batches with accelerate BatchSamplerShard cls under frame_per_batch setting
227 self.drop_last = True
228
229 def set_epoch(self, epoch: int) -> None:
230 """Sets the epoch for this sampler."""
231 self.epoch = epoch
232
233 def __iter__(self):
234 # Use both random_seed and epoch for deterministic but different shuffling per epoch
235 if self.random_seed is not None:
236 g = torch.Generator()
237 g.manual_seed(self.random_seed + self.epoch)
238 # Use PyTorch's random permutation for better reproducibility across PyTorch versions
239 indices = torch.randperm(len(self.batches), generator=g).tolist()
240 batches = [self.batches[i] for i in indices]
241 else:
242 batches = self.batches
243 return iter(batches)
244
245 def __len__(self):
246 return len(self.batches)
247
248
249 # Load dataset
250
251
252 def load_dataset(
253 dataset_name: str,
254 tokenizer: str = "pinyin",
255 dataset_type: str = "CustomDataset",
256 audio_type: str = "raw",
257 mel_spec_module: nn.Module | None = None,
258 mel_spec_kwargs: dict = dict(),
259 ) -> CustomDataset | HFDataset:
260 """
261 dataset_type - "CustomDataset" if you want to use tokenizer name and default data path to load for train_dataset
262 - "CustomDatasetPath" if you just want to pass the full path to a preprocessed dataset without relying on tokenizer
263 - "HFDataset" to load "<corpus>_<subset>" from "<corpus>/<corpus>", split "train.<subset>"
264 """
265
266 print("Loading dataset ...")
267
268 if dataset_type in ("CustomDataset", "CustomDatasetPath"):
269 data_path = dataset_name
270 if dataset_type == "CustomDataset":
271 data_path = str(files("f5_tts").joinpath(f"../../data/{dataset_name}_{tokenizer}"))
272 if audio_type == "raw":
273 try:
274 train_dataset = load_from_disk(f"{data_path}/raw")
275 except Exception:
276 train_dataset = Dataset_.from_file(f"{data_path}/raw.arrow")
277 elif audio_type == "mel":
278 train_dataset = Dataset_.from_file(f"{data_path}/mel.arrow")
279 else:
280 raise ValueError(f"Unsupported audio_type: {audio_type}")
281 with open(f"{data_path}/duration.json", encoding="utf-8") as f:
282 data_dict = json.load(f)
283 return CustomDataset(
284 train_dataset,
285 durations=data_dict["duration"],
286 preprocessed_mel=audio_type == "mel",
287 mel_spec_module=mel_spec_module,
288 **mel_spec_kwargs,
289 )
290
291 if dataset_type == "HFDataset":
292 pre, post = dataset_name.split("_", 1)
293 return HFDataset(
294 load_hf_dataset(
295 f"{pre}/{pre}", split=f"train.{post}", cache_dir=str(files("f5_tts").joinpath("../../data"))
296 ),
297 mel_spec_module=mel_spec_module,
298 **mel_spec_kwargs,
299 )
300
301 raise ValueError(f"Unsupported dataset_type: {dataset_type}")
302
303
304 # collation
305
306
307 def collate_fn(batch):
308 mel_specs = [item["mel_spec"].squeeze(0) for item in batch]
309 mel_lengths = torch.LongTensor([spec.shape[-1] for spec in mel_specs])
310 max_mel_length = mel_lengths.amax()
311
312 padded_mel_specs = []
313 for spec in mel_specs:
314 padding = (0, max_mel_length - spec.size(-1))
315 padded_spec = F.pad(spec, padding, value=0)
316 padded_mel_specs.append(padded_spec)
317
318 mel_specs = torch.stack(padded_mel_specs)
319
320 text = [item["text"] for item in batch]
321 text_lengths = torch.LongTensor([len(item) for item in text])
322
323 return dict(
324 mel=mel_specs,
325 mel_lengths=mel_lengths, # records for padding mask
326 text=text,
327 text_lengths=text_lengths,
328 )
329
329 lines PYTHON