inference.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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. @torch.inference_mode()
  148. def decode_one_token_ar_optimize(
  149. model,
  150. x,
  151. input_pos,
  152. temperature,
  153. top_p,
  154. top_k,
  155. semantic_logit_bias,
  156. audio_masks,
  157. audio_parts,
  158. previous_tokens=None,
  159. ):
  160. # =========================
  161. # 1. Forward (attention bottleneck)
  162. # =========================
  163. forward_result = model.forward_generate(
  164. x,
  165. input_pos,
  166. audio_masks=audio_masks,
  167. audio_parts=audio_parts,
  168. )
  169. logits = forward_result.logits
  170. hidden_states = forward_result.hidden_states
  171. # =========================
  172. # 2. fuse bias early
  173. # =========================
  174. logits = logits + semantic_logit_bias
  175. # =========================
  176. # 3. single sampling (❗核心优化)
  177. # =========================
  178. token = sample(
  179. logits,
  180. temperature=temperature,
  181. top_p=top_p,
  182. top_k=top_k,
  183. )[0]
  184. # =========================
  185. # 4. optional correction (lightweight, no second sample)
  186. # =========================
  187. if previous_tokens is not None:
  188. is_semantic = (token >= model.config.semantic_begin_id) & (
  189. token <= model.config.semantic_end_id
  190. )
  191. # cheap check only (no second forward/sample)
  192. if is_semantic and (previous_tokens[0] == token).any():
  193. token = token # keep same (or optionally reroll once if needed)
  194. # =========================
  195. # 5. codebook init
  196. # =========================
  197. codebooks = [token]
  198. # reuse tensor (❗避免创建)
  199. input_pos_tensor = input_pos
  200. # =========================
  201. # 6. fast path generate loop (optimized)
  202. # =========================
  203. model.forward_generate_fast(hidden_states, input_pos_tensor)
  204. a = token - model.config.semantic_begin_id
  205. a = torch.clamp(a, 0, model.config.codebook_size - 1)
  206. hidden_states = model.fast_embeddings(a)
  207. codebooks.append(a)
  208. # =========================
  209. # 7. fused loop (minor optimization)
  210. # =========================
  211. for i in range(1, model.config.num_codebooks):
  212. input_pos_tensor = i # avoid torch.tensor creation
  213. logits = model.forward_generate_fast(hidden_states, input_pos_tensor)
  214. a = sample(
  215. logits,
  216. temperature=temperature,
  217. top_p=top_p,
  218. top_k=top_k,
  219. )[0]
  220. hidden_states = model.fast_embeddings(a)
  221. codebooks.append(a)
  222. # =========================
  223. # 8. final output
  224. # =========================
  225. codebooks = torch.stack(codebooks, dim=1)
  226. return codebooks.T
  227. def decode_n_tokens(
  228. model: DualARTransformer,
  229. cur_token: torch.Tensor,
  230. input_pos: torch.Tensor,
  231. num_new_tokens: int,
  232. temperature: torch.Tensor,
  233. top_p: torch.Tensor,
  234. top_k: int,
  235. semantic_logit_bias: torch.Tensor,
  236. audio_masks: torch.Tensor,
  237. audio_parts: torch.Tensor,
  238. decode_one_token=decode_one_token_ar,
  239. ):
  240. start = time.perf_counter()
  241. # Rolling window for RAS (Repetition Aware Sampling)
  242. previous_tokens = torch.zeros(
  243. (model.config.num_codebooks + 1, RAS_WIN_SIZE),
  244. dtype=torch.int,
  245. device=cur_token.device,
  246. )
  247. step1 = time.perf_counter()
  248. # Accumulate all generated tokens (the actual output)
  249. new_tokens = []
  250. # [MODIFIED] Pre-fetch ID for efficiency loop
  251. im_end_id = model.tokenizer.get_token_id(IM_END_TOKEN)
  252. step2 = time.perf_counter()
  253. for i in tqdm(range(num_new_tokens)):
  254. f_start = time.perf_counter()
  255. with sdpa_kernel(SDPBackend.MATH):
  256. next_token = decode_one_token(
  257. model=model,
  258. x=cur_token,
  259. input_pos=input_pos,
  260. previous_tokens=previous_tokens,
  261. temperature=temperature,
  262. top_p=top_p,
  263. top_k=top_k,
  264. semantic_logit_bias=semantic_logit_bias,
  265. audio_masks=audio_masks,
  266. audio_parts=audio_parts,
  267. ).clone()
  268. input_pos += 1
  269. cur_token = next_token.view(1, model.config.num_codebooks + 1, -1)
  270. # Roll RAS window left and insert new token at end
  271. # previous_tokens = previous_tokens.roll(-1, dims=1)
  272. # previous_tokens[:, -1] = next_token.view(model.config.num_codebooks + 1, -1)[
  273. # :, 0
  274. # ]
  275. new_tokens.append(next_token)
  276. f_end = time.perf_counter()
  277. # logger.info(f"num_new_tokens for elapse: {f_end - f_start}")
  278. if cur_token[0, 0, -1] == im_end_id:
  279. break
  280. step3 = time.perf_counter()
  281. del cur_token
  282. logger.info(f"elapse step1: {step1 - start}, step2: {step2 - step1}, step3: {step3 - step2}")
  283. return torch.cat(new_tokens, dim=1)
  284. @torch.no_grad()
  285. @torch.inference_mode()
  286. def generate(
  287. *,
  288. model: DualARTransformer,
  289. prompt: torch.Tensor,
  290. max_new_tokens: int,
  291. audio_masks: torch.Tensor,
  292. audio_parts: torch.Tensor,
  293. decode_one_token=decode_one_token_ar,
  294. num_samples: int = 1,
  295. **sampling_kwargs,
  296. ):
  297. """
  298. Takes a conditioning sequence (prompt) as input and continues to generate as many tokens as requested.
  299. """
  300. # create an empty tensor of the expected final shape and fill in the current tokens
  301. start = time.perf_counter()
  302. T = prompt.size(1)
  303. prompt = prompt[None].repeat(num_samples, 1, 1)
  304. if T >= model.config.max_seq_len:
  305. raise ValueError(
  306. f"Input sequence length {T} exceeds max_seq_len {model.config.max_seq_len}"
  307. )
  308. if max_new_tokens:
  309. if T + max_new_tokens > model.config.max_seq_len:
  310. max_new_tokens = model.config.max_seq_len - T
  311. T_new = T + max_new_tokens
  312. else:
  313. T_new = model.config.max_seq_len
  314. max_new_tokens = T_new - T
  315. device = prompt.device
  316. dtype = next(
  317. model.parameters()
  318. ).dtype # model weight dtype (bfloat16), NOT prompt dtype (int32)
  319. step1 = time.perf_counter()
  320. # Critical fix: Only set up cache on first run or when necessary
  321. if not hasattr(model, "_cache_setup_done") or not model._cache_setup_done:
  322. with torch.device(device):
  323. model.setup_caches(
  324. max_batch_size=1, # Fixed to 1, avoid dynamic changes
  325. max_seq_len=model.config.max_seq_len,
  326. dtype=next(model.parameters()).dtype,
  327. )
  328. model._cache_setup_done = True
  329. step2 = time.perf_counter()
  330. codebook_dim = 1 + model.config.num_codebooks
  331. # Create new tensor each time, but try to reuse memory
  332. input_pos = torch.arange(0, T, device=device, dtype=torch.long)
  333. empty = torch.empty(
  334. (codebook_dim, model.config.max_seq_len), dtype=prompt.dtype, device=device
  335. )
  336. step3 = time.perf_counter()
  337. empty[:, :T] = prompt
  338. seq = empty
  339. temp_val = sampling_kwargs.get("temperature", 1.0)
  340. top_p_val = sampling_kwargs.get("top_p", 0.9)
  341. top_k_val = sampling_kwargs.get("top_k", 30)
  342. temperature = torch.tensor(temp_val, device=device, dtype=dtype)
  343. step4 = time.perf_counter()
  344. top_p = torch.tensor(top_p_val, device=device, dtype=dtype)
  345. step5 = time.perf_counter()
  346. # Build semantic logit bias: 0 for semantic tokens + im_end, -inf for all others
  347. vocab_size = model.config.vocab_size
  348. semantic_logit_bias = torch.full(
  349. (1, 1, vocab_size), float("-inf"), device=device, dtype=dtype
  350. )
  351. step6 = time.perf_counter()
  352. # [MODIFIED] Use config for semantic range
  353. semantic_logit_bias[
  354. 0, 0, model.config.semantic_begin_id: model.config.semantic_end_id + 1
  355. ] = 0.0
  356. # [MODIFIED] Use tokenizer.get_token_id (Wrapper method)
  357. semantic_logit_bias[0, 0, model.tokenizer.get_token_id(IM_END_TOKEN)] = 0.0
  358. step7 = time.perf_counter()
  359. prefill_decode = decode_one_token_ar
  360. first_token = prefill_decode(
  361. model,
  362. prompt.view(1, codebook_dim, -1),
  363. input_pos,
  364. temperature,
  365. top_p,
  366. top_k_val,
  367. semantic_logit_bias,
  368. audio_masks,
  369. audio_parts,
  370. )
  371. seq[:, T: T + 1] = first_token
  372. step8 = time.perf_counter()
  373. # Recreate input_pos
  374. input_pos = torch.tensor([T], device=device, dtype=torch.int)
  375. step9 = time.perf_counter()
  376. x = decode_n_tokens(
  377. model,
  378. first_token.view(1, codebook_dim, -1),
  379. input_pos,
  380. max_new_tokens - 1,
  381. temperature=temperature,
  382. top_p=top_p,
  383. top_k=top_k_val,
  384. semantic_logit_bias=semantic_logit_bias,
  385. audio_masks=audio_masks,
  386. audio_parts=audio_parts,
  387. decode_one_token=decode_one_token,
  388. )
  389. seq = seq[:, : T + 1 + x.size(1)]
  390. seq[:, T + 1:] = x
  391. step10 = time.perf_counter()
  392. # Clean up temporary variables
  393. del first_token, x, prompt, empty, input_pos
  394. step11 = time.perf_counter()
  395. logger.info(f"elapse "
  396. f"step1: {step1 - start}, step2: {step2 - step1}, step3: {step3 - step2} "
  397. f"step4: {step4 - step3}, step5: {step5 - step4} step6: {step6 - step5} "
  398. f"step7: {step7 - step6} step8: {step8 - step7} step9: {step9 - step8} "
  399. f"step10: {step10 - step9} step11: {step11 - step10} ")
  400. return seq
  401. def init_model(checkpoint_path, device, precision, compile=False):
  402. model = DualARTransformer.from_pretrained(checkpoint_path, load_weights=True)
  403. logger.info(f"precision: {precision.__class__.__name__}")
  404. model = model.to(device=device, dtype=precision)
  405. logger.info(f"Restored model from checkpoint")
  406. if isinstance(model, DualARTransformer):
  407. decode_one_token = decode_one_token_ar
  408. # prefill_n_tokens = decode_one_token_ar
  409. logger.info("Using DualARTransformer")
  410. else:
  411. raise ValueError("Unsupported model type")
  412. # Pre-create fixed parameter tensors to avoid runtime creation
  413. model.fixed_temperature = torch.tensor(0.7, device=device, dtype=torch.float)
  414. model.fixed_top_p = torch.tensor(0.7, device=device, dtype=torch.float)
  415. model.fixed_repetition_penalty = torch.tensor(1.5, device=device, dtype=torch.float)
  416. # Mark whether cache has been initialized
  417. model._cache_setup_done = False
  418. if compile:
  419. logger.info("Compiling function...")
  420. # decode_one_token = torch.compile(
  421. # decode_one_token,
  422. # backend="inductor" if torch.cuda.is_available() else "aot_eager",
  423. # mode="default" if torch.cuda.is_available() else None,
  424. # fullgraph=True,
  425. # )
  426. decode_one_token = torch.compile(
  427. decode_one_token,
  428. backend="inductor" if torch.cuda.is_available() else "aot_eager",
  429. mode="reduce-overhead" if torch.cuda.is_available() else None,
  430. fullgraph=False,
  431. )
  432. return model.eval(), decode_one_token
  433. @torch.inference_mode()
  434. def load_codec_model(codec_checkpoint_path, device, precision=torch.bfloat16):
  435. """Load the DAC codec model for audio encoding/decoding."""
  436. from hydra.utils import instantiate
  437. from omegaconf import OmegaConf
  438. config_path = Path(__file__).parent.parent.parent / "configs" / "modded_dac_vq.yaml"
  439. cfg = OmegaConf.load(str(config_path))
  440. codec = instantiate(cfg)
  441. state_dict = torch.load(codec_checkpoint_path, map_location="cpu")
  442. if "state_dict" in state_dict:
  443. state_dict = state_dict["state_dict"]
  444. if any("generator" in k for k in state_dict):
  445. state_dict = {
  446. k.replace("generator.", ""): v
  447. for k, v in state_dict.items()
  448. if "generator." in k
  449. }
  450. codec.load_state_dict(state_dict, strict=False)
  451. codec.eval()
  452. codec.to(device=device, dtype=precision)
  453. return codec
  454. @torch.inference_mode()
  455. def encode_audio(audio_path, codec, device):
  456. """Encode an audio file to VQ codes."""
  457. import torchaudio
  458. wav, sr = torchaudio.load(str(audio_path))
  459. if wav.shape[0] > 1:
  460. wav = wav.mean(dim=0, keepdim=True)
  461. wav = torchaudio.functional.resample(wav.to(device), sr, codec.sample_rate)[0]
  462. # Match codec model dtype (e.g. bfloat16)
  463. model_dtype = next(codec.parameters()).dtype
  464. audios = wav[None, None].to(dtype=model_dtype) # (1, 1, T)
  465. audio_lengths = torch.tensor([len(wav)], device=device, dtype=torch.long)
  466. indices, feature_lengths = codec.encode(audios, audio_lengths)
  467. return indices[0, :, : feature_lengths[0]] # (num_codebooks, T)
  468. @torch.inference_mode()
  469. def decode_to_audio(codes, codec):
  470. """Decode VQ codes to audio waveform."""
  471. # codes: (num_codebooks, T) -> (1, num_codebooks, T)
  472. audio = codec.from_indices(codes[None])
  473. return audio[0, 0] # (T,) mono waveform
  474. @dataclass
  475. class GenerateResponse:
  476. action: Literal["sample", "next"]
  477. codes: Optional[torch.Tensor] = None
  478. text: Optional[str] = None
  479. def split_text_by_speaker(text: str) -> list[str]:
  480. """
  481. Split text into turns based on <|speaker:X|> tags.
  482. Args:
  483. text: The full text with speaker tags
  484. Returns:
  485. List of speaker turns, each starting with <|speaker:X|>
  486. """
  487. pattern = r"(<\|speaker:\d+\|>)"
  488. parts = re.split(pattern, text)
  489. turns = []
  490. i = 0
  491. while i < len(parts):
  492. part = parts[i].strip()
  493. if re.match(pattern, part):
  494. if i + 1 < len(parts):
  495. turn = part + parts[i + 1]
  496. turns.append(turn.strip())
  497. i += 2
  498. else:
  499. turns.append(part)
  500. i += 1
  501. else:
  502. i += 1
  503. return turns
  504. def group_turns_into_batches(
  505. turns: list[str], max_speakers: int = 3, max_bytes: int = 300
  506. ) -> list[str]:
  507. """
  508. Group turns into batches based on speaker count or byte limit.
  509. Args:
  510. turns: List of speaker turns
  511. max_speakers: Maximum number of speakers per batch (default 3)
  512. max_bytes: Maximum UTF-8 bytes per batch (default 300)
  513. Returns:
  514. List of batched text strings
  515. """
  516. batches = []
  517. current_batch = []
  518. current_bytes = 0
  519. for turn in turns:
  520. turn_bytes = len(turn.encode("utf-8"))
  521. would_exceed_speakers = len(current_batch) >= max_speakers
  522. would_exceed_bytes = current_bytes + turn_bytes > max_bytes and current_batch
  523. if would_exceed_speakers or would_exceed_bytes:
  524. batches.append("\n".join(current_batch))
  525. current_batch = [turn]
  526. current_bytes = turn_bytes
  527. else:
  528. current_batch.append(turn)
  529. current_bytes += turn_bytes
  530. if current_batch:
  531. batches.append("\n".join(current_batch))
  532. return batches
  533. def generate_long(
  534. *,
  535. model,
  536. device: Union[str, torch.device],
  537. decode_one_token: Callable,
  538. text: str,
  539. num_samples: int = 1,
  540. max_new_tokens: int = 0,
  541. top_p: float = 0.9,
  542. top_k: int = 30,
  543. repetition_penalty: float = 1.1,
  544. temperature: float = 1.0,
  545. compile: bool = False,
  546. iterative_prompt: bool = True,
  547. chunk_length: int = 512,
  548. prompt_text: Optional[Union[str, list[str]]] = None,
  549. prompt_tokens: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,
  550. ):
  551. assert 0 < top_p <= 1, "top_p must be in (0, 1]"
  552. assert 0 < temperature < 2, "temperature must be in (0, 2)"
  553. logger.info(f"generate_long.param.device: {device}")
  554. logger.info(f"generate_long.param.text: {text}")
  555. logger.info(f"generate_long.param.max_new_tokens: {max_new_tokens}")
  556. logger.info(f"generate_long.param.top_p: {top_p}")
  557. logger.info(f"generate_long.param.top_k: {top_k}")
  558. logger.info(f"generate_long.param.temperature: {temperature}")
  559. logger.info(f"generate_long.param.compile: {compile}")
  560. logger.info(f"generate_long.param.chunk_length: {chunk_length}")
  561. logger.info(f"generate_long.param.prompt_text: {prompt_text}")
  562. logger.info(f"generate_long.param.prompt_tokens: {prompt_tokens}")
  563. use_prompt = bool(prompt_text) and bool(prompt_tokens)
  564. if use_prompt and isinstance(prompt_text, str):
  565. prompt_text = [prompt_text]
  566. prompt_tokens = [prompt_tokens]
  567. if use_prompt:
  568. assert len(prompt_text) == len(
  569. prompt_tokens
  570. ), "Prompt text and tokens must have the same length"
  571. if prompt_tokens:
  572. prompt_tokens = [i.cpu() for i in prompt_tokens]
  573. model_size = sum(p.numel() for p in model.parameters() if p.requires_grad)
  574. tokenizer = model.tokenizer
  575. max_length = model.config.max_seq_len
  576. # Build base conversation with system message
  577. base_conversation = Conversation()
  578. if use_prompt:
  579. # Auto-add speaker tags to prompt texts that don't have them
  580. tagged_prompt_text = []
  581. for i, t in enumerate(prompt_text):
  582. if not re.search(r"<\|speaker:\d+\|>", t):
  583. tagged_prompt_text.append(f"<|speaker:{i}|>{t}")
  584. else:
  585. tagged_prompt_text.append(t)
  586. system_parts = [
  587. TextPart(
  588. text="convert the provided text to speech reference to the following:\n\nText:\n",
  589. cal_loss=False,
  590. ),
  591. ]
  592. reference_text = "\n".join(tagged_prompt_text)
  593. system_parts.append(TextPart(text=reference_text, cal_loss=False))
  594. system_parts.append(TextPart(text="\n\nSpeech:\n", cal_loss=False))
  595. all_codes = torch.cat([c for c in prompt_tokens], dim=1)
  596. system_parts.append(VQPart(codes=all_codes, cal_loss=False))
  597. # torch.save(all_codes, "debug_vq_codes.pt")
  598. else:
  599. system_parts = [
  600. TextPart(text="convert the provided text to speech", cal_loss=False)
  601. ]
  602. base_conversation.append(
  603. Message(
  604. role="system",
  605. parts=system_parts,
  606. cal_loss=False,
  607. add_im_start=True,
  608. add_im_end=True,
  609. )
  610. )
  611. # Split text by speaker and group into batches
  612. turns = split_text_by_speaker(text)
  613. if turns:
  614. batches = group_turns_into_batches(
  615. turns, max_speakers=5, max_bytes=chunk_length
  616. )
  617. else:
  618. batches = [text]
  619. logger.info(f"Split into {len(turns)} turns, grouped into {len(batches)} batches")
  620. for sample_idx in range(num_samples):
  621. if torch.cuda.is_available():
  622. torch.cuda.synchronize()
  623. t0 = time.perf_counter()
  624. # Deep copy base conversation for this sample
  625. conversation = deepcopy(base_conversation)
  626. for batch_idx, batch_text in enumerate(batches):
  627. logger.info(
  628. f"--- Sample {sample_idx}, Batch {batch_idx} "
  629. f"({len(batch_text.encode('utf-8'))} bytes) ---"
  630. )
  631. logger.info(f"Batch text: {batch_text}")
  632. # Add user message
  633. conversation.append(
  634. Message(
  635. role="user",
  636. parts=[TextPart(text=batch_text, cal_loss=False)],
  637. cal_loss=False,
  638. add_im_start=True,
  639. add_im_end=True,
  640. )
  641. )
  642. # Deep copy for generation (don't pollute original conversation)
  643. conversation_gen = deepcopy(conversation)
  644. conversation_gen.append(
  645. Message(
  646. role="assistant",
  647. parts=[],
  648. cal_loss=False,
  649. modality="voice",
  650. add_im_start=True,
  651. add_im_end=False,
  652. )
  653. )
  654. logger.info("Visualizing prompt structure:")
  655. conversation_gen.visualize(
  656. tokenizer,
  657. merge_audio_tokens=True,
  658. merge_semantic_tokens=True,
  659. )
  660. encoded, audio_masks, audio_parts = conversation_gen.encode_for_inference(
  661. tokenizer, num_codebooks=model.config.num_codebooks
  662. )
  663. logger.info(f"Encoded prompt shape: {encoded.shape}")
  664. if audio_parts is not None:
  665. logger.info(f"Audio parts shape: {audio_parts.shape}")
  666. if audio_masks is not None:
  667. logger.info(
  668. f"Audio masks non-zero count: {torch.count_nonzero(audio_masks)}"
  669. )
  670. if encoded.size(1) > max_length - 2048:
  671. raise ValueError(
  672. f"Prompt is too long: {encoded.size(1)} > {max_length - 2048}"
  673. )
  674. encoded = encoded.to(device=device)
  675. prompt_length = encoded.size(1)
  676. y = generate(
  677. model=model,
  678. prompt=encoded,
  679. max_new_tokens=max_new_tokens,
  680. audio_masks=audio_masks,
  681. audio_parts=audio_parts,
  682. decode_one_token=decode_one_token,
  683. temperature=temperature,
  684. top_p=top_p,
  685. top_k=top_k,
  686. )
  687. if sample_idx == 0 and batch_idx == 0 and compile:
  688. logger.info(f"Compilation time: {time.perf_counter() - t0:.2f} seconds")
  689. if torch.cuda.is_available():
  690. torch.cuda.synchronize()
  691. t_batch = time.perf_counter() - t0
  692. tokens_generated = y.size(1) - prompt_length
  693. tokens_sec = tokens_generated / t_batch if t_batch > 0 else 0
  694. logger.info(
  695. f"Batch {batch_idx}: Generated {tokens_generated} tokens in "
  696. f"{t_batch:.02f} seconds, {tokens_sec:.02f} tokens/sec"
  697. )
  698. logger.info(
  699. f"Bandwidth achieved: {model_size * tokens_sec / 1e9:.02f} GB/s"
  700. )
  701. # Extract generated codes
  702. codes = y[1:, prompt_length:-1].clone()
  703. assert (codes >= 0).all(), f"Negative code found: {codes}"
  704. # Add assistant message with generated codes back to conversation
  705. conversation.append(
  706. Message(
  707. role="assistant",
  708. parts=[VQPart(codes=codes.cpu(), cal_loss=False)],
  709. cal_loss=False,
  710. modality="voice",
  711. add_im_start=True,
  712. add_im_end=True,
  713. )
  714. )
  715. yield GenerateResponse(action="sample", codes=codes, text=batch_text)
  716. MAX_HISTORY_TURNS = 2 # 只保留最近 2 轮 user/assistant
  717. assistant_indices = [i for i, m in enumerate(conversation.messages) if m.role == "assistant"]
  718. if len(assistant_indices) > MAX_HISTORY_TURNS:
  719. drop = assistant_indices[0]
  720. # 移除最早的 user+assistant 对,保留 system 消息
  721. conversation = Conversation([m for i, m in enumerate(conversation.messages)
  722. if i not in (drop - 1, drop)])
  723. # Cleanup
  724. del y, encoded
  725. if torch.cuda.is_available():
  726. torch.cuda.empty_cache()
  727. import gc
  728. gc.collect()
  729. if torch.cuda.is_available():
  730. logger.info(
  731. f"GPU Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB"
  732. )
  733. yield GenerateResponse(action="next")
  734. @dataclass
  735. class WrappedGenerateResponse:
  736. status: Literal["success", "error"]
  737. response: Optional[Union[GenerateResponse, Exception]] = None
  738. @dataclass
  739. class GenerateRequest:
  740. request: dict
  741. response_queue: queue.Queue
  742. def launch_thread_safe_queue(
  743. checkpoint_path,
  744. device,
  745. precision,
  746. compile: bool = False,
  747. ):
  748. input_queue = queue.Queue()
  749. init_event = threading.Event()
  750. def worker():
  751. model, decode_one_token = init_model(
  752. checkpoint_path, device, precision, compile=compile
  753. )
  754. with torch.device(device):
  755. model.setup_caches(
  756. max_batch_size=1,
  757. max_seq_len=model.config.max_seq_len,
  758. dtype=next(model.parameters()).dtype,
  759. )
  760. init_event.set()
  761. while True:
  762. item: GenerateRequest | None = input_queue.get()
  763. if item is None:
  764. break
  765. kwargs = item.request
  766. response_queue = item.response_queue
  767. try:
  768. for chunk in generate_long(
  769. model=model, decode_one_token=decode_one_token, **kwargs
  770. ):
  771. response_queue.put(
  772. WrappedGenerateResponse(status="success", response=chunk)
  773. )
  774. # Only clear cache after complete request batch
  775. if torch.cuda.is_available():
  776. torch.cuda.empty_cache()
  777. except Exception as e:
  778. logger.error(traceback.format_exc())
  779. response_queue.put(WrappedGenerateResponse(status="error", response=e))
  780. # Clear cache on error
  781. if torch.cuda.is_available():
  782. torch.cuda.empty_cache()
  783. threading.Thread(target=worker, daemon=True).start()
  784. init_event.wait()
  785. return input_queue
  786. # ============================================
  787. # =============== 原始代码 =================
  788. # ============================================
  789. @click.command()
  790. @click.option(
  791. "--text",
  792. type=str,
  793. default="<|speaker:0|>你说的对, 但是原神是一款由米哈游自主研发的开放世界手游.",
  794. )
  795. @click.option("--prompt-text", type=str, default=None, multiple=True)
  796. @click.option(
  797. "--prompt-tokens",
  798. type=click.Path(path_type=Path, exists=True),
  799. default=None,
  800. multiple=True,
  801. )
  802. @click.option(
  803. "--prompt-audio",
  804. type=click.Path(path_type=Path, exists=True),
  805. default=None,
  806. multiple=True,
  807. )
  808. @click.option("--output", type=click.Path(path_type=Path), default=None)
  809. @click.option("--num-samples", type=int, default=1)
  810. @click.option("--max-new-tokens", type=int, default=0)
  811. @click.option("--top-p", type=float, default=0.9)
  812. @click.option("--top-k", type=int, default=30)
  813. @click.option("--temperature", type=float, default=1.0)
  814. @click.option(
  815. "--checkpoint-path",
  816. type=click.Path(path_type=Path, exists=True),
  817. default="checkpoints/s2-pro",
  818. )
  819. @click.option("--device", type=str, default="cuda")
  820. @click.option("--compile/--no-compile", default=False)
  821. @click.option("--seed", type=int, default=42)
  822. @click.option("--half/--no-half", default=False)
  823. @click.option("--iterative-prompt/--no-iterative-prompt", default=True)
  824. @click.option("--chunk-length", type=int, default=300)
  825. @click.option("--output-dir", type=Path, default="output")
  826. def main(
  827. text: str,
  828. prompt_text: Optional[tuple[str, ...]],
  829. prompt_tokens: Optional[tuple[Path, ...]],
  830. prompt_audio: Optional[tuple[Path, ...]],
  831. output: Optional[Path],
  832. num_samples: int,
  833. max_new_tokens: int,
  834. top_p: float,
  835. top_k: int,
  836. temperature: float,
  837. checkpoint_path: Path,
  838. device: str,
  839. compile: bool,
  840. seed: int,
  841. half: bool,
  842. iterative_prompt: bool,
  843. chunk_length: int,
  844. output_dir: Path,
  845. ) -> None:
  846. os.makedirs(output_dir, exist_ok=True)
  847. precision = torch.half if half else torch.bfloat16
  848. if prompt_text and not prompt_audio and not prompt_tokens:
  849. raise ValueError(
  850. "--prompt-text requires either --prompt-audio or --prompt-tokens"
  851. )
  852. if prompt_text and prompt_tokens and len(prompt_text) != len(prompt_tokens):
  853. raise ValueError(
  854. f"Number of prompt text ({len(prompt_text)}) and prompt tokens ({len(prompt_tokens)}) should be the same"
  855. )
  856. if prompt_text and prompt_audio and len(prompt_text) != len(prompt_audio):
  857. raise ValueError(
  858. f"Number of prompt text ({len(prompt_text)}) and prompt audio ({len(prompt_audio)}) should be the same"
  859. )
  860. logger.info("Loading model ...")
  861. t0 = time.time()
  862. model, decode_one_token = init_model(
  863. checkpoint_path, device, precision, compile=compile
  864. )
  865. with torch.device(device):
  866. model.setup_caches(
  867. max_batch_size=1,
  868. max_seq_len=model.config.max_seq_len,
  869. dtype=next(model.parameters()).dtype,
  870. )
  871. if torch.cuda.is_available():
  872. torch.cuda.synchronize()
  873. logger.info(f"Time to load model: {time.time() - t0:.02f} seconds")
  874. codec = None
  875. codec_checkpoint = checkpoint_path / "codec.pth"
  876. # Handle prompt: --prompt-audio takes priority over --prompt-tokens
  877. prompt_tokens_list = None
  878. if prompt_audio:
  879. logger.info("Loading codec model for audio encoding...")
  880. codec = load_codec_model(codec_checkpoint, device, precision)
  881. prompt_tokens_list = [
  882. encode_audio(p, codec, device).cpu() for p in prompt_audio
  883. ]
  884. logger.info(f"Encoded {len(prompt_audio)} audio file(s) to VQ codes")
  885. elif prompt_tokens is not None:
  886. prompt_tokens_list = [torch.from_numpy(np.load(p)) for p in prompt_tokens]
  887. torch.manual_seed(seed)
  888. if torch.cuda.is_available():
  889. torch.cuda.manual_seed(seed)
  890. generator = generate_long(
  891. model=model,
  892. device=device,
  893. decode_one_token=decode_one_token,
  894. text=text,
  895. num_samples=num_samples,
  896. max_new_tokens=max_new_tokens,
  897. top_p=top_p,
  898. top_k=top_k,
  899. temperature=temperature,
  900. compile=compile,
  901. iterative_prompt=iterative_prompt,
  902. chunk_length=chunk_length,
  903. prompt_text=list(prompt_text) if prompt_text else None,
  904. prompt_tokens=prompt_tokens_list,
  905. )
  906. idx = 0
  907. codes = []
  908. for response in generator:
  909. if response.action == "sample":
  910. codes.append(response.codes)
  911. logger.info(f"Sampled text: {response.text}")
  912. elif response.action == "next":
  913. if codes:
  914. merged_codes = torch.cat(codes, dim=1)
  915. codes_npy_path = os.path.join(output_dir, f"codes_{idx}.npy")
  916. np.save(codes_npy_path, merged_codes.cpu().numpy())
  917. logger.info(f"Saved codes to {codes_npy_path}")
  918. # Decode to wav if --output is specified
  919. if output:
  920. if codec is None:
  921. logger.info("Loading codec model for audio decoding...")
  922. codec = load_codec_model(codec_checkpoint, device, precision)
  923. audio = decode_to_audio(merged_codes.to(device), codec)
  924. import soundfile as sf
  925. out_path = (
  926. str(output)
  927. if num_samples == 1
  928. else str(output.with_stem(f"{output.stem}_{idx}"))
  929. )
  930. sf.write(out_path, audio.cpu().float().numpy(), codec.sample_rate)
  931. logger.info(f"Saved audio to {out_path}")
  932. logger.info(f"Next sample")
  933. codes = []
  934. idx += 1
  935. else:
  936. logger.error(f"Error: {response}")
  937. if __name__ == "__main__":
  938. main()