text.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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.0,
  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. # Random sample based on speaker using a truncated normal distribution
  168. a = torch.tensor([0], dtype=torch.float32)
  169. torch.nn.init.trunc_normal_(
  170. a,
  171. mean=self.max_length // 2,
  172. std=self.max_length // 4,
  173. a=10,
  174. b=self.max_length,
  175. )
  176. remaining_tokens = a.long().item() - 4
  177. final_text, final_semantic = [], []
  178. # Shuffle unique lines, estimate that each sample is at least 20 tokens
  179. request = SampleDataRequest(num_samples=self.max_length // 20)
  180. response = self.stub.SampleData(request)
  181. if len(response.samples) == 0:
  182. # Invalid group
  183. return None
  184. samples = list(response.samples)
  185. while remaining_tokens > 0 and len(samples) > 0:
  186. if random.random() < self.repetition_prob:
  187. # Repeat the same sentence
  188. sentence = samples[-1]
  189. else:
  190. sentence = samples.pop()
  191. text, length = self.tokenize_sentence(
  192. sentence.text, sentence.phones, mode=mode
  193. )
  194. remaining_tokens -= length + len(sentence.semantics[0].values)
  195. final_text.append(text)
  196. final_semantic.append(sentence.semantics)
  197. final_text = "[INST] " + " ".join(final_text) + " [/INST]"
  198. encoded = self.tokenizer.encode(
  199. final_text,
  200. add_special_tokens=False,
  201. truncation=False,
  202. max_length=10**6,
  203. )
  204. semantic_length = sum([len(i[0].values) for i in final_semantic])
  205. # Single codebook
  206. if len(final_semantic[0]) == 1:
  207. semantic_tokens = [f"<s:{j}>" for i in final_semantic for j in i[0].values]
  208. tokenized = self.tokenizer.encode(
  209. f" ".join(semantic_tokens),
  210. add_special_tokens=False,
  211. truncation=False,
  212. max_length=10**6,
  213. )
  214. # Pack the tokens and semantics (add <s> and </s> to semantic tokens)
  215. tokens = (
  216. [self.tokenizer.bos_token_id]
  217. + encoded
  218. + tokenized
  219. + [self.tokenizer.eos_token_id]
  220. )
  221. tokens = torch.tensor([tokens], dtype=torch.long)
  222. labels = tokens.clone()
  223. labels[0, : len(encoded) + 1] = -100 # Mask out the <s> and query tokens
  224. else:
  225. # Pack the tokens and semantics (add <s> and </s> to semantic tokens)
  226. tokens = (
  227. [self.tokenizer.bos_token_id]
  228. + encoded
  229. + [self.tokenizer.pad_token_id] * semantic_length
  230. + [self.tokenizer.eos_token_id]
  231. )
  232. codes = [[0] * (len(encoded) + 1) for _ in range(len(final_semantic[0]))]
  233. for segment in final_semantic:
  234. for book_idx, book in enumerate(segment):
  235. for j in book.values:
  236. codes[book_idx].append(int(j) + 2)
  237. for book in codes:
  238. book.append(1)
  239. tokens = [tokens] + codes
  240. tokens = torch.tensor(tokens, dtype=torch.long)
  241. labels = tokens.clone()
  242. labels[
  243. 1:, : len(encoded) + 1
  244. ] = -100 # Mask out the <s> tokens for semantic
  245. return {
  246. "tokens": tokens[:, :-1],
  247. "labels": labels[:, 1:],
  248. }
  249. @dataclass
  250. class TextDataCollator:
  251. tokenizer: AutoTokenizer
  252. max_length: int = 1024
  253. def __call__(self, examples):
  254. tokens, attention_masks, labels = [], [], []
  255. for example in examples:
  256. _tokens = example["tokens"][:, : self.max_length]
  257. _labels = example["labels"][:, : self.max_length]
  258. _attention_mask = torch.ones((self.max_length,), dtype=torch.bool)
  259. _attention_mask[: _tokens.size(1)] = False
  260. assert _tokens.size(1) == _labels.size(
  261. 1
  262. ), f"{_tokens.size(1)} != {_labels.size(1)}"
  263. if _tokens.size(1) < self.max_length:
  264. _tokens = F.pad(
  265. _tokens,
  266. (0, self.max_length - _tokens.size(1)),
  267. value=self.tokenizer.eos_token_id,
  268. )
  269. _labels = F.pad(
  270. _labels, (0, self.max_length - _labels.size(1)), value=-100
  271. )
  272. tokens.append(_tokens)
  273. attention_masks.append(_attention_mask)
  274. labels.append(_labels)
  275. tokens = torch.stack(tokens, dim=0)
  276. attention_masks = torch.stack(attention_masks, dim=0)
  277. labels = torch.stack(labels, dim=0)
  278. return {
  279. "inputs": tokens,
  280. "attention_masks": attention_masks,
  281. "labels": labels,
  282. }
  283. class InterleaveDataset(IterableDataset):
  284. def __init__(
  285. self,
  286. datasets: list[IterableDataset],
  287. probabilities: list[float],
  288. seed: int = 42,
  289. ):
  290. super().__init__()
  291. self.datasets = datasets
  292. self.probabilities = probabilities
  293. self.seed = seed
  294. def __iter__(self):
  295. rng = np.random.default_rng(self.seed)
  296. dataset_iterators = [iter(dataset) for dataset in self.datasets]
  297. while True:
  298. # Random choice one
  299. dataset_idx = rng.choice(len(self.datasets), p=self.probabilities)
  300. dataset_iterator = dataset_iterators[dataset_idx]
  301. try:
  302. yield next(dataset_iterator)
  303. except StopIteration:
  304. # Exhausted, create a new iterator
  305. dataset_iterators[dataset_idx] = iter(self.datasets[dataset_idx])
  306. yield next(dataset_iterators[dataset_idx])
  307. class TextDataModule(LightningDataModule):
  308. def __init__(
  309. self,
  310. train_dataset: Union[StreamTextDataset, AutoAugTextDataset, InterleaveDataset],
  311. val_dataset: Union[StreamTextDataset, AutoAugTextDataset, InterleaveDataset],
  312. batch_size: int = 32,
  313. tokenizer: AutoTokenizer = None,
  314. max_length: int = 1024,
  315. num_workers: int = 4,
  316. ):
  317. super().__init__()
  318. self.train_dataset = train_dataset
  319. self.val_dataset = val_dataset
  320. self.batch_size = batch_size
  321. self.tokenizer = tokenizer
  322. self.max_length = max_length
  323. self.num_workers = num_workers
  324. def train_dataloader(self):
  325. return DataLoader(
  326. self.train_dataset,
  327. batch_size=self.batch_size,
  328. collate_fn=TextDataCollator(self.tokenizer, self.max_length),
  329. num_workers=self.num_workers,
  330. )
  331. def val_dataloader(self):
  332. return DataLoader(
  333. self.val_dataset,
  334. batch_size=self.batch_size,
  335. collate_fn=TextDataCollator(self.tokenizer, self.max_length),
  336. num_workers=self.num_workers,
  337. )
  338. if __name__ == "__main__":
  339. import json
  340. from tqdm import tqdm
  341. ds = AutoAugTextDataset(
  342. tokenizer=AutoTokenizer.from_pretrained("fishaudio/speech-lm-v1"),
  343. )
  344. dm = TextDataModule(
  345. train_dataset=ds,
  346. val_dataset=ds,
  347. tokenizer=ds.tokenizer,
  348. batch_size=16,
  349. max_length=1024,
  350. num_workers=0,
  351. )
  352. for batch in tqdm(dm.train_dataloader()):
  353. pass