inference.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  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(False)
  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. return model.eval(), decode_one_token
  351. @torch.inference_mode()
  352. def load_codec_model(codec_checkpoint_path, device, precision=torch.bfloat16):
  353. """Load the DAC codec model for audio encoding/decoding."""
  354. from hydra.utils import instantiate
  355. from omegaconf import OmegaConf
  356. config_path = Path(__file__).parent.parent.parent / "configs" / "modded_dac_vq.yaml"
  357. cfg = OmegaConf.load(str(config_path))
  358. codec = instantiate(cfg)
  359. state_dict = torch.load(codec_checkpoint_path, map_location="cpu")
  360. if "state_dict" in state_dict:
  361. state_dict = state_dict["state_dict"]
  362. if any("generator" in k for k in state_dict):
  363. state_dict = {
  364. k.replace("generator.", ""): v
  365. for k, v in state_dict.items()
  366. if "generator." in k
  367. }
  368. codec.load_state_dict(state_dict, strict=False)
  369. codec.eval()
  370. codec.to(device=device, dtype=precision)
  371. return codec
  372. @torch.inference_mode()
  373. def encode_audio(audio_path, codec, device):
  374. """Encode an audio file to VQ codes."""
  375. import torchaudio
  376. wav, sr = torchaudio.load(str(audio_path))
  377. if wav.shape[0] > 1:
  378. wav = wav.mean(dim=0, keepdim=True)
  379. wav = torchaudio.functional.resample(wav.to(device), sr, codec.sample_rate)[0]
  380. # Match codec model dtype (e.g. bfloat16)
  381. model_dtype = next(codec.parameters()).dtype
  382. audios = wav[None, None].to(dtype=model_dtype) # (1, 1, T)
  383. audio_lengths = torch.tensor([len(wav)], device=device, dtype=torch.long)
  384. indices, feature_lengths = codec.encode(audios, audio_lengths)
  385. return indices[0, :, : feature_lengths[0]] # (num_codebooks, T)
  386. @torch.inference_mode()
  387. def decode_to_audio(codes, codec):
  388. """Decode VQ codes to audio waveform."""
  389. # codes: (num_codebooks, T) -> (1, num_codebooks, T)
  390. audio = codec.from_indices(codes[None])
  391. return audio[0, 0] # (T,) mono waveform
  392. @dataclass
  393. class GenerateResponse:
  394. action: Literal["sample", "next"]
  395. codes: Optional[torch.Tensor] = None
  396. text: Optional[str] = None
  397. def split_text_by_speaker(text: str) -> list[str]:
  398. """
  399. Split text into turns based on <|speaker:X|> tags.
  400. Args:
  401. text: The full text with speaker tags
  402. Returns:
  403. List of speaker turns, each starting with <|speaker:X|>
  404. """
  405. pattern = r"(<\|speaker:\d+\|>)"
  406. parts = re.split(pattern, text)
  407. turns = []
  408. i = 0
  409. while i < len(parts):
  410. part = parts[i].strip()
  411. if re.match(pattern, part):
  412. if i + 1 < len(parts):
  413. turn = part + parts[i + 1]
  414. turns.append(turn.strip())
  415. i += 2
  416. else:
  417. turns.append(part)
  418. i += 1
  419. else:
  420. i += 1
  421. return turns
  422. def group_turns_into_batches(
  423. turns: list[str], max_speakers: int = 3, max_bytes: int = 300
  424. ) -> list[str]:
  425. """
  426. Group turns into batches based on speaker count or byte limit.
  427. Args:
  428. turns: List of speaker turns
  429. max_speakers: Maximum number of speakers per batch (default 3)
  430. max_bytes: Maximum UTF-8 bytes per batch (default 300)
  431. Returns:
  432. List of batched text strings
  433. """
  434. batches = []
  435. current_batch = []
  436. current_bytes = 0
  437. for turn in turns:
  438. turn_bytes = len(turn.encode("utf-8"))
  439. would_exceed_speakers = len(current_batch) >= max_speakers
  440. would_exceed_bytes = current_bytes + turn_bytes > max_bytes and current_batch
  441. if would_exceed_speakers or would_exceed_bytes:
  442. batches.append("\n".join(current_batch))
  443. current_batch = [turn]
  444. current_bytes = turn_bytes
  445. else:
  446. current_batch.append(turn)
  447. current_bytes += turn_bytes
  448. if current_batch:
  449. batches.append("\n".join(current_batch))
  450. return batches
  451. def generate_long(
  452. *,
  453. model,
  454. device: Union[str, torch.device],
  455. decode_one_token: Callable,
  456. text: str,
  457. num_samples: int = 1,
  458. max_new_tokens: int = 0,
  459. top_p: float = 0.9,
  460. top_k: int = 30,
  461. repetition_penalty: float = 1.1,
  462. temperature: float = 1.0,
  463. compile: bool = False,
  464. iterative_prompt: bool = True,
  465. chunk_length: int = 512,
  466. prompt_text: Optional[Union[str, list[str]]] = None,
  467. prompt_tokens: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,
  468. ):
  469. assert 0 < top_p <= 1, "top_p must be in (0, 1]"
  470. assert 0 < temperature < 2, "temperature must be in (0, 2)"
  471. logger.info(f"generate_long.param.device: {device}")
  472. logger.info(f"generate_long.param.text: {text}")
  473. logger.info(f"generate_long.param.max_new_tokens: {max_new_tokens}")
  474. logger.info(f"generate_long.param.top_p: {top_p}")
  475. logger.info(f"generate_long.param.top_k: {top_k}")
  476. logger.info(f"generate_long.param.temperature: {temperature}")
  477. logger.info(f"generate_long.param.compile: {compile}")
  478. logger.info(f"generate_long.param.chunk_length: {chunk_length}")
  479. logger.info(f"generate_long.param.prompt_text: {prompt_text}")
  480. logger.info(f"generate_long.param.prompt_tokens: {prompt_tokens}")
  481. use_prompt = bool(prompt_text) and bool(prompt_tokens)
  482. if use_prompt and isinstance(prompt_text, str):
  483. prompt_text = [prompt_text]
  484. prompt_tokens = [prompt_tokens]
  485. if use_prompt:
  486. assert len(prompt_text) == len(
  487. prompt_tokens
  488. ), "Prompt text and tokens must have the same length"
  489. if prompt_tokens:
  490. prompt_tokens = [i.cpu() for i in prompt_tokens]
  491. model_size = sum(p.numel() for p in model.parameters() if p.requires_grad)
  492. tokenizer = model.tokenizer
  493. max_length = model.config.max_seq_len
  494. # Build base conversation with system message
  495. base_conversation = Conversation()
  496. if use_prompt:
  497. # Auto-add speaker tags to prompt texts that don't have them
  498. tagged_prompt_text = []
  499. for i, t in enumerate(prompt_text):
  500. if not re.search(r"<\|speaker:\d+\|>", t):
  501. tagged_prompt_text.append(f"<|speaker:{i}|>{t}")
  502. else:
  503. tagged_prompt_text.append(t)
  504. system_parts = [
  505. TextPart(
  506. text="convert the provided text to speech reference to the following:\n\nText:\n",
  507. cal_loss=False,
  508. ),
  509. ]
  510. reference_text = "\n".join(tagged_prompt_text)
  511. system_parts.append(TextPart(text=reference_text, cal_loss=False))
  512. system_parts.append(TextPart(text="\n\nSpeech:\n", cal_loss=False))
  513. all_codes = torch.cat([c for c in prompt_tokens], dim=1)
  514. system_parts.append(VQPart(codes=all_codes, cal_loss=False))
  515. # torch.save(all_codes, "debug_vq_codes.pt")
  516. else:
  517. system_parts = [
  518. TextPart(text="convert the provided text to speech", cal_loss=False)
  519. ]
  520. base_conversation.append(
  521. Message(
  522. role="system",
  523. parts=system_parts,
  524. cal_loss=False,
  525. add_im_start=True,
  526. add_im_end=True,
  527. )
  528. )
  529. # Split text by speaker and group into batches
  530. turns = split_text_by_speaker(text)
  531. if turns:
  532. batches = group_turns_into_batches(
  533. turns, max_speakers=5, max_bytes=chunk_length
  534. )
  535. else:
  536. batches = [text]
  537. logger.info(f"Split into {len(turns)} turns, grouped into {len(batches)} batches")
  538. for sample_idx in range(num_samples):
  539. if torch.cuda.is_available():
  540. torch.cuda.synchronize()
  541. t0 = time.perf_counter()
  542. # Deep copy base conversation for this sample
  543. conversation = deepcopy(base_conversation)
  544. for batch_idx, batch_text in enumerate(batches):
  545. logger.info(
  546. f"--- Sample {sample_idx}, Batch {batch_idx} "
  547. f"({len(batch_text.encode('utf-8'))} bytes) ---"
  548. )
  549. logger.info(f"Batch text: {batch_text}")
  550. # Add user message
  551. conversation.append(
  552. Message(
  553. role="user",
  554. parts=[TextPart(text=batch_text, cal_loss=False)],
  555. cal_loss=False,
  556. add_im_start=True,
  557. add_im_end=True,
  558. )
  559. )
  560. # Deep copy for generation (don't pollute original conversation)
  561. conversation_gen = deepcopy(conversation)
  562. conversation_gen.append(
  563. Message(
  564. role="assistant",
  565. parts=[],
  566. cal_loss=False,
  567. modality="voice",
  568. add_im_start=True,
  569. add_im_end=False,
  570. )
  571. )
  572. logger.info("Visualizing prompt structure:")
  573. conversation_gen.visualize(
  574. tokenizer,
  575. merge_audio_tokens=True,
  576. merge_semantic_tokens=True,
  577. )
  578. encoded, audio_masks, audio_parts = conversation_gen.encode_for_inference(
  579. tokenizer, num_codebooks=model.config.num_codebooks
  580. )
  581. logger.info(f"Encoded prompt shape: {encoded.shape}")
  582. if audio_parts is not None:
  583. logger.info(f"Audio parts shape: {audio_parts.shape}")
  584. if audio_masks is not None:
  585. logger.info(
  586. f"Audio masks non-zero count: {torch.count_nonzero(audio_masks)}"
  587. )
  588. if encoded.size(1) > max_length - 2048:
  589. raise ValueError(
  590. f"Prompt is too long: {encoded.size(1)} > {max_length - 2048}"
  591. )
  592. encoded = encoded.to(device=device)
  593. prompt_length = encoded.size(1)
  594. y = generate(
  595. model=model,
  596. prompt=encoded,
  597. max_new_tokens=max_new_tokens,
  598. audio_masks=audio_masks,
  599. audio_parts=audio_parts,
  600. decode_one_token=decode_one_token,
  601. temperature=temperature,
  602. top_p=top_p,
  603. top_k=top_k,
  604. )
  605. if sample_idx == 0 and batch_idx == 0 and compile:
  606. logger.info(f"Compilation time: {time.perf_counter() - t0:.2f} seconds")
  607. if torch.cuda.is_available():
  608. torch.cuda.synchronize()
  609. t_batch = time.perf_counter() - t0
  610. tokens_generated = y.size(1) - prompt_length
  611. tokens_sec = tokens_generated / t_batch if t_batch > 0 else 0
  612. logger.info(
  613. f"Batch {batch_idx}: Generated {tokens_generated} tokens in "
  614. f"{t_batch:.02f} seconds, {tokens_sec:.02f} tokens/sec"
  615. )
  616. logger.info(
  617. f"Bandwidth achieved: {model_size * tokens_sec / 1e9:.02f} GB/s"
  618. )
  619. # Extract generated codes
  620. codes = y[1:, prompt_length:-1].clone()
  621. assert (codes >= 0).all(), f"Negative code found: {codes}"
  622. # Add assistant message with generated codes back to conversation
  623. conversation.append(
  624. Message(
  625. role="assistant",
  626. parts=[VQPart(codes=codes.cpu(), cal_loss=False)],
  627. cal_loss=False,
  628. modality="voice",
  629. add_im_start=True,
  630. add_im_end=True,
  631. )
  632. )
  633. yield GenerateResponse(action="sample", codes=codes, text=batch_text)
  634. MAX_HISTORY_TURNS = 2 # 只保留最近 2 轮 user/assistant
  635. assistant_indices = [i for i, m in enumerate(conversation.messages) if m.role == "assistant"]
  636. if len(assistant_indices) > MAX_HISTORY_TURNS:
  637. drop = assistant_indices[0]
  638. # 移除最早的 user+assistant 对,保留 system 消息
  639. conversation = Conversation([m for i, m in enumerate(conversation.messages)
  640. if i not in (drop - 1, drop)])
  641. # Cleanup
  642. del y, encoded
  643. if torch.cuda.is_available():
  644. torch.cuda.empty_cache()
  645. import gc
  646. gc.collect()
  647. if torch.cuda.is_available():
  648. logger.info(
  649. f"GPU Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB"
  650. )
  651. yield GenerateResponse(action="next")
  652. @dataclass
  653. class WrappedGenerateResponse:
  654. status: Literal["success", "error"]
  655. response: Optional[Union[GenerateResponse, Exception]] = None
  656. @dataclass
  657. class GenerateRequest:
  658. request: dict
  659. response_queue: queue.Queue
  660. def launch_thread_safe_queue(
  661. checkpoint_path,
  662. device,
  663. precision,
  664. compile: bool = False,
  665. ):
  666. input_queue = queue.Queue()
  667. init_event = threading.Event()
  668. def worker():
  669. model, decode_one_token = init_model(
  670. checkpoint_path, device, precision, compile=compile
  671. )
  672. with torch.device(device):
  673. model.setup_caches(
  674. max_batch_size=1,
  675. max_seq_len=model.config.max_seq_len,
  676. dtype=next(model.parameters()).dtype,
  677. )
  678. init_event.set()
  679. while True:
  680. item: GenerateRequest | None = input_queue.get()
  681. if item is None:
  682. break
  683. kwargs = item.request
  684. response_queue = item.response_queue
  685. try:
  686. for chunk in generate_long(
  687. model=model, decode_one_token=decode_one_token, **kwargs
  688. ):
  689. response_queue.put(
  690. WrappedGenerateResponse(status="success", response=chunk)
  691. )
  692. # Only clear cache after complete request batch
  693. if torch.cuda.is_available():
  694. torch.cuda.empty_cache()
  695. except Exception as e:
  696. logger.error(traceback.format_exc())
  697. response_queue.put(WrappedGenerateResponse(status="error", response=e))
  698. # Clear cache on error
  699. if torch.cuda.is_available():
  700. torch.cuda.empty_cache()
  701. threading.Thread(target=worker, daemon=True).start()
  702. init_event.wait()
  703. return input_queue
  704. # ============================================
  705. # =============== 原始代码 =================
  706. # ============================================
  707. @click.command()
  708. @click.option(
  709. "--text",
  710. type=str,
  711. default="<|speaker:0|>你说的对, 但是原神是一款由米哈游自主研发的开放世界手游.",
  712. )
  713. @click.option("--prompt-text", type=str, default=None, multiple=True)
  714. @click.option(
  715. "--prompt-tokens",
  716. type=click.Path(path_type=Path, exists=True),
  717. default=None,
  718. multiple=True,
  719. )
  720. @click.option(
  721. "--prompt-audio",
  722. type=click.Path(path_type=Path, exists=True),
  723. default=None,
  724. multiple=True,
  725. )
  726. @click.option("--output", type=click.Path(path_type=Path), default=None)
  727. @click.option("--num-samples", type=int, default=1)
  728. @click.option("--max-new-tokens", type=int, default=0)
  729. @click.option("--top-p", type=float, default=0.9)
  730. @click.option("--top-k", type=int, default=30)
  731. @click.option("--temperature", type=float, default=1.0)
  732. @click.option(
  733. "--checkpoint-path",
  734. type=click.Path(path_type=Path, exists=True),
  735. default="checkpoints/s2-pro",
  736. )
  737. @click.option("--device", type=str, default="cuda")
  738. @click.option("--compile/--no-compile", default=False)
  739. @click.option("--seed", type=int, default=42)
  740. @click.option("--half/--no-half", default=False)
  741. @click.option("--iterative-prompt/--no-iterative-prompt", default=True)
  742. @click.option("--chunk-length", type=int, default=300)
  743. @click.option("--output-dir", type=Path, default="output")
  744. def main(
  745. text: str,
  746. prompt_text: Optional[tuple[str, ...]],
  747. prompt_tokens: Optional[tuple[Path, ...]],
  748. prompt_audio: Optional[tuple[Path, ...]],
  749. output: Optional[Path],
  750. num_samples: int,
  751. max_new_tokens: int,
  752. top_p: float,
  753. top_k: int,
  754. temperature: float,
  755. checkpoint_path: Path,
  756. device: str,
  757. compile: bool,
  758. seed: int,
  759. half: bool,
  760. iterative_prompt: bool,
  761. chunk_length: int,
  762. output_dir: Path,
  763. ) -> None:
  764. os.makedirs(output_dir, exist_ok=True)
  765. precision = torch.half if half else torch.bfloat16
  766. if prompt_text and not prompt_audio and not prompt_tokens:
  767. raise ValueError(
  768. "--prompt-text requires either --prompt-audio or --prompt-tokens"
  769. )
  770. if prompt_text and prompt_tokens and len(prompt_text) != len(prompt_tokens):
  771. raise ValueError(
  772. f"Number of prompt text ({len(prompt_text)}) and prompt tokens ({len(prompt_tokens)}) should be the same"
  773. )
  774. if prompt_text and prompt_audio and len(prompt_text) != len(prompt_audio):
  775. raise ValueError(
  776. f"Number of prompt text ({len(prompt_text)}) and prompt audio ({len(prompt_audio)}) should be the same"
  777. )
  778. logger.info("Loading model ...")
  779. t0 = time.time()
  780. model, decode_one_token = init_model(
  781. checkpoint_path, device, precision, compile=compile
  782. )
  783. with torch.device(device):
  784. model.setup_caches(
  785. max_batch_size=1,
  786. max_seq_len=model.config.max_seq_len,
  787. dtype=next(model.parameters()).dtype,
  788. )
  789. if torch.cuda.is_available():
  790. torch.cuda.synchronize()
  791. logger.info(f"Time to load model: {time.time() - t0:.02f} seconds")
  792. codec = None
  793. codec_checkpoint = checkpoint_path / "codec.pth"
  794. # Handle prompt: --prompt-audio takes priority over --prompt-tokens
  795. prompt_tokens_list = None
  796. if prompt_audio:
  797. logger.info("Loading codec model for audio encoding...")
  798. codec = load_codec_model(codec_checkpoint, device, precision)
  799. prompt_tokens_list = [
  800. encode_audio(p, codec, device).cpu() for p in prompt_audio
  801. ]
  802. logger.info(f"Encoded {len(prompt_audio)} audio file(s) to VQ codes")
  803. elif prompt_tokens is not None:
  804. prompt_tokens_list = [torch.from_numpy(np.load(p)) for p in prompt_tokens]
  805. torch.manual_seed(seed)
  806. if torch.cuda.is_available():
  807. torch.cuda.manual_seed(seed)
  808. generator = generate_long(
  809. model=model,
  810. device=device,
  811. decode_one_token=decode_one_token,
  812. text=text,
  813. num_samples=num_samples,
  814. max_new_tokens=max_new_tokens,
  815. top_p=top_p,
  816. top_k=top_k,
  817. temperature=temperature,
  818. compile=compile,
  819. iterative_prompt=iterative_prompt,
  820. chunk_length=chunk_length,
  821. prompt_text=list(prompt_text) if prompt_text else None,
  822. prompt_tokens=prompt_tokens_list,
  823. )
  824. idx = 0
  825. codes = []
  826. for response in generator:
  827. if response.action == "sample":
  828. codes.append(response.codes)
  829. logger.info(f"Sampled text: {response.text}")
  830. elif response.action == "next":
  831. if codes:
  832. merged_codes = torch.cat(codes, dim=1)
  833. codes_npy_path = os.path.join(output_dir, f"codes_{idx}.npy")
  834. np.save(codes_npy_path, merged_codes.cpu().numpy())
  835. logger.info(f"Saved codes to {codes_npy_path}")
  836. # Decode to wav if --output is specified
  837. if output:
  838. if codec is None:
  839. logger.info("Loading codec model for audio decoding...")
  840. codec = load_codec_model(codec_checkpoint, device, precision)
  841. audio = decode_to_audio(merged_codes.to(device), codec)
  842. import soundfile as sf
  843. out_path = (
  844. str(output)
  845. if num_samples == 1
  846. else str(output.with_stem(f"{output.stem}_{idx}"))
  847. )
  848. sf.write(out_path, audio.cpu().float().numpy(), codec.sample_rate)
  849. logger.info(f"Saved audio to {out_path}")
  850. logger.info(f"Next sample")
  851. codes = []
  852. idx += 1
  853. else:
  854. logger.error(f"Error: {response}")
  855. if __name__ == "__main__":
  856. main()