File size: 13,832 Bytes
ff502d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""tyger's encoder as a streaming step: each 320 ms hop encodes only its new frames, against cached state.

The reference re-encodes an 8 s window per stream every hop and keeps the newest 4 of its 101 layer-15 frames. Nothing
in the encoder looks ahead (causal subsampling, causal convolutions, attention to the current frame and the 56 before
it), so a frame's layer-15 output depends only on audio up to it. Two things differ from the reference:

  * the newest frame of a window sees the window's end (zero padding in the STFT and the subsampling), so it is
    computed again at the next hop, with the audio that followed: each step runs 5 frames, the previous hop's newest
    and the 4 new ones, returns the 4 new ones, and caches the first 4 for later hops;
  * the reference cuts every window to 8 s, so its frames lose history older than 8 s; the cache doesn't. Up to 8 s
    into a stream both give the same frames; after that they differ by however much that history matters. RULE.md's
    agreement test measures it.

Per stream the step carries, for each of the 15 layers, the keys and values of the last 56 committed frames and the
last 8 inputs of the depthwise convolution (6.4 MB as fp32). The log-mels of a hop come from the last 1.28 s of audio.

    ../sava-onnx/.venv/bin/python -I stream.py export --out export
    ../sava-onnx/.venv/bin/python -I stream.py check
    ../sava-onnx/.venv/bin/python -I stream.py features --model export --int8 --out runs/stream-int8
    ../sava-onnx/.venv/bin/python -I stream.py speed --model export --int8 --threads 4
"""
from __future__ import annotations

import argparse
import sys
import time
from pathlib import Path

import numpy as np

HERE = Path(__file__).parent
sys.path[:0] = [str(HERE), str(HERE.parent)]  # vendor/ is one level up
import tyger_ref as tr  # noqa: E402
from vendor.tyger_s2s.constants import HOP_FRAMES, HOP_N  # noqa: E402
from vendor.tyger_s2s.rules import frame_energy  # noqa: E402

CACHE = 56           # attention left context, in encoder frames
KERNEL = 9           # depthwise convolution
STEP = HOP_FRAMES + 1
TAIL_N = 4 * HOP_N   # 1.28 s of audio for a hop's log-mels: covers the 5 frames' subsampling inputs


def build(layers_only=False):
    """(subsampling module, step module), weights from data/l15.safetensors."""
    import torch
    from safetensors.torch import load_file
    from torch import nn

    import l15

    full = l15.L15()
    full.load_state_dict(load_file(str(HERE / "data" / "l15.safetensors")), strict=True)
    full.eval()

    class Step(nn.Module):
        """5 subsampled frames + caches -> their layer-15 outputs + the caches with the first 4 frames added."""

        def __init__(self):
            super().__init__()
            self.layers = full.layers
            d = full.d
            inv = 1.0 / (10000.0 ** (torch.arange(0, d, 2, dtype=torch.float32) / d))
            f = torch.arange(CACHE + STEP, dtype=torch.float32)[:, None] * inv      # offsets 0 .. 60
            pos = torch.stack([f.sin(), f.cos()], -1).reshape(CACHE + STEP, d)
            with torch.no_grad():
                for i, layer in enumerate(self.layers):
                    a = layer.self_attn
                    rel = a.relative_k_proj(pos).view(-1, a.h, a.dk).permute(1, 2, 0).contiguous()  # (h, dk, 61)
                    self.register_buffer(f"relk_{i}", rel)
            slot = torch.arange(CACHE + STEP)
            offset = (CACHE + torch.arange(STEP))[:, None] - slot[None, :]                  # (5, 61)
            self.register_buffer("offset_index", offset.clamp(0, CACHE + STEP - 1))
            self.register_buffer("in_context", (offset >= 0) & (offset <= l15.LEFT))
            self.register_buffer("slot", slot)

        def forward(self, x, k_cache, v_cache, conv_cache, valid):
            allowed = self.in_context & ((self.slot >= CACHE - valid) | (self.slot >= CACHE))[None, :]
            new_k, new_v, new_c = [], [], []
            for i, layer in enumerate(self.layers):
                a = layer.self_attn
                x = x + 0.5 * layer.feed_forward1(layer.norm_feed_forward1(x))
                h = layer.norm_self_att(x)
                q = a.q_proj(h).view(1, STEP, a.h, a.dk).transpose(1, 2)                  # (1, h, 5, dk)
                k_new, v_new = a.k_proj(h), a.v_proj(h)                                    # (1, 5, d)
                k = torch.cat([k_cache[i:i + 1], k_new], 1).view(1, -1, a.h, a.dk).transpose(1, 2)
                v = torch.cat([v_cache[i:i + 1], v_new], 1).view(1, -1, a.h, a.dk).transpose(1, 2)
                scale = a.dk ** -0.5
                ac = ((q + a.bias_u.view(1, a.h, 1, a.dk)) @ k.transpose(2, 3)) * scale      # (1, h, 5, 61)
                by_offset = (q + a.bias_v.view(1, a.h, 1, a.dk)) @ getattr(self, f"relk_{i}")  # (1, h, 5, 61)
                bd = torch.gather(by_offset, 3, self.offset_index.expand(1, a.h, STEP, CACHE + STEP)) * scale
                w = torch.softmax((ac + bd).masked_fill(~allowed, float("-inf")), dim=-1)
                x = x + a.o_proj((w @ v).transpose(1, 2).reshape(1, STEP, -1))
                c = layer.conv
                g = nn.functional.glu(c.pointwise_conv1(layer.norm_conv(x)), dim=-1)        # (1, 5, d)
                seq = torch.cat([conv_cache[i:i + 1], g], 1).transpose(1, 2)               # (1, d, 8 + 5)
                y = c.depthwise_conv(seq).transpose(1, 2)                                  # (1, 5, d)
                x = x + c.pointwise_conv2(nn.functional.silu(c.norm(y)))
                x = x + 0.5 * layer.feed_forward2(layer.norm_feed_forward2(x))
                x = layer.norm_out(x)
                new_k.append(torch.cat([k_cache[i], k_new[0, :HOP_FRAMES]], 0)[-CACHE:])
                new_v.append(torch.cat([v_cache[i], v_new[0, :HOP_FRAMES]], 0)[-CACHE:])
                new_c.append(torch.cat([conv_cache[i], g[0, :HOP_FRAMES]], 0)[-(KERNEL - 1):])
            return x, torch.stack(new_k), torch.stack(new_v), torch.stack(new_c)

    return full.subsampling.eval(), Step().eval()


def export(out: Path) -> None:
    import torch

    sub, step = build()
    d, n = 1024, len(step.layers)
    with torch.no_grad():
        torch.onnx.export(sub, (torch.zeros(1, 129, 128),), str(out / "subsampling.onnx"), dynamo=False,
                          input_names=["mel"], output_names=["frames"],
                          dynamic_axes={"mel": {1: "mel_frames"}, "frames": {1: "frames"}}, opset_version=17)
        args = (torch.zeros(1, STEP, d), torch.zeros(n, CACHE, d), torch.zeros(n, CACHE, d),
                torch.zeros(n, KERNEL - 1, d), torch.zeros(1, dtype=torch.long))
        torch.onnx.export(step, args, str(out / "l15_step.onnx"), dynamo=False,
                          input_names=["frames", "k_cache", "v_cache", "conv_cache", "valid"],
                          output_names=["l15", "k_cache_out", "v_cache_out", "conv_cache_out"], opset_version=17)


def quantize(folder: Path) -> None:
    """As export.py: 8-bit weights for the learned linear layers only. The positional terms (relk_*, a learned linear
    already applied to fixed sinusoids) stay fp32."""
    import onnx
    from onnxruntime.quantization import QuantType, quantize_dynamic

    for name in ("subsampling", "l15_step"):
        model = onnx.load(str(folder / f"{name}.onnx"), load_external_data=False)
        exclude = [nd.name for nd in model.graph.node if nd.op_type == "MatMul" and any("relk" in i for i in nd.input)]
        quantize_dynamic(str(folder / f"{name}.onnx"), str(folder / f"{name}.int8.onnx"), weight_type=QuantType.QInt8,
                         per_channel=True, op_types_to_quantize=["MatMul"], nodes_to_exclude=exclude,
                         extra_options={"MatMulConstBOnly": True})
        print(name, "kept fp32:", len(exclude), "positional MatMuls")
    for p in sorted(folder.glob("*.onnx")):
        print(f"{p.name}: {p.stat().st_size / 1e6:.0f} MB")


class Stream:
    """One audio stream through the streaming encoder: push a hop's audio, get its newest 4 layer-15 frames."""

    def __init__(self, sub_sess, step_sess, mel):
        self.sub, self.step, self.mel = sub_sess, step_sess, mel
        self.audio = np.zeros(0, np.float32)
        self.k = np.zeros((15, CACHE, 1024), np.float32)
        self.v = np.zeros((15, CACHE, 1024), np.float32)
        self.c = np.zeros((15, KERNEL - 1, 1024), np.float32)
        self.valid = 0

    def push(self, hop: np.ndarray) -> np.ndarray:
        self.audio = np.concatenate([self.audio, hop])[-TAIL_N:]
        frames = self.sub.run(None, {"mel": self.mel(self.audio)[None]})[0][:, -STEP:]
        y, self.k, self.v, self.c = self.step.run(None, {
            "frames": frames, "k_cache": self.k, "v_cache": self.v, "conv_cache": self.c,
            "valid": np.array([self.valid], np.int64)})
        self.valid = min(self.valid + HOP_FRAMES, CACHE)
        return y[0, -HOP_FRAMES:]


class Port:
    def __init__(self, folder: Path, int8: bool, threads: int):
        import port
        from l15 import LogMel

        suffix = ".int8.onnx" if int8 else ".onnx"
        self.sub = port.session(folder / f"subsampling{suffix}", threads)
        self.step = port.session(folder / f"l15_step{suffix}", threads)
        self.mel = LogMel(np.load(HERE / "data" / "mel_filters.npy"))

    def stream(self) -> Stream:
        return Stream(self.sub, self.step, self.mel)


def run(p: Port, user: np.ndarray, agent: np.ndarray, timings=None):
    """The same frames as tyger_ref.run, from the streaming encoder: (frames, 1024) x2 and (frames,) energies."""
    su, sa = p.stream(), p.stream()
    hus, has, acts = [], [], []
    tail_u = np.zeros(0, np.float32)
    for start in range(0, min(len(user), len(agent)) - HOP_N + 1, HOP_N):
        t0 = time.perf_counter()
        uh, ah = user[start:start + HOP_N], agent[start:start + HOP_N]
        hus.append(su.push(uh)); has.append(sa.push(ah))
        tail_u = np.concatenate([tail_u, uh])[-HOP_N:]
        acts.append(frame_energy(tail_u)[-HOP_FRAMES:])
        if timings is not None:
            timings.append(time.perf_counter() - t0)
    return np.concatenate(hus), np.concatenate(has), np.concatenate(acts)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    sub = parser.add_subparsers(dest="command", required=True)
    e = sub.add_parser("export"); e.add_argument("--out", type=Path, required=True)
    c = sub.add_parser("check", help="streamed vs reference frames, by hop")
    c.add_argument("--model", type=Path, default=HERE / "export"); c.add_argument("--int8", action="store_true")
    f = sub.add_parser("features")
    f.add_argument("--model", type=Path, default=HERE / "export"); f.add_argument("--int8", action="store_true")
    f.add_argument("--out", type=Path, required=True); f.add_argument("--threads", type=int, default=4)
    s = sub.add_parser("speed")
    s.add_argument("--model", type=Path, default=HERE / "export"); s.add_argument("--int8", action="store_true")
    s.add_argument("--threads", type=int, default=4); s.add_argument("--hops", type=int, default=200)
    args = parser.parse_args()

    if args.command == "export":
        export(args.out)
        quantize(args.out)
        return
    if args.command == "check":
        p = Port(args.model, args.int8, 4)
        name, mode, user, agent = next(tr.segments(1))
        hu, _, act = run(p, user, agent)
        ref = np.load(HERE / "runs" / "ref" / f"{name}-{mode}.npz")
        d = np.abs(hu - ref["hu"]).max(1).reshape(-1, HOP_FRAMES).max(1)
        cos = (hu * ref["hu"]).sum(1) / np.linalg.norm(hu, axis=1) / np.linalg.norm(ref["hu"], axis=1)
        print(f"energies equal: {np.allclose(act, ref['act'])}")
        for lo, hi in ((0, 25), (25, 50), (50, 100), (100, len(d))):
            print(f"hops {lo:>3}-{hi - 1:<3}: max |difference| {d[lo:hi].max():.2e}, "
                  f"min cosine {cos[lo * 4:hi * 4].min():.5f} (reference scale {np.abs(ref['hu']).max():.0f})")
        return

    p = Port(args.model, args.int8, args.threads)
    if args.command == "features":
        args.out.mkdir(parents=True, exist_ok=True)
        for name, mode, user, agent in tr.segments():
            path = args.out / f"{name}-{mode}.npz"
            if path.exists():
                continue
            timings: list[float] = []
            hu, ha, act = run(p, user, agent, timings)
            np.savez(path, hu=hu, ha=ha, act=act, hop_seconds=np.array(timings))
            print(f"{name} {mode}: {len(act)} frames, median hop {np.median(timings) * 1e3:.1f} ms", flush=True)
        return

    # speed: as port.py speed (same audio, both streams speech), plus the GRU's 4 frames per hop
    import port

    turn_taker = port.TurnTaker(HERE / "export" / "turn_taker.onnx", args.threads)
    _, call, start = next(tr.calls())
    need = (args.hops + 30) * HOP_N
    user, agent = call[start:start + need], call[start + 60 * tr.SR:start + 60 * tr.SR + need]
    su, sa = p.stream(), p.stream()
    times = []
    for k in range(args.hops + 30):
        t0 = time.perf_counter()
        hu, ha = su.push(user[k * HOP_N:(k + 1) * HOP_N]), sa.push(agent[k * HOP_N:(k + 1) * HOP_N])
        act = frame_energy(user[k * HOP_N:(k + 1) * HOP_N])
        for i in range(HOP_FRAMES):
            turn_taker(hu[i], ha[i], float(act[i]), 2)
        times.append(time.perf_counter() - t0)
    steady = np.array(times[25:25 + args.hops])
    print(f"streaming {'int8' if args.int8 else 'fp32'}, {args.threads} threads: {len(steady)} hops, "
          f"median {np.median(steady) * 1e3:.1f} ms, p90 {np.percentile(steady, 90) * 1e3:.1f} ms, "
          f"max {steady.max() * 1e3:.1f} ms per 320 ms hop -> {'PASS' if np.percentile(steady, 90) < 0.32 else 'FAIL'}")


if __name__ == "__main__":
    main()