-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprepare_data.py
More file actions
378 lines (295 loc) · 11.7 KB
/
prepare_data.py
File metadata and controls
378 lines (295 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import argparse
import hashlib
import os
from typing import Any
from dotenv import load_dotenv
import numpy as np
import yaml
from datasets import DatasetDict
import torch
from WavTokenizer.encoder.utils import convert_audio
from WavTokenizer.decoder.pretrained import WavTokenizer
from BigCodec.vq.codec_encoder import CodecEncoder
from BigCodec.vq.codec_decoder import CodecDecoder
from src.quantize.wavtokenizer import quantize_wavtokenizer_batch
from src.utils.data import DATASET_2_LOAD_FUNCTION
from src.utils.decoding import (
decode_audio_wav,
decode_audio_speech,
decode_audio_fish,
decode_audio_bigcodec,
)
load_dotenv()
hf_token = os.getenv("HF_TOKEN")
parser = argparse.ArgumentParser(description="Train a model with configuration.")
parser.add_argument(
"--config", type=str, help="Path to the config.yaml file", required=True
)
parser.add_argument(
"--debug",
action="store_true",
help="If set, example of reconstructed audio is saved",
)
args = parser.parse_args()
# Load config
with open(args.config, "r") as file:
config = yaml.safe_load(file)
path_to_cache = config["path_to_cache"]
config_path = config["quantizer_config_path"]
ckpt_path = config["quantizer_ckpt_path"]
quantizer_type = config["quantizer_type"]
data = config["raw_data"]
prepared_data_path = config["prepared_data_path"]
device = "cuda:0"
class BigCodecTokenizer:
def __init__(self, ckpt_path):
ckpt = torch.load(ckpt_path, map_location="cpu")
encoder = CodecEncoder()
encoder.load_state_dict(ckpt["CodecEnc"])
self.encoder = encoder.eval().cuda()
decoder = CodecDecoder()
decoder.load_state_dict(ckpt["generator"])
self.decoder = decoder.eval().cuda()
def encode(self, wav):
vq_emb = self.encoder(wav.unsqueeze(1))
_, vq_code, _ = self.decoder(vq_emb, vq=True)
return vq_code
def resample(audio: np.ndarray, sr: int, target_sr: int):
audio = torch.tensor(audio, dtype=torch.float32)
audio = audio.unsqueeze(0)
if sr != target_sr:
# 1 as last arg corresponds to mono audio
audio = convert_audio(audio, sr, target_sr, 1)
return audio
def quantize_speechtokenizer(row: dict[str, Any], quantizer):
from speechtokenizer import SpeechTokenizer
quantizer: SpeechTokenizer
audio_data, sample_rate = row["audio"]["array"], row["audio"]["sampling_rate"]
audio = resample(audio_data, sample_rate, quantizer.sample_rate)
audio = audio.view(1, 1, len(audio))
codes = quantizer.encode(audio)
codes = codes.squeeze(1)
codes = codes.cpu()
return {"audio_tokens": codes.numpy()}
def quantize_wavtokenizer(row: dict[str, Any], quantizer):
audio_data, sample_rate = row["audio"]["array"], int(row["audio"]["sampling_rate"])
audio = resample(audio_data, sample_rate, 24000)
bandwidth_id = torch.tensor([0])
audio = audio.to(quantizer.head.out.weight.device)
_, codes = quantizer.encode_infer(audio, bandwidth_id=bandwidth_id)
codes = codes.squeeze(1)
codes = codes.cpu()
return {"audio_tokens": codes.numpy()}
def quantize_bigcodec_tokenizer(row: dict[str, Any], quantizer: BigCodecTokenizer):
audio_data, sample_rate = row["audio"]["array"], row["audio"]["sampling_rate"]
audio = resample(audio_data, sample_rate, 16000)
codes = quantizer.encode(audio)
codes = codes.squeeze(0, 1)
codes = codes.cpu()
return {"audio_tokens": codes.numpy()}
def quantize_bigcodec_tokenizer_batched(
row: dict[str, Any], quantizer: BigCodecTokenizer
):
sample_rate = row["audio"][0]["sampling_rate"]
audio_arrays = []
for arr in row["audio"]:
resampled = resample(arr["array"], sample_rate, 16000)
audio_arrays.append(resampled)
max_length = max(array.shape[1] for array in audio_arrays)
padded_audio_tensors = [
torch.nn.functional.pad(
tensor, (0, max_length - tensor.shape[1]), mode="constant", value=0
)
for tensor in audio_arrays
]
audio = torch.stack(padded_audio_tensors, dim=0).squeeze(1)
codes = quantizer.encode(audio)
codes = codes.squeeze(0)
codes = codes.cpu()
return {"audio_tokens": codes.numpy()}
def quantize_fishtokenizer(row: dict[str, Any], quantizer):
audio_data, sample_rate = row["audio"]["array"], row["audio"]["sampling_rate"]
text = row["text"]
audio = resample(audio_data, sample_rate, quantizer.sample_rate)
audio = audio.unsqueeze(0)
audio_tokens = quantizer.encode_audio(audio)
semantic_tokens = quantizer.encode_text(text)
audio_tokens = audio_tokens.cpu()
semantic_tokens = semantic_tokens.cpu()
return {
"audio_tokens": audio_tokens.numpy(),
"semantic_tokens": semantic_tokens.numpy(),
}
def verify_decoding(example, quantizer, quantizer_type: str):
if quantizer_type == "speech":
codes = quantize_speechtokenizer(example, quantizer)["audio_tokens"]
codes = torch.tensor(codes, dtype=torch.float32, device=device)
flattened = codes.t().contiguous().view(1, -1)
audio = decode_audio_speech(
flattened,
quantizer,
quantizer.quantizer.bins + 1,
codes.shape[-1],
)
elif quantizer_type == "wav":
codes = quantize_wavtokenizer(example, quantizer)["audio_tokens"]
codes = torch.tensor(codes, dtype=torch.long, device=device)
audio = decode_audio_wav(
codes,
quantizer,
quantizer.feature_extractor.encodec.quantizer.bins + 1,
1,
)
elif quantizer_type == "big-codec":
codes = quantize_bigcodec_tokenizer(example, quantizer)["audio_tokens"]
codes = torch.tensor(codes, dtype=torch.long, device=device)
codes = codes.view(1, -1, 1)
audio = decode_audio_bigcodec(
codes,
quantizer,
quantizer.decoder.quantizer.layers[0].codebook_size,
quantizer.decoder.quantizer.num_quantizers,
)
elif quantizer_type == "fish":
codes = quantize_fishtokenizer(example, quantizer)["audio_tokens"]
codes = torch.tensor(codes, dtype=torch.long, device=device)
flattened = codes.t().contiguous().view(1, -1)
audio = decode_audio_fish(
flattened,
quantizer,
quantizer.codebook_size + 1,
quantizer.num_codebooks,
)
else:
raise ValueError("Unknown tokenize type.")
audio.write(f"test_quantization_{quantizer_type}.wav")
if __name__ == "__main__":
config_path = config["quantizer_config_path"]
ckpt_path = config["quantizer_ckpt_path"]
train_dataset, val_dataset = DATASET_2_LOAD_FUNCTION[data](path_to_cache)
hash_value = "_" + hashlib.md5(data.encode()).hexdigest()
print(
"Number of samples in dataset:",
f"train - {len(train_dataset)}, val - {len(val_dataset)}",
)
if quantizer_type == "speech":
from speechtokenizer import SpeechTokenizer
quantizer = SpeechTokenizer.load_from_checkpoint(config_path, ckpt_path)
quantizer.eval().to(device)
codebook_size = quantizer.quantizer.bins
elif quantizer_type == "wav":
quantizer = WavTokenizer.from_pretrained0802(config_path, ckpt_path)
quantizer = quantizer.to(device)
codebook_size = quantizer.feature_extractor.encodec.quantizer.bins
elif quantizer_type == "big-codec":
quantizer = BigCodecTokenizer(ckpt_path)
elif quantizer_type == "fish":
from src.fish_tokenizer import FishAudioTokenizer
quantizer = FishAudioTokenizer(ckpt_path, config_path)
else:
raise ValueError("Unknown tokenize type.")
if args.debug:
verify_decoding(train_dataset[0], quantizer, quantizer_type)
else:
if quantizer_type == "speech":
print("Using speech tokenizer.")
train_dataset = train_dataset.map(
quantize_speechtokenizer,
fn_kwargs={"quantizer": quantizer},
remove_columns=["audio"],
cache_file_name=os.path.join(
path_to_cache, f"tokenize_train_speech_{hash_value}"
),
)
val_dataset = val_dataset.map(
quantize_speechtokenizer,
fn_kwargs={"quantizer": quantizer},
remove_columns=["audio"],
cache_file_name=os.path.join(
path_to_cache, f"tokenize_val_speech_{hash_value}"
),
)
elif quantizer_type == "wav":
print("Using wav tokenizer.")
def filter_long_audio(examples):
result_list = []
for example in examples["audio"]:
is_ok = example["array"].shape[-1] < example["sampling_rate"] * 10
result_list.append(is_ok)
return result_list
# from multiprocess import set_start_method
# set_start_method("spawn")
# train_dataset = train_dataset.select(range(10000))
train_dataset = train_dataset.filter(
filter_long_audio, batched=True, keep_in_memory=True, num_proc=16
)
train_dataset = train_dataset.map(
quantize_wavtokenizer_batch,
remove_columns=["audio"],
keep_in_memory=True,
fn_kwargs={"quantizer": quantizer},
batched=True,
batch_size=50,
# num_proc=16,
)
val_dataset = val_dataset.filter(
filter_long_audio, batched=True, keep_in_memory=True, num_proc=16
)
val_dataset = val_dataset.map(
quantize_wavtokenizer_batch,
remove_columns=["audio"],
keep_in_memory=True,
fn_kwargs={"quantizer": quantizer},
batched=True,
batch_size=50,
# num_proc=16,
)
elif quantizer_type == "big-codec":
print("Using BigCodec tokenizer.")
train_dataset = train_dataset.map(
quantize_bigcodec_tokenizer_batched,
batched=True,
batch_size=2,
fn_kwargs={"quantizer": quantizer},
cache_file_name=os.path.join(
path_to_cache, f"tokenize_train_bigcodec_{hash_value}"
),
)
val_dataset = val_dataset.map(
quantize_bigcodec_tokenizer_batched,
batched=True,
batch_size=2,
fn_kwargs={"quantizer": quantizer},
cache_file_name=os.path.join(
path_to_cache, f"tokenize_val_bigcodec_{hash_value}"
),
)
elif quantizer_type == "fish":
print("Using fish tokenizer.")
train_dataset = train_dataset.map(
quantize_fishtokenizer,
remove_columns=["audio"],
fn_kwargs={"quantizer": quantizer},
cache_file_name=os.path.join(
path_to_cache, f"tokenize_train_fish_{hash_value}"
),
)
val_dataset = val_dataset.map(
quantize_fishtokenizer,
fn_kwargs={"quantizer": quantizer},
remove_columns=["audio"],
cache_file_name=os.path.join(
path_to_cache, f"tokenize_val_fish_{hash_value}"
),
)
else:
raise ValueError("Unknown tokenize type.")
dataset = DatasetDict(
{
"train": train_dataset,
"validation": val_dataset,
}
)
dataset.push_to_hub(
"Vikhrmodels/" + prepared_data_path, private=True, token=hf_token
)