From ad9b78dca2a4d5cef285ca7e672941df276f1643 Mon Sep 17 00:00:00 2001 From: lywy233 Date: Wed, 21 Oct 2026 16:57:06 +0800 Subject: [PATCH] perf(v5): add opt-in acoustic batching and CUDA Graph replay --- GPT_SoVITS/TTS_infer_pack/TTS.py | 74 +++++++++- GPT_SoVITS/f5_tts/model/backbones/dit.py | 24 +++- GPT_SoVITS/module/models.py | 40 +++++- GPT_SoVITS/module/models_v5.py | 32 ++++- GPT_SoVITS/module/v5_acoustic.py | 164 +++++++++++++++++++++++ docs/en/v5_acoustic_inference.md | 94 +++++++++++++ test_v5_acoustic.py | 137 +++++++++++++++++++ tools/benchmark_v5_acoustic.py | 120 +++++++++++++++++ 8 files changed, 664 insertions(+), 21 deletions(-) create mode 100644 GPT_SoVITS/module/v5_acoustic.py create mode 100644 docs/en/v5_acoustic_inference.md create mode 100644 test_v5_acoustic.py create mode 100644 tools/benchmark_v5_acoustic.py diff --git a/GPT_SoVITS/TTS_infer_pack/TTS.py b/GPT_SoVITS/TTS_infer_pack/TTS.py index 4f757371..ff0df5c8 100644 --- a/GPT_SoVITS/TTS_infer_pack/TTS.py +++ b/GPT_SoVITS/TTS_infer_pack/TTS.py @@ -32,6 +32,7 @@ from feature_extractor.cnhubert import CNHubert from module.mel_processing import mel_spectrogram_torch, spectrogram_torch from module.models import SynthesizerTrn, SynthesizerTrnV3, Generator from module.models_v5 import synthesize_v5_mel, V5_VERSIONS +from module.v5_acoustic import synthesize_v5_mel_batch, V5AcousticGraphRunner from peft import LoraConfig, get_peft_model from process_ckpt import get_sovits_version_from_path_fast, load_sovits_new from transformers import AutoModelForMaskedLM, AutoTokenizer @@ -510,6 +511,19 @@ class TTS: else: self.configs: TTS_Config = TTS_Config(configs) + # These options affect non-streaming V5 acoustic synthesis only. Keep + # the existing path by default: batching changes FP16 rounding, while + # graph capture trades first-shape latency and memory for faster reuse. + self._v5_acoustic_batch_size = int(os.environ.get("GSVV5_ACOUSTIC_BATCH_SIZE", "0")) + graph_capacity = int(os.environ.get("GSVV5_ACOUSTIC_GRAPH_CAPACITY", "64")) + if self._v5_acoustic_batch_size < 0 or graph_capacity < 1: + raise ValueError("V5 acoustic batch size must be nonnegative and graph capacity positive") + self._v5_acoustic_graph_runner = ( + V5AcousticGraphRunner(max_entries=graph_capacity) + if self._v5_acoustic_batch_size and os.environ.get("GSVV5_ACOUSTIC_CUDA_GRAPH", "0") == "1" + else None + ) + self.t2s_model: Text2SemanticLightningModule = None self.t2s_accel = None self.streaming_accel = None @@ -578,6 +592,9 @@ class TTS: self.bert_model = self.bert_model.half() def init_vits_weights(self, weights_path: str): + # Release graph references to old acoustic weights before loading a replacement. + if self._v5_acoustic_graph_runner is not None: + self._v5_acoustic_graph_runner.clear() self.configs.vits_weights_path = weights_path version, model_version, if_lora_v3 = get_sovits_version_from_path_fast(weights_path) if "Pro" in model_version: @@ -1905,6 +1922,50 @@ class TTS: return audio + @torch.inference_mode() + def _using_v5_acoustic_batch( + self, + idx_list, + semantic_tokens_list, + batch_phones, + speed, + sample_steps, + cfg_rate, + ): + # Reference conditioning is identical across this request's text segments. + # Compute it once per batch; do not cache any target or generated features. + prompt_tokens = self.prompt_cache["prompt_semantic"].unsqueeze(0).unsqueeze(0).to(self.configs.device) + prompt_phones = torch.LongTensor(self.prompt_cache["phones"]).unsqueeze(0).to(self.configs.device) + spec = self.prompt_cache["refer_spec"][0] + if isinstance(spec, tuple): + spec = spec[0] + spec = spec.to(dtype=self.precision, device=self.configs.device) + reference_features, ge = self.vits_model.decode_encp(prompt_tokens, prompt_phones, spec) + audio = self.prompt_cache["raw_audio"].to(self.configs.device).float() + if audio.shape[0] == 2: + audio = audio.mean(0).unsqueeze(0) + if self.prompt_cache["raw_sr"] != 32000: + audio = resample(audio, self.prompt_cache["raw_sr"], 32000, self.configs.device) + reference_mel = norm_spec(mel_fn_v4(audio)).to(self.precision) + targets = [] + for i, idx in enumerate(idx_list): + tokens = semantic_tokens_list[i][-idx:].unsqueeze(0).unsqueeze(0) + phones = batch_phones[i].unsqueeze(0).to(self.configs.device) + features, _ = self.vits_model.decode_encp(tokens, phones, spec, ge, speed) + targets.append(features) + mels = synthesize_v5_mel_batch( + self.vits_model, + reference_features, + targets, + reference_mel, + steps=sample_steps, + cfg=cfg_rate, + max_batch=self._v5_acoustic_batch_size, + runner=self._v5_acoustic_graph_runner, + ) + # Preserve per-utterance vocoder boundaries and the caller's segment order. + return [self.vocoder(denorm_spec(mel).to(self.precision))[0, 0] for mel in mels] + def using_vocoder_synthesis_batched_infer( self, idx_list: List[int], @@ -1917,11 +1978,22 @@ class TTS: sample_steps = (4 if self.configs.version == "v5turbo" else 32) if sample_steps is None else int(sample_steps) cfg_rate = (1.30 if self.configs.version == "v5dev" else 0.0) if cfg_rate is None else float(cfg_rate) if self.configs.version in V5_VERSIONS: + if self._v5_acoustic_batch_size: + return self._using_v5_acoustic_batch( + idx_list, + semantic_tokens_list, + batch_phones, + speed, + sample_steps, + cfg_rate, + ) return [ self.using_vocoder_synthesis( semantic_tokens_list[i][-idx:].unsqueeze(0).unsqueeze(0), batch_phones[i].unsqueeze(0).to(self.configs.device), - speed=speed, sample_steps=sample_steps, cfg_rate=cfg_rate, + speed=speed, + sample_steps=sample_steps, + cfg_rate=cfg_rate, ) for i, idx in enumerate(idx_list) ] diff --git a/GPT_SoVITS/f5_tts/model/backbones/dit.py b/GPT_SoVITS/f5_tts/model/backbones/dit.py index 46570fcf..d1b95be2 100644 --- a/GPT_SoVITS/f5_tts/model/backbones/dit.py +++ b/GPT_SoVITS/f5_tts/model/backbones/dit.py @@ -51,7 +51,9 @@ class TextEmbedding(nn.Module): # possible extra modeling if self.extra_modeling: # sinus pos emb - batch_start = torch.zeros((batch,), dtype=torch.long) + # Keep positional indices on the model device. CPU indices trigger a + # host-to-device copy that cannot be captured by a CUDA Graph. + batch_start = torch.zeros((batch,), dtype=torch.long, device=text.device) pos_idx = get_pos_embed_indices(batch_start, seq_len, max_pos=self.precompute_max_pos) text_pos_embed = self.freqs_cis[pos_idx] @@ -132,7 +134,7 @@ class DiT(nn.Module): return ckpt_forward - def prepare_static_cache(self, cond0, x_lens, text0): + def prepare_static_cache(self, cond0, x_lens, text0, all_valid=False, use_negative_condition=True): text = text0.transpose(2, 1) cond = cond0.transpose(2, 1) seq_len = cond.shape[1] @@ -141,16 +143,24 @@ class DiT(nn.Module): mel_dim = cond.shape[-1] static = F.linear( torch.cat((cond, text_embed), dim=-1), - projection.weight[:, mel_dim:], projection.bias, + projection.weight[:, mel_dim:], + projection.bias, ) - negative_static = F.linear( - torch.cat((torch.zeros_like(cond), text_embed), dim=-1), - projection.weight[:, mel_dim:], projection.bias, + negative_static = ( + F.linear( + torch.cat((torch.zeros_like(cond), text_embed), dim=-1), + projection.weight[:, mel_dim:], + projection.bias, + ) + if use_negative_condition + else static ) return { "condition": static, "negative_condition": negative_static, - "mask": sequence_mask(x_lens, max_length=seq_len).to(cond.device), + # Equal-length buckets contain no padding. Omitting the all-True + # mask permits Flash SDPA; padded callers retain their original mask. + "mask": None if all_valid else sequence_mask(x_lens, max_length=seq_len).to(cond.device), "rope": self.rotary_embed.forward_from_seq_len(seq_len), } diff --git a/GPT_SoVITS/module/models.py b/GPT_SoVITS/module/models.py index 0e1f5acd..f3e39fb0 100644 --- a/GPT_SoVITS/module/models.py +++ b/GPT_SoVITS/module/models.py @@ -1117,13 +1117,34 @@ 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, generator=None): + def inference( + self, + mu, + x_lens, + prompt, + n_timesteps, + temperature=1.0, + inference_cfg_rate=0, + generator=None, + initial_noise=None, + all_valid=False, + ): """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, generator=generator) * temperature + # Explicit per-window noise lets the V5 scheduler reorder independent + # windows without changing the RNG draws made in original segment order. + if initial_noise is None: + initial_noise = torch.randn([B, self.in_channels, T], device=mu.device, dtype=mu.dtype, generator=generator) + elif ( + initial_noise.shape != (B, self.in_channels, T) + or initial_noise.device != mu.device + or initial_noise.dtype != mu.dtype + ): + raise ValueError("initial_noise must match the CFM input shape, device and dtype") + x = initial_noise * temperature prompt_len = prompt.size(-1) prompt_x = torch.zeros_like(x, dtype=mu.dtype) prompt_x[..., :prompt_len] = prompt[..., :prompt_len] @@ -1134,12 +1155,17 @@ class CFM(torch.nn.Module): text_cache = None text_cfg_cache = None dt_cache = None - static_cache = (self.estimator.prepare_static_cache(prompt_x, x_lens, mu) - if self.use_conditioner_cache and self.use_static_cache else None) - d_tensor = (torch.ones(x.shape[0], device=x.device, dtype=mu.dtype) * d - if self.use_step_embedding else None) + cache_options = {"all_valid": True, "use_negative_condition": inference_cfg_rate > 1e-5} if all_valid else {} + static_cache = ( + self.estimator.prepare_static_cache(prompt_x, x_lens, mu, **cache_options) + if self.use_conditioner_cache and self.use_static_cache + else None + ) + d_tensor = torch.ones(x.shape[0], device=x.device, dtype=mu.dtype) * d if self.use_step_embedding else None for j in range(n_timesteps): - t_tensor = torch.ones(x.shape[0], device=x.device, dtype=mu.dtype) * (t if self.use_step_embedding else j * d) + t_tensor = torch.ones(x.shape[0], device=x.device, dtype=mu.dtype) * ( + t if self.use_step_embedding else j * d + ) step_condition = {"dt_base_bootstrap": d_tensor, "dt_cache": dt_cache} if self.use_step_embedding else {} v_pred, text_emb, dt = self.estimator( x, diff --git a/GPT_SoVITS/module/models_v5.py b/GPT_SoVITS/module/models_v5.py index c8f595bc..28702339 100644 --- a/GPT_SoVITS/module/models_v5.py +++ b/GPT_SoVITS/module/models_v5.py @@ -19,14 +19,34 @@ class CFMV5(CFM): self.use_step_embedding = False self.cfg_drop_text = False self.noise_temperature = V5_TEMPERATURE - self.use_static_cache = os.environ.get( - "GSVV5_CFM_STATIC_CACHE", os.environ.get("GSVV4_CFM_STATIC_CACHE", "1") - ) != "0" + self.use_static_cache = ( + os.environ.get("GSVV5_CFM_STATIC_CACHE", os.environ.get("GSVV4_CFM_STATIC_CACHE", "1")) != "0" + ) @torch.inference_mode() - def inference(self, mu, x_lens, prompt, n_timesteps, temperature=V5_TEMPERATURE, - inference_cfg_rate=1.30, generator=None): - return super().inference(mu, x_lens, prompt, n_timesteps, temperature, inference_cfg_rate, generator=generator) + def inference( + self, + mu, + x_lens, + prompt, + n_timesteps, + temperature=V5_TEMPERATURE, + inference_cfg_rate=1.30, + generator=None, + initial_noise=None, + all_valid=False, + ): + return super().inference( + mu, + x_lens, + prompt, + n_timesteps, + temperature, + inference_cfg_rate, + generator=generator, + initial_noise=initial_noise, + all_valid=all_valid, + ) def forward(self, x1, x_lens, prompt_lens, mu, use_grad_ckpt): b = x1.shape[0] diff --git a/GPT_SoVITS/module/v5_acoustic.py b/GPT_SoVITS/module/v5_acoustic.py new file mode 100644 index 00000000..bbf0becc --- /dev/null +++ b/GPT_SoVITS/module/v5_acoustic.py @@ -0,0 +1,164 @@ +"""Opt-in V5 acoustic scheduling; no padding, generated-output cache or new weights.""" + +from collections import OrderedDict, defaultdict + +import torch + + +@torch.inference_mode() +def infer_equal_length(cfm, mu, prompt, noise, steps, cfg): + lengths = torch.full((mu.shape[0],), mu.shape[1], dtype=torch.long, device=mu.device) + return cfm.inference(mu, lengths, prompt, steps, inference_cfg_rate=cfg, initial_noise=noise, all_valid=True) + + +@torch.inference_mode() +def synthesize_v5_mel_batch( + model, + reference_features, + targets, + reference_mel, + steps=4, + cfg=0.0, + max_batch=8, + noises=None, + stats=None, + runner=None, +): + """Batch independent windows, retaining the original within-segment dependency.""" + from module.models_v5 import ( + V5_MAX_TARGET_CHUNK_FRAMES, + V5_REFERENCE_FRAMES, + V5_ROLLING_TAIL_FRAMES, + V5_TOTAL_CHUNK_FRAMES, + ) + + if max_batch < 1: + raise ValueError("max_batch must be positive") + if not targets or any(t.shape[-1] < 1 for t in targets): + raise ValueError("nonempty targets required") + frames = min(reference_features.shape[-1], reference_mel.shape[-1]) + if frames < 1: + raise ValueError("nonempty reference required") + ref_mel = reference_mel[..., :frames][..., -V5_REFERENCE_FRAMES:] + ref_feat = reference_features[..., :frames][..., -V5_REFERENCE_FRAMES:] + frames = ref_mel.shape[-1] + chunk = min(V5_TOTAL_CHUNK_FRAMES - frames, V5_MAX_TARGET_CHUNK_FRAMES) + # Allocate in the original segment/window order and original individual shapes. + # Batching must not change the CUDA RNG draws, nor cache generated audio/noise. + if noises is None: + noises = [ + [ + torch.randn(1, model.cfm.in_channels, frames + part.shape[-1], device=target.device, dtype=target.dtype) + for part in target.split(chunk, dim=-1) + ] + for target in targets + ] + chunks = [list(t.split(chunk, dim=-1)) for t in targets] + results = [[] for _ in targets] + rolling_mel = [ref_mel for _ in targets] + rolling_feat = [ref_feat for _ in targets] + runner = runner or infer_equal_length + for wave in range(max(map(len, chunks))): + buckets = defaultdict(list) + for i, parts in enumerate(chunks): + if wave < len(parts): + buckets[parts[wave].shape[-1]].append(i) + for length, indices in buckets.items(): + for begin in range(0, len(indices), max_batch): + ids = indices[begin : begin + max_batch] + prompts, conditions, ns = [], [], [] + for i in ids: + if wave == 0: + prompt, feat = ref_mel, ref_feat + else: + tail = min(V5_ROLLING_TAIL_FRAMES, frames, rolling_mel[i].shape[-1], rolling_feat[i].shape[-1]) + prefix = frames - tail + prompt = torch.cat((ref_mel[..., :prefix], rolling_mel[i][..., -tail:]), -1) + feat = torch.cat((ref_feat[..., :prefix], rolling_feat[i][..., -tail:]), -1) + prompts.append(prompt) + conditions.append(torch.cat((feat, chunks[i][wave]), -1).transpose(2, 1)) + ns.append(noises[i][wave]) + mu, prompt, noise = (torch.cat(xs, 0) for xs in (conditions, prompts, ns)) + generated = runner(model.cfm, mu, prompt, noise, steps, cfg)[..., frames:] + if stats is not None: + stats.append({"batch": len(ids), "frames": frames + length, "wave": wave}) + for row, i in enumerate(ids): + # clone separates each output from graph/static/shared batch storage. + result = generated[row : row + 1].clone() + results[i].append(result) + rolling_mel[i] = result[..., -frames:].to(ref_mel.dtype) + rolling_feat[i] = chunks[i][wave][..., -frames:] + return [torch.cat(xs, -1) for xs in results] + + +class V5AcousticGraphRunner: + """Bounded per-pipeline graphs; callers must serialize use and copy outputs.""" + + def __init__(self, max_entries=64): + if max_entries < 1: + raise ValueError("max_entries must be positive") + self.max_entries = max_entries + self.entries = OrderedDict() + self.hits = self.misses = self.evictions = 0 + self.model_context = None + self.pool = None + + @torch.inference_mode() + def __call__(self, cfm, mu, prompt, noise, steps, cfg): + if mu.device.type != "cuda": + return infer_equal_length(cfm, mu, prompt, noise, steps, cfg) + parameter = next(cfm.parameters()) + context = (id(cfm), parameter.data_ptr(), parameter.dtype, parameter.device) + if self.model_context != context: + self.entries.clear() + self.pool = torch.cuda.graph_pool_handle() + self.model_context = context + # Graphs bind weight addresses: drop old entries after model/device/dtype changes. + key = ( + id(cfm), + tuple(mu.shape), + tuple(prompt.shape), + mu.dtype, + mu.device, + steps, + cfg, + cfm.use_conditioner_cache, + cfm.use_static_cache, + cfm.noise_temperature, + ) + if key in self.entries: + self.hits += 1 + entry = self.entries.pop(key) + self.entries[key] = entry + else: + self.misses += 1 + static_mu, static_prompt, static_noise = mu.clone(), prompt.clone(), noise.clone() + # Side-stream warmup initializes lazy kernels/rotary buffers before capture. + stream = torch.cuda.Stream(device=mu.device) + stream.wait_stream(torch.cuda.current_stream(mu.device)) + with torch.cuda.stream(stream): + for _ in range(2): + infer_equal_length(cfm, static_mu, static_prompt, static_noise, steps, cfg) + torch.cuda.current_stream(mu.device).wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, pool=self.pool): + output = infer_equal_length(cfm, static_mu, static_prompt, static_noise, steps, cfg) + entry = (static_mu, static_prompt, static_noise, graph, output) + if len(self.entries) >= self.max_entries: + self.entries.popitem(last=False) + self.evictions += 1 + self.entries[key] = entry + entry[0].copy_(mu) + entry[1].copy_(prompt) + entry[2].copy_(noise) + entry[3].replay() + # Caller immediately clones slices before the next shared-pool graph replay. + return entry[4] + + def clear(self): + self.entries.clear() + self.pool = None + self.model_context = None + + def stats(self): + return {"entries": len(self.entries), "hits": self.hits, "misses": self.misses, "evictions": self.evictions} diff --git a/docs/en/v5_acoustic_inference.md b/docs/en/v5_acoustic_inference.md new file mode 100644 index 00000000..e609ee56 --- /dev/null +++ b/docs/en/v5_acoustic_inference.md @@ -0,0 +1,94 @@ +# Opt-in V5 acoustic batching and CUDA Graphs + +The non-streaming V5 fast-inference path normally synthesizes each text segment +separately, even when GPT uses a large `batch_size`. This option batches +**equal-length acoustic windows from independent segments**, and can capture +the complete Euler sampling computation in CUDA Graphs. It uses the same +weights, sample steps, CFG and per-segment rolling context. + +## Enable + +With a config selecting `v5turbo` or `v5dev`: + +```bash +GSVV5_ACOUSTIC_BATCH_SIZE=8 GSVV5_ACOUSTIC_CUDA_GRAPH=1 \ + python api_v2.py -c path/to/v5_config.yaml +``` + +| Environment variable | Default | Meaning | +| --- | --- | --- | +| `GSVV5_ACOUSTIC_BATCH_SIZE` | `0` | `0` preserves the existing acoustic path; a positive value limits the acoustic microbatch size. Independent of the request's GPT `batch_size`. | +| `GSVV5_ACOUSTIC_CUDA_GRAPH` | `0` | `1` enables acoustic Graph capture when acoustic batching is enabled. CPU execution uses eager inference. | +| `GSVV5_ACOUSTIC_GRAPH_CAPACITY` | `64` | Maximum cached Graph shapes per pipeline, with LRU eviction. A count limit, not a byte limit. | + +Set `GSVV5_ACOUSTIC_CUDA_GRAPH=0` to use acoustic batching without first-shape +Graph capture costs. Unset these variables to use the existing path. + +This only affects the non-streaming `parallel_infer=True` V5 vocoder path. +Semantic streaming, training, other model versions and the GPT attention/Graph +options are unchanged. It does not batch separate API requests. Calls using a +single pipeline instance must remain serialized, as in the API pipeline lock. + +## Computation and compatibility + +- Windows are grouped by their exact target length, without padding. Later + windows of the same segment still wait for the previous generated tail. +- Reference conditioning is calculated once per acoustic batch. No generated + waveform, target conditioning or random noise is cached across requests. +- Noise is drawn in the original segment/window order and individual shapes + before scheduling. Reordering independent windows therefore does not change + which noise belongs to a window or the final RNG state. +- Equal-length windows have no padding; omitting their all-valid attention mask + permits Flash SDPA where available. Padded callers keep their original mask. +- Positional indices stay on the model device, avoiding a CPU-to-GPU transfer + that would prevent CUDA Graph capture. +- Graph inputs and noise are updated on every replay. Old graph references are + released on acoustic model reload; device/dtype changes invalidate the cache. + +Batching and changing the attention backend can produce FP16 rounding +differences. Waveforms are not promised to be bitwise identical. Enabling the +option does not reduce sample steps or remove rolling conditioning. + +## Costs and limits + +New shapes require eager warmup and capture, so a cold request may be slower. +Shape-diverse workloads can have a lower cache hit rate, and graph pools retain +GPU memory. Short single-segment inputs cannot benefit from segment batching. +The DiT computation and within-segment rolling dependency remain. + +The feature is opt-in because the speed/memory/cold-latency tradeoff depends on +the workload. Lower the acoustic batch size or disable acoustic Graphs when +memory or cold latency matters more than repeated-shape throughput. + +## Reproduce + +No checkpoints or recordings are included in the tests: + +```bash +python -m unittest test_v5_acoustic -v +python -m unittest test_api_v2_streaming test_official_streaming -q +``` + +With downloaded models, a local reference recording/transcript and a long +Chinese text file, run the following **in separate processes**. Both commands +measure preloaded requests, report the first request separately, then average +three formal requests. GPT uses the same legacy path in both cases to isolate +acoustic changes; WAV disk writes are outside the measured work. + +```bash +python tools/benchmark_v5_acoustic.py \ + --config path/to/v5_config.yaml --ref-audio path/to/reference.wav \ + --prompt-text 'Reference transcript' --text-file path/to/long_zh.txt \ + --output baseline.json + +python tools/benchmark_v5_acoustic.py \ + --config path/to/v5_config.yaml --ref-audio path/to/reference.wav \ + --prompt-text 'Reference transcript' --text-file path/to/long_zh.txt \ + --acoustic-batch-size 8 --acoustic-cuda-graph --output optimized.json +``` + +`peak_reserved_bytes` includes allocator/Graph pools retained by the process; +it is not the same as whole-device NVML memory usage. Reuse the same text, +reference, model/config, seed and GPT batch size, and check output duration +before comparing RTF. Short-utterance latency cannot be inferred from a +long-text large-batch throughput result. diff --git a/test_v5_acoustic.py b/test_v5_acoustic.py new file mode 100644 index 00000000..0c09076d --- /dev/null +++ b/test_v5_acoustic.py @@ -0,0 +1,137 @@ +"""V5 acoustic scheduling/CFM tests; no checkpoints or reference recordings needed.""" + +import sys +import unittest +from pathlib import Path +from types import SimpleNamespace + +import torch + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT / "GPT_SoVITS")) +from module.models_v5 import CFMV5, synthesize_v5_mel +from module.v5_acoustic import V5AcousticGraphRunner, synthesize_v5_mel_batch + +from GPT_SoVITS.f5_tts.model.backbones.dit import DiT + + +class ToyCFM(torch.nn.Module): + in_channels = 2 + noise_temperature = 0.875 + use_conditioner_cache = True + use_static_cache = True + + def __init__(self): + super().__init__() + self.scale = torch.nn.Parameter(torch.tensor(0.2)) + + def inference(self, mu, lengths, prompt, steps, inference_cfg_rate=0.0, initial_noise=None, all_valid=False): + noise = ( + torch.randn(mu.shape[0], 2, mu.shape[1], device=mu.device, dtype=mu.dtype) + if initial_noise is None + else initial_noise + ) + return mu.transpose(2, 1) * self.scale + noise * 0.1 + prompt.mean(-1, keepdim=True) * 0.3 + + +class SchedulerTests(unittest.TestCase): + def test_rng_order_lengths_and_rolling_context(self): + model = SimpleNamespace(version="v5turbo", cfm=ToyCFM()) + for reference_length in (17, 400, 600): + reference = torch.randn(1, 2, reference_length) + mel = torch.randn_like(reference) + chunk = min(1000 - min(reference_length, 500), 640) + targets = [torch.randn(1, 2, n) for n in (5, chunk, chunk * 2 + 13, chunk + 8, chunk * 3, 5)] + torch.manual_seed(22) + expected = [synthesize_v5_mel(model, reference, target, mel, 4, 0.0) for target in targets] + expected_rng = torch.get_rng_state() + torch.manual_seed(22) + stats = [] + actual = synthesize_v5_mel_batch(model, reference, targets, mel, max_batch=4, stats=stats) + self.assertTrue(all(torch.equal(a, b) for a, b in zip(expected, actual))) + self.assertTrue(torch.equal(expected_rng, torch.get_rng_state())) + self.assertEqual([x.shape[-1] for x in actual], [x.shape[-1] for x in targets]) + self.assertTrue(any(x["batch"] > 1 for x in stats)) + + def test_invalid_inputs(self): + model = SimpleNamespace(cfm=ToyCFM()) + reference = torch.zeros(1, 2, 10) + for targets, batch in (([], 4), ([reference], 0), ([reference[..., :0]], 4)): + with self.assertRaises(ValueError): + synthesize_v5_mel_batch(model, reference, targets, reference, max_batch=batch) + with self.assertRaises(ValueError): + synthesize_v5_mel_batch(model, reference[..., :0], [reference], reference) + + +class CFMTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + torch.manual_seed(1) + cls.cfm = CFMV5( + 4, DiT(dim=32, depth=1, heads=2, mel_dim=4, text_dim=16, conv_layers=1, use_step_embedding=False) + ).eval() + cls.mu = torch.randn(2, 15, 16) + cls.prompt = torch.randn(2, 4, 5) + cls.lengths = torch.tensor([15, 15]) + + def test_explicit_noise_and_cfg(self): + for cfg in (0.0, 1.3): + torch.manual_seed(7) + expected = self.cfm.inference(self.mu, self.lengths, self.prompt, 4, inference_cfg_rate=cfg) + torch.manual_seed(7) + noise = torch.randn(2, 4, 15) + actual = self.cfm.inference( + self.mu, self.lengths, self.prompt, 4, inference_cfg_rate=cfg, initial_noise=noise + ) + self.assertTrue(torch.equal(expected, actual)) + optimized = self.cfm.inference( + self.mu, self.lengths, self.prompt, 4, inference_cfg_rate=cfg, initial_noise=noise, all_valid=True + ) + torch.testing.assert_close(actual, optimized, atol=1e-5, rtol=1e-5) + + def test_padded_mask_is_preserved(self): + cache = self.cfm.estimator.prepare_static_cache( + torch.zeros(2, 4, 15), torch.tensor([15, 11]), self.mu.transpose(2, 1) + ) + self.assertTrue(cache["mask"][0].all()) + self.assertTrue(cache["mask"][1, :11].all()) + self.assertFalse(cache["mask"][1, 11:].any()) + cache = self.cfm.estimator.prepare_static_cache( + torch.zeros(2, 4, 15), self.lengths, self.mu.transpose(2, 1), all_valid=True, use_negative_condition=False + ) + self.assertIsNone(cache["mask"]) + self.assertIs(cache["condition"], cache["negative_condition"]) + + def test_invalid_noise(self): + with self.assertRaises(ValueError): + self.cfm.inference(self.mu, self.lengths, self.prompt, 4, initial_noise=torch.zeros(2, 4, 14)) + + +@unittest.skipUnless(torch.cuda.is_available(), "CUDA Graph tests require CUDA") +class GraphTests(unittest.TestCase): + def test_replay_eviction_and_model_invalidation(self): + runner = V5AcousticGraphRunner(max_entries=2) + model = ToyCFM().eval().cuda() + for length in (6, 6, 7, 8, 6): + mu = torch.randn(1, length, 2, device="cuda") + prompt = torch.randn(1, 2, 2, device="cuda") + noise = torch.randn(1, 2, length, device="cuda") + expected = model.inference(mu, None, prompt, 4, initial_noise=noise) + actual = runner(model, mu, prompt, noise, 4, 0.0).clone() + self.assertTrue(torch.equal(expected, actual)) + self.assertLessEqual(len(runner.entries), 2) + self.assertEqual(runner.hits, 1) + self.assertEqual(runner.evictions, 2) + model = ToyCFM().eval().cuda() + model.scale.data.fill_(0.7) + expected = model.inference(mu, None, prompt, 4, initial_noise=noise) + self.assertTrue(torch.equal(runner(model, mu, prompt, noise, 4, 0.0), expected)) + self.assertEqual(len(runner.entries), 1) + runner.clear() + self.assertFalse(runner.entries) + self.assertIsNone(runner.model_context) + + +if __name__ == "__main__": + torch.set_num_threads(2) + unittest.main() diff --git a/tools/benchmark_v5_acoustic.py b/tools/benchmark_v5_acoustic.py new file mode 100644 index 00000000..b0723c77 --- /dev/null +++ b/tools/benchmark_v5_acoustic.py @@ -0,0 +1,120 @@ +"""Measure preloaded, non-streaming V5 requests without private model/test assets.""" + +import argparse +import hashlib +import json +import os +import statistics +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / "GPT_SoVITS")] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", required=True) + parser.add_argument("--ref-audio", required=True) + parser.add_argument("--prompt-text", required=True) + parser.add_argument("--text-file", required=True) + parser.add_argument("--batch-size", type=int, default=40) + parser.add_argument("--acoustic-batch-size", type=int, default=0) + parser.add_argument("--acoustic-cuda-graph", action="store_true") + parser.add_argument("--runs", type=int, default=3) + parser.add_argument("--output") + args = parser.parse_args() + if args.runs < 1 or args.batch_size < 1 or args.acoustic_batch_size < 0: + parser.error("runs/batch-size must be positive and acoustic-batch-size nonnegative") + if args.acoustic_cuda_graph and not args.acoustic_batch_size: + parser.error("acoustic-cuda-graph requires acoustic-batch-size > 0") + config = str(Path(args.config).resolve()) + reference = str(Path(args.ref_audio).resolve()) + text = Path(args.text_file).read_text(encoding="utf-8") + output = Path(args.output).resolve() if args.output else None + os.chdir(ROOT) + os.environ["GSVV5_ACOUSTIC_BATCH_SIZE"] = str(args.acoustic_batch_size) + os.environ["GSVV5_ACOUSTIC_CUDA_GRAPH"] = "1" if args.acoustic_cuda_graph else "0" + + import torch + from TTS_infer_pack.TTS import TTS, TTS_Config + + torch.set_num_threads(2) + torch.set_num_interop_threads(1) + pipeline = TTS(TTS_Config(config)) + if pipeline.configs.version not in {"v5turbo", "v5dev"}: + parser.error("config must select a V5 model") + device = torch.device(pipeline.configs.device) + if device.type != "cuda": + parser.error("this benchmark requires a CUDA config") + request = { + "text": text, + "text_lang": "all_zh", + "ref_audio_path": reference, + "prompt_text": args.prompt_text, + "prompt_lang": "all_zh", + "text_split_method": "cut1", + "batch_size": args.batch_size, + "parallel_infer": True, + "split_bucket": True, + "batch_threshold": 0.75, + "fragment_interval": 0.3, + "seed": 20261020, + "top_k": 15, + "top_p": 1.0, + "temperature": 1.0, + "repetition_penalty": 1.35, + "speed_factor": 1.0, + "sample_steps": 4 if pipeline.configs.version == "v5turbo" else 32, + "cfg_rate": 0.0 if pipeline.configs.version == "v5turbo" else 1.3, + "return_fragment": False, + "streaming_mode": False, + "use_cuda_graph": False, + "use_flash_attention": False, + } + records = [] + for repeat in range(args.runs + 1): + torch.cuda.synchronize(device) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + pieces = list(pipeline.run(request)) + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + if len(pieces) != 1: + raise RuntimeError("Expected one non-streaming waveform") + rate, audio = pieces[0] + duration = len(audio) / rate + if duration <= 0: + raise RuntimeError("Empty waveform") + records.append( + { + "warmup": repeat == 0, + "seconds": elapsed, + "audio_seconds": duration, + "rtf": elapsed / duration, + "peak_allocated_bytes": torch.cuda.max_memory_allocated(device), + "peak_reserved_bytes": torch.cuda.max_memory_reserved(device), + } + ) + result = { + "gpu": torch.cuda.get_device_name(device), + "torch": torch.__version__, + "model": pipeline.configs.version, + "is_half": pipeline.configs.is_half, + "text_sha256": hashlib.sha256(text.encode()).hexdigest(), + "batch_size": args.batch_size, + "acoustic_batch_size": args.acoustic_batch_size, + "acoustic_cuda_graph": args.acoustic_cuda_graph, + "mean_seconds": statistics.mean(r["seconds"] for r in records[1:]), + "mean_rtf": statistics.mean(r["rtf"] for r in records[1:]), + "records": records, + } + rendered = json.dumps(result, indent=2) + if output: + output.write_text(rendered, encoding="utf-8") + print(rendered) + + +if __name__ == "__main__": + main()