Debian Codegraph @

examples/inference/distributed/distributed_speech_generation.py

raw
1 # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 import json
17 import os
18 import pathlib
19 import queue
20 from concurrent.futures import ThreadPoolExecutor
21 from typing import Union
22
23 import fire
24 import scipy.io.wavfile
25 import torch
26 from datasets import load_dataset
27 from transformers import AutoTokenizer, VitsModel
28
29 from accelerate import PartialState
30 from accelerate.utils import tqdm
31
32
33 """
34 Requirements: transformers accelerate fire scipy datasets
35 pip install transformers accelerate fire scipy datasets
36 Example usage:
37 accelerate launch distributed_speech_generation.py --output_path outputs --batch_size 8 --num_workers 2 --dataset_split train
38 """
39
40 """
41 To run the speech generation
42 import scipy.io.wavfile
43 import numpy as np
44 from IPython.display import Audio
45 sample_rate, audio_data = scipy.io.wavfile.read('path_to_you_wav_file.wav')
46 audio_data = audio_data.astype(np.float32) / 32762.0
47 Audio(audio_data, rate=sample_rate)
48 """
49
50
51 def load_pokemon_data(split: str, max_text_length: int):
52 """Load Pokemon descriptions from the dataset"""
53 ds = load_dataset("svjack/pokemon-blip-captions-en-zh", split=split)
54
55 # Create dataset of dictionaries
56 dataset = []
57 for idx, text in enumerate(ds["en_text"]):
58 if len(text.strip()) > 0: # Skip empty descriptions
59 dataset.append(
60 {
61 "id": f"pokemon_{idx:06d}",
62 "text": text.strip()[:max_text_length], # Truncate long descriptions
63 "original_text": text.strip(), # Keep original for metadata
64 }
65 )
66 return dataset
67
68
69 class ExistsFilter:
70 def __init__(self, output_dir: Union[pathlib.Path, str]):
71 current_files = [f.split(".wav")[0] for f in os.listdir(output_dir) if f.endswith(".wav")]
72 self.processed_files = set(current_files)
73 print(f"Existing audio files found: {len(self.processed_files)}.")
74
75 def __call__(self, x):
76 return x["id"] not in self.processed_files
77
78
79 def preprocess_fn(sample, tokenizer, max_text_length: int):
80 inputs = tokenizer(sample["text"], padding=False, truncation=True, max_length=max_text_length, return_tensors="pt")
81
82 return {
83 "input_ids": inputs["input_ids"][0].tolist(),
84 "attention_mask": inputs["attention_mask"][0].tolist(),
85 "id": sample["id"],
86 "text": sample["text"],
87 "original_text": sample["original_text"],
88 }
89
90
91 def collate_fn(examples, tokenizer):
92 """Collate batch of examples with proper padding"""
93 # Find max length in this batch
94 max_length = max(len(example["input_ids"]) for example in examples)
95
96 # Pad sequences to max_length
97 input_ids_list = []
98 attention_mask_list = []
99
100 for example in examples:
101 # Get current lengths
102 curr_len = len(example["input_ids"])
103 padding_length = max_length - curr_len
104
105 # Pad sequences
106 padded_input_ids = example["input_ids"] + [tokenizer.pad_token_id] * padding_length
107 padded_attention_mask = example["attention_mask"] + [0] * padding_length
108
109 input_ids_list.append(padded_input_ids)
110 attention_mask_list.append(padded_attention_mask)
111
112 # Convert to tensors
113 input_ids = torch.tensor(input_ids_list, dtype=torch.long)
114 attention_mask = torch.tensor(attention_mask_list, dtype=torch.long)
115
116 ids = [example["id"] for example in examples]
117 texts = [example["text"] for example in examples]
118 original_texts = [example["original_text"] for example in examples]
119
120 return {
121 "input_ids": input_ids,
122 "attention_mask": attention_mask,
123 "ids": ids,
124 "texts": texts,
125 "original_texts": original_texts,
126 }
127
128
129 def create_dataloader(dataset, batch_size, distributed_state, tokenizer):
130 """Create dataloader with preprocessing"""
131 processed_dataset = [preprocess_fn(item, tokenizer, max_text_length=200) for item in dataset]
132
133 # Split dataset for distributed processing
134 if distributed_state.num_processes > 1:
135 chunk_size = len(processed_dataset) // distributed_state.num_processes
136 start_idx = distributed_state.process_index * chunk_size
137 end_idx = (
138 start_idx + chunk_size
139 if distributed_state.process_index < distributed_state.num_processes - 1
140 else len(processed_dataset)
141 )
142 processed_dataset = processed_dataset[start_idx:end_idx]
143
144 # Create batches
145 batches = []
146 for i in range(0, len(processed_dataset), batch_size):
147 batch = processed_dataset[i : i + batch_size]
148 batches.append(collate_fn(batch, tokenizer))
149 return batches
150
151
152 def save_results(output_queue: queue.Queue, output_dir: pathlib.Path, sampling_rate: int):
153 while True:
154 try:
155 item = output_queue.get(timeout=5)
156 if item is None:
157 break
158 waveforms, ids, texts, original_texts = item
159
160 # Save each audio file and its metadata
161 for waveform, file_id, text, original_text in zip(waveforms, ids, texts, original_texts):
162 # Save audio
163 wav_path = output_dir / f"{file_id}.wav"
164 scipy.io.wavfile.write(wav_path, rate=sampling_rate, data=waveform.cpu().float().numpy())
165
166 # Save metadata with both truncated and original text
167 metadata = {
168 "text_used": text,
169 "original_text": original_text,
170 "model": "facebook/mms-tts-eng",
171 "sampling_rate": sampling_rate,
172 }
173 metadata_path = output_dir / f"{file_id}_metadata.json"
174 with metadata_path.open("w") as f:
175 json.dump(metadata, f, indent=4)
176
177 except queue.Empty:
178 continue
179
180
181 def main(
182 output_path: str = "speech_data",
183 batch_size: int = 8,
184 num_workers: int = 2,
185 dataset_split: str = "train",
186 model_name: str = "facebook/mms-tts-eng",
187 max_text_length: int = 200,
188 ):
189 output_dir = pathlib.Path(output_path)
190 output_dir.mkdir(parents=True, exist_ok=True)
191 distributed_state = PartialState()
192
193 # Load model and tokenizer
194 model = VitsModel.from_pretrained(
195 model_name,
196 device_map=distributed_state.device,
197 torch_dtype=torch.float32,
198 )
199
200 tokenizer = AutoTokenizer.from_pretrained(model_name)
201
202 # Load and filter data
203 dataset = load_pokemon_data(dataset_split, max_text_length)
204 exist_filter = ExistsFilter(output_dir)
205 dataset = [item for item in dataset if exist_filter(item)]
206
207 distributed_state.print(f"Processing {len(dataset)} Pokemon descriptions")
208
209 # Create dataloader
210 batches = create_dataloader(dataset, batch_size, distributed_state, tokenizer)
211
212 # Setup output queue and save thread
213 output_queue = queue.Queue()
214 save_thread = ThreadPoolExecutor(max_workers=num_workers)
215 save_future = save_thread.submit(save_results, output_queue, output_dir, model.config.sampling_rate)
216
217 try:
218 for batch in tqdm(batches, desc="Generating Pokemon descriptions"):
219 with torch.no_grad():
220 outputs = model(
221 input_ids=batch["input_ids"].to(distributed_state.device, dtype=torch.long),
222 attention_mask=batch["attention_mask"].to(distributed_state.device, dtype=torch.long),
223 ).waveform
224
225 output_queue.put((outputs, batch["ids"], batch["texts"], batch["original_texts"]))
226 finally:
227 output_queue.put(None)
228 save_thread.shutdown(wait=True)
229
230 save_future.result()
231
232
233 if __name__ == "__main__":
234 fire.Fire(main)