__init__.py 6.1 KB

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