inference.py 33 KB

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