text.py 13 KB

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