inference.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. import os
  2. import queue
  3. import re
  4. import threading
  5. import time
  6. import traceback
  7. from copy import deepcopy
  8. from dataclasses import dataclass
  9. from pathlib import Path
  10. from typing import Callable, Literal, Optional, Tuple, Union
  11. import click
  12. import numpy as np
  13. import torch
  14. import torch._inductor.config
  15. from loguru import logger
  16. from tqdm import tqdm
  17. from fish_speech.content_sequence import (
  18. TextPart,
  19. VQPart,
  20. )
  21. from fish_speech.conversation import Conversation, Message
  22. from fish_speech.tokenizer import IM_END_TOKEN
  23. os.environ["TOKENIZERS_PARALLELISM"] = "false"
  24. torch._inductor.config.coordinate_descent_tuning = True
  25. torch._inductor.config.triton.unique_kernel_names = True
  26. if hasattr(torch._inductor.config, "fx_graph_cache"):
  27. torch._inductor.config.fx_graph_cache = True
  28. from torch.nn.attention import SDPBackend, sdpa_kernel
  29. from fish_speech.models.text2semantic.llama import (
  30. BaseTransformer,
  31. DualARTransformer,
  32. NaiveTransformer,
  33. )
  34. def multinomial_sample_one_no_sync(probs_sort):
  35. q = torch.rand_like(probs_sort)
  36. q = -torch.log(q)
  37. return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int)
  38. RAS_WIN_SIZE = 10 # window for Repetition Aware Sampling
  39. RAS_HIGH_TEMP = 1.0
  40. RAS_HIGH_TOP_P = 0.9
  41. def logits_to_probs(
  42. logits,
  43. temperature: torch.Tensor,
  44. top_p: torch.Tensor,
  45. top_k: int, # 注意: 我看到你传进来的是 int,这很关键
  46. ) -> torch.Tensor:
  47. sorted_logits, sorted_indices = torch.sort(logits, descending=True)
  48. cum_probs = torch.cumsum(torch.nn.functional.softmax(sorted_logits, dim=-1), dim=-1)
  49. indices = torch.arange(sorted_logits.shape[-1], device=sorted_logits.device)
  50. top_k_mask = indices >= top_k
  51. sorted_indices_to_remove = (cum_probs > top_p) | top_k_mask
  52. sorted_indices_to_remove[0] = False # 单元素修改问题不大,或者写成 | (indices != 0)
  53. indices_to_remove = sorted_indices_to_remove.scatter(
  54. dim=-1, index=sorted_indices, src=sorted_indices_to_remove
  55. )
  56. logits = torch.where(
  57. indices_to_remove, float("-Inf"), logits
  58. ) # 同样替换 masked_fill_ 为 torch.where
  59. logits = logits / torch.clip(temperature, min=1e-5)
  60. probs = torch.nn.functional.softmax(logits, dim=-1)
  61. return probs
  62. def sample(
  63. logits,
  64. temperature: torch.Tensor,
  65. top_p: torch.Tensor,
  66. top_k: int,
  67. ) -> Tuple[torch.Tensor, torch.Tensor]:
  68. probs = logits_to_probs(
  69. logits=logits[0, -1],
  70. temperature=temperature,
  71. top_p=top_p,
  72. top_k=top_k,
  73. )
  74. idx_next = multinomial_sample_one_no_sync(probs)
  75. return idx_next, probs
  76. def decode_one_token_ar(
  77. model: DualARTransformer,
  78. x: torch.Tensor,
  79. input_pos: torch.Tensor,
  80. temperature: torch.Tensor,
  81. top_p: torch.Tensor,
  82. top_k: int,
  83. semantic_logit_bias: torch.Tensor,
  84. audio_masks: torch.Tensor,
  85. audio_parts: torch.Tensor,
  86. previous_tokens: Optional[torch.Tensor] = None,
  87. ) -> torch.Tensor:
  88. forward_result = model.forward_generate(
  89. x,
  90. input_pos,
  91. audio_masks=audio_masks,
  92. audio_parts=audio_parts,
  93. )
  94. logits = forward_result.logits # (1, 1, vocab_size)
  95. hidden_states = forward_result.hidden_states
  96. # Apply constrained decoding: only allow semantic tokens + im_end
  97. biased_logits = logits + semantic_logit_bias
  98. # Normal sample
  99. main_token_normal = sample(
  100. biased_logits, temperature=temperature, top_p=top_p, top_k=top_k
  101. )[0]
  102. # RAS: also sample with high temp to use as fallback if token repeats
  103. high_temp = torch.tensor(
  104. RAS_HIGH_TEMP, device=temperature.device, dtype=temperature.dtype
  105. )
  106. high_top_p = torch.tensor(RAS_HIGH_TOP_P, device=top_p.device, dtype=top_p.dtype)
  107. main_token_high = sample(
  108. biased_logits, temperature=high_temp, top_p=high_top_p, top_k=top_k
  109. )[0]
  110. # Use high-temp sample if: token is semantic AND token is in previous window
  111. if previous_tokens is not None:
  112. in_window = (previous_tokens[0] == main_token_normal).any()
  113. # Use tensor ops (&, torch.where) instead of Python (and, if) — torch.compile requires no data-dependent branching
  114. is_semantic = (main_token_normal >= model.config.semantic_begin_id) & (
  115. main_token_normal <= model.config.semantic_end_id
  116. )
  117. should_use_high = in_window & is_semantic
  118. main_token_normal = torch.where(
  119. should_use_high, main_token_high, main_token_normal
  120. )
  121. codebooks = [main_token_normal]
  122. input_pos = torch.tensor([0], device=hidden_states.device, dtype=torch.long)
  123. model.forward_generate_fast(hidden_states, input_pos)
  124. a = codebooks[0] - model.config.semantic_begin_id
  125. a = torch.clamp(a, min=0, max=model.config.codebook_size - 1)
  126. hidden_states = model.fast_embeddings(a)
  127. codebooks.append(a)
  128. for codebook_idx in range(1, model.config.num_codebooks):
  129. input_pos = torch.tensor(
  130. [codebook_idx], device=hidden_states.device, dtype=torch.long
  131. )
  132. logits = model.forward_generate_fast(hidden_states, input_pos)
  133. short_logits = logits # DualAR predicts config.codebook_size number of tokens
  134. # Convert logits to probs (no constrain for fast codebooks)
  135. a = sample(
  136. short_logits,
  137. temperature=temperature,
  138. top_p=top_p,
  139. top_k=top_k,
  140. )[0]
  141. hidden_states = model.fast_embeddings(a)
  142. codebooks.append(a)
  143. codebooks = torch.stack(codebooks, dim=1)
  144. # Only delete references, let Python GC handle cleanup
  145. del logits, hidden_states, forward_result
  146. return codebooks.T
  147. def decode_n_tokens(
  148. model: DualARTransformer,
  149. cur_token: torch.Tensor,
  150. input_pos: torch.Tensor,
  151. num_new_tokens: int,
  152. temperature: torch.Tensor,
  153. top_p: torch.Tensor,
  154. top_k: int,
  155. semantic_logit_bias: torch.Tensor,
  156. audio_masks: torch.Tensor,
  157. audio_parts: torch.Tensor,
  158. decode_one_token=decode_one_token_ar,
  159. ):
  160. start = time.perf_counter()
  161. # Rolling window for RAS (Repetition Aware Sampling)
  162. previous_tokens = torch.zeros(
  163. (model.config.num_codebooks + 1, RAS_WIN_SIZE),
  164. dtype=torch.int,
  165. device=cur_token.device,
  166. )
  167. step1 = time.perf_counter()
  168. # Accumulate all generated tokens (the actual output)
  169. new_tokens = []
  170. # [MODIFIED] Pre-fetch ID for efficiency loop
  171. im_end_id = model.tokenizer.get_token_id(IM_END_TOKEN)
  172. step2 = time.perf_counter()
  173. for i in tqdm(range(num_new_tokens)):
  174. f_start = time.perf_counter()
  175. with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
  176. next_token = decode_one_token(
  177. model=model,
  178. x=cur_token,
  179. input_pos=input_pos,
  180. previous_tokens=previous_tokens,
  181. temperature=temperature,
  182. top_p=top_p,
  183. top_k=top_k,
  184. semantic_logit_bias=semantic_logit_bias,
  185. audio_masks=audio_masks,
  186. audio_parts=audio_parts,
  187. ).clone()
  188. input_pos += 1
  189. cur_token = next_token.view(1, model.config.num_codebooks + 1, -1)
  190. # Roll RAS window left and insert new token at end
  191. previous_tokens = previous_tokens.roll(-1, dims=1)
  192. previous_tokens[:, -1] = next_token.view(model.config.num_codebooks + 1, -1)[
  193. :, 0
  194. ]
  195. new_tokens.append(next_token)
  196. f_end = time.perf_counter()
  197. # logger.info(f"num_new_tokens for elapse: {f_end - f_start}")
  198. if cur_token[0, 0, -1] == im_end_id:
  199. break
  200. step3 = time.perf_counter()
  201. del cur_token
  202. logger.info(f"elapse step1: {step1 - start}, step2: {step2 - step1}, step3: {step3 - step2}")
  203. return torch.cat(new_tokens, dim=1)
  204. @torch.no_grad()
  205. @torch.inference_mode()
  206. def generate(
  207. *,
  208. model: DualARTransformer,
  209. prompt: torch.Tensor,
  210. max_new_tokens: int,
  211. audio_masks: torch.Tensor,
  212. audio_parts: torch.Tensor,
  213. decode_one_token=decode_one_token_ar,
  214. num_samples: int = 1,
  215. **sampling_kwargs,
  216. ):
  217. """
  218. Takes a conditioning sequence (prompt) as input and continues to generate as many tokens as requested.
  219. """
  220. # create an empty tensor of the expected final shape and fill in the current tokens
  221. start = time.perf_counter()
  222. T = prompt.size(1)
  223. prompt = prompt[None].repeat(num_samples, 1, 1)
  224. if T >= model.config.max_seq_len:
  225. raise ValueError(
  226. f"Input sequence length {T} exceeds max_seq_len {model.config.max_seq_len}"
  227. )
  228. if max_new_tokens:
  229. if T + max_new_tokens > model.config.max_seq_len:
  230. max_new_tokens = model.config.max_seq_len - T
  231. T_new = T + max_new_tokens
  232. else:
  233. T_new = model.config.max_seq_len
  234. max_new_tokens = T_new - T
  235. device = prompt.device
  236. dtype = next(
  237. model.parameters()
  238. ).dtype # model weight dtype (bfloat16), NOT prompt dtype (int32)
  239. step1 = time.perf_counter()
  240. # Critical fix: Only set up cache on first run or when necessary
  241. if not hasattr(model, "_cache_setup_done") or not model._cache_setup_done:
  242. with torch.device(device):
  243. model.setup_caches(
  244. max_batch_size=1, # Fixed to 1, avoid dynamic changes
  245. max_seq_len=model.config.max_seq_len,
  246. dtype=next(model.parameters()).dtype,
  247. )
  248. model._cache_setup_done = True
  249. step2 = time.perf_counter()
  250. codebook_dim = 1 + model.config.num_codebooks
  251. # Create new tensor each time, but try to reuse memory
  252. input_pos = torch.arange(0, T, device=device, dtype=torch.long)
  253. empty = torch.empty(
  254. (codebook_dim, model.config.max_seq_len), dtype=prompt.dtype, device=device
  255. )
  256. step3 = time.perf_counter()
  257. empty[:, :T] = prompt
  258. seq = empty
  259. temp_val = sampling_kwargs.get("temperature", 1.0)
  260. top_p_val = sampling_kwargs.get("top_p", 0.9)
  261. top_k_val = sampling_kwargs.get("top_k", 30)
  262. temperature = torch.tensor(temp_val, device=device, dtype=dtype)
  263. step4 = time.perf_counter()
  264. top_p = torch.tensor(top_p_val, device=device, dtype=dtype)
  265. step5 = time.perf_counter()
  266. # Build semantic logit bias: 0 for semantic tokens + im_end, -inf for all others
  267. vocab_size = model.config.vocab_size
  268. semantic_logit_bias = torch.full(
  269. (1, 1, vocab_size), float("-inf"), device=device, dtype=dtype
  270. )
  271. step6 = time.perf_counter()
  272. # [MODIFIED] Use config for semantic range
  273. semantic_logit_bias[
  274. 0, 0, model.config.semantic_begin_id: model.config.semantic_end_id + 1
  275. ] = 0.0
  276. # [MODIFIED] Use tokenizer.get_token_id (Wrapper method)
  277. semantic_logit_bias[0, 0, model.tokenizer.get_token_id(IM_END_TOKEN)] = 0.0
  278. step7 = time.perf_counter()
  279. prefill_decode = decode_one_token_ar
  280. first_token = prefill_decode(
  281. model,
  282. prompt.view(1, codebook_dim, -1),
  283. input_pos,
  284. temperature,
  285. top_p,
  286. top_k_val,
  287. semantic_logit_bias,
  288. audio_masks,
  289. audio_parts,
  290. )
  291. seq[:, T: T + 1] = first_token
  292. step8 = time.perf_counter()
  293. # Recreate input_pos
  294. input_pos = torch.tensor([T], device=device, dtype=torch.int)
  295. step9 = time.perf_counter()
  296. x = decode_n_tokens(
  297. model,
  298. first_token.view(1, codebook_dim, -1),
  299. input_pos,
  300. max_new_tokens - 1,
  301. temperature=temperature,
  302. top_p=top_p,
  303. top_k=top_k_val,
  304. semantic_logit_bias=semantic_logit_bias,
  305. audio_masks=audio_masks,
  306. audio_parts=audio_parts,
  307. decode_one_token=decode_one_token,
  308. )
  309. seq = seq[:, : T + 1 + x.size(1)]
  310. seq[:, T + 1:] = x
  311. step10 = time.perf_counter()
  312. # Clean up temporary variables
  313. del first_token, x, prompt, empty, input_pos
  314. step11 = time.perf_counter()
  315. logger.info(f"elapse "
  316. f"step1: {step1 - start}, step2: {step2 - step1}, step3: {step3 - step2} "
  317. f"step4: {step4 - step3}, step5: {step5 - step4} step6: {step6 - step5} "
  318. f"step7: {step7 - step6} step8: {step8 - step7} step9: {step9 - step8} "
  319. f"step10: {step10 - step9} step11: {step11 - step10} ")
  320. return seq
  321. def init_model(checkpoint_path, device, precision, compile=False):
  322. torch.backends.cuda.enable_flash_sdp(False)
  323. torch.backends.cuda.enable_math_sdp(True)
  324. torch.backends.cuda.enable_mem_efficient_sdp(True)
  325. torch.backends.cuda.enable_cudnn_sdp(True)
  326. model = DualARTransformer.from_pretrained(checkpoint_path, load_weights=True)
  327. logger.info(f"precision: {precision.__class__.__name__}")
  328. model = model.to(device=device, dtype=precision)
  329. logger.info(f"Restored model from checkpoint")
  330. if isinstance(model, DualARTransformer):
  331. decode_one_token = decode_one_token_ar
  332. # prefill_n_tokens = decode_one_token_ar
  333. logger.info("Using DualARTransformer")
  334. else:
  335. raise ValueError("Unsupported model type")
  336. # Pre-create fixed parameter tensors to avoid runtime creation
  337. model.fixed_temperature = torch.tensor(0.7, device=device, dtype=torch.float)
  338. model.fixed_top_p = torch.tensor(0.7, device=device, dtype=torch.float)
  339. model.fixed_repetition_penalty = torch.tensor(1.5, device=device, dtype=torch.float)
  340. # Mark whether cache has been initialized
  341. model._cache_setup_done = False
  342. if compile:
  343. logger.info("Compiling function...")
  344. # decode_one_token = torch.compile(
  345. # decode_one_token,
  346. # backend="inductor" if torch.cuda.is_available() else "aot_eager",
  347. # mode="default" if torch.cuda.is_available() else None,
  348. # fullgraph=True,
  349. # )
  350. decode_one_token = torch.compile(
  351. decode_one_token,
  352. backend="inductor" if torch.cuda.is_available() else "aot_eager",
  353. mode="reduce-overhead" if torch.cuda.is_available() else None,
  354. fullgraph=False,
  355. )
  356. return model.eval(), decode_one_token
  357. @torch.inference_mode()
  358. def load_codec_model(codec_checkpoint_path, device, precision=torch.bfloat16):
  359. """Load the DAC codec model for audio encoding/decoding."""
  360. from hydra.utils import instantiate
  361. from omegaconf import OmegaConf
  362. config_path = Path(__file__).parent.parent.parent / "configs" / "modded_dac_vq.yaml"
  363. cfg = OmegaConf.load(str(config_path))
  364. codec = instantiate(cfg)
  365. state_dict = torch.load(codec_checkpoint_path, map_location="cpu")
  366. if "state_dict" in state_dict:
  367. state_dict = state_dict["state_dict"]
  368. if any("generator" in k for k in state_dict):
  369. state_dict = {
  370. k.replace("generator.", ""): v
  371. for k, v in state_dict.items()
  372. if "generator." in k
  373. }
  374. codec.load_state_dict(state_dict, strict=False)
  375. codec.eval()
  376. codec.to(device=device, dtype=precision)
  377. return codec
  378. @torch.inference_mode()
  379. def encode_audio(audio_path, codec, device):
  380. """Encode an audio file to VQ codes."""
  381. import torchaudio
  382. wav, sr = torchaudio.load(str(audio_path))
  383. if wav.shape[0] > 1:
  384. wav = wav.mean(dim=0, keepdim=True)
  385. wav = torchaudio.functional.resample(wav.to(device), sr, codec.sample_rate)[0]
  386. # Match codec model dtype (e.g. bfloat16)
  387. model_dtype = next(codec.parameters()).dtype
  388. audios = wav[None, None].to(dtype=model_dtype) # (1, 1, T)
  389. audio_lengths = torch.tensor([len(wav)], device=device, dtype=torch.long)
  390. indices, feature_lengths = codec.encode(audios, audio_lengths)
  391. return indices[0, :, : feature_lengths[0]] # (num_codebooks, T)
  392. @torch.inference_mode()
  393. def decode_to_audio(codes, codec):
  394. """Decode VQ codes to audio waveform."""
  395. # codes: (num_codebooks, T) -> (1, num_codebooks, T)
  396. audio = codec.from_indices(codes[None])
  397. return audio[0, 0] # (T,) mono waveform
  398. @dataclass
  399. class GenerateResponse:
  400. action: Literal["sample", "next"]
  401. codes: Optional[torch.Tensor] = None
  402. text: Optional[str] = None
  403. def split_text_by_speaker(text: str) -> list[str]:
  404. """
  405. Split text into turns based on <|speaker:X|> tags.
  406. Args:
  407. text: The full text with speaker tags
  408. Returns:
  409. List of speaker turns, each starting with <|speaker:X|>
  410. """
  411. pattern = r"(<\|speaker:\d+\|>)"
  412. parts = re.split(pattern, text)
  413. turns = []
  414. i = 0
  415. while i < len(parts):
  416. part = parts[i].strip()
  417. if re.match(pattern, part):
  418. if i + 1 < len(parts):
  419. turn = part + parts[i + 1]
  420. turns.append(turn.strip())
  421. i += 2
  422. else:
  423. turns.append(part)
  424. i += 1
  425. else:
  426. i += 1
  427. return turns
  428. def group_turns_into_batches(
  429. turns: list[str], max_speakers: int = 3, max_bytes: int = 300
  430. ) -> list[str]:
  431. """
  432. Group turns into batches based on speaker count or byte limit.
  433. Args:
  434. turns: List of speaker turns
  435. max_speakers: Maximum number of speakers per batch (default 3)
  436. max_bytes: Maximum UTF-8 bytes per batch (default 300)
  437. Returns:
  438. List of batched text strings
  439. """
  440. batches = []
  441. current_batch = []
  442. current_bytes = 0
  443. for turn in turns:
  444. turn_bytes = len(turn.encode("utf-8"))
  445. would_exceed_speakers = len(current_batch) >= max_speakers
  446. would_exceed_bytes = current_bytes + turn_bytes > max_bytes and current_batch
  447. if would_exceed_speakers or would_exceed_bytes:
  448. batches.append("\n".join(current_batch))
  449. current_batch = [turn]
  450. current_bytes = turn_bytes
  451. else:
  452. current_batch.append(turn)
  453. current_bytes += turn_bytes
  454. if current_batch:
  455. batches.append("\n".join(current_batch))
  456. return batches
  457. def generate_long(
  458. *,
  459. model,
  460. device: Union[str, torch.device],
  461. decode_one_token: Callable,
  462. text: str,
  463. num_samples: int = 1,
  464. max_new_tokens: int = 0,
  465. top_p: float = 0.9,
  466. top_k: int = 30,
  467. repetition_penalty: float = 1.1,
  468. temperature: float = 1.0,
  469. compile: bool = False,
  470. iterative_prompt: bool = True,
  471. chunk_length: int = 512,
  472. prompt_text: Optional[Union[str, list[str]]] = None,
  473. prompt_tokens: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,
  474. ):
  475. assert 0 < top_p <= 1, "top_p must be in (0, 1]"
  476. assert 0 < temperature < 2, "temperature must be in (0, 2)"
  477. logger.info(f"generate_long.param.device: {device}")
  478. logger.info(f"generate_long.param.text: {text}")
  479. logger.info(f"generate_long.param.max_new_tokens: {max_new_tokens}")
  480. logger.info(f"generate_long.param.top_p: {top_p}")
  481. logger.info(f"generate_long.param.top_k: {top_k}")
  482. logger.info(f"generate_long.param.temperature: {temperature}")
  483. logger.info(f"generate_long.param.compile: {compile}")
  484. logger.info(f"generate_long.param.chunk_length: {chunk_length}")
  485. logger.info(f"generate_long.param.prompt_text: {prompt_text}")
  486. logger.info(f"generate_long.param.prompt_tokens: {prompt_tokens}")
  487. use_prompt = bool(prompt_text) and bool(prompt_tokens)
  488. if use_prompt and isinstance(prompt_text, str):
  489. prompt_text = [prompt_text]
  490. prompt_tokens = [prompt_tokens]
  491. if use_prompt:
  492. assert len(prompt_text) == len(
  493. prompt_tokens
  494. ), "Prompt text and tokens must have the same length"
  495. if prompt_tokens:
  496. prompt_tokens = [i.cpu() for i in prompt_tokens]
  497. model_size = sum(p.numel() for p in model.parameters() if p.requires_grad)
  498. tokenizer = model.tokenizer
  499. max_length = model.config.max_seq_len
  500. # Build base conversation with system message
  501. base_conversation = Conversation()
  502. if use_prompt:
  503. # Auto-add speaker tags to prompt texts that don't have them
  504. tagged_prompt_text = []
  505. for i, t in enumerate(prompt_text):
  506. if not re.search(r"<\|speaker:\d+\|>", t):
  507. tagged_prompt_text.append(f"<|speaker:{i}|>{t}")
  508. else:
  509. tagged_prompt_text.append(t)
  510. system_parts = [
  511. TextPart(
  512. text="convert the provided text to speech reference to the following:\n\nText:\n",
  513. cal_loss=False,
  514. ),
  515. ]
  516. reference_text = "\n".join(tagged_prompt_text)
  517. system_parts.append(TextPart(text=reference_text, cal_loss=False))
  518. system_parts.append(TextPart(text="\n\nSpeech:\n", cal_loss=False))
  519. all_codes = torch.cat([c for c in prompt_tokens], dim=1)
  520. system_parts.append(VQPart(codes=all_codes, cal_loss=False))
  521. # torch.save(all_codes, "debug_vq_codes.pt")
  522. else:
  523. system_parts = [
  524. TextPart(text="convert the provided text to speech", cal_loss=False)
  525. ]
  526. base_conversation.append(
  527. Message(
  528. role="system",
  529. parts=system_parts,
  530. cal_loss=False,
  531. add_im_start=True,
  532. add_im_end=True,
  533. )
  534. )
  535. # Split text by speaker and group into batches
  536. turns = split_text_by_speaker(text)
  537. if turns:
  538. batches = group_turns_into_batches(
  539. turns, max_speakers=5, max_bytes=chunk_length
  540. )
  541. else:
  542. batches = [text]
  543. logger.info(f"Split into {len(turns)} turns, grouped into {len(batches)} batches")
  544. for sample_idx in range(num_samples):
  545. if torch.cuda.is_available():
  546. torch.cuda.synchronize()
  547. t0 = time.perf_counter()
  548. # Deep copy base conversation for this sample
  549. conversation = deepcopy(base_conversation)
  550. for batch_idx, batch_text in enumerate(batches):
  551. logger.info(
  552. f"--- Sample {sample_idx}, Batch {batch_idx} "
  553. f"({len(batch_text.encode('utf-8'))} bytes) ---"
  554. )
  555. logger.info(f"Batch text: {batch_text}")
  556. # Add user message
  557. conversation.append(
  558. Message(
  559. role="user",
  560. parts=[TextPart(text=batch_text, cal_loss=False)],
  561. cal_loss=False,
  562. add_im_start=True,
  563. add_im_end=True,
  564. )
  565. )
  566. # Deep copy for generation (don't pollute original conversation)
  567. conversation_gen = deepcopy(conversation)
  568. conversation_gen.append(
  569. Message(
  570. role="assistant",
  571. parts=[],
  572. cal_loss=False,
  573. modality="voice",
  574. add_im_start=True,
  575. add_im_end=False,
  576. )
  577. )
  578. logger.info("Visualizing prompt structure:")
  579. conversation_gen.visualize(
  580. tokenizer,
  581. merge_audio_tokens=True,
  582. merge_semantic_tokens=True,
  583. )
  584. encoded, audio_masks, audio_parts = conversation_gen.encode_for_inference(
  585. tokenizer, num_codebooks=model.config.num_codebooks
  586. )
  587. logger.info(f"Encoded prompt shape: {encoded.shape}")
  588. if audio_parts is not None:
  589. logger.info(f"Audio parts shape: {audio_parts.shape}")
  590. if audio_masks is not None:
  591. logger.info(
  592. f"Audio masks non-zero count: {torch.count_nonzero(audio_masks)}"
  593. )
  594. if encoded.size(1) > max_length - 2048:
  595. raise ValueError(
  596. f"Prompt is too long: {encoded.size(1)} > {max_length - 2048}"
  597. )
  598. encoded = encoded.to(device=device)
  599. prompt_length = encoded.size(1)
  600. y = generate(
  601. model=model,
  602. prompt=encoded,
  603. max_new_tokens=max_new_tokens,
  604. audio_masks=audio_masks,
  605. audio_parts=audio_parts,
  606. decode_one_token=decode_one_token,
  607. temperature=temperature,
  608. top_p=top_p,
  609. top_k=top_k,
  610. )
  611. if sample_idx == 0 and batch_idx == 0 and compile:
  612. logger.info(f"Compilation time: {time.perf_counter() - t0:.2f} seconds")
  613. if torch.cuda.is_available():
  614. torch.cuda.synchronize()
  615. t_batch = time.perf_counter() - t0
  616. tokens_generated = y.size(1) - prompt_length
  617. tokens_sec = tokens_generated / t_batch if t_batch > 0 else 0
  618. logger.info(
  619. f"Batch {batch_idx}: Generated {tokens_generated} tokens in "
  620. f"{t_batch:.02f} seconds, {tokens_sec:.02f} tokens/sec"
  621. )
  622. logger.info(
  623. f"Bandwidth achieved: {model_size * tokens_sec / 1e9:.02f} GB/s"
  624. )
  625. # Extract generated codes
  626. codes = y[1:, prompt_length:-1].clone()
  627. assert (codes >= 0).all(), f"Negative code found: {codes}"
  628. # Add assistant message with generated codes back to conversation
  629. conversation.append(
  630. Message(
  631. role="assistant",
  632. parts=[VQPart(codes=codes.cpu(), cal_loss=False)],
  633. cal_loss=False,
  634. modality="voice",
  635. add_im_start=True,
  636. add_im_end=True,
  637. )
  638. )
  639. yield GenerateResponse(action="sample", codes=codes, text=batch_text)
  640. MAX_HISTORY_TURNS = 2 # 只保留最近 2 轮 user/assistant
  641. assistant_indices = [i for i, m in enumerate(conversation.messages) if m.role == "assistant"]
  642. if len(assistant_indices) > MAX_HISTORY_TURNS:
  643. drop = assistant_indices[0]
  644. # 移除最早的 user+assistant 对,保留 system 消息
  645. conversation = Conversation([m for i, m in enumerate(conversation.messages)
  646. if i not in (drop - 1, drop)])
  647. # Cleanup
  648. del y, encoded
  649. if torch.cuda.is_available():
  650. torch.cuda.empty_cache()
  651. import gc
  652. gc.collect()
  653. if torch.cuda.is_available():
  654. logger.info(
  655. f"GPU Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB"
  656. )
  657. yield GenerateResponse(action="next")
  658. @dataclass
  659. class WrappedGenerateResponse:
  660. status: Literal["success", "error"]
  661. response: Optional[Union[GenerateResponse, Exception]] = None
  662. @dataclass
  663. class GenerateRequest:
  664. request: dict
  665. response_queue: queue.Queue
  666. def launch_thread_safe_queue(
  667. checkpoint_path,
  668. device,
  669. precision,
  670. compile: bool = False,
  671. ):
  672. input_queue = queue.Queue()
  673. init_event = threading.Event()
  674. def worker():
  675. model, decode_one_token = init_model(
  676. checkpoint_path, device, precision, compile=compile
  677. )
  678. with torch.device(device):
  679. model.setup_caches(
  680. max_batch_size=1,
  681. max_seq_len=model.config.max_seq_len,
  682. dtype=next(model.parameters()).dtype,
  683. )
  684. init_event.set()
  685. while True:
  686. item: GenerateRequest | None = input_queue.get()
  687. if item is None:
  688. break
  689. kwargs = item.request
  690. response_queue = item.response_queue
  691. try:
  692. for chunk in generate_long(
  693. model=model, decode_one_token=decode_one_token, **kwargs
  694. ):
  695. response_queue.put(
  696. WrappedGenerateResponse(status="success", response=chunk)
  697. )
  698. # Only clear cache after complete request batch
  699. if torch.cuda.is_available():
  700. torch.cuda.empty_cache()
  701. except Exception as e:
  702. logger.error(traceback.format_exc())
  703. response_queue.put(WrappedGenerateResponse(status="error", response=e))
  704. # Clear cache on error
  705. if torch.cuda.is_available():
  706. torch.cuda.empty_cache()
  707. threading.Thread(target=worker, daemon=True).start()
  708. init_event.wait()
  709. return input_queue
  710. # ============================================
  711. # =============== 原始代码 =================
  712. # ============================================
  713. @click.command()
  714. @click.option(
  715. "--text",
  716. type=str,
  717. default="<|speaker:0|>你说的对, 但是原神是一款由米哈游自主研发的开放世界手游.",
  718. )
  719. @click.option("--prompt-text", type=str, default=None, multiple=True)
  720. @click.option(
  721. "--prompt-tokens",
  722. type=click.Path(path_type=Path, exists=True),
  723. default=None,
  724. multiple=True,
  725. )
  726. @click.option(
  727. "--prompt-audio",
  728. type=click.Path(path_type=Path, exists=True),
  729. default=None,
  730. multiple=True,
  731. )
  732. @click.option("--output", type=click.Path(path_type=Path), default=None)
  733. @click.option("--num-samples", type=int, default=1)
  734. @click.option("--max-new-tokens", type=int, default=0)
  735. @click.option("--top-p", type=float, default=0.9)
  736. @click.option("--top-k", type=int, default=30)
  737. @click.option("--temperature", type=float, default=1.0)
  738. @click.option(
  739. "--checkpoint-path",
  740. type=click.Path(path_type=Path, exists=True),
  741. default="checkpoints/s2-pro",
  742. )
  743. @click.option("--device", type=str, default="cuda")
  744. @click.option("--compile/--no-compile", default=False)
  745. @click.option("--seed", type=int, default=42)
  746. @click.option("--half/--no-half", default=False)
  747. @click.option("--iterative-prompt/--no-iterative-prompt", default=True)
  748. @click.option("--chunk-length", type=int, default=300)
  749. @click.option("--output-dir", type=Path, default="output")
  750. def main(
  751. text: str,
  752. prompt_text: Optional[tuple[str, ...]],
  753. prompt_tokens: Optional[tuple[Path, ...]],
  754. prompt_audio: Optional[tuple[Path, ...]],
  755. output: Optional[Path],
  756. num_samples: int,
  757. max_new_tokens: int,
  758. top_p: float,
  759. top_k: int,
  760. temperature: float,
  761. checkpoint_path: Path,
  762. device: str,
  763. compile: bool,
  764. seed: int,
  765. half: bool,
  766. iterative_prompt: bool,
  767. chunk_length: int,
  768. output_dir: Path,
  769. ) -> None:
  770. os.makedirs(output_dir, exist_ok=True)
  771. precision = torch.half if half else torch.bfloat16
  772. if prompt_text and not prompt_audio and not prompt_tokens:
  773. raise ValueError(
  774. "--prompt-text requires either --prompt-audio or --prompt-tokens"
  775. )
  776. if prompt_text and prompt_tokens and len(prompt_text) != len(prompt_tokens):
  777. raise ValueError(
  778. f"Number of prompt text ({len(prompt_text)}) and prompt tokens ({len(prompt_tokens)}) should be the same"
  779. )
  780. if prompt_text and prompt_audio and len(prompt_text) != len(prompt_audio):
  781. raise ValueError(
  782. f"Number of prompt text ({len(prompt_text)}) and prompt audio ({len(prompt_audio)}) should be the same"
  783. )
  784. logger.info("Loading model ...")
  785. t0 = time.time()
  786. model, decode_one_token = init_model(
  787. checkpoint_path, device, precision, compile=compile
  788. )
  789. with torch.device(device):
  790. model.setup_caches(
  791. max_batch_size=1,
  792. max_seq_len=model.config.max_seq_len,
  793. dtype=next(model.parameters()).dtype,
  794. )
  795. if torch.cuda.is_available():
  796. torch.cuda.synchronize()
  797. logger.info(f"Time to load model: {time.time() - t0:.02f} seconds")
  798. codec = None
  799. codec_checkpoint = checkpoint_path / "codec.pth"
  800. # Handle prompt: --prompt-audio takes priority over --prompt-tokens
  801. prompt_tokens_list = None
  802. if prompt_audio:
  803. logger.info("Loading codec model for audio encoding...")
  804. codec = load_codec_model(codec_checkpoint, device, precision)
  805. prompt_tokens_list = [
  806. encode_audio(p, codec, device).cpu() for p in prompt_audio
  807. ]
  808. logger.info(f"Encoded {len(prompt_audio)} audio file(s) to VQ codes")
  809. elif prompt_tokens is not None:
  810. prompt_tokens_list = [torch.from_numpy(np.load(p)) for p in prompt_tokens]
  811. torch.manual_seed(seed)
  812. if torch.cuda.is_available():
  813. torch.cuda.manual_seed(seed)
  814. generator = generate_long(
  815. model=model,
  816. device=device,
  817. decode_one_token=decode_one_token,
  818. text=text,
  819. num_samples=num_samples,
  820. max_new_tokens=max_new_tokens,
  821. top_p=top_p,
  822. top_k=top_k,
  823. temperature=temperature,
  824. compile=compile,
  825. iterative_prompt=iterative_prompt,
  826. chunk_length=chunk_length,
  827. prompt_text=list(prompt_text) if prompt_text else None,
  828. prompt_tokens=prompt_tokens_list,
  829. )
  830. idx = 0
  831. codes = []
  832. for response in generator:
  833. if response.action == "sample":
  834. codes.append(response.codes)
  835. logger.info(f"Sampled text: {response.text}")
  836. elif response.action == "next":
  837. if codes:
  838. merged_codes = torch.cat(codes, dim=1)
  839. codes_npy_path = os.path.join(output_dir, f"codes_{idx}.npy")
  840. np.save(codes_npy_path, merged_codes.cpu().numpy())
  841. logger.info(f"Saved codes to {codes_npy_path}")
  842. # Decode to wav if --output is specified
  843. if output:
  844. if codec is None:
  845. logger.info("Loading codec model for audio decoding...")
  846. codec = load_codec_model(codec_checkpoint, device, precision)
  847. audio = decode_to_audio(merged_codes.to(device), codec)
  848. import soundfile as sf
  849. out_path = (
  850. str(output)
  851. if num_samples == 1
  852. else str(output.with_stem(f"{output.stem}_{idx}"))
  853. )
  854. sf.write(out_path, audio.cpu().float().numpy(), codec.sample_rate)
  855. logger.info(f"Saved audio to {out_path}")
  856. logger.info(f"Next sample")
  857. codes = []
  858. idx += 1
  859. else:
  860. logger.error(f"Error: {response}")
  861. if __name__ == "__main__":
  862. main()