diff --git a/GPT_SoVITS/Accel/PyTorch/AR/structs.py b/GPT_SoVITS/Accel/PyTorch/AR/structs.py index 6590ae45..348b91fd 100644 --- a/GPT_SoVITS/Accel/PyTorch/AR/structs.py +++ b/GPT_SoVITS/Accel/PyTorch/AR/structs.py @@ -7,6 +7,7 @@ from __future__ import annotations from collections.abc import Generator, MutableSequence from dataclasses import dataclass, field from queue import Empty, SimpleQueue +from threading import Event from typing import TYPE_CHECKING, Literal, Optional, Protocol, Union import torch @@ -50,6 +51,7 @@ class T2SRequest: stream_interval: Optional[int] = None return_partial: bool = True debug: bool = False + max_decode_steps: Optional[int] = None @dataclass @@ -60,6 +62,7 @@ class T2SStreamResponse: finished: bool = False result: Optional[T2SResult] = None exception: Optional[Exception] = None + ready_event: Optional[torch.cuda.Event] = None @dataclass @@ -67,6 +70,7 @@ class T2SRequestHandle: request_id: Union[str, int] queue: SimpleQueue[T2SStreamResponse] = field(default_factory=SimpleQueue) done: bool = False + cancelled: Event = field(default_factory=Event) def get_nowait(self) -> Optional[T2SStreamResponse]: try: @@ -151,8 +155,13 @@ class T2SSession: self.prefill_len = self.x_lens + request.prompts.size(1) self.input_pos = self.prefill_len.clone().reshape(bsz) - self.max_decode_steps = min(int(decoder.max_seq_length - int(self.input_pos.max().item())), 640) - self.max_decode_steps = max(1, self.max_decode_steps) + limit = 640 if request.max_decode_steps is None else request.max_decode_steps + if limit <= 0: + raise ValueError("max_decode_steps must be positive") + available_steps = int(decoder.max_seq_length - int(self.input_pos.max().item())) + if available_steps <= 0: + raise ValueError("Text and reference exceed the GPT context capacity") + self.max_decode_steps = min(available_steps, limit) # EOS self.completed = torch.zeros(bsz, device=device, dtype=torch.bool) diff --git a/GPT_SoVITS/Accel/PyTorch/AR/t2s_engine.py b/GPT_SoVITS/Accel/PyTorch/AR/t2s_engine.py index 7b611fa0..52185b0d 100644 --- a/GPT_SoVITS/Accel/PyTorch/AR/t2s_engine.py +++ b/GPT_SoVITS/Accel/PyTorch/AR/t2s_engine.py @@ -113,11 +113,28 @@ class T2SEngine(T2SEngineProtocol): def stream_generate(self, request: T2SRequest, show_progress: bool = False): """Generator yielding streaming responses until completion.""" handle = self.add_request(request, stream_interval=request.stream_interval, show_progress=show_progress) - while True: - resp = handle.queue.get() - yield resp - if resp.finished: - break + try: + while True: + resp = handle.queue.get() + yield resp + if resp.finished: + break + finally: + if not handle.done: + self.cancel_request(handle) + + def cancel_request(self, handle: T2SRequestHandle, timeout: float = 5.0): + """Cancel on the runner owner thread and wait before reusing global RNG.""" + handle.cancelled.set() + deadline = time.monotonic() + timeout + while not handle.done: + if self._stop_event.is_set(): + return + if self._loop_thread is None or not self._loop_thread.is_alive(): + raise RuntimeError("GPT owner thread stopped before cancellation completed") + if time.monotonic() >= deadline: + raise RuntimeError("GPT cancellation timed out") + time.sleep(0.001) def generate(self, request: T2SRequest, show_progress: bool = False): """Blocking generate that consumes the streaming queue until finished.""" @@ -158,10 +175,13 @@ class T2SEngine(T2SEngineProtocol): result=result, exception=exception, ) - handle.queue.put(payload) + if tokens is not None and self.device.type == "cuda": + payload.ready_event = torch.cuda.Event() + payload.ready_event.record(torch.cuda.current_stream(self.device)) if finished: handle.done = True self.handles.pop(session.request_id, None) + handle.queue.put(payload) def _maybe_stream_partial(self, session: T2SSession): if session.stream_interval <= 0: @@ -179,13 +199,14 @@ class T2SEngine(T2SEngineProtocol): self, session: T2SSession, exception: Optional[Exception] = None, + cancelled: bool = False, ): request = session.request infer_time = max(time.perf_counter() - session.start_time, 1e-6) infer_speed = (session.total_tokens / infer_time if session.total_tokens else 0.0, infer_time) status: Literal["Success", "Error"] = "Error" if exception else "Success" - if exception: + if exception and not cancelled: logger.error(f"T2S request {session.request_id} failed: {exception}") traceback.print_exc() @@ -229,6 +250,10 @@ class T2SEngine(T2SEngineProtocol): except Empty: break + if handle.cancelled.is_set(): + handle.done = True + self.handles.pop(request.request_id, None) + continue try: session = self.model_runner.prefill(request) except Exception as e: @@ -269,11 +294,22 @@ class T2SEngine(T2SEngineProtocol): new_added = True return new_added + @torch.inference_mode() def _background_loop(self): torch.set_grad_enabled(False) while not self._stop_event.is_set(): self._drain_new_requests() + # Only this owner thread may mutate the runner or its session lists. + for session in list(self.waiting_bind) + list(self.model_runner.bound_sessions): + handle = self.handles.get(session.request_id) + if handle is not None and handle.cancelled.is_set(): + if session in self.waiting_bind: + self.waiting_bind.remove(session) + else: + self.model_runner.unbind_session(session) + self._finalize_session(session, RuntimeError("T2S request cancelled"), cancelled=True) + if not self.model_runner.bound_sessions: if not self.waiting_bind: time.sleep(0.001) @@ -305,6 +341,7 @@ class T2SEngine(T2SEngineProtocol): max_batch_size: int = 1, backend: str = "Flash-Attn-Varlen-CUDAGraph", quantize_mode: Optional[Literal["Int8", "FP8", "FP8_E4M3FN"]] = None, + max_seq_length: Optional[int] = None, ) -> T2SDecoderABC: logger.info(f"Loading Text2Semantic Weights from {weights_path} with {backend} Backend") module_path = f".backends.{backend.lower().replace('-', '_').replace('cudagraph', 'cuda_graph')}" @@ -316,7 +353,10 @@ class T2SEngine(T2SEngineProtocol): load_options["mmap"] = True dict_s1 = torch.load(weights_path, **load_options) config = dict_s1["config"] - decoder: T2SDecoderABC = decoder_cls(config, max_batch_size=max_batch_size) + decoder_options = {"max_batch_size": max_batch_size} + if max_seq_length is not None: + decoder_options["max_seq_length"] = max_seq_length + decoder: T2SDecoderABC = decoder_cls(config, **decoder_options) state_dict = dict_s1["weight"] decoder.load_state_dict(state_dict) diff --git a/GPT_SoVITS/Accel/adapter.py b/GPT_SoVITS/Accel/adapter.py index 01a3fbfc..18aa72e9 100644 --- a/GPT_SoVITS/Accel/adapter.py +++ b/GPT_SoVITS/Accel/adapter.py @@ -2,6 +2,7 @@ from __future__ import annotations import threading from itertools import count +from queue import Empty import torch @@ -19,7 +20,9 @@ class AccelInference: max_batch_size=32, use_cuda_graph=True, use_flash_attention=True, + max_seq_length=None, ): + self.max_seq_length = max_seq_length self.device = torch.device(device if device is not None else "cuda" if torch.cuda.is_available() else "cpu") self.dtype = dtype self.max_batch_size = max_batch_size @@ -33,6 +36,7 @@ class AccelInference: weights_path, max_batch_size=max_batch_size, backend=self.backend, + max_seq_length=self.max_seq_length, ) self.engine = None self.graph_enabled = False @@ -40,6 +44,7 @@ class AccelInference: self._request_ids = count() self._mode_lock = threading.RLock() + @torch.inference_mode() def prepare(self, use_cuda_graph=True, use_flash_attention=True): with self._mode_lock: backend, graph = resolve_acceleration( @@ -57,6 +62,7 @@ class AccelInference: self.weights_path, max_batch_size=self.max_batch_size, backend=backend, + max_seq_length=self.max_seq_length, ) self.backend = backend if self.engine is None or self.graph_enabled != graph: @@ -141,6 +147,82 @@ class AccelInference: tokens.append(result.result[0]) return tokens, [token.numel() for token in tokens] + def infer_stream( + self, x, prompts, bert_feature, *, chunk_length=16, max_decode_steps=1500, + top_k=15, top_p=1.0, temperature=1.0, early_stop_num=-1, + repetition_penalty=1.35, use_cuda_graph=True, use_flash_attention=True, + stop=None, stream_state=None, + ): + """Yield (cumulative semantic tokens, finished) for one unsplit utterance. + + Engine partials are deltas; the final result is already complete. Keeping + that distinction here prevents duplicated tokens at EOS. + """ + if chunk_length <= 0 or max_decode_steps <= 0: + raise ValueError("Streaming token interval and limit must be positive") + with self._mode_lock: + if not self.prepare(use_cuda_graph, use_flash_attention): + raise RuntimeError("Semantic streaming requires AR acceleration") + prompt = (torch.empty((1, 0), dtype=torch.long, device=x.device) + if prompts is None else prompts) + capacity = self.decoder.max_seq_length - x.numel() - prompt.shape[-1] + limit = min(max_decode_steps, capacity) + if early_stop_num > 0: + limit = min(limit, early_stop_num) + if limit <= 1: + raise ValueError("Text and reference exceed the GPT context capacity") + request = T2SRequest( + x=[x], x_lens=torch.tensor([x.numel()], dtype=torch.long), + prompts=prompt, bert_feature=[bert_feature], valid_length=1, + top_k=int(top_k), top_p=float(top_p), temperature=float(temperature), + early_stop_num=int(early_stop_num), repetition_penalty=float(repetition_penalty), + use_cuda_graph=self.graph_enabled, request_id=f"tts-{next(self._request_ids)}", + return_partial=True, stream_interval=int(chunk_length), max_decode_steps=int(limit), + ) + engine = self.engine + handle = engine.add_request(request) + if stream_state is not None: + stream_state["handle"] = handle + cumulative = None + try: + while stop is None or not stop.is_set(): + try: + response = handle.queue.get(timeout=0.05) + except Empty: + if engine._stop_event.is_set(): + raise RuntimeError("GPT engine stopped during semantic streaming") + # A hybrid consumer can recheck its playback budget while + # waiting for a planned larger block, then fall back promptly. + if stream_state is not None and stream_state.get("poll_partial") and cumulative is not None: + if stop is not None and stop.is_set(): + break + yield cumulative, False + continue + if response.ready_event is not None: + response.ready_event.wait(torch.cuda.current_stream(self.device)) + if response.exception is not None: + raise response.exception + if response.finished: + result = response.result + if result is None or result.exception is not None: + raise (result.exception if result else RuntimeError("Missing GPT result")) + if not result.result: + raise RuntimeError("GPT produced no semantic tokens") + tokens = result.result[0] + if not 0 < tokens.numel() < limit: + raise ValueError("GPT reached its token limit; shorten the input text") + if cumulative is not None and not torch.equal(tokens[:cumulative.numel()], cumulative): + raise RuntimeError("GPT final tokens disagree with the streamed prefix") + yield tokens, True + return + if response.tokens: + delta = response.tokens[0] + cumulative = delta if cumulative is None else torch.cat((cumulative, delta)) + yield cumulative, False + finally: + if not handle.done: + engine.cancel_request(handle) + def close(self): with self._mode_lock: if self.engine is not None: diff --git a/GPT_SoVITS/TTS_infer_pack/TTS.py b/GPT_SoVITS/TTS_infer_pack/TTS.py index 80d18977..3f14a284 100644 --- a/GPT_SoVITS/TTS_infer_pack/TTS.py +++ b/GPT_SoVITS/TTS_infer_pack/TTS.py @@ -512,6 +512,7 @@ class TTS: self.t2s_model: Text2SemanticLightningModule = None self.t2s_accel = None + self.streaming_accel = None self.vits_model: Union[SynthesizerTrn, SynthesizerTrnV3] = None self.bert_tokenizer: AutoTokenizer = None self.bert_model: AutoModelForMaskedLM = None @@ -678,6 +679,9 @@ class TTS: def init_t2s_weights(self, weights_path: str): + if self.streaming_accel is not None: + self.streaming_accel.close() + self.streaming_accel = None if self.t2s_accel is not None: self.t2s_accel.close() self.t2s_accel = None @@ -791,6 +795,9 @@ class TTS: print("Half precision is not supported on CPU.") return + if self.streaming_accel is not None: + self.streaming_accel.close() + self.streaming_accel = None if self.t2s_accel is not None: self.t2s_accel.close() self.t2s_accel = None @@ -827,6 +834,9 @@ class TTS: Args: device: torch.device, the device to use for all models. """ + if self.streaming_accel is not None: + self.streaming_accel.close() + self.streaming_accel = None if self.t2s_accel is not None: self.t2s_accel.close() self.t2s_accel = None @@ -1167,7 +1177,31 @@ class TTS: fixed_length_chunk = inputs.get("fixed_length_chunk", False) chunk_split_thershold = 0.0 # 该值代表语义token与mute token的余弦相似度阈值,若大于该阈值,则视为可切分点。 - if streaming_mode and self.configs.use_vocoder: + gpt_streaming = inputs.get("gpt_streaming", False) + if gpt_streaming: + from .streaming import (validate_streaming_options, PipelineStop, semantic_updates, + v2_token_chunks, v5_reference, stream_v5_windows, + StreamingWindowSchedule) + validate_streaming_options(inputs, self.configs.version) + stream_stop = PipelineStop(self) + stream_options = dict(inputs, sample_steps=sample_steps, cfg_rate=cfg_rate, + speed_factor=speed_factor, + streaming_chunk_seconds=inputs.get("streaming_chunk_seconds", 2.0), + streaming_lookahead_seconds=inputs.get("streaming_lookahead_seconds", 0.12), + streaming_overlap_seconds=inputs.get("streaming_overlap_seconds", 0.04), + gpt_streaming_lookahead_seconds=inputs.get("gpt_streaming_lookahead_seconds", 0.5)) + acoustic_rng = torch.Generator(device=self.configs.device).manual_seed(actual_seed) + # Reference semantic codes depend on the active SoVITS model. + if getattr(self, "_streaming_ref_model", None) != id(self.vits_model): + ref_audio_path = ref_audio_path or self.prompt_cache["ref_audio_path"] + if not ref_audio_path: + raise ValueError("A reloadable reference audio is required after model changes") + self.prompt_cache["ref_audio_path"] = None + self._streaming_ref_model = id(self.vits_model) + if self.prompt_cache["prompt_lang"] != prompt_lang: + self.prompt_cache["prompt_text"] = None + + if streaming_mode and self.configs.use_vocoder and not gpt_streaming: print(i18n("SoVits V3/4模型不支持流式推理模式,已自动回退到分段返回模式")) streaming_mode = False return_fragment = True @@ -1287,7 +1321,10 @@ class TTS: ) else: print(f"############ {i18n('切分文本')} ############") - texts = self.text_preprocessor.pre_seg_text(text, text_lang, text_split_method) + texts = self.text_preprocessor.pre_seg_text( + text.replace("\n", " ") if gpt_streaming else text, text_lang, text_split_method) + if gpt_streaming and len(texts) > 1: + raise ValueError("Text exceeds the single-session frontend limit; shorten the input") data = [] for i in range(len(texts)): if i % batch_size == 0: @@ -1323,6 +1360,7 @@ class TTS: return batch[0] t2 = time.perf_counter() + streaming_tokens = streaming_audio = semantic_token_generator = None try: print("############ 推理 ############") ###### inference ###### @@ -1490,27 +1528,56 @@ class TTS: ) batch_audio_fragment.append(audio_fragment) + elif gpt_streaming and self.configs.version in V5_VERSIONS: + reference = v5_reference(self) + # Validate the acoustic context before starting the AR owner thread. + frames = round(stream_options["streaming_chunk_seconds"] * 100) + future = round(stream_options["streaming_lookahead_seconds"] * 100) + if reference[6].shape[-1] + frames + future > 1000: + raise ValueError("Reference plus streaming window exceeds the V5 context") + streaming_tokens = semantic_updates(self, all_phoneme_ids[0], prompt, + all_bert_features[0], stream_options, stream_stop) + streaming_audio = stream_v5_windows(self.vits_model, self.vocoder, denorm_spec, + self.configs.device, streaming_tokens, batch_phones[0], reference, + stream_options, stream_stop) + for pcm in streaming_audio: + yield output_sr, pcm + streaming_audio.close() + streaming_tokens.close() + streaming_audio = streaming_tokens = None + yield output_sr, np.zeros(int(output_sr * fragment_interval), dtype=np.int16) + t4 = time.perf_counter() else: # refer_audio_spec: torch.Tensor = [ # item.to(dtype=self.precision, device=self.configs.device) # for item in self.prompt_cache["refer_spec"] # ] - semantic_token_generator =self.t2s_model.model.infer_panel( - all_phoneme_ids[0].unsqueeze(0), - all_phoneme_lens, - prompt, - all_bert_features[0].unsqueeze(0), - top_k=top_k, - top_p=top_p, - temperature=temperature, - early_stop_num=self.configs.hz * self.configs.max_sec, - max_len=max_len, - repetition_penalty=repetition_penalty, - streaming_mode=True, - chunk_length=min_chunk_length, - mute_emb_sim_matrix=self.configs.mute_emb_sim_matrix if not fixed_length_chunk else None, - chunk_split_thershold=chunk_split_thershold, - ) + window_schedule = None + if gpt_streaming: + if inputs.get("streaming_window_mode", "fixed") == "hybrid": + window_schedule = StreamingWindowSchedule(min_chunk_length, min_chunk_length * 4) + streaming_tokens = semantic_updates(self, all_phoneme_ids[0], prompt, + all_bert_features[0], stream_options, stream_stop) + semantic_token_generator = v2_token_chunks(streaming_tokens, min_chunk_length, + self.configs.mute_emb_sim_matrix if not fixed_length_chunk else None, + chunk_split_thershold, schedule=window_schedule) + else: + semantic_token_generator =self.t2s_model.model.infer_panel( + all_phoneme_ids[0].unsqueeze(0), + all_phoneme_lens, + prompt, + all_bert_features[0].unsqueeze(0), + top_k=top_k, + top_p=top_p, + temperature=temperature, + early_stop_num=self.configs.hz * self.configs.max_sec, + max_len=max_len, + repetition_penalty=repetition_penalty, + streaming_mode=True, + chunk_length=min_chunk_length, + mute_emb_sim_matrix=self.configs.mute_emb_sim_matrix if not fixed_length_chunk else None, + chunk_split_thershold=chunk_split_thershold, + ) t4 = time.perf_counter() t_34 += t4 - t3 phones = batch_phones[0].unsqueeze(0).to(self.configs.device) @@ -1575,7 +1642,8 @@ class TTS: result_length=semantic_tokens.shape[-1]+overlap_len if not is_first_chunk else None, overlap_frames=last_latent[:,:,-overlap_len*(2 if self.vits_model.semantic_frame_rate == "25hz" else 1):] \ if last_latent is not None else None, - padding_length=token_padding_length + padding_length=token_padding_length, + **({"generator": acoustic_rng} if gpt_streaming else {}) ) audio_chunk=audio_chunk.detach()[0, 0, :] else: @@ -1590,7 +1658,7 @@ class TTS: audio_chunk_ = audio_chunk_[:-overlap_size] elif is_first_chunk and is_final: is_first_chunk = False - elif not is_first_chunk and not is_final: + elif not is_first_chunk and (not is_final or gpt_streaming): audio_chunk_ = self.sola_algorithm([last_audio_chunk, audio_chunk_], overlap_size) audio_chunk_ = ( audio_chunk_[last_audio_chunk.shape[0]-overlap_size:-overlap_size] if not is_final \ @@ -1599,7 +1667,7 @@ class TTS: last_latent = latent last_audio_chunk = audio_chunk - yield self.audio_postprocess( + audio_result = self.audio_postprocess( [[audio_chunk_]], output_sr, None, @@ -1608,12 +1676,19 @@ class TTS: 0.0, super_sampling if self.configs.use_vocoder and self.configs.version == "v3" else False, ) + if window_schedule is not None: + window_schedule.observe(semantic_tokens.numel(), audio_result[1].size, output_sr) + yield audio_result if is_first_package: print(f"first_package_delay: {time.perf_counter()-t0:.3f}") is_first_package = False + if gpt_streaming: + semantic_token_generator.close() + streaming_tokens.close() + streaming_tokens = None yield output_sr, np.zeros(int(output_sr*fragment_interval), dtype=np.int16) t5 = time.perf_counter() @@ -1653,6 +1728,8 @@ class TTS: ) except Exception as e: + if gpt_streaming: + raise traceback.print_exc() # 必须返回一个空音频, 否则会导致显存不释放。 yield 16000, np.zeros(int(16000), dtype=np.int16) @@ -1665,6 +1742,11 @@ class TTS: self.init_vits_weights(self.configs.vits_weights_path) raise e finally: + if gpt_streaming: + stream_stop.set() + for iterator in (streaming_audio, semantic_token_generator, streaming_tokens): + if iterator is not None: + iterator.close() self.empty_cache() def empty_cache(self): diff --git a/GPT_SoVITS/TTS_infer_pack/streaming.py b/GPT_SoVITS/TTS_infer_pack/streaming.py new file mode 100644 index 00000000..87d4b8ce --- /dev/null +++ b/GPT_SoVITS/TTS_infer_pack/streaming.py @@ -0,0 +1,311 @@ +"""Opt-in API v2 semantic streaming. Ordinary inference remains in TTS.run.""" +import math +import threading +import time +import torch +from tools.acceleration import create_acceleration + + +def validate_streaming_options(req, version, api_mode=False): + if not req.get("gpt_streaming", False): + return + if version not in {"v2ProPlus", "v5turbo", "v5dev"}: + raise ValueError("gpt_streaming supports v2ProPlus, v5turbo and v5dev") + mode = req.get("streaming_mode", False) + if (api_mode and (type(mode) is not int or mode not in (2, 3))) or (not api_mode and mode not in (True, 2, 3)): + raise ValueError("gpt_streaming requires streaming_mode=2 or 3") + if req.get("text_split_method", "cut5") != "cut0" or req.get("batch_size", 1) != 1: + raise ValueError("gpt_streaming requires text_split_method=cut0 and batch_size=1") + if req.get("if_freeze", False): + raise ValueError("gpt_streaming cannot freeze semantic tokens") + if req.get("streaming_window_mode", "fixed") not in {"fixed", "hybrid"}: + raise ValueError("streaming_window_mode must be fixed or hybrid") + if req.get("media_type", "wav") not in {"wav", "raw"}: + raise ValueError("gpt_streaming supports wav or raw PCM") + if version.startswith("v5") and not str(req.get("prompt_text") or "").strip(): + raise ValueError("V5 semantic streaming requires prompt_text") + if version.startswith("v5") and req.get("aux_ref_audio_paths"): + raise ValueError("V5 semantic streaming supports one reference audio") + for key, default, lower, upper in ( + ("streaming_chunk_seconds", 2.0, 0.2, 5.0), + ("streaming_lookahead_seconds", 0.12, 0.0, 0.5), + ("streaming_overlap_seconds", 0.04, 0.0, 0.2), + ("gpt_streaming_lookahead_seconds", 0.5, 0.16, 2.0), + ("speed_factor", 1.0, 0.1, 4.0), + ("fragment_interval", 0.3, 0.0, 10.0), + ): + value = float(req.get(key, default)) + if not math.isfinite(value) or not lower <= value <= upper: + raise ValueError(f"{key} must be between {lower} and {upper}") + if req.get("min_chunk_length", 16) < 1 or req.get("overlap_length", 2) < 1: + raise ValueError("Streaming token intervals and overlaps must be positive") + steps = req.get("sample_steps") + if steps is not None and steps < 1: + raise ValueError("sample_steps must be positive") + cfg = req.get("cfg_rate") + if cfg is not None and (not math.isfinite(float(cfg)) or float(cfg) < 0): + raise ValueError("cfg_rate must be finite and nonnegative") + + +class PipelineStop: + def __init__(self, pipeline): + self.pipeline = pipeline + self.cancelled = threading.Event() + + def is_set(self): + return self.cancelled.is_set() or self.pipeline.stop_flag + + def set(self): + self.cancelled.set() + + +def semantic_updates(pipeline, x, prompt, bert, req, stop): + # A separate decoder leaves the ordinary context and cache unchanged. + acceleration = pipeline.streaming_accel + if acceleration is None: + acceleration = create_acceleration( + pipeline.configs.t2s_weights_path, device=pipeline.configs.device, + dtype=pipeline.precision, max_batch_size=1, max_seq_length=2048, + use_cuda_graph=req.get("use_cuda_graph", True), + use_flash_attention=req.get("use_flash_attention", True)) + pipeline.streaming_accel = acceleration + if acceleration is None: + raise ValueError("gpt_streaming requires a supported AR acceleration backend") + stream_state = {"poll_partial": req.get("streaming_window_mode", "fixed") == "hybrid"} + updates = acceleration.infer_stream( + x, prompt, bert, chunk_length=min(16, req.get("min_chunk_length", 16)), + max_decode_steps=min(1500, pipeline.configs.hz * pipeline.configs.max_sec), + top_k=req.get("top_k", 15), top_p=req.get("top_p", 1), + temperature=req.get("temperature", 1), + early_stop_num=pipeline.configs.hz * pipeline.configs.max_sec, + repetition_penalty=req.get("repetition_penalty", 1.35), + use_cuda_graph=req.get("use_cuda_graph", True), + use_flash_attention=req.get("use_flash_attention", True), stop=stop, stream_state=stream_state) + try: + yield from updates + finally: + stop.set() + updates.close() + + +class StreamingWindowSchedule: + """Grow only when emitted PCM leaves time for another block. + + The clock starts before waiting for AR. Observations include AR waits, + acoustic decoding, CPU transfer and time spent yielding to the caller. + Playback slack assumes immediate playback of the first emitted PCM; it + does not claim to know a remote player's queue or network delays. + """ + def __init__(self, initial_units, max_units): + self.initial = initial_units + self.maximum = max(initial_units, max_units) + self.last_units = initial_units + self.started = time.perf_counter() + self.first_pcm_at = None + self.audio_seconds = 0.0 + self.cost_per_unit = None + + def choose(self, available_units): + if self.first_pcm_at is None: + return min(self.initial, available_units) + slack = self.audio_seconds - (time.perf_counter() - self.first_pcm_at) + growth_limit = min(self.maximum, max(self.initial, round(self.last_units * 1.5))) + candidates = {self.initial, self.maximum} + size = self.initial + while size < self.maximum: + size = min(self.maximum, max(size + 1, round(size * 1.5))) + candidates.add(size) + for size in sorted(candidates, reverse=True): + if size > min(available_units, growth_limit): + continue + if self.cost_per_unit * size * 1.25 + 0.1 <= slack: + return size + # A smaller known block is preferable to waiting for a larger prefix. + return min(self.initial, available_units) + + def observe(self, units, samples, sample_rate): + now = time.perf_counter() + rate = (now - self.started) / max(1, units) + self.cost_per_unit = rate if self.cost_per_unit is None else max(rate, self.cost_per_unit * 0.8) + if self.first_pcm_at is None: + self.first_pcm_at = now + self.audio_seconds += samples / sample_rate + self.last_units = units + self.started = now + + +def v2_token_chunks(updates, chunk_length, mute_emb_sim_matrix=None, threshold=0.0, schedule=None): + """Convert cumulative AR prefixes to non-overlapping V2 decoder deltas.""" + cursor = previous_length = 0 + try: + for tokens, finished in updates: + tokens = tokens.reshape(-1) + if tokens.numel() < previous_length: + raise RuntimeError("Semantic stream moved backwards") + previous_length = tokens.numel() + if finished and schedule is None: + tail = tokens[cursor:] + yield (tail.unsqueeze(0) if tail.numel() else None), True + return + while cursor < tokens.numel(): + available = tokens.numel() - cursor + length = schedule.choose(available if finished else schedule.maximum) if schedule is not None else chunk_length + if not finished and available < length + (2 if mute_emb_sim_matrix is not None else 0): + break + if schedule is not None and not finished and available < chunk_length: + break + if finished and available <= length: + yield tokens[cursor:].unsqueeze(0), True + return + if mute_emb_sim_matrix is None: + end = cursor + length + else: + similarity = mute_emb_sim_matrix[tokens[cursor:]] + pairs = (similarity[:-1] >= threshold) & (similarity[1:] >= threshold) + pairs[:chunk_length-1] = False + if schedule is not None: + pairs[length:] = False + if not pairs.any(): + if schedule is None: + break + end = cursor + length + else: + scores = (similarity[:-1] + similarity[1:]).masked_fill(~pairs, -torch.inf) + offset = int(scores.argmax().item()) + end = cursor + offset + 1 + final = finished and end == tokens.numel() + yield tokens[cursor:end].unsqueeze(0), final + cursor = end + if final: + return + if finished: + yield None, True + return + finally: + updates.close() + + +def v5_reference(pipeline): + from .TTS import resample, mel_fn_v4, norm_spec + cache = pipeline.prompt_cache + spec = cache["refer_spec"][0][0].to(pipeline.configs.device, dtype=pipeline.precision) + prompt = cache["prompt_semantic"].reshape(1, 1, -1).to(pipeline.configs.device) + phones = torch.tensor(cache["phones"], device=pipeline.configs.device).unsqueeze(0) + features, ge = pipeline.vits_model.decode_encp(prompt, phones, spec) + audio = cache["raw_audio"].to(pipeline.configs.device).float().mean(0, keepdim=True) + if cache["raw_sr"] != 32000: + audio = resample(audio, cache["raw_sr"], 32000, pipeline.configs.device) + mel = norm_spec(mel_fn_v4(audio)).to(pipeline.precision) + limit = min(mel.shape[-1], features.shape[-1]) + count = min(500, limit) + return (cache["phones"], cache["bert_features"], prompt, + spec, features[..., :limit][..., -count:], ge, mel[..., :limit][..., -count:]) + + +@torch.inference_mode() +def stream_v5_windows(vq_model, vocoder, denorm_spec, device, token_updates, phones, reference, req, stop): + """Yield PCM once a core window plus future semantic context is available. + + The encoder has noncausal attention: finite lookahead trades full-utterance + context for latency. Emitted samples are never regenerated or sent twice. + """ + core = max(1, round(req["streaming_chunk_seconds"] * 100)) + hybrid = req.get("streaming_window_mode", "fixed") == "hybrid" + future = round(req["streaming_lookahead_seconds"] * 100) + holdback = max(16, round(req["gpt_streaming_lookahead_seconds"] * 100)) + fade_frames = min(round(req["streaming_overlap_seconds"] * 100), core - 1) + fade = fade_frames * 480 + left_frames = max(24, fade_frames) + ref_features, ref_mel = reference[4], reference[6] + count = min(500, ref_features.shape[-1], ref_mel.shape[-1]) + ref_features, ref_mel = ref_features[..., -count:], ref_mel[..., -count:] + if count + core + future > 1000: + raise ValueError("Reference plus streaming window exceeds the V5 1000-frame context") + # The AR sampler uses the global CUDA RNG. CFM must not advance that RNG + # while AR is still decoding on its owner thread. + rng = torch.Generator(device=device).manual_seed(torch.initial_seed()) + phone_tensor = torch.tensor(phones, device=device, dtype=torch.long).unsqueeze(0) + alpha = torch.linspace(0, 1, fade, device=ref_mel.device, dtype=torch.float32) if fade else None + history = ref_mel[..., :0] + feature_history = ref_features[..., :0] + pending = None + cursor = previous_tokens = 0 + schedule = StreamingWindowSchedule(core, min(1000-count, 640)) if hybrid else None + for tokens, finished in token_updates: + if stop.is_set(): + return + if tokens.numel() < previous_tokens: + raise RuntimeError("Semantic stream moved backwards") + previous_tokens = tokens.numel() + if schedule is not None: + core = schedule.choose(schedule.maximum) + # V5: 25 Hz semantic tokens -> 100 Hz acoustic features at speed 1. + window_future = 0 if hybrid and cursor else future + needed = math.ceil((cursor + core + window_future + holdback) * req["speed_factor"] / 4) + if not finished and tokens.numel() < needed: + continue + target, _ = vq_model.decode_encp( + tokens.reshape(1, 1, -1).long(), phone_tensor, + reference[3], reference[5], req["speed_factor"]) + total = target.shape[-1] + safe_end = total if finished else max(0, total - window_future - holdback) + while cursor < total and (finished or cursor + core <= safe_end): + if stop.is_set(): + return + if schedule is not None: + core = schedule.choose(safe_end-cursor if finished else schedule.maximum) + window_future = 0 if cursor else future + if not finished and cursor+core > safe_end: + break + end = min(cursor + core, total) + if cursor == 0: + prompt, features = ref_mel, ref_features + else: + tail = min(32, count, history.shape[-1]) + prefix = count - tail + prompt = torch.cat((ref_mel[..., :prefix], history[..., -tail:]), -1) + tail_features = feature_history[..., -tail:] if hybrid else target[..., cursor-tail:cursor] + features = torch.cat((ref_features[..., :prefix], tail_features), -1) + mu = torch.cat((features, target[..., cursor:min(end + window_future, total)]), -1).transpose(2, 1) + lengths = torch.full((mu.shape[0],), mu.shape[1], device=mu.device, dtype=torch.long) + generated = vq_model.cfm.inference( + mu, lengths, prompt, req["sample_steps"], + inference_cfg_rate=req["cfg_rate"], generator=rng + )[..., prompt.shape[-1]:].to(ref_mel.dtype) + accepted = generated[..., :end-cursor] + left = history[..., -left_frames:] + audio = vocoder(denorm_spec(torch.cat((left, generated), -1)))[0, 0].float() + offset = left.shape[-1] * 480 + current = audio[offset:offset+(end-cursor)*480] + if current.numel() != (end-cursor)*480: + raise RuntimeError("Vocoder returned an incomplete acoustic window") + prefix_audio = current[:0] if pending is None else ( + pending * (1-alpha) + audio[offset-fade:offset] * alpha) + if fade and (not finished or end != total): + # Keep at most one overlap; the next window supplies its right context. + emitted = torch.cat((prefix_audio, current[:-fade])) + pending = current[-fade:] + else: + emitted = torch.cat((prefix_audio, current)) + pending = None + history = torch.cat((history, accepted), -1)[..., -max(left_frames, 32):] + feature_history = torch.cat((feature_history, target[..., cursor:end]), -1)[..., -max(left_frames, 32):] + units = end-cursor + cursor = end + if stop.is_set(): + return + if not torch.isfinite(emitted).all(): + raise RuntimeError("Non-finite V5 audio") + pcm = (emitted.clamp(-1, 1) * 32767).to(torch.int16).cpu().numpy() + if schedule is not None: + schedule.observe(units, pcm.size, 48000) + yield pcm + if finished: + if cursor != total: + raise RuntimeError("Semantic streaming did not flush all acoustic frames") + # EOS may arrive exactly at a previously emitted core boundary. + if pending is not None: + yield (pending.clamp(-1, 1) * 32767).to(torch.int16).cpu().numpy() + return + if not stop.is_set(): + raise RuntimeError("Semantic stream ended without a final result") diff --git a/GPT_SoVITS/module/models.py b/GPT_SoVITS/module/models.py index dbdeee19..0e1f5acd 100644 --- a/GPT_SoVITS/module/models.py +++ b/GPT_SoVITS/module/models.py @@ -1040,7 +1040,7 @@ class SynthesizerTrn(nn.Module): @torch.no_grad() - def decode_streaming(self, codes, text, refer, noise_scale=0.5, speed=1, sv_emb=None, result_length:int=None, overlap_frames:torch.Tensor=None, padding_length:int=None): + def decode_streaming(self, codes, text, refer, noise_scale=0.5, speed=1, sv_emb=None, result_length:int=None, overlap_frames:torch.Tensor=None, padding_length:int=None, generator=None): def get_ge(refer, sv_emb): ge = None if refer is not None: @@ -1084,7 +1084,9 @@ class SynthesizerTrn(nn.Module): overlap_frames=overlap_frames, padding_length=padding_length ) - z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale + noise = (torch.randn_like(m_p) if generator is None else + torch.randn(m_p.shape, device=m_p.device, dtype=m_p.dtype, generator=generator)) + z_p = m_p + noise * torch.exp(logs_p) * noise_scale z = self.flow(z_p, y_mask, g=ge, reverse=True) @@ -1115,13 +1117,13 @@ class CFM(torch.nn.Module): self.noise_temperature = None @torch.inference_mode() - def inference(self, mu, x_lens, prompt, n_timesteps, temperature=1.0, inference_cfg_rate=0): + def inference(self, mu, x_lens, prompt, n_timesteps, temperature=1.0, inference_cfg_rate=0, generator=None): """Forward diffusion""" n_timesteps, inference_cfg_rate = int(n_timesteps), float(inference_cfg_rate) B, T = mu.size(0), mu.size(1) if self.noise_temperature is not None: temperature = self.noise_temperature - x = torch.randn([B, self.in_channels, T], device=mu.device, dtype=mu.dtype) * temperature + x = torch.randn([B, self.in_channels, T], device=mu.device, dtype=mu.dtype, generator=generator) * temperature prompt_len = prompt.size(-1) prompt_x = torch.zeros_like(x, dtype=mu.dtype) prompt_x[..., :prompt_len] = prompt[..., :prompt_len] diff --git a/GPT_SoVITS/module/models_v5.py b/GPT_SoVITS/module/models_v5.py index b2337c0a..c8f595bc 100644 --- a/GPT_SoVITS/module/models_v5.py +++ b/GPT_SoVITS/module/models_v5.py @@ -25,8 +25,8 @@ class CFMV5(CFM): @torch.inference_mode() def inference(self, mu, x_lens, prompt, n_timesteps, temperature=V5_TEMPERATURE, - inference_cfg_rate=1.30): - return super().inference(mu, x_lens, prompt, n_timesteps, temperature, inference_cfg_rate) + inference_cfg_rate=1.30, generator=None): + return super().inference(mu, x_lens, prompt, n_timesteps, temperature, inference_cfg_rate, generator=generator) def forward(self, x1, x_lens, prompt_lens, mu, use_grad_ckpt): b = x1.shape[0] diff --git a/api_v2.py b/api_v2.py index 8a343ad7..b646b310 100644 --- a/api_v2.py +++ b/api_v2.py @@ -44,9 +44,18 @@ POST: "streaming_mode": False, # bool or int. return audio chunk by chunk.T he available options are: 0,1,2,3 or True/False (0/False: Disabled | 1/True: Best Quality, Slowest response speed (old version streaming_mode) | 2: Medium Quality, Slow response speed | 3: Lower Quality, Faster response speed ) "overlap_length": 2, # int. overlap length of semantic tokens for streaming mode. "min_chunk_length": 16, # int. The minimum chunk length of semantic tokens for streaming mode. (affects audio chunk size) + "gpt_streaming": false, # bool. opt in to semantic-token streaming. + "streaming_chunk_seconds": 2.0, + "streaming_window_mode": "fixed", + "streaming_lookahead_seconds": 0.12, + "streaming_overlap_seconds": 0.04, + "gpt_streaming_lookahead_seconds": 0.5, + "use_flash_attention": true, } ``` +When `gpt_streaming` is enabled, use model `v2ProPlus`, `v5turbo` or `v5dev`, integer `streaming_mode` 2 or 3, `text_split_method="cut0"`, `batch_size=1`, and `media_type="raw"` or `"wav"`. `streaming_window_mode` defaults to `fixed`; `hybrid` is supported for these models. On v2ProPlus, the first chunk retains `min_chunk_length` and later chunks can reach four times that token count; on V5, `streaming_chunk_seconds` controls the first chunk. + RESP: 成功: 直接返回 wav 音频流, http code 200 失败: 返回包含错误信息的 json, http code 400 @@ -115,17 +124,22 @@ sys.path.append(now_dir) sys.path.append("%s/GPT_SoVITS" % (now_dir)) import argparse +import asyncio +import anyio import subprocess import wave import signal import numpy as np import soundfile as sf -from fastapi import FastAPI, Response +from fastapi import FastAPI, Request, Response from fastapi.responses import StreamingResponse, JSONResponse +from starlette.background import BackgroundTask +from starlette.concurrency import run_in_threadpool import uvicorn from io import BytesIO from tools.i18n.i18n import I18nAuto from GPT_SoVITS.TTS_infer_pack.TTS import TTS, TTS_Config +from GPT_SoVITS.TTS_infer_pack.streaming import validate_streaming_options from GPT_SoVITS.TTS_infer_pack.text_segmentation_method import get_method_names as get_cut_method_names from pydantic import BaseModel import threading @@ -182,6 +196,50 @@ class TTS_Request(BaseModel): super_sampling: bool = False overlap_length: int = 2 min_chunk_length: int = 16 + gpt_streaming: bool = False + streaming_chunk_seconds: float = 2.0 + streaming_window_mode: str = "fixed" + streaming_lookahead_seconds: float = 0.12 + streaming_overlap_seconds: float = 0.04 + gpt_streaming_lookahead_seconds: float = 0.5 + use_flash_attention: bool = True + + +_tts_pipeline_lock = asyncio.Lock() +_STREAM_END = object() + + +async def _await_shielded(awaitable): + task = asyncio.ensure_future(awaitable) + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + # AnyIO cancellation is level-triggered. Shield the in-flight worker call + # until it finishes, then let the original cancellation unwind the stream. + with anyio.CancelScope(shield=True): + try: + await task + except BaseException: + pass + raise + + +async def _run_in_threadpool_shielded(function, *args): + return await _await_shielded(run_in_threadpool(function, *args)) + + +def _next_or_end(iterator): + try: + return next(iterator) + except StopIteration: + return _STREAM_END + + +async def _next_tts_chunk(iterator, skip_empty=False): + while True: + item = await _run_in_threadpool_shielded(_next_or_end, iterator) + if item is _STREAM_END or not skip_empty or item[1].size > 0: + return item def pack_ogg(io_buffer: BytesIO, data: np.ndarray, rate: int): @@ -348,7 +406,7 @@ def check_params(req: dict): return None -async def tts_handle(req: dict): +async def tts_handle(req: dict, raw_streaming_mode=None): """ Text to speech handler. @@ -383,72 +441,136 @@ async def tts_handle(req: dict): StreamingResponse: audio stream response. """ - streaming_mode = req.get("streaming_mode", False) - return_fragment = req.get("return_fragment", False) - media_type = req.get("media_type", "wav") + await _tts_pipeline_lock.acquire() + tts_generator = None + response_owns_lock = False + stream_cleanup_task = None - check_res = check_params(req) - if check_res is not None: - return check_res - - if streaming_mode == 0: - streaming_mode = False - return_fragment = False - fixed_length_chunk = False - elif streaming_mode == 1: - streaming_mode = False - return_fragment = True - fixed_length_chunk = False - elif streaming_mode == 2: - streaming_mode = True - return_fragment = False - fixed_length_chunk = False - elif streaming_mode == 3: - streaming_mode = True - return_fragment = False - fixed_length_chunk = True - - else: - return JSONResponse(status_code=400, content={"message": f"the value of streaming_mode must be 0, 1, 2, 3(int) or true/false(bool)"}) - - req["streaming_mode"] = streaming_mode - req["return_fragment"] = return_fragment - req["fixed_length_chunk"] = fixed_length_chunk - - print(f"{streaming_mode} {return_fragment} {fixed_length_chunk}") - - streaming_mode = streaming_mode or return_fragment + async def cleanup_stream(): + nonlocal stream_cleanup_task + if stream_cleanup_task is None: + async def close_and_release(): + try: + if tts_generator is not None: + close = getattr(tts_generator, "close", None) + if callable(close): + await _run_in_threadpool_shielded(close) + finally: + _tts_pipeline_lock.release() + stream_cleanup_task = asyncio.create_task(close_and_release()) + await _await_shielded(stream_cleanup_task) try: - tts_generator = tts_pipeline.run(req) + check_res = check_params(req) + if check_res is not None: + return check_res + + gpt_streaming = req.get("gpt_streaming", False) + if gpt_streaming: + try: + validation_req = dict(req) + if raw_streaming_mode is not None: + validation_req["streaming_mode"] = raw_streaming_mode + validate_streaming_options( + validation_req, + getattr(tts_pipeline.configs, "version", tts_config.version), + api_mode=True, + ) + except (TypeError, ValueError) as e: + return JSONResponse(status_code=400, content={"message": str(e)}) + + streaming_mode = req.get("streaming_mode", False) + return_fragment = req.get("return_fragment", False) + media_type = req.get("media_type", "wav") + + if streaming_mode == 0: + streaming_mode = False + return_fragment = False + fixed_length_chunk = False + elif streaming_mode == 1: + streaming_mode = False + return_fragment = True + fixed_length_chunk = False + elif streaming_mode == 2: + streaming_mode = True + return_fragment = False + fixed_length_chunk = False + elif streaming_mode == 3: + streaming_mode = True + return_fragment = False + fixed_length_chunk = True + else: + return JSONResponse(status_code=400, content={"message": f"the value of streaming_mode must be 0, 1, 2, 3(int) or true/false(bool)"}) + + req["streaming_mode"] = streaming_mode + req["return_fragment"] = return_fragment + req["fixed_length_chunk"] = fixed_length_chunk + + print(f"{streaming_mode} {return_fragment} {fixed_length_chunk}") + + streaming_mode = streaming_mode or return_fragment + tts_generator = await _run_in_threadpool_shielded(tts_pipeline.run, req) if streaming_mode: + first_chunk = _STREAM_END + if gpt_streaming: + first_chunk = await _next_tts_chunk(tts_generator, skip_empty=True) + if first_chunk is _STREAM_END: + return JSONResponse( + status_code=400, + content={"message": "tts failed", "Exception": "stream produced no PCM audio"}, + ) - def streaming_generator(tts_generator: Generator, media_type: str): - if_frist_chunk = True - for sr, chunk in tts_generator: - if if_frist_chunk and media_type == "wav": - yield wave_header_chunk(sample_rate=sr) - media_type = "raw" - if_frist_chunk = False - yield pack_audio(BytesIO(), chunk, sr, media_type).getvalue() + async def streaming_generator(): + nonlocal media_type + first_audio = True + item = first_chunk + try: + while True: + if item is _STREAM_END: + item = await _next_tts_chunk(tts_generator, skip_empty=gpt_streaming) + if item is _STREAM_END: + break - # _media_type = f"audio/{media_type}" if not (streaming_mode and media_type in ["wav", "raw"]) else f"audio/x-{media_type}" - return StreamingResponse( - streaming_generator( - tts_generator, - media_type, - ), + sr, chunk = item + if first_audio and media_type == "wav": + yield wave_header_chunk(sample_rate=sr) + media_type = "raw" + first_audio = False + packed = await _run_in_threadpool_shielded( + pack_audio, BytesIO(), chunk, sr, media_type + ) + yield packed.getvalue() + item = _STREAM_END + finally: + await cleanup_stream() + + response = StreamingResponse( + streaming_generator(), media_type=f"audio/{media_type}", + background=BackgroundTask(cleanup_stream), ) + response_owns_lock = True + return response - else: - sr, audio_data = next(tts_generator) - audio_data = pack_audio(BytesIO(), audio_data, sr, media_type).getvalue() - return Response(audio_data, media_type=f"audio/{media_type}") + item = await _next_tts_chunk(tts_generator) + if item is _STREAM_END: + raise RuntimeError("TTS produced no audio") + sr, audio_data = item + packed = await _run_in_threadpool_shielded(pack_audio, BytesIO(), audio_data, sr, media_type) + return Response(packed.getvalue(), media_type=f"audio/{media_type}") except Exception as e: return JSONResponse(status_code=400, content={"message": "tts failed", "Exception": str(e)}) + finally: + if not response_owns_lock: + try: + if tts_generator is not None: + close = getattr(tts_generator, "close", None) + if callable(close): + await _run_in_threadpool_shielded(close) + finally: + _tts_pipeline_lock.release() @APP.get("/control") @@ -460,6 +582,7 @@ async def control(command: str = None): @APP.get("/tts") async def tts_get_endpoint( + request: Request, text: str = None, text_lang: str = None, ref_audio_path: str = None, @@ -486,6 +609,13 @@ async def tts_get_endpoint( streaming_mode: Union[bool, int] = False, overlap_length: int = 2, min_chunk_length: int = 16, + gpt_streaming: bool = False, + streaming_chunk_seconds: float = 2.0, + streaming_window_mode: str = "fixed", + streaming_lookahead_seconds: float = 0.12, + streaming_overlap_seconds: float = 0.04, + gpt_streaming_lookahead_seconds: float = 0.5, + use_flash_attention: bool = True, ): req = { "text": text, @@ -514,20 +644,33 @@ async def tts_get_endpoint( "super_sampling": super_sampling, "overlap_length": int(overlap_length), "min_chunk_length": int(min_chunk_length), + "gpt_streaming": gpt_streaming, + "streaming_chunk_seconds": float(streaming_chunk_seconds), + "streaming_window_mode": streaming_window_mode, + "streaming_lookahead_seconds": float(streaming_lookahead_seconds), + "streaming_overlap_seconds": float(streaming_overlap_seconds), + "gpt_streaming_lookahead_seconds": float(gpt_streaming_lookahead_seconds), + "use_flash_attention": use_flash_attention, } - return await tts_handle(req) + raw_streaming_mode = request.query_params.get("streaming_mode") + if raw_streaming_mode in {"2", "3"}: + raw_streaming_mode = int(raw_streaming_mode) + return await tts_handle(req, raw_streaming_mode=raw_streaming_mode) @APP.post("/tts") -async def tts_post_endpoint(request: TTS_Request): +async def tts_post_endpoint(request: TTS_Request, raw_request: Request): req = request.dict() - return await tts_handle(req) + request_body = await raw_request.json() + raw_streaming_mode = request_body.get("streaming_mode", request.streaming_mode) + return await tts_handle(req, raw_streaming_mode=raw_streaming_mode) @APP.get("/set_refer_audio") async def set_refer_aduio(refer_audio_path: str = None): try: - tts_pipeline.set_ref_audio(refer_audio_path) + async with _tts_pipeline_lock: + await _run_in_threadpool_shielded(tts_pipeline.set_ref_audio, refer_audio_path) except Exception as e: return JSONResponse(status_code=400, content={"message": "set refer audio failed", "Exception": str(e)}) return JSONResponse(status_code=200, content={"message": "success"}) @@ -557,7 +700,8 @@ async def set_gpt_weights(weights_path: str = None): try: if weights_path in ["", None]: return JSONResponse(status_code=400, content={"message": "gpt weight path is required"}) - tts_pipeline.init_t2s_weights(weights_path) + async with _tts_pipeline_lock: + await _run_in_threadpool_shielded(tts_pipeline.init_t2s_weights, weights_path) except Exception as e: return JSONResponse(status_code=400, content={"message": "change gpt weight failed", "Exception": str(e)}) @@ -569,7 +713,8 @@ async def set_sovits_weights(weights_path: str = None): try: if weights_path in ["", None]: return JSONResponse(status_code=400, content={"message": "sovits weight path is required"}) - tts_pipeline.init_vits_weights(weights_path) + async with _tts_pipeline_lock: + await _run_in_threadpool_shielded(tts_pipeline.init_vits_weights, weights_path) except Exception as e: return JSONResponse(status_code=400, content={"message": "change sovits weight failed", "Exception": str(e)}) return JSONResponse(status_code=200, content={"message": "success"}) diff --git a/docs/en/semantic_streaming.md b/docs/en/semantic_streaming.md new file mode 100644 index 00000000..bf033341 --- /dev/null +++ b/docs/en/semantic_streaming.md @@ -0,0 +1,111 @@ +# Opt-in accelerated semantic streaming (API v2) + +API v2 accepts `gpt_streaming=true` for V2ProPlus, V5 Turbo and V5 Dev. +The default is `false`: existing routes, sampling defaults, ordinary inference, +fragment streaming, and the legacy V2 streaming path stay available. +V5 without this switch retains the official fallback to complete fragments. + +## Request + +Use the existing `GET /tts` or `POST /tts`, with these options: + +```json +{ + "text": "早上好,今天也要记得给自己留一点休息的时间。", + "text_lang": "zh", + "ref_audio_path": "reference.wav", + "prompt_text": "参考音频对应的文字。", + "prompt_lang": "zh", + "text_split_method": "cut0", + "batch_size": 1, + "streaming_mode": 2, + "gpt_streaming": true, + "media_type": "raw", + "streaming_chunk_seconds": 2.0, + "streaming_window_mode": "fixed", + "streaming_lookahead_seconds": 0.12, + "streaming_overlap_seconds": 0.04, + "gpt_streaming_lookahead_seconds": 0.5 +} +``` + +Both HTTP methods expose the same new defaults. `streaming_mode` must be the +integer 2 or 3; its existing meaning is preserved when the new switch is off. +V2ProPlus uses `min_chunk_length` (16 semantic tokens by default), +`overlap_length` and the existing VITS streaming decoder. Mode 2 chooses a +silence boundary, while mode 3 uses fixed semantic chunks. Deltas never repeat +lookahead tokens; an empty EOS flushes the pending audio overlap once. + +V5 uses the acoustic window options above. `sample_steps` and `cfg_rate` keep +the existing model defaults (Turbo: 4/0; Dev: 32/1.3), unless explicitly set. +A nonempty reference transcript and one reference audio are required for V5. +Auxiliary references remain supported by the V2ProPlus path. + +### Fixed and progressive hybrid windows + +`streaming_window_mode` accepts `fixed` (the unchanged default) or `hybrid`. +Both keep the complete text in one GPT session and preserve the requested +sampling steps, CFG and speed. + +For V5, `streaming_chunk_seconds` sets every acoustic window in fixed mode, +or only the first window in hybrid mode. Hybrid gradually grows later windows +when recent delivery costs and estimated playable PCM leave enough time. The +upper limit is the official `min(1000-reference_frames, 640)` acoustic frames. +The first window is not delayed just to fill a larger later window. +While waiting for a planned later window, the semantic stream rechecks the +budget every 50 ms and can fall back to the initial window using its already +available prefix. A larger block is never selected merely because it fits +the model context. + +For V2ProPlus, `min_chunk_length` remains the first semantic block size +(16 tokens by default). Hybrid can grow later blocks up to four times this +size, using the same scheduler and the existing VITS decoder and audio +overlap. In mode 2, silence-boundary search is bounded by the selected block; +if no boundary is available, hybrid emits the selected block rather than +waiting for the whole utterance. Fixed mode retains the old boundary logic. + +The scheduler times PCM delivery, estimates remaining playback from emitted +samples and elapsed time, and leaves headroom before growing a block. It +does not inspect GPU utilization or receive actual player progress. Clients +must still consume PCM promptly and use a persistent playback queue. This +reduces scheduling-induced stalls; it is not a guarantee against arbitrary +device or network pauses. All block decisions are local to the request. + +The complete text enters one GPT session. Newlines are joined; inputs exceeding +the frontend single-session limit are rejected rather than silently split. +This is not incremental LLM text input. A separate AR decoder has 2048 context +positions; generated tokens are limited to 1500 and the remaining context. +Reaching the limit is an error rather than successful truncation. + +## Audio and resource lifetime + +`raw` emits mono signed 16-bit little-endian PCM. V5 is 48 kHz; V2ProPlus uses +its model sample rate. `wav` emits one WAV header followed by PCM. No new +endpoint or client framing protocol is needed. Stream errors after audio has +started terminate the response; errors before the first PCM return HTTP 400. + +A pipeline serves one inference stream at a time. Model/reference updates wait +until the current stream closes. Disconnect cleanup waits for a synchronous +in-flight decoder call to finish, then cancels AR on its owner thread and +releases the pipeline lock. It does not attempt to interrupt a CUDA kernel. + +The optional path requires a supported AR acceleration backend. With the switch +off, existing CPU/nonaccelerated inference remains available. CUDA Graph and +FlashAttention selection use the existing acceleration controls. + +V5's semantic encoder has noncausal attention: finite future context cannot +guarantee sample-for-sample equality with full-utterance synthesis. Listen to +prosody and seams. Independent acoustic RNG prevents diffusion step counts +from changing the concurrently sampled GPT tokens. The optional `generator` +arguments preserve the original global RNG behavior when omitted. + +First PCM arrival is a network measurement, not the first audible phoneme or +sound-device start. Client buffering adds latency. Compare warmed trials with +the same text, reference, seed and AR context size; different cache sizes can +change floating-point sampling even with the same seed. + +## Regression checks + +```text +python -m unittest test_official_streaming test_api_v2_streaming +``` diff --git a/test_api_v2_streaming.py b/test_api_v2_streaming.py new file mode 100644 index 00000000..80ac8820 --- /dev/null +++ b/test_api_v2_streaming.py @@ -0,0 +1,481 @@ +"""GPU-free API v2 compatibility and semantic-streaming regression tests.""" +import asyncio +import importlib.util +import inspect +import sys +import threading +import types +import unittest +from pathlib import Path +from unittest.mock import patch + +import numpy as np +from fastapi.testclient import TestClient + + +def _module(name, package=False, **attributes): + result = types.ModuleType(name) + if package: + result.__path__ = [] + for key, value in attributes.items(): + setattr(result, key, value) + return result + + +class _FakeConfig: + def __init__(self, _path): + self.languages = {"zh", "en"} + self.version = "v2ProPlus" + + +class _FakePipeline: + def __init__(self, config): + self.configs = config + self.calls = [] + self.script_factory = None + self.closed = [] + self.setter_calls = [] + + def run(self, request): + self.calls.append(dict(request)) + if self.script_factory is not None: + return self.script_factory(request) + + def generate(): + try: + yield 32000, np.array([100, -100], dtype=np.int16) + yield 32000, np.array([200, -200], dtype=np.int16) + finally: + self.closed.append(request.get("text")) + + return generate() + + def set_ref_audio(self, path): + self.setter_calls.append(("ref", path, threading.current_thread().name)) + + def init_t2s_weights(self, path): + self.setter_calls.append(("gpt", path, threading.current_thread().name)) + + def init_vits_weights(self, path): + self.setter_calls.append(("sovits", path, threading.current_thread().name)) + + +def _load_api_module(): + root = Path(__file__).resolve().parent + portable = _module( + "tools.portable_runtime", + FFMPEG_EXE="ffmpeg", + activate=lambda **_kwargs: None, + ) + i18n = _module("tools.i18n.i18n", I18nAuto=lambda: object()) + tts = _module("GPT_SoVITS.TTS_infer_pack.TTS", TTS=_FakePipeline, TTS_Config=_FakeConfig) + segmentation = _module( + "GPT_SoVITS.TTS_infer_pack.text_segmentation_method", + get_method_names=lambda: [f"cut{index}" for index in range(6)], + ) + streaming_name = "GPT_SoVITS.TTS_infer_pack.streaming" + streaming_spec = importlib.util.spec_from_file_location( + streaming_name, root / "GPT_SoVITS" / "TTS_infer_pack" / "streaming.py" + ) + streaming = importlib.util.module_from_spec(streaming_spec) + replacements = { + "tools": _module("tools", package=True), + "tools.portable_runtime": portable, + "tools.i18n": _module("tools.i18n", package=True), + "tools.i18n.i18n": i18n, + "tools.acceleration": _module("tools.acceleration", create_acceleration=lambda *_args, **_kwargs: None), + "torch": _module("torch", inference_mode=lambda: lambda function: function), + "GPT_SoVITS": _module("GPT_SoVITS", package=True), + "GPT_SoVITS.TTS_infer_pack": _module("GPT_SoVITS.TTS_infer_pack", package=True), + "GPT_SoVITS.TTS_infer_pack.TTS": tts, + "GPT_SoVITS.TTS_infer_pack.text_segmentation_method": segmentation, + streaming_name: streaming, + } + spec = importlib.util.spec_from_file_location("api_v2_streaming_test_module", root / "api_v2.py") + api = importlib.util.module_from_spec(spec) + replacements[spec.name] = api + with patch.dict(sys.modules, replacements), patch.object(sys, "argv", [sys.argv[0]]): + streaming_spec.loader.exec_module(streaming) + spec.loader.exec_module(api) + return api + + +class APIV2StreamingTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.api = _load_api_module() + + def setUp(self): + self.api.tts_config.version = "v2ProPlus" + self.api.tts_pipeline = _FakePipeline(self.api.tts_config) + self.client = TestClient(self.api.APP) + self.client.__enter__() + + def tearDown(self): + self.client.__exit__(None, None, None) + self.assertFalse(self.api._tts_pipeline_lock.locked()) + + def request(self, **updates): + request = { + "text": "你好,今天开心吗?", + "text_lang": "zh", + "ref_audio_path": "reference.wav", + "prompt_lang": "zh", + "prompt_text": "你好。", + } + request.update(updates) + return request + + def test_existing_defaults_and_routes_are_preserved(self): + post_defaults = { + "text": None, + "text_lang": None, + "ref_audio_path": None, + "aux_ref_audio_paths": None, + "prompt_lang": None, + "prompt_text": "", + "top_k": 15, + "top_p": 1, + "temperature": 1, + "text_split_method": "cut5", + "batch_size": 1, + "batch_threshold": 0.75, + "split_bucket": True, + "speed_factor": 1.0, + "fragment_interval": 0.3, + "seed": -1, + "media_type": "wav", + "streaming_mode": False, + "parallel_infer": True, + "use_cuda_graph": True, + "repetition_penalty": 1.35, + "sample_steps": None, + "cfg_rate": None, + "super_sampling": False, + "overlap_length": 2, + "min_chunk_length": 16, + } + fields = getattr(self.api.TTS_Request, "model_fields", None) + if fields is None: + fields = self.api.TTS_Request.__fields__ + for name, expected in post_defaults.items(): + self.assertEqual(fields[name].default, expected, name) + + get_defaults = { + "text": None, + "text_lang": None, + "ref_audio_path": None, + "aux_ref_audio_paths": None, + "prompt_lang": None, + "prompt_text": "", + "top_k": 15, + "top_p": 1, + "temperature": 1, + "text_split_method": "cut5", + "batch_size": 1, + "batch_threshold": 0.75, + "split_bucket": True, + "speed_factor": 1.0, + "fragment_interval": 0.3, + "seed": -1, + "media_type": "wav", + "parallel_infer": True, + "use_cuda_graph": True, + "repetition_penalty": 1.35, + "sample_steps": None, + "cfg_rate": None, + "super_sampling": False, + "streaming_mode": False, + "overlap_length": 2, + "min_chunk_length": 16, + } + signature = inspect.signature(self.api.tts_get_endpoint) + for name, expected in get_defaults.items(): + self.assertEqual(signature.parameters[name].default, expected, name) + + new_defaults = { + "gpt_streaming": False, + "streaming_chunk_seconds": 2.0, + "streaming_window_mode": "fixed", + "streaming_lookahead_seconds": 0.12, + "streaming_overlap_seconds": 0.04, + "gpt_streaming_lookahead_seconds": 0.5, + "use_flash_attention": True, + } + for name, expected in new_defaults.items(): + self.assertEqual(fields[name].default, expected, name) + self.assertEqual(signature.parameters[name].default, expected, name) + + routes = {} + for route in self.api.APP.routes: + if hasattr(route, "methods"): + routes.setdefault(route.path, set()).update(route.methods) + self.assertEqual(routes["/tts"], {"GET", "POST"}) + self.assertEqual(routes["/control"], {"GET"}) + self.assertEqual(routes["/set_refer_audio"], {"GET"}) + self.assertEqual(routes["/set_gpt_weights"], {"GET"}) + self.assertEqual(routes["/set_sovits_weights"], {"GET"}) + + def test_get_and_post_pass_the_same_new_options(self): + request = self.request( + text_split_method="cut0", + streaming_mode=2, + gpt_streaming=True, + streaming_chunk_seconds=1.5, + streaming_lookahead_seconds=0.1, + streaming_overlap_seconds=0.03, + gpt_streaming_lookahead_seconds=0.6, + use_flash_attention=False, + ) + post_response = self.client.post("/tts", json=request) + self.assertEqual(post_response.status_code, 200, post_response.text) + post_call = self.api.tts_pipeline.calls[-1] + + get_response = self.client.get("/tts", params=request) + self.assertEqual(get_response.status_code, 200, get_response.text) + get_call = self.api.tts_pipeline.calls[-1] + self.assertEqual(get_call, post_call) + self.assertEqual(get_call["streaming_mode"], True) + self.assertEqual(get_call["streaming_window_mode"], "fixed") + self.assertFalse(get_call["fixed_length_chunk"]) + self.assertFalse(get_call["use_flash_attention"]) + + def test_hybrid_window_mode_is_exposed_and_validated(self): + self.api.tts_pipeline.configs.version = "v5turbo" + request = self.request( + text_split_method="cut0", + streaming_mode=2, + gpt_streaming=True, + streaming_window_mode="hybrid", + ) + post_response = self.client.post("/tts", json=request) + self.assertEqual(post_response.status_code, 200, post_response.text) + self.assertEqual(self.api.tts_pipeline.calls[-1]["streaming_window_mode"], "hybrid") + + get_response = self.client.get("/tts", params=request) + self.assertEqual(get_response.status_code, 200, get_response.text) + self.assertEqual(self.api.tts_pipeline.calls[-1], self.api.tts_pipeline.calls[-2]) + + invalid_mode = dict(request, streaming_window_mode="unknown") + self.assertEqual(self.client.post("/tts", json=invalid_mode).status_code, 400) + self.api.tts_pipeline.configs.version = "v2ProPlus" + v2_request = dict(request, text="V2 hybrid", prompt_text="参考") + v2_response = self.client.post("/tts", json=v2_request) + self.assertEqual(v2_response.status_code, 200, v2_response.text) + self.assertEqual(self.api.tts_pipeline.calls[-1]["streaming_window_mode"], "hybrid") + + disabled = dict(v2_request, gpt_streaming=False) + response = self.client.post("/tts", json=disabled) + self.assertEqual(response.status_code, 200, response.text) + self.assertFalse(self.api.tts_pipeline.calls[-1]["gpt_streaming"]) + self.assertEqual(self.api.tts_pipeline.calls[-1]["streaming_window_mode"], "hybrid") + + def test_old_streaming_modes_keep_their_mapping(self): + expected = { + 0: (False, False, False), + 1: (False, True, False), + 2: (True, False, False), + 3: (True, False, True), + False: (False, False, False), + True: (False, True, False), + } + for mode, mapping in expected.items(): + response = self.client.post("/tts", json=self.request(streaming_mode=mode)) + self.assertEqual(response.status_code, 200, response.text) + call = self.api.tts_pipeline.calls[-1] + self.assertEqual( + (call["streaming_mode"], call["return_fragment"], call["fixed_length_chunk"]), + mapping, + ) + + def test_api_validator_sees_original_mode_and_rejects_invalid_options(self): + valid = self.request(text_split_method="cut0", streaming_mode=3, gpt_streaming=True) + response = self.client.post("/tts", json=valid) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(self.api.tts_pipeline.calls[-1]["fixed_length_chunk"], True) + + before = len(self.api.tts_pipeline.calls) + for bad in ( + {"streaming_mode": True}, + {"streaming_mode": 1}, + {"streaming_mode": 4}, + {"streaming_mode": 2.0}, + {"streaming_mode": "2"}, + {"streaming_mode": 2, "text_split_method": "cut5"}, + {"streaming_mode": 2, "media_type": "ogg"}, + {"streaming_mode": 2, "streaming_chunk_seconds": 0}, + ): + invalid = self.request(text_split_method="cut0", streaming_mode=2, gpt_streaming=True) + invalid.update(bad) + response = self.client.post("/tts", json=invalid) + self.assertEqual(response.status_code, 400) + self.assertEqual(len(self.api.tts_pipeline.calls), before) + + invalid_get = self.request(text_split_method="cut0", streaming_mode="2.0", gpt_streaming=True) + response = self.client.get("/tts", params=invalid_get) + self.assertEqual(response.status_code, 400) + self.assertEqual(len(self.api.tts_pipeline.calls), before) + + self.api.tts_pipeline.configs.version = "v4" + invalid_version = self.request(text_split_method="cut0", streaming_mode=2, gpt_streaming=True) + response = self.client.post("/tts", json=invalid_version) + self.assertEqual(response.status_code, 400) + self.assertEqual(len(self.api.tts_pipeline.calls), before) + + def test_streamed_wav_contains_one_header_and_empty_first_chunks_are_skipped(self): + def generate(_request): + yield 32000, np.array([], dtype=np.int16) + yield 32000, np.array([100, -100], dtype=np.int16) + yield 32000, np.array([200, -200], dtype=np.int16) + + self.api.tts_pipeline.script_factory = generate + response = self.client.post( + "/tts", + json=self.request(text_split_method="cut0", streaming_mode=2, gpt_streaming=True), + ) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(response.content[:4], b"RIFF") + self.assertEqual(response.content.count(b"RIFF"), 1) + self.assertEqual(len(response.content), 44 + 8) + self.assertEqual( + response.content[44:], + np.array([100, -100, 200, -200], dtype=np.int16).tobytes(), + ) + + def test_raw_stream_has_no_container_header(self): + response = self.client.post( + "/tts", + json=self.request( + text_split_method="cut0", + streaming_mode=2, + gpt_streaming=True, + media_type="raw", + ), + ) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(response.content, np.array([100, -100, 200, -200], dtype=np.int16).tobytes()) + + def test_no_valid_first_pcm_returns_400_and_releases_lock(self): + self.api.tts_pipeline.script_factory = lambda _request: iter( + [(32000, np.array([], dtype=np.int16))] + ) + response = self.client.post( + "/tts", + json=self.request(text_split_method="cut0", streaming_mode=2, gpt_streaming=True), + ) + self.assertEqual(response.status_code, 400) + self.assertIn("no PCM audio", response.json()["Exception"]) + self.assertFalse(self.api._tts_pipeline_lock.locked()) + + +class CancellationTests(unittest.IsolatedAsyncioTestCase): + @classmethod + def setUpClass(cls): + cls.api = _load_api_module() + + async def test_asgi_disconnect_closes_generator_before_next_request(self): + pipeline = _FakePipeline(self.api.tts_config) + self.api.tts_pipeline = pipeline + entered_blocking_next = threading.Event() + continue_generator = threading.Event() + closed = threading.Event() + + def generate(request): + try: + yield 32000, np.array([1, 2], dtype=np.int16) + yield 32000, np.array([3, 4], dtype=np.int16) + entered_blocking_next.set() + continue_generator.wait(timeout=5) + yield 32000, np.array([5, 6], dtype=np.int16) + finally: + closed.set() + pipeline.closed.append(request.get("text")) + + pipeline.script_factory = generate + request = { + "text": "取消后继续", + "text_lang": "zh", + "ref_audio_path": "reference.wav", + "prompt_lang": "zh", + "prompt_text": "参考", + "text_split_method": "cut0", + "batch_size": 1, + "media_type": "wav", + "streaming_mode": 2, + "gpt_streaming": True, + } + response = await self.api.tts_handle(dict(request)) + messages = [] + + async def receive_disconnect(): + reached_next = await asyncio.to_thread(entered_blocking_next.wait, 2) + if not reached_next: + continue_generator.set() + self.fail("stream did not reach the blocking next() call") + threading.Timer(0.1, continue_generator.set).start() + return {"type": "http.disconnect"} + + async def send(message): + messages.append(message) + + scope = { + "type": "http", + "asgi": {"version": "3.0", "spec_version": "2.3"}, + "http_version": "1.1", + "method": "POST", + "scheme": "http", + "path": "/tts", + "raw_path": b"/tts", + "query_string": b"", + "headers": [], + "client": ("127.0.0.1", 12345), + "server": ("testserver", 80), + "root_path": "", + } + try: + await response(scope, receive_disconnect, send) + finally: + continue_generator.set() + + self.assertTrue(closed.is_set()) + self.assertTrue(any(message.get("type") == "http.response.start" for message in messages)) + self.assertFalse(self.api._tts_pipeline_lock.locked()) + + pipeline.script_factory = None + next_response = await self.api.tts_handle(dict(request)) + chunks = [chunk async for chunk in next_response.body_iterator] + self.assertTrue(chunks) + self.assertFalse(self.api._tts_pipeline_lock.locked()) + + async def test_model_switch_waits_for_the_active_stream(self): + self.api.tts_config.version = "v2ProPlus" + pipeline = _FakePipeline(self.api.tts_config) + self.api.tts_pipeline = pipeline + request = { + "text": "边播边切模型", + "text_lang": "zh", + "ref_audio_path": "reference.wav", + "prompt_lang": "zh", + "prompt_text": "参考", + "text_split_method": "cut0", + "batch_size": 1, + "media_type": "wav", + "streaming_mode": 2, + "gpt_streaming": True, + } + response = await self.api.tts_handle(dict(request)) + setter = asyncio.create_task(self.api.set_gpt_weights("weights.pth")) + await asyncio.sleep(0.02) + self.assertEqual(pipeline.setter_calls, []) + + chunks = [chunk async for chunk in response.body_iterator] + result = await setter + self.assertTrue(chunks) + self.assertEqual(result.status_code, 200) + self.assertEqual(pipeline.setter_calls[0][:2], ("gpt", "weights.pth")) + self.assertNotEqual(pipeline.setter_calls[0][2], "MainThread") + self.assertFalse(self.api._tts_pipeline_lock.locked()) + + +if __name__ == "__main__": + unittest.main() diff --git a/test_official_streaming.py b/test_official_streaming.py new file mode 100644 index 00000000..e51fe07a --- /dev/null +++ b/test_official_streaming.py @@ -0,0 +1,536 @@ +"""Regressions for the opt-in official streaming path, without loading weights.""" +from concurrent.futures import ThreadPoolExecutor +import importlib.util +from itertools import count +import sys +import threading +import numpy as np +import unittest +from unittest.mock import patch +from pathlib import Path +from types import SimpleNamespace +import torch + +sys.path[:0] = [str(Path(__file__).resolve().parent), str(Path(__file__).resolve().parent / "GPT_SoVITS")] +from GPT_SoVITS.Accel.adapter import AccelInference +from GPT_SoVITS.Accel.PyTorch.AR.structs import T2SRequestHandle, T2SResult, T2SStreamResponse +from GPT_SoVITS.Accel.PyTorch.AR.t2s_engine import T2SEngine +from module.models import CFM, SynthesizerTrn + +# Load the official helper file directly so importing its package does not +# eagerly import the full TTS stack (and its optional librosa/numba cache). +_streaming_path = Path(__file__).resolve().parent / "GPT_SoVITS" / "TTS_infer_pack" / "streaming.py" +_streaming_spec = importlib.util.spec_from_file_location("GPT_SoVITS.TTS_infer_pack.streaming", _streaming_path) +_streaming_module = importlib.util.module_from_spec(_streaming_spec) +_streaming_spec.loader.exec_module(_streaming_module) +v2_token_chunks = _streaming_module.v2_token_chunks +validate_streaming_options = _streaming_module.validate_streaming_options +PipelineStop = _streaming_module.PipelineStop +stream_v5_windows = _streaming_module.stream_v5_windows +StreamingWindowSchedule = _streaming_module.StreamingWindowSchedule + + +class WindowScheduleTests(unittest.TestCase): + def test_progressive_windows_preserve_playback_lead_on_a_slower_device(self): + clock = [0.0] + with patch.object(_streaming_module.time, "perf_counter", side_effect=lambda: clock[0]): + schedule = StreamingWindowSchedule(200, 541) + self.assertEqual(schedule.choose(2000), 200) + clock[0] += 1.2 + schedule.observe(200, 94080, 48000) + sizes = [] + for _ in range(8): + size = schedule.choose(2000) + sizes.append(size) + elapsed = 0.2 + 0.5 * size / 100 + available = schedule.audio_seconds - (clock[0]-schedule.first_pcm_at) + self.assertLess(elapsed, available) + clock[0] += elapsed + schedule.observe(size, size*480, 48000) + self.assertEqual(sizes[0], 200) + self.assertIn(300, sizes) + self.assertIn(541, sizes) + # Immediately switching to the largest window would stall despite RTF < 1. + self.assertGreater(0.2+0.5*5.41, 1.96) + self.assertLess(0.2+0.5*5.41, 5.41) + + def test_backpressure_and_slower_observations_reduce_window_growth(self): + clock = [0.0] + with patch.object(_streaming_module.time, "perf_counter", side_effect=lambda: clock[0]): + schedule = StreamingWindowSchedule(16, 64) + clock[0] = 0.05 + schedule.observe(16, 17920, 32000) + self.assertEqual(schedule.choose(1000), 24) + clock[0] += 0.5 + self.assertEqual(schedule.choose(1000), 16) + schedule.observe(16, 20480, 32000) + self.assertEqual(schedule.choose(1000), 16) + + def test_short_available_tail_is_flushed_without_padding(self): + schedule = StreamingWindowSchedule(200, 541) + self.assertEqual(schedule.choose(17), 17) + + +class ReferenceTests(unittest.TestCase): + def test_reference_features_align_before_tail_crop(self): + features = torch.arange(8).reshape(1, 1, -1).float() + mel = torch.arange(5).reshape(1, 1, -1).float() + cache = dict(refer_spec=[(torch.zeros(1, 2, 4), None)], + prompt_semantic=torch.ones(4, dtype=torch.long), phones=[1, 2], + bert_features=torch.zeros(1024, 2), raw_audio=torch.zeros(1, 10), raw_sr=32000) + pipeline = SimpleNamespace(prompt_cache=cache, precision=torch.float32, + configs=SimpleNamespace(device=torch.device("cpu")), + vits_model=SimpleNamespace(decode_encp=lambda *args: (features, None))) + stub = SimpleNamespace(resample=None, mel_fn_v4=lambda _: mel, norm_spec=lambda x: x) + with patch.dict(sys.modules, {"GPT_SoVITS.TTS_infer_pack.TTS": stub}): + reference = _streaming_module.v5_reference(pipeline) + torch.testing.assert_close(reference[4], features[..., :5]) + torch.testing.assert_close(reference[6], mel) + + +class AdapterTests(unittest.TestCase): + def adapter(self, partials=(), final=None, error=None): + handle = T2SRequestHandle("test") + for partial in partials: + handle.queue.put(T2SStreamResponse("test", 0, [torch.tensor(partial)])) + if final is not None or error is not None: + handle.queue.put(T2SStreamResponse("test", -1, None, finished=True, + result=T2SResult(result=[torch.tensor(final)] if final is not None else None, + exception=error), exception=error)) + handle.done = True + a = AccelInference.__new__(AccelInference) + a.device = torch.device("cpu") + a._mode_lock = threading.RLock() + a._request_ids = count() + a.graph_enabled = False + a.decoder = SimpleNamespace(max_seq_length=1024) + requests = [] + def add(req): + requests.append(req) + return handle + def cancel(h): + h.cancelled.set() + h.done = True + a.engine = SimpleNamespace(add_request=add, cancel_request=cancel, _stop_event=threading.Event()) + a.prepare = lambda *args: True + return a, handle, requests + + def stream(self, a, **kw): + return a.infer_stream(torch.ones(4, dtype=torch.long), torch.ones(1, 2, dtype=torch.long), + torch.zeros(1024, 4), max_decode_steps=20, **kw) + + def test_decoder_graph_preparation_keeps_inference_context_consistent(self): + a, _, _ = self.adapter(final=[1, 2]) + a.engine = None + a.backend = "fake" + a.dtype = torch.float32 + a.graph_failed = False + seen = [] + def engine(*args, **kwargs): + seen.append(torch.is_inference_mode_enabled()) + return SimpleNamespace(model_runner=SimpleNamespace(graph_applicable=True, graph_error=None)) + with patch("GPT_SoVITS.Accel.adapter.resolve_acceleration", return_value=("fake", True)), \ + patch("GPT_SoVITS.Accel.adapter.T2SEngine", engine): + self.assertTrue(AccelInference.prepare(a)) + self.assertEqual(seen, [True]) + self.assertFalse(torch.is_inference_mode_enabled()) + + def test_partial_deltas_and_complete_final_are_not_duplicated(self): + a, _, requests = self.adapter([[1, 2], [3, 4]], [1, 2, 3, 4, 5]) + updates = list(self.stream(a)) + self.assertEqual([t.tolist() for t, _ in updates], [[1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5]]) + self.assertEqual([done for _, done in updates], [False, False, True]) + self.assertEqual(requests[0].max_decode_steps, 20) + + def test_final_prefix_mismatch_is_rejected(self): + a, _, _ = self.adapter([[1, 2]], [3, 4, 5]) + with self.assertRaisesRegex(RuntimeError, "disagree"): + list(self.stream(a)) + + def test_limit_is_an_error_instead_of_successful_truncation(self): + a, _, _ = self.adapter(final=list(range(20))) + with self.assertRaisesRegex(ValueError, "token limit"): + list(self.stream(a)) + + def test_error_is_propagated(self): + a, _, _ = self.adapter(error=RuntimeError("decoder failed")) + with self.assertRaisesRegex(RuntimeError, "decoder failed"): + list(self.stream(a)) + + def test_close_on_another_thread_cancels_without_rlock_owner_error(self): + a, handle, _ = self.adapter([[1, 2]]) + iterator = self.stream(a) + def lock_is_available(): + acquired = a._mode_lock.acquire(False) + if acquired: + a._mode_lock.release() + return acquired + with ThreadPoolExecutor(max_workers=1) as first, ThreadPoolExecutor(max_workers=1) as second: + first.submit(next, iterator).result() + second.submit(iterator.close).result() + self.assertTrue(second.submit(lock_is_available).result()) + self.assertTrue(handle.cancelled.is_set()) + + def test_stop_interrupts_an_empty_queue(self): + a, handle, _ = self.adapter() + stop = threading.Event() + iterator = self.stream(a, stop=stop) + timer = threading.Timer(0.03, stop.set) + timer.start() + try: + self.assertEqual(list(iterator), []) + finally: + timer.join() + self.assertTrue(handle.cancelled.is_set()) + + def test_hybrid_heartbeat_rechecks_waiting_prefix_and_still_cancels(self): + a,handle,_ = self.adapter([[1,2]]) + stop = threading.Event() + iterator = self.stream(a,stop=stop,stream_state={"poll_partial":True}) + first,done = next(iterator) + heartbeat,done = next(iterator) + self.assertFalse(done) + self.assertTrue(torch.equal(first,heartbeat)) + stop.set() + self.assertEqual(list(iterator),[]) + self.assertTrue(handle.cancelled.is_set()) + + def test_stop_during_heartbeat_wait_does_not_yield_a_stale_prefix(self): + a,handle,_ = self.adapter([[1,2]]) + stop = threading.Event() + iterator = self.stream(a,stop=stop,stream_state={"poll_partial":True}) + next(iterator) + timer = threading.Timer(0.01,stop.set);timer.start() + try:self.assertEqual(list(iterator),[]) + finally:timer.join() + self.assertTrue(handle.cancelled.is_set()) + + +class AcousticTests(unittest.TestCase): + def fixture(self, frames): + calls, decoded, progress = [], [], [] + class Diffusion: + def inference(self, mu, lengths, prompt, steps, inference_cfg_rate, generator): + calls.append(mu.shape[1]) + torch.randn(1, generator=generator) + return mu.transpose(1, 2) + def enc(tokens, *args): + n = tokens.numel() * 4 + decoded.append(n) + return torch.arange(n).float().view(1, 1, -1) / 2000, None + w = SimpleNamespace(device="cpu", vq_model=SimpleNamespace(cfm=Diffusion(), decode_encp=enc), + denorm_spec=lambda mel: mel, hifigan_model=lambda mel: mel.repeat_interleave(480, -1)) + ref = torch.zeros(1, 1, 50) + reference = (None, None, None, None, ref, None, ref) + req = dict(streaming_chunk_seconds=2, streaming_lookahead_seconds=.12, + gpt_streaming_lookahead_seconds=.5, streaming_overlap_seconds=.04, + speed_factor=1, sample_steps=16, cfg_rate=0) + def updates(): + for n in range(16, frames//4, 16): + progress.append((n, False)) + yield torch.arange(n), False + progress.append((frames//4, True)) + yield torch.arange(frames//4), True + return w, reference, req, updates(), calls, decoded, progress + + def stream(self, w, updates, phones, reference, req, stop): + return stream_v5_windows(w.vq_model, w.hifigan_model, w.denorm_spec, + w.device, updates, phones, reference, req, stop) + + def test_prefixes_preserve_every_frame_in_order_and_flush_tail(self): + for frames in (4, 196, 200, 204, 400, 404, 856): + with self.subTest(frames=frames): + w, ref, req, updates, calls, decoded, progress = self.fixture(frames) + output = list(self.stream(w, updates, [], ref, req, threading.Event())) + pcm = np.concatenate(output) + expected = (torch.arange(frames).repeat_interleave(480).float()/2000*32767).to(torch.int16).numpy() + self.assertEqual(pcm.size, frames*480) + np.testing.assert_allclose(pcm.astype(float), expected.astype(float), atol=1) + self.assertTrue(all(n <= 1000 for n in calls)) + + def test_first_window_precedes_eos_and_skips_unproductive_prefixes(self): + w, ref, req, updates, calls, decoded, progress = self.fixture(856) + iterator = self.stream(w, updates, [], ref, req, threading.Event()) + first = next(iterator) + self.assertEqual(first.size, 196*480) + self.assertFalse(progress[-1][1]) + self.assertEqual(decoded, [320]) + iterator.close() + + def test_cancel_does_not_generate_another_window(self): + w, ref, req, updates, calls, _, _ = self.fixture(856) + stop = threading.Event() + iterator = self.stream(w, updates, [], ref, req, stop) + next(iterator) + stop.set() + self.assertEqual(list(iterator), []) + self.assertEqual(len(calls), 1) + + def test_missing_eos_is_rejected(self): + w, ref, req, _, _, _, _ = self.fixture(856) + updates = iter([(torch.arange(80), False)]) + with self.assertRaisesRegex(RuntimeError, "without a final"): + list(self.stream(w, updates, [], ref, req, threading.Event())) + + + def test_hybrid_preserves_short_and_exact_boundary_frames(self): + for frames in (4,196,200,204,400,404,856,1600): + w,ref,req,updates,calls,_,_ = self.fixture(frames) + req["streaming_window_mode"] = "hybrid" + pcm = np.concatenate(list(self.stream(w,updates,[],ref,req,threading.Event()))) + expected = (torch.arange(frames).repeat_interleave(480).float()/2000*32767).to(torch.int16).numpy() + np.testing.assert_allclose(pcm.astype(float),expected.astype(float),atol=1) + self.assertTrue(all(n<=1000 for n in calls)) + + def test_hybrid_gradually_grows_without_receiver_underrun(self): + w,ref,req,_,calls,_,_ = self.fixture(2200) + req["streaming_window_mode"] = "hybrid" + clock = [0.0] + original = w.vq_model.cfm.inference + spans = [] + def inference(mu,lengths,prompt,*args,**kwargs): + span = mu.shape[1]-prompt.shape[-1] + spans.append(span) + clock[0] += 0.2+0.5*span/100 + return original(mu,lengths,prompt,*args,**kwargs) + w.vq_model.cfm.inference = inference + updates = iter([(torch.arange(80),False),(torch.arange(400),False),(torch.arange(550),True)]) + with patch.object(_streaming_module.time,"perf_counter",side_effect=lambda:clock[0]): + chunks = [];first = None;playable = 0.0 + for pcm in self.stream(w,updates,[],ref,req,threading.Event()): + if first is None:first=clock[0] + self.assertLessEqual(clock[0]-first,playable+1e-6) + playable += pcm.size/48000 + chunks.append(pcm) + self.assertEqual(sum(x.size for x in chunks),2200*480) + self.assertIn(300,spans) + self.assertTrue(any(n>400 for n in spans)) + self.assertTrue(all(n<=1000 for n in calls)) + + def test_waiting_for_a_larger_window_falls_back_on_heartbeat(self): + w,ref,req,_,_,_,_ = self.fixture(1000) + req["streaming_window_mode"] = "hybrid" + clock = [0.0];spans=[] + original = w.vq_model.cfm.inference + def inference(mu,lengths,prompt,*args,**kwargs): + span=mu.shape[1]-prompt.shape[-1];spans.append(span) + clock[0] += 0.2+0.5*span/100 + return original(mu,lengths,prompt,*args,**kwargs) + w.vq_model.cfm.inference=inference + def updates(): + yield torch.arange(80),False + yield torch.arange(128),False + yield torch.arange(184),False + clock[0] += 0.5 + yield torch.arange(184),False + yield torch.arange(250),True + with patch.object(_streaming_module.time,"perf_counter",side_effect=lambda:clock[0]): + first=None;playable=0. + for pcm in self.stream(w,updates(),[],ref,req,threading.Event()): + if first is None:first=clock[0] + self.assertLessEqual(clock[0]-first,playable+1e-6) + playable+=pcm.size/48000 + self.assertEqual(spans[:3],[212,200,200]) + + +class RNGTests(unittest.TestCase): + def test_cfm_generator_preserves_global_rng_and_is_reproducible(self): + class Estimator(torch.nn.Module): + def forward(self, x, *args, **kwargs): + return torch.zeros_like(x).transpose(1, 2), None, None + model = CFM(1, Estimator()) + mu, prompt, lengths = torch.zeros(1, 40, 1), torch.zeros(1, 1, 10), torch.tensor([40]) + torch.manual_seed(123) + original = torch.random.get_rng_state().clone() + def generate(): + return model.inference(mu, lengths, prompt, 2, + generator=torch.Generator().manual_seed(456)) + first, second = generate(), generate() + self.assertTrue(torch.equal(first, second)) + self.assertTrue(torch.equal(original, torch.random.get_rng_state())) + model.inference(mu, lengths, prompt, 2) + self.assertFalse(torch.equal(original, torch.random.get_rng_state())) + + +class CancelTests(unittest.TestCase): + def test_owner_thread_releases_waiting_and_bound_sessions(self): + for waiting in (True, False): + e = T2SEngine.__new__(T2SEngine) + e._stop_event = threading.Event() + e._loop_thread = None + handle = T2SRequestHandle("test") + handle.cancelled.set() + session = SimpleNamespace(request_id="test") + e.handles = {"test":handle} + e.waiting_bind = [session] if waiting else [] + bound = [] if waiting else [session] + with torch.inference_mode(): + inference_buffer = torch.ones(1) + def unbind(s): + inference_buffer[0] = 0 + bound.remove(s) + e.model_runner = SimpleNamespace(bound_sessions=bound, unbind_session=unbind) + def step(): + e._stop_event.set() + return [] + e.model_runner.decode_step = step + e._drain_new_requests = lambda: None + finalized = [] + def finalize(s, exc, cancelled=False): + finalized.append(cancelled) + e._stop_event.set() + e._finalize_session = finalize + e._background_loop() + self.assertEqual(finalized, [True]) + self.assertEqual(e.waiting_bind, []) + self.assertEqual(bound, []) + + +class TokenChunksTests(unittest.TestCase): + def updates(self, sizes): + for i, n in enumerate(sizes): + yield torch.arange(n), i == len(sizes)-1 + + def flattened(self, outputs): + tensors = [tokens.reshape(-1) for tokens, _ in outputs if tokens is not None] + return torch.cat(tensors).tolist() if tensors else [] + + def test_fixed_delta_tail_and_exact_boundary_eos(self): + for sizes in [(16, 32, 37), (16, 32, 32), (5,), (16, 64, 68)]: + with self.subTest(sizes=sizes): + out = list(v2_token_chunks(self.updates(sizes), 16)) + self.assertEqual(self.flattened(out), list(range(sizes[-1]))) + self.assertTrue(out[-1][1]) + self.assertEqual(sum(final for _, final in out), 1) + + def test_silence_pair_emits_only_through_the_cut(self): + scores = torch.full((80,), -1.) + scores[15:17] = 1. + scores[35:37] = 1. + out = list(v2_token_chunks(self.updates([24, 48, 60]), 16, scores)) + self.assertEqual(self.flattened(out), list(range(60))) + self.assertEqual(out[0][0].numel(), 16) + self.assertTrue(out[-1][1]) + + def test_no_silence_waits_for_eos(self): + out = list(v2_token_chunks(self.updates([16, 32, 40]), 16, torch.full((80,), -1.))) + self.assertEqual(len(out), 1) + self.assertEqual(self.flattened(out), list(range(40))) + + def test_single_last_token_is_not_a_silence_pair(self): + scores = torch.full((80,), -1.) + scores[23] = 1. + out = list(v2_token_chunks(self.updates([24, 26]), 16, scores)) + self.assertEqual(len(out), 1) + self.assertEqual(self.flattened(out), list(range(26))) + + def test_closing_consumer_closes_upstream(self): + closed = [] + def updates(): + try: + yield torch.arange(16), False + yield torch.arange(32), True + finally: + closed.append(True) + chunks = v2_token_chunks(updates(), 16) + next(chunks) + chunks.close() + self.assertEqual(closed, [True]) + + def test_decreasing_prefix_is_rejected(self): + with self.assertRaisesRegex(RuntimeError, "backwards"): + list(v2_token_chunks(self.updates([32, 16]), 16)) + + + def test_hybrid_eos_flush_is_bounded_and_silence_wait_does_not_stall(self): + clock = [0.0] + with patch.object(_streaming_module.time,"perf_counter",side_effect=lambda:clock[0]): + schedule = StreamingWindowSchedule(16,64) + output = [];playable = 0.0;first = None + iterator = v2_token_chunks(self.updates([32,200]),16,torch.full((220,),-1.),schedule=schedule) + for tokens,finished in iterator: + if tokens is None:continue + n = tokens.numel();clock[0] += 0.01+n*0.005 + if first is None:first=clock[0] + self.assertLessEqual(clock[0]-first,playable+1e-6) + samples = int((n-(2 if not output else 0))*1280) + schedule.observe(n,samples,32000) + playable += samples/32000 + output.append((tokens,finished)) + self.assertEqual(self.flattened(output),list(range(200))) + self.assertTrue(output[-1][1]) + self.assertEqual(sum(final for _,final in output),1) + self.assertEqual(output[0][0].numel(),16) + self.assertTrue(any(tokens.numel()>16 for tokens,_ in output)) + self.assertTrue(all(tokens.numel()<=64 for tokens,_ in output)) + + +class ValidationTests(unittest.TestCase): + def req(self, **changes): + req = dict(gpt_streaming=True, streaming_mode=2, text_split_method="cut0", batch_size=1, prompt_text="hello") + req.update(changes) + return req + + def test_old_requests_are_not_revalidated(self): + validate_streaming_options(dict(gpt_streaming=False, streaming_mode=0), "v1", api_mode=True) + + def test_modes_versions_and_finite_window_limits(self): + for version in ["v5turbo", "v5dev", "v2ProPlus"]: + validate_streaming_options(self.req(), version, api_mode=True) + for patch in [dict(streaming_mode=True), dict(streaming_mode=0), dict(streaming_mode=2.0), dict(batch_size=2), + dict(text_split_method="cut5"), dict(media_type="aac"), + dict(streaming_chunk_seconds=float("nan")), dict(speed_factor=0), + dict(cfg_rate=float("inf")), dict(overlap_length=0)]: + with self.subTest(patch=patch), self.assertRaises(ValueError): + validate_streaming_options(self.req(**patch), "v5turbo", api_mode=True) + with self.assertRaises(ValueError): + validate_streaming_options(self.req(aux_ref_audio_paths=["ref.wav"]), "v5turbo", api_mode=True) + validate_streaming_options(self.req(aux_ref_audio_paths=["ref.wav"]), "v2ProPlus", api_mode=True) + with self.assertRaises(ValueError): + validate_streaming_options(self.req(), "v4", api_mode=True) + + def test_pipeline_stop_and_disconnect_share_a_stop_signal(self): + pipeline = SimpleNamespace(stop_flag=False) + stop = PipelineStop(pipeline) + self.assertFalse(stop.is_set()) + pipeline.stop_flag = True + self.assertTrue(stop.is_set()) + pipeline.stop_flag = False + stop.set() + self.assertTrue(stop.is_set()) + + +class AcousticRNGTests(unittest.TestCase): + def fixture(self): + shape = (1, 2, 32) + model = SimpleNamespace( + version="v2", is_v2pro=False, semantic_frame_rate="25hz", + quantizer=SimpleNamespace(decode=lambda codes: torch.zeros(1, 2, codes.shape[-1])), + enc_p=lambda *args, **kwargs: (None, torch.zeros(shape), torch.zeros(shape), + torch.ones(shape), None, None), + flow=lambda z, *args, **kwargs: z, + dec=lambda z, **kwargs: z) + return model + + def decode(self, model, **kw): + return SynthesizerTrn.decode_streaming(model, torch.zeros(1, 1, 16, dtype=torch.long), + torch.ones(1, 4, dtype=torch.long), None, **kw)[0] + + def test_private_v2_noise_does_not_advance_ar_rng(self): + model = self.fixture() + torch.manual_seed(29) + state = torch.random.get_rng_state().clone() + first = self.decode(model, generator=torch.Generator().manual_seed(7)) + self.assertTrue(torch.equal(state, torch.random.get_rng_state())) + self.assertTrue(torch.equal(first, self.decode(model, generator=torch.Generator().manual_seed(7)))) + self.assertGreater(first.abs().sum().item(), 0) + + def test_default_v2_noise_retains_global_rng_behavior(self): + torch.manual_seed(29) + state = torch.random.get_rng_state().clone() + self.decode(self.fixture()) + self.assertFalse(torch.equal(state, torch.random.get_rng_state())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/acceleration.py b/tools/acceleration.py index adba07f7..dd058e9e 100644 --- a/tools/acceleration.py +++ b/tools/acceleration.py @@ -73,6 +73,7 @@ def create_acceleration( max_batch_size=32, use_cuda_graph=True, use_flash_attention=True, + max_seq_length=None, ): backend, _ = resolve_acceleration(device, dtype, use_cuda_graph, use_flash_attention) if backend is None: @@ -90,4 +91,5 @@ def create_acceleration( max_batch_size=max_batch_size, use_cuda_graph=use_cuda_graph, use_flash_attention=use_flash_attention, + max_seq_length=max_seq_length, )