[Perf][CosyVoice3] Bounded-window incremental HiFT vocoder streaming (#7521)
Signed-off-by: Zhengyuan Su <su.zhengyuan@u.nus.edu>
This commit is contained in:
1 parent
fa639b889e
commit
538eddd74d
8 files changed
+1224
-84
No files matched your search
@@ -98,6 +98,46 @@ class ResBlock(torch.nn.Module):
|
||||
remove_weight_norm(self.convs2[idx])
|
||||
|
||||
|
||||
def _carry_phase_at_boundary(
|
||||
cum_total: torch.Tensor,
|
||||
phase_acc: torch.Tensor | None,
|
||||
next_overlap: int,
|
||||
*,
|
||||
dim: int,
|
||||
trim: int = 0,
|
||||
) -> torch.Tensor | None:
|
||||
"""Accumulated phase (mod 1) carried into the next streaming window.
|
||||
|
||||
Shared by SineGen and SineGen2 so harmonic phase stays continuous across
|
||||
chunk boundaries when HiFT runs over a bounded mel window. ``cum_total``
|
||||
must already include ``phase_acc``; falls back to it unchanged if
|
||||
``next_overlap`` (+ ``trim``) covers the whole window.
|
||||
"""
|
||||
length = cum_total.shape[dim]
|
||||
if next_overlap >= length + trim:
|
||||
return phase_acc
|
||||
idx = length + trim - next_overlap - 1
|
||||
return cum_total.narrow(dim, idx, 1) % 1
|
||||
|
||||
|
||||
def _wrapped_slice(buf: torch.Tensor, offset: int, length: int, dim: int = 1) -> torch.Tensor:
|
||||
"""``length`` elements of ``buf`` along ``dim`` starting at ``offset``,
|
||||
wrapping (mod ``buf.shape[dim]``) instead of running past the end and
|
||||
coming back short. Shared by SineGen/SineGen2/SourceModuleHnNSF's
|
||||
position-indexed noise buffers, now that streams can outlast their 300s.
|
||||
"""
|
||||
n = buf.shape[dim]
|
||||
start = offset % n
|
||||
parts = []
|
||||
remaining = length
|
||||
while remaining > 0:
|
||||
take = min(remaining, n - start)
|
||||
parts.append(buf.narrow(dim, start, take))
|
||||
remaining -= take
|
||||
start = 0
|
||||
return parts[0] if len(parts) == 1 else torch.cat(parts, dim=dim)
|
||||
|
||||
|
||||
class SineGen(torch.nn.Module):
|
||||
"""Definition of sine generator
|
||||
SineGen(samp_rate, harmonic_num = 0,
|
||||
@@ -114,13 +154,24 @@ class SineGen(torch.nn.Module):
|
||||
segment is always sin(np.pi) or cos(0)
|
||||
"""
|
||||
|
||||
def __init__(self, samp_rate, harmonic_num=0, sine_amp=0.1, noise_std=0.003, voiced_threshold=0):
|
||||
def __init__(self, samp_rate, harmonic_num=0, sine_amp=0.1, noise_std=0.003, voiced_threshold=0, causal=False):
|
||||
super().__init__()
|
||||
self.sine_amp = sine_amp
|
||||
self.noise_std = noise_std
|
||||
self.harmonic_num = harmonic_num
|
||||
self.sampling_rate = samp_rate
|
||||
self.voiced_threshold = voiced_threshold
|
||||
self.causal = causal
|
||||
# Fixed per model instance like SineGen2's rand_ini, not redrawn per
|
||||
# call, or each harmonic jumps to a new random phase every window.
|
||||
self.phase_vec = Uniform(low=-np.pi, high=np.pi).sample(sample_shape=(1, harmonic_num + 1, 1))
|
||||
self.phase_vec[:, 0, :] = 0
|
||||
if causal:
|
||||
self.register_buffer(
|
||||
"noise_buf",
|
||||
torch.randn(1, 300 * 24000, harmonic_num + 1),
|
||||
persistent=False,
|
||||
)
|
||||
|
||||
def _f02uv(self, f0):
|
||||
# generate uv signal
|
||||
@@ -128,22 +179,32 @@ class SineGen(torch.nn.Module):
|
||||
return uv
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, f0):
|
||||
def forward(self, f0, phase_acc=None, next_overlap=0, trim=0, noise_offset=0):
|
||||
"""sine_tensor, uv = forward(f0)
|
||||
input F0: tensor(batchsize=1, dim=1, length)
|
||||
f0 for unvoiced steps should be 0
|
||||
output sine_tensor: tensor(batchsize=1, length, dim)
|
||||
output uv: tensor(batchsize=1, length, 1)
|
||||
|
||||
``next_overlap`` and ``trim`` are sample-indexed here (``f0`` arrives
|
||||
post-``f0_upsamp``), unlike SineGen2 which downsamples to mel rate
|
||||
before its own cumsum -- callers must scale both by samples-per-mel.
|
||||
"""
|
||||
f0 = f0.transpose(1, 2)
|
||||
F_mat = torch.zeros((f0.size(0), self.harmonic_num + 1, f0.size(-1))).to(f0.device)
|
||||
for i in range(self.harmonic_num + 1):
|
||||
F_mat[:, i : i + 1, :] = f0 * (i + 1) / self.sampling_rate
|
||||
|
||||
theta_mat = 2 * np.pi * (torch.cumsum(F_mat, dim=-1) % 1)
|
||||
u_dist = Uniform(low=-np.pi, high=np.pi)
|
||||
phase_vec = u_dist.sample(sample_shape=(f0.size(0), self.harmonic_num + 1, 1)).to(F_mat.device)
|
||||
phase_vec[:, 0, :] = 0
|
||||
cum = torch.cumsum(F_mat, dim=-1)
|
||||
cum_total = cum if phase_acc is None else phase_acc + cum
|
||||
theta_mat = 2 * np.pi * (cum_total % 1)
|
||||
new_phase_acc = _carry_phase_at_boundary(cum_total, phase_acc, next_overlap, dim=-1, trim=trim)
|
||||
if self.causal:
|
||||
phase_vec = self.phase_vec.to(F_mat.device)
|
||||
else:
|
||||
u_dist = Uniform(low=-np.pi, high=np.pi)
|
||||
phase_vec = u_dist.sample(sample_shape=(f0.size(0), self.harmonic_num + 1, 1)).to(F_mat.device)
|
||||
phase_vec[:, 0, :] = 0
|
||||
|
||||
# generate sine waveforms
|
||||
sine_waves = self.sine_amp * torch.sin(theta_mat + phase_vec)
|
||||
@@ -155,11 +216,16 @@ class SineGen(torch.nn.Module):
|
||||
# std = self.sine_amp/3 -> max value ~ self.sine_amp
|
||||
# . for voiced regions is self.noise_std
|
||||
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
|
||||
noise = noise_amp * torch.randn_like(sine_waves)
|
||||
if self.training is False and self.causal is True:
|
||||
noise = noise_amp * _wrapped_slice(self.noise_buf, noise_offset, sine_waves.shape[-1]).transpose(1, 2)
|
||||
else:
|
||||
noise = noise_amp * torch.randn_like(sine_waves)
|
||||
|
||||
# first: set the unvoiced part to 0 by uv
|
||||
# then: additive noise
|
||||
sine_waves = sine_waves * uv + noise
|
||||
if self.causal:
|
||||
return sine_waves.transpose(1, 2), uv.transpose(1, 2), noise, new_phase_acc
|
||||
return sine_waves.transpose(1, 2), uv.transpose(1, 2), noise
|
||||
|
||||
|
||||
@@ -215,7 +281,7 @@ class SineGen2(torch.nn.Module):
|
||||
uv = (f0 > self.voiced_threshold).type(torch.float32)
|
||||
return uv
|
||||
|
||||
def _f02sine(self, f0_values):
|
||||
def _f02sine(self, f0_values, phase_acc=None, next_overlap=0, trim=0):
|
||||
"""f0_values: (batchsize, length, dim)
|
||||
where dim indicates fundamental tone and overtones
|
||||
"""
|
||||
@@ -223,9 +289,12 @@ class SineGen2(torch.nn.Module):
|
||||
# because 2 * np.pi * n doesn't affect phase
|
||||
rad_values = (f0_values / self.sampling_rate) % 1
|
||||
|
||||
# initial phase noise (no noise for fundamental component)
|
||||
# initial phase noise (no noise for fundamental component). Only applied
|
||||
# on the genuine first chunk of a stream (see rationale above the class);
|
||||
# phase_acc is None exactly when there is no carried-forward phase yet.
|
||||
if self.training is False and self.causal is True:
|
||||
rad_values[:, 0, :] = rad_values[:, 0, :] + self.rand_ini.to(rad_values.device)
|
||||
if phase_acc is None:
|
||||
rad_values[:, 0, :] = rad_values[:, 0, :] + self.rand_ini.to(rad_values.device)
|
||||
else:
|
||||
rand_ini = torch.rand(f0_values.shape[0], f0_values.shape[2], device=f0_values.device)
|
||||
rand_ini[:, 0] = 0
|
||||
@@ -237,7 +306,10 @@ class SineGen2(torch.nn.Module):
|
||||
rad_values.transpose(1, 2), scale_factor=1 / self.upsample_scale, mode="linear"
|
||||
).transpose(1, 2)
|
||||
|
||||
phase = torch.cumsum(rad_values, dim=1) * 2 * np.pi
|
||||
cum = torch.cumsum(rad_values, dim=1)
|
||||
phase = cum if phase_acc is None else cum + phase_acc
|
||||
new_phase_acc = _carry_phase_at_boundary(phase, phase_acc, next_overlap, dim=1, trim=trim)
|
||||
phase = phase * 2 * np.pi
|
||||
phase = torch.nn.functional.interpolate(
|
||||
phase.transpose(1, 2) * self.upsample_scale,
|
||||
scale_factor=self.upsample_scale,
|
||||
@@ -272,9 +344,10 @@ class SineGen2(torch.nn.Module):
|
||||
|
||||
# get the sines
|
||||
sines = torch.cos(i_phase * 2 * np.pi)
|
||||
return sines
|
||||
new_phase_acc = None
|
||||
return (sines, new_phase_acc) if self.causal else sines
|
||||
|
||||
def forward(self, f0):
|
||||
def forward(self, f0, phase_acc=None, next_overlap=0, trim=0, noise_offset=0):
|
||||
"""sine_tensor, uv = forward(f0)
|
||||
input F0: tensor(batchsize=1, length, dim=1)
|
||||
f0 for unvoiced steps should be 0
|
||||
@@ -284,8 +357,12 @@ class SineGen2(torch.nn.Module):
|
||||
# fundamental component
|
||||
fn = torch.multiply(f0, self.harmonic_ids)
|
||||
|
||||
# generate sine waveforms
|
||||
sine_waves = self._f02sine(fn) * self.sine_amp
|
||||
if self.causal:
|
||||
sine_waves, new_phase_acc = self._f02sine(fn, phase_acc, next_overlap, trim)
|
||||
else:
|
||||
sine_waves = self._f02sine(fn)
|
||||
new_phase_acc = None
|
||||
sine_waves = sine_waves * self.sine_amp
|
||||
|
||||
# generate uv signal
|
||||
uv = self._f02uv(f0)
|
||||
@@ -295,14 +372,15 @@ class SineGen2(torch.nn.Module):
|
||||
# . for voiced regions is self.noise_std
|
||||
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
|
||||
if self.training is False and self.causal is True:
|
||||
noise = noise_amp * self.sine_waves[:, : sine_waves.shape[1]].to(sine_waves.device)
|
||||
# indexed by absolute sample position, not window-relative position
|
||||
noise = noise_amp * _wrapped_slice(self.sine_waves, noise_offset, sine_waves.shape[1]).to(sine_waves.device)
|
||||
else:
|
||||
noise = noise_amp * torch.randn_like(sine_waves)
|
||||
|
||||
# first: set the unvoiced part to 0 by uv
|
||||
# then: additive noise
|
||||
sine_waves = sine_waves * uv + noise
|
||||
return sine_waves, uv, noise
|
||||
return (sine_waves, uv, noise, new_phase_acc) if self.causal else (sine_waves, uv, noise)
|
||||
|
||||
|
||||
class SourceModuleHnNSF(torch.nn.Module):
|
||||
@@ -338,10 +416,13 @@ class SourceModuleHnNSF(torch.nn.Module):
|
||||
|
||||
self.sine_amp = sine_amp
|
||||
self.noise_std = add_noise_std
|
||||
self.upsample_scale = upsample_scale
|
||||
|
||||
# to produce sine waveforms
|
||||
if sinegen_type == "1":
|
||||
self.l_sin_gen = SineGen(sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshold)
|
||||
self.l_sin_gen = SineGen(
|
||||
sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshold, causal=causal
|
||||
)
|
||||
else:
|
||||
self.l_sin_gen = SineGen2(
|
||||
sampling_rate, upsample_scale, harmonic_num, sine_amp, add_noise_std, voiced_threshold, causal=causal
|
||||
@@ -354,24 +435,38 @@ class SourceModuleHnNSF(torch.nn.Module):
|
||||
if causal is True:
|
||||
self.uv = torch.rand(1, 300 * 24000, 1)
|
||||
|
||||
def forward(self, x):
|
||||
def forward(self, x, phase_acc=None, uv_offset=0, next_overlap=0, trim=0):
|
||||
"""
|
||||
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
||||
F0_sampled (batchsize, length, 1)
|
||||
Sine_source (batchsize, length, 1)
|
||||
noise_source (batchsize, length 1)
|
||||
"""
|
||||
# source for harmonic branch
|
||||
with torch.no_grad():
|
||||
sine_wavs, uv, _ = self.l_sin_gen(x)
|
||||
if not self.causal:
|
||||
sine_wavs, uv, _ = self.l_sin_gen(x)
|
||||
new_phase_acc = None
|
||||
elif isinstance(self.l_sin_gen, SineGen):
|
||||
# next_overlap/trim arrive in mel frames; SineGen needs samples.
|
||||
sine_wavs, uv, _, new_phase_acc = self.l_sin_gen(
|
||||
x,
|
||||
phase_acc,
|
||||
next_overlap * self.upsample_scale,
|
||||
trim * self.upsample_scale,
|
||||
noise_offset=uv_offset,
|
||||
)
|
||||
else:
|
||||
sine_wavs, uv, _, new_phase_acc = self.l_sin_gen(
|
||||
x, phase_acc, next_overlap, trim, noise_offset=uv_offset
|
||||
)
|
||||
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
|
||||
|
||||
# source for noise branch, in the same shape as uv
|
||||
if self.training is False and self.causal is True:
|
||||
noise = self.uv[:, : uv.shape[1]] * self.sine_amp / 3
|
||||
noise = _wrapped_slice(self.uv, uv_offset, uv.shape[1]) * self.sine_amp / 3
|
||||
else:
|
||||
noise = torch.randn_like(uv) * self.sine_amp / 3
|
||||
return sine_merge, noise, uv
|
||||
return sine_merge, noise, uv, new_phase_acc
|
||||
|
||||
|
||||
class HiFTGenerator(nn.Module):
|
||||
@@ -606,7 +701,7 @@ class HiFTGenerator(nn.Module):
|
||||
f0 = self.f0_predictor(speech_feat)
|
||||
# f0->source
|
||||
s = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
|
||||
s, _, _ = self.m_source(s)
|
||||
s, _, _, _ = self.m_source(s)
|
||||
s = s.transpose(1, 2)
|
||||
# mel+source->speech
|
||||
generated_speech = self.decode(x=speech_feat, s=s)
|
||||
@@ -622,7 +717,7 @@ class HiFTGenerator(nn.Module):
|
||||
f0 = self.f0_predictor(speech_feat)
|
||||
# f0->source
|
||||
s = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
|
||||
s, _, _ = self.m_source(s)
|
||||
s, _, _, _ = self.m_source(s)
|
||||
s = s.transpose(1, 2)
|
||||
# use cache_source to avoid glitch
|
||||
if cache_source.shape[2] != 0:
|
||||
@@ -785,14 +880,28 @@ class CausalHiFTGenerator(HiFTGenerator):
|
||||
return x
|
||||
|
||||
@torch.inference_mode()
|
||||
def inference(self, speech_feat: torch.Tensor, finalize: bool = True) -> torch.Tensor:
|
||||
def inference(
|
||||
self,
|
||||
speech_feat: torch.Tensor,
|
||||
finalize: bool = True,
|
||||
phase_acc: torch.Tensor | None = None,
|
||||
uv_offset: int = 0,
|
||||
next_overlap: int = 0,
|
||||
trim: int = 0,
|
||||
f0_margin: int = 0,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
# mel->f0 NOTE f0_predictor precision is crucial for causal inference, move
|
||||
# self.f0_predictor to cpu if necessary
|
||||
self.f0_predictor.to("cpu")
|
||||
f0 = self.f0_predictor(speech_feat.cpu(), finalize=finalize).to(speech_feat)
|
||||
if f0_margin > 0:
|
||||
f0 = f0[:, f0_margin:]
|
||||
speech_feat = speech_feat[:, :, f0_margin:]
|
||||
# f0->source
|
||||
s = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
|
||||
s, _, _ = self.m_source(s)
|
||||
s, _, _, new_phase_acc = self.m_source(
|
||||
s, phase_acc=phase_acc, uv_offset=uv_offset, next_overlap=next_overlap, trim=trim
|
||||
)
|
||||
s = s.transpose(1, 2)
|
||||
if finalize is True:
|
||||
generated_speech = self.decode(x=speech_feat, s=s, finalize=finalize)
|
||||
@@ -800,7 +909,7 @@ class CausalHiFTGenerator(HiFTGenerator):
|
||||
generated_speech = self.decode(
|
||||
x=speech_feat[:, :, : -self.f0_predictor.condnet[0].causal_padding], s=s, finalize=finalize
|
||||
)
|
||||
return generated_speech, s
|
||||
return generated_speech, s, new_phase_acc
|
||||
|
||||
|
||||
class CausalConv1dUpsample(torch.nn.Conv1d):
|
||||
@@ -954,6 +1063,11 @@ class CausalConvRNNF0Predictor(nn.Module):
|
||||
nn.ELU(),
|
||||
)
|
||||
self.classifier = nn.Linear(in_features=cond_channels, out_features=self.num_class)
|
||||
self.left_context_frames = sum(
|
||||
layer.causal_padding
|
||||
for layer in self.condnet
|
||||
if isinstance(layer, CausalConv1d) and layer.causal_type == "left"
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor, finalize: bool = True) -> torch.Tensor:
|
||||
if finalize is True:
|
||||
|
||||
@@ -9,10 +9,8 @@ This module contains the code2wav (token-to-waveform) stage which uses:
|
||||
3. HiFiGAN vocoder for waveform synthesis
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from typing import cast
|
||||
from typing import TypedDict, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -39,6 +37,21 @@ from vllm_omni.transformers_utils.configs.cosyvoice3 import CosyVoice3Config
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class StreamingFlowItem(TypedDict, total=False):
|
||||
"""One entry of the batched-streaming item list passed to forward_streaming_batch."""
|
||||
|
||||
index: int
|
||||
req_id: str | None
|
||||
stream_finished: bool
|
||||
token: torch.Tensor
|
||||
prompt_token: torch.Tensor
|
||||
prompt_feat: torch.Tensor
|
||||
embedding: torch.Tensor
|
||||
cache_state: dict[str, torch.Tensor] | None
|
||||
token_offset_tokens: int
|
||||
finalize: bool
|
||||
|
||||
|
||||
class CosyVoice3Code2Wav(nn.Module):
|
||||
"""CosyVoice3 Code2Wav stage for token-to-waveform conversion.
|
||||
|
||||
@@ -119,6 +132,10 @@ class CosyVoice3Code2Wav(nn.Module):
|
||||
self.mel_cache_len = 20
|
||||
self.source_cache_len = int(self.mel_cache_len * 256)
|
||||
self.speech_window = np.hamming(2 * self.source_cache_len)
|
||||
# Must cover decode()'s own causal receptive field, not just the F0
|
||||
# margin; window_len=48 already passes
|
||||
# test_incremental_hift_bounded_window_is_close, so 64 has headroom.
|
||||
self._hift_window_len = 64
|
||||
|
||||
@property
|
||||
def input_frame_rate(self) -> int:
|
||||
@@ -226,40 +243,79 @@ class CosyVoice3Code2Wav(nn.Module):
|
||||
chunk_mel = feat.to(device=hift_weight.device, dtype=hift_weight.dtype)
|
||||
|
||||
cached_mel = None if not cache_state else cache_state.get("mel")
|
||||
speech_offset_obj = None if not cache_state else cache_state.get("speech_offset")
|
||||
try:
|
||||
speech_offset = int(speech_offset_obj) if speech_offset_obj is not None else 0
|
||||
except (TypeError, ValueError):
|
||||
speech_offset = 0
|
||||
|
||||
cached_offset = 0 if not cache_state else int(cache_state.get("mel_offset", 0))
|
||||
window_len = self._hift_window_len
|
||||
samples_per_mel = int(np.prod(self.hift.upsample_rates) * self.hift.istft_params["hop_len"])
|
||||
trim = int(self.hift.f0_predictor.condnet[0].causal_padding)
|
||||
f0_margin_frames = int(self.hift.f0_predictor.left_context_frames)
|
||||
f0_margin = 0
|
||||
if isinstance(cached_mel, torch.Tensor) and cached_mel.numel() > 0:
|
||||
cached_mel = cached_mel.to(device=chunk_mel.device, dtype=chunk_mel.dtype)
|
||||
tts_mel = torch.cat([cached_mel, chunk_mel], dim=-1) if chunk_mel.numel() > 0 else cached_mel
|
||||
total_hist = cached_mel.shape[-1]
|
||||
overlap = min(window_len + trim, total_hist)
|
||||
window_mel = torch.cat([cached_mel[..., -overlap:], chunk_mel], dim=-1)
|
||||
window_offset = cached_offset + total_hist - overlap
|
||||
uv_offset = window_offset * samples_per_mel
|
||||
f0_margin = min(f0_margin_frames, total_hist - overlap)
|
||||
f0_input_mel = (
|
||||
torch.cat(
|
||||
[cached_mel[..., total_hist - overlap - f0_margin : total_hist - overlap], window_mel], dim=-1
|
||||
)
|
||||
if f0_margin > 0
|
||||
else window_mel
|
||||
)
|
||||
else:
|
||||
tts_mel = chunk_mel
|
||||
window_mel = chunk_mel
|
||||
f0_input_mel = chunk_mel
|
||||
window_offset = 0
|
||||
uv_offset = 0
|
||||
|
||||
if tts_mel.shape[-1] == 0:
|
||||
phase_acc = None if not cache_state else cache_state.get("phase_acc")
|
||||
if phase_acc is not None:
|
||||
phase_acc = phase_acc.to(device=chunk_mel.device, dtype=chunk_mel.dtype)
|
||||
|
||||
if window_mel.shape[-1] == 0:
|
||||
tts_speech = torch.zeros((chunk_mel.shape[0], 1, 0), device=chunk_mel.device, dtype=chunk_mel.dtype)
|
||||
new_phase_acc = phase_acc
|
||||
else:
|
||||
tts_speech, _ = self.hift.inference(speech_feat=tts_mel, finalize=finalize)
|
||||
next_overlap = min(window_len + trim, window_mel.shape[-1])
|
||||
# On finalize the F0 predictor consumes the whole window (it does not
|
||||
# hold back `trim` frames), so trim must not inflate the phase-carry
|
||||
# index -- it would point past the end of a short window.
|
||||
carry_trim = 0 if finalize else trim
|
||||
tts_speech, _, new_phase_acc = self.hift.inference(
|
||||
speech_feat=f0_input_mel,
|
||||
finalize=finalize,
|
||||
phase_acc=phase_acc,
|
||||
uv_offset=uv_offset,
|
||||
next_overlap=next_overlap,
|
||||
trim=carry_trim,
|
||||
f0_margin=f0_margin,
|
||||
)
|
||||
|
||||
tts_speech = tts_speech.reshape(tts_speech.shape[0], -1)
|
||||
speech_offset = max(0, min(speech_offset, int(tts_speech.shape[-1])))
|
||||
emitted_speech = tts_speech[:, speech_offset:]
|
||||
new_samples = chunk_mel.shape[-1] * samples_per_mel
|
||||
if finalize:
|
||||
frames_withheld_per_chunk = trim + self.hift.conv_pre_look_right + 1
|
||||
released = frames_withheld_per_chunk * samples_per_mel
|
||||
emitted_speech = tts_speech[:, -(new_samples + released) :]
|
||||
else:
|
||||
emitted_speech = tts_speech[:, -new_samples:] if new_samples > 0 else tts_speech[:, :0]
|
||||
|
||||
if finalize:
|
||||
return emitted_speech.reshape(emitted_speech.shape[0], 1, -1), None
|
||||
|
||||
new_state = {
|
||||
"mel": tts_mel.detach().cpu().contiguous(),
|
||||
"speech_offset": int(tts_speech.shape[-1]),
|
||||
"mel": f0_input_mel.detach().cpu().contiguous(),
|
||||
"mel_offset": window_offset - f0_margin,
|
||||
"phase_acc": new_phase_acc.detach().cpu().contiguous() if new_phase_acc is not None else None,
|
||||
}
|
||||
return emitted_speech.reshape(emitted_speech.shape[0], 1, -1), new_state
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward_streaming_batch(
|
||||
self,
|
||||
items: list[dict[str, object]],
|
||||
items: list[StreamingFlowItem],
|
||||
*,
|
||||
n_timesteps: int = 10,
|
||||
) -> list[tuple[torch.Tensor, dict[str, torch.Tensor] | None]]:
|
||||
@@ -270,20 +326,16 @@ class CosyVoice3Code2Wav(nn.Module):
|
||||
group and passed to the flow as per-row token lengths.
|
||||
"""
|
||||
results: list[tuple[torch.Tensor, dict[str, torch.Tensor] | None] | None] = [None] * len(items)
|
||||
groups: dict[tuple[int, int, int, bool], list[tuple[int, dict[str, object]]]] = {}
|
||||
groups: dict[tuple[int, int, int, bool], list[tuple[int, StreamingFlowItem]]] = {}
|
||||
for index, item in enumerate(items):
|
||||
token = item["token"]
|
||||
prompt_token = item["prompt_token"]
|
||||
prompt_feat = item["prompt_feat"]
|
||||
embedding = item["embedding"]
|
||||
assert isinstance(token, torch.Tensor)
|
||||
assert isinstance(prompt_token, torch.Tensor)
|
||||
assert isinstance(prompt_feat, torch.Tensor)
|
||||
assert isinstance(embedding, torch.Tensor)
|
||||
assert isinstance(item["token"], torch.Tensor)
|
||||
assert isinstance(item["prompt_token"], torch.Tensor)
|
||||
assert isinstance(item["prompt_feat"], torch.Tensor)
|
||||
assert isinstance(item["embedding"], torch.Tensor)
|
||||
key = (
|
||||
int(prompt_token.shape[1]),
|
||||
int(prompt_feat.shape[1]),
|
||||
int(embedding.shape[1]),
|
||||
int(item["prompt_token"].shape[1]),
|
||||
int(item["prompt_feat"].shape[1]),
|
||||
int(item["embedding"].shape[1]),
|
||||
bool(item.get("finalize", False)),
|
||||
)
|
||||
groups.setdefault(key, []).append((index, item))
|
||||
@@ -305,11 +357,11 @@ class CosyVoice3Code2Wav(nn.Module):
|
||||
if len(group) == 1:
|
||||
index, item = group[0]
|
||||
result = self.forward_streaming(
|
||||
token=item["token"], # type: ignore[arg-type]
|
||||
prompt_token=item["prompt_token"], # type: ignore[arg-type]
|
||||
prompt_feat=item["prompt_feat"], # type: ignore[arg-type]
|
||||
embedding=item["embedding"], # type: ignore[arg-type]
|
||||
cache_state=item.get("cache_state"), # type: ignore[arg-type]
|
||||
token=item["token"],
|
||||
prompt_token=item["prompt_token"],
|
||||
prompt_feat=item["prompt_feat"],
|
||||
embedding=item["embedding"],
|
||||
cache_state=item.get("cache_state"),
|
||||
n_timesteps=n_timesteps,
|
||||
token_offset_tokens=int(item.get("token_offset_tokens", 0)),
|
||||
finalize=bool(item.get("finalize", False)),
|
||||
@@ -318,15 +370,13 @@ class CosyVoice3Code2Wav(nn.Module):
|
||||
continue
|
||||
|
||||
token_tensors = [item["token"] for _, item in group]
|
||||
assert all(isinstance(token, torch.Tensor) for token in token_tensors)
|
||||
token_lens = torch.tensor(
|
||||
[int(token.shape[1]) for token in token_tensors], # type: ignore[union-attr]
|
||||
[int(token.shape[1]) for token in token_tensors],
|
||||
dtype=torch.int32,
|
||||
)
|
||||
max_token_len = int(token_lens.max().item())
|
||||
padded_tokens = []
|
||||
for token in token_tensors:
|
||||
assert isinstance(token, torch.Tensor)
|
||||
if int(token.shape[1]) == max_token_len:
|
||||
padded_tokens.append(token)
|
||||
else:
|
||||
@@ -337,9 +387,9 @@ class CosyVoice3Code2Wav(nn.Module):
|
||||
)
|
||||
padded_tokens.append(torch.cat([token, pad], dim=1))
|
||||
tokens = torch.cat(padded_tokens, dim=0)
|
||||
prompt_tokens = torch.cat([item["prompt_token"] for _, item in group], dim=0) # type: ignore[list-item]
|
||||
prompt_feats = torch.cat([item["prompt_feat"] for _, item in group], dim=0) # type: ignore[list-item]
|
||||
embeddings = torch.cat([item["embedding"] for _, item in group], dim=0) # type: ignore[list-item]
|
||||
prompt_tokens = torch.cat([item["prompt_token"] for _, item in group], dim=0)
|
||||
prompt_feats = torch.cat([item["prompt_feat"] for _, item in group], dim=0)
|
||||
embeddings = torch.cat([item["embedding"] for _, item in group], dim=0)
|
||||
prompt_token_lens = torch.full((len(group),), prompt_tokens.shape[1], dtype=torch.int32)
|
||||
prompt_feat_lens = torch.full((len(group),), prompt_feats.shape[1], dtype=torch.int32)
|
||||
finalize = bool(group[0][1].get("finalize", False))
|
||||
@@ -370,7 +420,7 @@ class CosyVoice3Code2Wav(nn.Module):
|
||||
row_feat = row_feat[:, :, trim_mel:]
|
||||
results[index] = self._stream_hift_from_feat(
|
||||
row_feat,
|
||||
cache_state=item.get("cache_state"), # type: ignore[arg-type]
|
||||
cache_state=item.get("cache_state"),
|
||||
finalize=finalize,
|
||||
)
|
||||
|
||||
@@ -443,7 +493,7 @@ class CosyVoice3Code2Wav(nn.Module):
|
||||
dtype=tts_mel.dtype,
|
||||
)
|
||||
else:
|
||||
tts_speech, _ = self.hift.inference(speech_feat=tts_mel, finalize=True)
|
||||
tts_speech, _, _ = self.hift.inference(speech_feat=tts_mel, finalize=True)
|
||||
|
||||
return tts_speech
|
||||
|
||||
|
||||
Reference in new issue
Block a user