__init__.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. import gc
  2. import queue
  3. from typing import Generator
  4. import numpy as np
  5. import torch
  6. from loguru import logger
  7. from fish_speech.inference_engine.reference_loader import ReferenceLoader
  8. from fish_speech.inference_engine.utils import InferenceResult, wav_chunk_header
  9. from fish_speech.inference_engine.vq_manager import VQManager
  10. from fish_speech.models.text2semantic.inference import (
  11. GenerateRequest,
  12. GenerateResponse,
  13. WrappedGenerateResponse,
  14. )
  15. from fish_speech.models.vqgan.modules.firefly import FireflyArchitecture
  16. from fish_speech.text.chn_text_norm.text import Text as ChnNormedText
  17. from fish_speech.utils import autocast_exclude_mps, set_seed
  18. from fish_speech.utils.schema import ServeTTSRequest
  19. class TTSInferenceEngine(ReferenceLoader, VQManager):
  20. def __init__(
  21. self,
  22. llama_queue: queue.Queue,
  23. decoder_model: FireflyArchitecture,
  24. precision: torch.dtype,
  25. compile: bool,
  26. ) -> None:
  27. super().__init__()
  28. self.llama_queue = llama_queue
  29. self.decoder_model = decoder_model
  30. self.precision = precision
  31. self.compile = compile
  32. @torch.inference_mode()
  33. def inference(self, req: ServeTTSRequest) -> Generator[InferenceResult, None, None]:
  34. """
  35. Main inference function:
  36. - Loads the reference audio and text.
  37. - Calls the LLAMA model for inference.
  38. - Decodes the VQ tokens to audio.
  39. """
  40. ref_id: str | None = req.reference_id
  41. prompt_tokens, prompt_texts = [], []
  42. # Load the reference audio and text based on id or hash
  43. if ref_id is not None:
  44. prompt_tokens, prompt_texts = self.load_by_id(ref_id, req.use_memory_cache)
  45. elif req.references:
  46. prompt_tokens, prompt_texts = self.load_by_hash(
  47. req.references, req.use_memory_cache
  48. )
  49. # Set the random seed if provided
  50. if req.seed is not None:
  51. set_seed(req.seed)
  52. logger.warning(f"set seed: {req.seed}")
  53. # Get the symbolic tokens from the LLAMA model
  54. response_queue = self.send_Llama_request(req, prompt_tokens, prompt_texts)
  55. # Get the sample rate from the decoder model
  56. sample_rate = self.decoder_model.spec_transform.sample_rate
  57. # If streaming, send the header
  58. if req.streaming:
  59. yield InferenceResult(
  60. code="header",
  61. audio=(
  62. sample_rate,
  63. np.array(wav_chunk_header(sample_rate=sample_rate)),
  64. ),
  65. error=None,
  66. )
  67. segments = []
  68. while True:
  69. # Get the response from the LLAMA model
  70. wrapped_result: WrappedGenerateResponse = response_queue.get()
  71. if wrapped_result.status == "error":
  72. yield InferenceResult(
  73. code="error",
  74. audio=None,
  75. error=(
  76. wrapped_result.response
  77. if isinstance(wrapped_result.response, Exception)
  78. else Exception("Unknown error")
  79. ),
  80. )
  81. break
  82. # Check the response type
  83. if not isinstance(wrapped_result.response, GenerateResponse):
  84. raise TypeError(
  85. "Expected GenerateResponse, got {type(wrapped_result.response).__name__}"
  86. )
  87. result: GenerateResponse = wrapped_result.response
  88. if result.action != "next":
  89. segment = self.get_audio_segment(result)
  90. if req.streaming: # Used only by the API server
  91. yield InferenceResult(
  92. code="segment",
  93. audio=(sample_rate, segment),
  94. error=None,
  95. )
  96. segments.append(segment)
  97. else:
  98. break
  99. # Clean up the memory
  100. if torch.cuda.is_available():
  101. torch.cuda.empty_cache()
  102. gc.collect()
  103. # Edge case: no audio generated
  104. if len(segments) == 0:
  105. yield InferenceResult(
  106. code="error",
  107. audio=None,
  108. error=RuntimeError("No audio generated, please check the input text."),
  109. )
  110. else:
  111. # Streaming or not, return the final audio
  112. audio = np.concatenate(segments, axis=0)
  113. yield InferenceResult(
  114. code="final",
  115. audio=(sample_rate, audio),
  116. error=None,
  117. )
  118. return None
  119. def send_Llama_request(
  120. self, req: ServeTTSRequest, prompt_tokens: list, prompt_texts: list
  121. ) -> queue.Queue:
  122. """
  123. Send a request to the LLAMA model to generate the symbolic tokens.
  124. """
  125. # Prepare the request
  126. request = dict(
  127. device=self.decoder_model.device,
  128. max_new_tokens=req.max_new_tokens,
  129. text=(
  130. req.text
  131. if not req.normalize
  132. else ChnNormedText(raw_text=req.text).normalize()
  133. ),
  134. top_p=req.top_p,
  135. repetition_penalty=req.repetition_penalty,
  136. temperature=req.temperature,
  137. compile=self.compile,
  138. iterative_prompt=req.chunk_length > 0,
  139. chunk_length=req.chunk_length,
  140. max_length=4096,
  141. prompt_tokens=prompt_tokens,
  142. prompt_text=prompt_texts,
  143. )
  144. # Create a queue to get the response
  145. response_queue = queue.Queue()
  146. # Send the request to the LLAMA model
  147. self.llama_queue.put(
  148. GenerateRequest(
  149. request=request,
  150. response_queue=response_queue,
  151. )
  152. )
  153. return response_queue
  154. def get_audio_segment(self, result: GenerateResponse) -> np.ndarray:
  155. """
  156. Decode the VQ tokens to audio.
  157. """
  158. # Don't use autocast on MPS devices
  159. with autocast_exclude_mps(
  160. device_type=self.decoder_model.device.type, dtype=self.precision
  161. ):
  162. # Decode the symbolic tokens to audio
  163. segment = self.decode_vq_tokens(codes=result.codes)
  164. # Convert the audio to numpy
  165. return segment.float().cpu().numpy()