File size: 8,852 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""Audio tokens -> 24 kHz waveform with the released Step-Audio 2 decoder (token2wav.py
in stepfun-ai/Step-Audio2, weights in stepfun-ai/Step-Audio-2-mini/token2wav).

The released streaming recipe is kept as is: 25 tokens per chunk plus the flow model's
look-ahead, tokens >= 6561 dropped, last chunk flushed with last_chunk=True.

The released Token2wav holds one stream's caches on the object. To serve many sessions,
each reply owns a copy of the freshly primed caches, and they are swapped in for the
duration of one call. Each decoder has one worker thread; several decoders can be loaded.
"""
import asyncio
import copy
import sys
import time
from concurrent.futures import ThreadPoolExecutor

CHUNK = 25
MAX_AUDIO_TOKEN = 6561
# the token sequence the released example (examples-vllm-stream.py) uses to warm the decoder up
WARMUP_TOKENS = [1493, 4299, 4218, 2049, 528, 2752, 4850, 4569, 4575, 6372, 2127, 4068, 2312, 4993, 4769, 2300, 226, 2175, 2160, 2152,
                 6311, 6065, 4859, 5102, 4615, 6534, 6426, 1763, 2249, 2209, 5938, 1725, 6048, 3816, 6058, 958, 63, 4460, 5914, 2379,
                 735, 5319, 4593, 2328, 890, 35, 751, 1483, 1484, 1483, 2112, 303, 4753, 2301, 5507, 5588, 5261, 5744, 5501, 2341,
                 2001, 2252, 2344, 1860, 2031, 414, 4366, 4366, 6059, 5300, 4814, 5092, 5100, 1923, 3054, 4320, 4296, 2148, 4371, 5831,
                 5084, 5027, 4946, 4946, 2678, 575, 575, 521, 518, 638, 1367, 2804, 3402, 4299]


def _restore_torchaudio_load():
    """The released decoder (and s3tokenizer) read the voice prompt with torchaudio.load.
    Current torchaudio routes that through TorchCodec, which needs FFmpeg libraries on the
    host. Reading the wav with soundfile gives the same samples and changes nothing on the host."""
    import soundfile as sf
    import torch
    import torchaudio

    def load(path, *args, **kwargs):
        x, sr = sf.read(str(path), dtype="float32", always_2d=True)
        return torch.from_numpy(x.T.copy()), sr

    torchaudio.load = load


class NativeSpeechOut:
    """first_chunk  audio tokens in a reply's first chunk (released recipe: 25, one second of speech).
    min_chunk    smallest later chunk, used only while the caller's play buffer is below low_water_ms.
    workers      independent decoders, each on its own thread; a reply stays on one of them.

    Measured in the second run: a first chunk of 12 alone brought the first audio from 0.88 s to
    0.56 s for one stream and made it stutter (8 underruns in 3 turns), because the second chunk
    of 25 was not ready when the short first one had played out. So later chunks are small only
    while the buffer is low, and go back to 25 once it has filled."""

    def __init__(self, step_audio2_dir, token2wav_dir, prompt_wav, float16=False, first_chunk=CHUNK, min_chunk=CHUNK,
                 low_water_ms=0, workers=1, whole_short=False):
        _restore_torchaudio_load()
        self.first_chunk, self.min_chunk, self.low_water_ms = first_chunk, min_chunk, low_water_ms
        self.whole_short = whole_short
        sys.path.insert(0, str(step_audio2_dir))
        from token2wav import Token2wav            # released code, imported unchanged
        self.prompt = str(prompt_wav)
        self.units, self._next = [], 0
        for _ in range(workers):
            t2w = Token2wav(str(token2wav_dir), float16=float16)
            t2w.set_stream_cache(self.prompt)
            self.units.append({"t2w": t2w, "fresh": copy.deepcopy((t2w.stream_cache, t2w.hift_cache_dict)),
                               "pool": ThreadPoolExecutor(max_workers=1)})
        self.lookahead = int(self.units[0]["t2w"].flow.pre_lookahead_len)
        # Warm up, as the released streaming example does: without it the first reply's first
        # audio took 7.6 s (probe) and 8.3 s (server), against 0.76 s once warm.
        for _ in self.units:
            st = self.new_reply()
            for i in range(0, 3 * CHUNK, CHUNK):
                self._decode(st, WARMUP_TOKENS[i: i + CHUNK + self.lookahead], False)
            self._decode(st, WARMUP_TOKENS[-CHUNK:], True)
        # Every chunk length is a new tensor shape, and the first decode of a new shape can stall for
        # seconds (measured: one 6 s call in the middle of a reply, 75 underruns). So every length this
        # configuration can produce is decoded once here: each chunk size in use, and every possible
        # length of a reply's last chunk.
        sizes = sorted({first_chunk} | set(range(min(min_chunk, CHUNK), CHUNK + 1)))
        for n in sizes:
            st = self.new_reply()
            self._decode(st, WARMUP_TOKENS[: n + self.lookahead], False)
            self._decode(st, WARMUP_TOKENS[n: n + CHUNK + self.lookahead], False)
        for n in range(1, CHUNK + self.lookahead + 1):
            st = self.new_reply()
            self._decode(st, WARMUP_TOKENS[: CHUNK + self.lookahead], False)
            self._decode(st, WARMUP_TOKENS[CHUNK: CHUNK + n], True)

        if whole_short:
            for unit in range(len(self.units)):
                for n in range(1, max(first_chunk, CHUNK) + self.lookahead + 1):
                    self._decode_whole({"unit": unit, "decodes": 0, "decode_ms": 0.0}, WARMUP_TOKENS[:n])

    def _decode_whole(self, st, tokens):
        """A reply shorter than one chunk, decoded in one piece: the body of the released Token2wav.__call__
        (flow.inference, then the vocoder) without its wav-file wrapper.

        Measured in the third run with Whisper: of the one-word answers ("valid", "ten") decoded by the
        streaming path as a lone last chunk, only 71 of 94 were recognisable, and some clips lasted 0.16 s."""
        import numpy as np
        import torch
        t2w, t0 = self.units[st["unit"]]["t2w"], time.perf_counter()
        prompt_speech_tokens, prompt_speech_tokens_lens, spk_emb, prompt_mels, prompt_mels_lens = t2w.cache[self.prompt]
        tok = torch.tensor([tokens], dtype=torch.int32, device="cuda")
        lens = torch.tensor([tok.shape[1]], dtype=torch.int32, device="cuda")
        with torch.inference_mode():
            with torch.amp.autocast("cuda", dtype=torch.float16 if t2w.float16 else torch.float32):
                mel = t2w.flow.inference(tok, lens, prompt_speech_tokens, prompt_speech_tokens_lens, prompt_mels, prompt_mels_lens, spk_emb, 10)
            wav, _ = t2w.hift(speech_feat=mel)
        st["decodes"] += 1
        st["decode_ms"] += (time.perf_counter() - t0) * 1000
        return (np.clip(wav.float().cpu().numpy(), -1.0, 1.0) * 32767.0).astype("<i2").tobytes()

    def new_reply(self):
        unit = self._next % len(self.units)
        self._next += 1
        return {"unit": unit, "cache": copy.deepcopy(self.units[unit]["fresh"]), "buf": [], "first": True, "decodes": 0, "decode_ms": 0.0}

    def _decode(self, st, tokens, last):
        t2w, t0 = self.units[st["unit"]]["t2w"], time.perf_counter()
        t2w.stream_cache, t2w.hift_cache_dict = st["cache"]
        pcm = t2w.stream(tokens, prompt_wav=self.prompt, last_chunk=last)
        st["cache"] = (t2w.stream_cache, t2w.hift_cache_dict)
        st["decodes"] += 1
        st["decode_ms"] += (time.perf_counter() - t0) * 1000
        return pcm

    async def feed(self, st, tokens, buffered_ms=None):
        """Add audio tokens; returns the PCM16 chunks (bytes, 24 kHz mono) that became ready.
        buffered_ms: how much reply audio the caller still has queued (None = not playing yet)."""
        st["buf"] += [t for t in tokens if t < MAX_AUDIO_TOKEN]
        loop, out, pool = asyncio.get_running_loop(), [], self.units[st["unit"]]["pool"]
        while True:
            avail = len(st["buf"]) - self.lookahead
            if st["first"]:
                n = self.first_chunk
            elif buffered_ms is not None and buffered_ms < self.low_water_ms:
                n = max(self.min_chunk, min(avail, CHUNK))
            else:
                n = CHUNK
            if avail < n:
                return out
            pcm = await loop.run_in_executor(pool, self._decode, st, st["buf"][: n + self.lookahead], False)
            out.append(pcm)
            st["buf"], st["first"] = st["buf"][n:], False
            if buffered_ms is not None:
                buffered_ms += len(pcm) / 48          # 24 kHz, 16 bit: 48 bytes per millisecond

    async def finish(self, st):
        if not st["buf"]:
            return []
        tokens, st["buf"] = st["buf"], []
        pool = self.units[st["unit"]]["pool"]
        if self.whole_short and st["first"]:          # nothing was decoded yet: the whole reply is shorter than one chunk
            return [await asyncio.get_running_loop().run_in_executor(pool, self._decode_whole, st, tokens)]
        return [await asyncio.get_running_loop().run_in_executor(pool, self._decode, st, tokens, True)]