text.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import json
  2. import random
  3. import re
  4. from dataclasses import dataclass
  5. from itertools import chain
  6. from pathlib import Path
  7. from random import Random
  8. from typing import Optional, Union
  9. import grpc
  10. import numpy as np
  11. import pyarrow.parquet as pq
  12. import torch
  13. import torch.nn.functional as F
  14. from datasets.download.streaming_download_manager import xopen
  15. from huggingface_hub import HfApi
  16. from lightning import LightningDataModule
  17. from torch.distributed import get_rank, get_world_size, is_initialized
  18. from torch.utils.data import DataLoader, IterableDataset, get_worker_info
  19. from transformers import AutoTokenizer
  20. from fish_speech.datasets.protos.text_data_pb2 import SampleDataRequest
  21. from fish_speech.datasets.protos.text_data_pb2_grpc import DataServiceStub
  22. from fish_speech.text.symbols import pad as pad_symbol
  23. from fish_speech.text.symbols import pu_symbols
  24. from fish_speech.utils import RankedLogger
  25. from fish_speech.utils.braceexpand import braceexpand
  26. log = RankedLogger(__name__, rank_zero_only=True)
  27. def split_by_rank_worker(files):
  28. # We need to know the total number of devices
  29. # to split the data properly
  30. total_devices = 1
  31. if is_initialized():
  32. total_devices = get_world_size()
  33. worker_info = get_worker_info()
  34. if worker_info is not None:
  35. total_devices *= worker_info.num_workers
  36. if len(files) < total_devices:
  37. # Repeat the files N times to match the number of devices
  38. files = files * (total_devices // len(files) + 1)
  39. # DDP
  40. if is_initialized():
  41. files = files[get_rank() :: get_world_size()]
  42. # Split by worker
  43. if worker_info is not None:
  44. files = files[worker_info.id :: worker_info.num_workers]
  45. return files
  46. class StreamTextDataset(IterableDataset):
  47. def __init__(
  48. self,
  49. files: Optional[Union[list[str], str]] = None,
  50. prefix: Optional[str] = None,
  51. seed: int = 42,
  52. parquet_batch_size: int = 10000,
  53. repo: str = "uonlp/CulturaX",
  54. ):
  55. super().__init__()
  56. self.seed = seed
  57. self.parquet_batch_size = parquet_batch_size
  58. self.repo = repo
  59. if files is None and prefix is None:
  60. raise ValueError("Either files or prefix must be specified")
  61. if prefix is not None:
  62. files = HfApi().list_repo_files(repo, repo_type="dataset")
  63. files = [
  64. f for f in files if f.startswith(prefix) and f.endswith(".parquet")
  65. ]
  66. log.info(f"Found {len(files)} files in {repo} with prefix {prefix}")
  67. else:
  68. if isinstance(files, str):
  69. files = [files]
  70. files = list(chain.from_iterable(map(braceexpand, files)))
  71. log.info(f"Expanded {len(files)} files in {repo}")
  72. # Get sharded files
  73. self.files = sorted(files)
  74. Random(seed).shuffle(self.files)
  75. def __iter__(self):
  76. files = split_by_rank_worker(self.files)
  77. random.shuffle(files)
  78. for filename in files:
  79. try:
  80. yield from self.parse_data(filename)
  81. except Exception as e:
  82. log.exception(f"Failed to parse {filename}: {e}")
  83. def parse_data(self, filename: str):
  84. for data in self.parse_data_internal(filename):
  85. text = data["text"]
  86. expression = re.compile(r"\[INST\] (.*) \[/INST\] (.*) </s>")
  87. match = expression.match(text)
  88. if match is None:
  89. continue
  90. text = match.group(1)
  91. semantic = match.group(2)
  92. # Convert semantic to ids
  93. expression = re.compile(r"<semantic_(\d+)>")
  94. # 0 and 1 are reserved for <s> and </s>
  95. semantic = [0] + [int(i) + 2 for i in expression.findall(semantic)] + [1]
  96. yield {"text": text, "semantic": [semantic]}
  97. def parse_data_internal(self, filename: str):
  98. url = f"https://huggingface.co/datasets/{self.repo}/resolve/main/{filename}"
  99. with xopen(url, mode="rb") as stream:
  100. parquet_file = pq.ParquetFile(stream)
  101. for batch in parquet_file.iter_batches(
  102. batch_size=self.parquet_batch_size, columns=["text"]
  103. ):
  104. # In-batch shuffling
  105. texts = [{"text": text.as_py()} for text in batch["text"]]
  106. random.shuffle(texts)
  107. yield from texts
  108. class AutoAugTextDataset(IterableDataset):
  109. """
  110. Auto Augment Dataset by Speaker
  111. 1. Random concatenate multiple sentences from the same speaker to form a longer sentence
  112. 2. Automatically normalize the text
  113. 3. Mix text and phones
  114. """
  115. def __init__(
  116. self,
  117. server: str = "localhost:50051",
  118. seed: int = 42,
  119. phones_prob: float = 0.3,
  120. repetition_prob: float = 0.1,
  121. max_length: int = 1024,
  122. tokenizer: AutoTokenizer = None,
  123. ):
  124. """
  125. Args:
  126. server: gRPC server address
  127. seed: random seed
  128. phones_prob: probability to use phones
  129. repetition_prob: probability to repeat the same sentence
  130. max_length: max length of the text
  131. tokenizer: tokenizer
  132. """
  133. super().__init__()
  134. self.seed = seed
  135. self.phones_prob = phones_prob
  136. self.max_length = max_length
  137. self.tokenizer = tokenizer
  138. self.repetition_prob = repetition_prob
  139. # Read all lines, and group by speaker
  140. self.channel = grpc.insecure_channel(server)
  141. self.stub = DataServiceStub(self.channel)
  142. def __iter__(self):
  143. while True:
  144. yield self.augment()
  145. def tokenize_sentence(self, sentence: str, phones: list[str], mode: str = "sample"):
  146. if (
  147. mode == "sample" and (random.random() < self.phones_prob)
  148. ) or mode == "phones":
  149. sentence = " ".join(
  150. [
  151. (f"<p:{i}>" if i not in pu_symbols and i != pad_symbol else i)
  152. for i in phones
  153. ]
  154. )
  155. tokens = self.tokenizer.encode(
  156. f"{sentence}",
  157. max_length=10**6,
  158. add_special_tokens=False,
  159. truncation=False,
  160. )
  161. return sentence, len(tokens)
  162. def augment(self):
  163. # 50% to pure text or pure phones
  164. # mode = "sample"
  165. # if random.random() < 0.5:
  166. # mode = random.choice(["text", "phones"])
  167. mode = "phones"
  168. # Random sample based on speaker using a truncated normal distribution
  169. a = torch.tensor([0], dtype=torch.float32)
  170. torch.nn.init.trunc_normal_(
  171. a,
  172. mean=self.max_length // 2,
  173. std=self.max_length // 4,
  174. a=10,
  175. b=self.max_length,
  176. )
  177. remaining_tokens = a.long().item() - 4
  178. final_text, final_semantic = [], []
  179. # Shuffle unique lines, estimate that each sample is at least 20 tokens
  180. request = SampleDataRequest(num_samples=self.max_length // 20)
  181. response = self.stub.SampleData(request)
  182. if len(response.samples) == 0:
  183. # Invalid group
  184. return None
  185. samples = list(response.samples)
  186. while remaining_tokens > 0 and len(samples) > 0:
  187. if random.random() < self.repetition_prob:
  188. # Repeat the same sentence
  189. sentence = samples[-1]
  190. else:
  191. sentence = samples.pop()
  192. text, length = self.tokenize_sentence(
  193. sentence.text, sentence.phones, mode=mode
  194. )
  195. remaining_tokens -= length + len(sentence.semantics[0].values)
  196. final_text.append(text)
  197. final_semantic.append(sentence.semantics)
  198. final_text = "[INST] " + " ".join(final_text) + " [/INST]"
  199. encoded = self.tokenizer.encode(
  200. final_text,
  201. add_special_tokens=False,
  202. truncation=False,
  203. max_length=10**6,
  204. )
  205. semantic_length = sum([len(i[0].values) for i in final_semantic])
  206. # Single codebook
  207. if len(final_semantic[0]) == 1:
  208. semantic_tokens = [f"<s:{j}>" for i in final_semantic for j in i[0].values]
  209. tokenized = self.tokenizer.encode(
  210. f" ".join(semantic_tokens),
  211. add_special_tokens=False,
  212. truncation=False,
  213. max_length=10**6,
  214. )
  215. # Pack the tokens and semantics (add <s> and </s> to semantic tokens)
  216. tokens = (
  217. [self.tokenizer.bos_token_id]
  218. + encoded
  219. + tokenized
  220. + [self.tokenizer.eos_token_id]
  221. )
  222. tokens = torch.tensor([tokens], dtype=torch.long)
  223. labels = tokens.clone()
  224. labels[0, : len(encoded) + 1] = -100 # Mask out the <s> and query tokens
  225. else:
  226. # Pack the tokens and semantics (add <s> and </s> to semantic tokens)
  227. tokens = (
  228. [self.tokenizer.bos_token_id]
  229. + encoded
  230. + [self.tokenizer.pad_token_id] * semantic_length
  231. + [self.tokenizer.eos_token_id]
  232. )
  233. codes = [[0] * (len(encoded) + 1) for _ in range(len(final_semantic[0]))]
  234. for segment in final_semantic:
  235. for book_idx, book in enumerate(segment):
  236. for j in book.values:
  237. codes[book_idx].append(int(j) + 2)
  238. for book in codes:
  239. book.append(1)
  240. tokens = [tokens] + codes
  241. tokens = torch.tensor(tokens, dtype=torch.long)
  242. labels = tokens.clone()
  243. labels[
  244. 1:, : len(encoded) + 1
  245. ] = -100 # Mask out the <s> tokens for semantic
  246. return {
  247. "tokens": tokens[:, :-1],
  248. "labels": labels[:, 1:],
  249. }
  250. @dataclass
  251. class TextDataCollator:
  252. tokenizer: AutoTokenizer
  253. max_length: int = 1024
  254. def __call__(self, examples):
  255. tokens, attention_masks, labels = [], [], []
  256. for example in examples:
  257. _tokens = example["tokens"][:, : self.max_length]
  258. _labels = example["labels"][:, : self.max_length]
  259. _attention_mask = torch.ones((self.max_length,), dtype=torch.bool)
  260. _attention_mask[: _tokens.size(1)] = False
  261. assert _tokens.size(1) == _labels.size(
  262. 1
  263. ), f"{_tokens.size(1)} != {_labels.size(1)}"
  264. if _tokens.size(1) < self.max_length:
  265. _tokens = F.pad(
  266. _tokens,
  267. (0, self.max_length - _tokens.size(1)),
  268. value=self.tokenizer.eos_token_id,
  269. )
  270. _labels = F.pad(
  271. _labels, (0, self.max_length - _labels.size(1)), value=-100
  272. )
  273. tokens.append(_tokens)
  274. attention_masks.append(_attention_mask)
  275. labels.append(_labels)
  276. tokens = torch.stack(tokens, dim=0)
  277. attention_masks = torch.stack(attention_masks, dim=0)
  278. labels = torch.stack(labels, dim=0)
  279. return {
  280. "inputs": tokens,
  281. "attention_masks": attention_masks,
  282. "labels": labels,
  283. }
  284. class InterleaveDataset(IterableDataset):
  285. def __init__(
  286. self,
  287. datasets: list[IterableDataset],
  288. probabilities: list[float],
  289. seed: int = 42,
  290. ):
  291. super().__init__()
  292. self.datasets = datasets
  293. self.probabilities = probabilities
  294. self.seed = seed
  295. def __iter__(self):
  296. rng = np.random.default_rng(self.seed)
  297. dataset_iterators = [iter(dataset) for dataset in self.datasets]
  298. while True:
  299. # Random choice one
  300. dataset_idx = rng.choice(len(self.datasets), p=self.probabilities)
  301. dataset_iterator = dataset_iterators[dataset_idx]
  302. try:
  303. yield next(dataset_iterator)
  304. except StopIteration:
  305. # Exhausted, create a new iterator
  306. dataset_iterators[dataset_idx] = iter(self.datasets[dataset_idx])
  307. yield next(dataset_iterators[dataset_idx])
  308. class TextDataModule(LightningDataModule):
  309. def __init__(
  310. self,
  311. train_dataset: Union[StreamTextDataset, AutoAugTextDataset, InterleaveDataset],
  312. val_dataset: Union[StreamTextDataset, AutoAugTextDataset, InterleaveDataset],
  313. batch_size: int = 32,
  314. tokenizer: AutoTokenizer = None,
  315. max_length: int = 1024,
  316. num_workers: int = 4,
  317. ):
  318. super().__init__()
  319. self.train_dataset = train_dataset
  320. self.val_dataset = val_dataset
  321. self.batch_size = batch_size
  322. self.tokenizer = tokenizer
  323. self.max_length = max_length
  324. self.num_workers = num_workers
  325. def train_dataloader(self):
  326. return DataLoader(
  327. self.train_dataset,
  328. batch_size=self.batch_size,
  329. collate_fn=TextDataCollator(self.tokenizer, self.max_length),
  330. num_workers=self.num_workers,
  331. )
  332. def val_dataloader(self):
  333. return DataLoader(
  334. self.val_dataset,
  335. batch_size=self.batch_size,
  336. collate_fn=TextDataCollator(self.tokenizer, self.max_length),
  337. num_workers=self.num_workers,
  338. )
  339. if __name__ == "__main__":
  340. import json
  341. from tqdm import tqdm
  342. ds = AutoAugTextDataset(
  343. tokenizer=AutoTokenizer.from_pretrained("fishaudio/speech-lm-v1"),
  344. )
  345. dm = TextDataModule(
  346. train_dataset=ds,
  347. val_dataset=ds,
  348. tokenizer=ds.tokenizer,
  349. batch_size=16,
  350. max_length=1024,
  351. num_workers=0,
  352. )
  353. for batch in tqdm(dm.train_dataloader()):
  354. pass