File size: 8,445 Bytes
d65bf0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""tyger, run the plain way on the CPU: the reference the port is checked against (RULE.md).

Mirrors tyger-s2s's own `scripts/validate/reference.py`: the HF processor's features, the Nemotron encoder with
`num_lookahead_tokens=0` read at layer 15, a rolling 8 s window per stream re-encoded every 320 ms hop, the hop's
newest 4 frames passed on. The GRU and the turn rules are in `turns.py`; this file only produces each hop's layer-15
frames and energies, which do not depend on the turn rules.

    python -I tyger_ref.py features --out runs/ref
"""
from __future__ import annotations

import argparse
import hashlib
import json
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
from vendor.tyger_s2s.constants import HOP_FRAMES, HOP_N, L15, SR, WINDOW_S  # noqa: E402
from vendor.tyger_s2s.rules import frame_energy  # noqa: E402

BUNDLE = HERE / "data" / "tyger"
WINDOW_N = int(WINDOW_S * SR)


def sha256(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 24), b""):
            h.update(block)
    return h.hexdigest()


def load(folder: Path = BUNDLE, check: bool = True):
    """-> (Nemotron encoder, processor, TurnTaker, config), fp32 on the CPU, as tyger-s2s's bundle.load builds them."""
    import torch
    from safetensors.torch import load_file
    from transformers import AutoConfig, AutoModel, AutoProcessor

    from vendor.tyger_s2s.controller import TurnTaker

    config = json.loads((folder / "config.json").read_text())
    if check and sha256(folder / "model.safetensors") != config["weights_sha256"]:
        raise ValueError("model.safetensors doesn't match its checksum")
    parts = {"nemotron": {}, "turn_taker": {}}
    for k, v in load_file(str(folder / "model.safetensors")).items():
        prefix, _, name = k.partition(".")
        parts[prefix][name] = v
    nemotron = AutoModel.from_config(AutoConfig.from_pretrained(folder / "nemotron"), dtype=torch.float32)
    nemotron.load_state_dict(parts["nemotron"], strict=True)
    arch = config["controller"]["architecture"]
    turn_taker = TurnTaker(arch["width"], arch["layers"])
    turn_taker.load_state_dict(parts["turn_taker"], strict=True)
    proc = AutoProcessor.from_pretrained(folder / "nemotron")
    return nemotron.encoder.eval(), proc, turn_taker.eval(), config


class Encoder:
    """Layer 15 of a window, computed as reference.py does (full features from the processor, then the encoder);
    the encoder stops after layer 15, which leaves layer 15 unchanged. All-zero windows are encoded once per length."""

    def __init__(self, encoder, proc):
        import torch

        self.encoder, self.proc, self.torch = encoder, proc, torch
        self._zero: dict[int, np.ndarray] = {}
        self._layers = encoder.layers
        encoder.layers = encoder.layers[:L15]

    def __call__(self, wav: np.ndarray) -> np.ndarray:
        if not wav.any() and len(wav) in self._zero:
            return self._zero[len(wav)]
        with self.torch.no_grad():
            inp = self.proc(wav, sampling_rate=SR, return_tensors="pt")
            out = self.encoder(input_features=inp["input_features"], attention_mask=inp.get("attention_mask"),
                               num_lookahead_tokens=0).last_hidden_state[0].numpy()
        if not wav.any():
            self._zero[len(wav)] = out
        return out


def hops(user: np.ndarray, agent: np.ndarray):
    """(user window, agent window) after each 320 ms hop, as rules.begin_hop slides them."""
    win_u = win_a = np.zeros(0, np.float32)
    for start in range(0, min(len(user), len(agent)) - HOP_N + 1, HOP_N):
        win_u = np.concatenate([win_u, user[start:start + HOP_N]])[-WINDOW_N:]
        win_a = np.concatenate([win_a, agent[start:start + HOP_N]])[-WINDOW_N:]
        yield win_u, win_a


def hop_frames(encode, win_u, win_a):
    """The hop's newest frames: (user layer 15, agent layer 15, user energy dB), as engine.process takes them."""
    hu, ha, act = encode(win_u), encode(win_a), frame_energy(win_u)
    n = min(HOP_FRAMES, len(hu), len(ha), len(act))
    return hu[-n:], ha[-n:], act[-n:]


def run(encode, user, agent, timings=None):
    """All hops of one segment -> (frames, 1024) user and agent features and (frames,) energies."""
    hus, has, acts = [], [], []
    for win_u, win_a in hops(user, agent):
        t0 = time.perf_counter()
        hu, ha, act = hop_frames(encode, win_u, win_a)
        if timings is not None:
            timings.append(time.perf_counter() - t0)
        hus.append(hu); has.append(ha); acts.append(act)
    return np.concatenate(hus), np.concatenate(has), np.concatenate(acts)


def calls():
    """(name, 16 kHz mono audio, sample where its annotation starts) for each of the 28 CallHome calls on disk."""
    import io

    import soundfile
    from pyarrow import parquet

    shard = HERE / "data" / "callhome" / "eng" / "data-00000-of-00005.parquet"
    table = parquet.ParquetFile(shard)
    n = 0
    for group in range(table.num_row_groups):
        for row in table.read_row_group(group).to_pylist():
            audio, rate = soundfile.read(io.BytesIO(row["audio"]["bytes"]), dtype="float32", always_2d=True)
            assert rate == SR
            yield f"call{n:02d}", audio.mean(1), int(min(row["timestamps_start"]) * SR)
            n += 1


def segments(limit: int = 0):
    """The test audio of RULE.md: (name, mode, user, agent) for each of the 28 CallHome calls."""
    for n, (name, audio, start) in enumerate(calls()):
        if limit and n == limit:
            return
        listen = audio[start:start + 120 * SR]
        yield name, "listen", listen, np.zeros_like(listen)
        yield name, "speaking", audio[start:start + 30 * SR], audio[start + 60 * SR:start + 90 * SR]


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    sub = parser.add_subparsers(dest="command", required=True)
    f = sub.add_parser("features", help="layer-15 frames of the test audio")
    f.add_argument("--out", type=Path, required=True)
    f.add_argument("--limit", type=int, default=0)
    f.add_argument("--threads", type=int, default=0)
    s = sub.add_parser("speed", help="time per hop of the original, on the audio port.py speed uses")
    s.add_argument("--threads", type=int, default=1)
    s.add_argument("--hops", type=int, default=200)
    args = parser.parse_args()

    import torch

    if args.threads:
        torch.set_num_threads(args.threads)
    encoder, proc, turn_taker, _ = load()
    encode = Encoder(encoder, proc)
    if args.command == "speed":
        _, call, start = next(calls())
        need = (args.hops + 30) * HOP_N
        user, agent = call[start:start + need], call[start + 60 * SR:start + 60 * SR + need]
        times, state = [], None
        for win_u, win_a in hops(user, agent):
            t0 = time.perf_counter()
            hu, ha, act = hop_frames(encode, win_u, win_a)
            with torch.no_grad():
                for i in range(len(act)):
                    db = ((torch.tensor([[float(act[i])]]) + 50) / 25).clamp(-3, 3)
                    _, state = turn_taker(torch.from_numpy(hu[i])[None, None], torch.from_numpy(ha[i])[None, None],
                                          db, torch.tensor([[2]]), state)
            times.append(time.perf_counter() - t0)
        steady = np.array(times[25:25 + args.hops])
        print(f"original (PyTorch fp32), {args.threads} threads: {len(steady)} hops, median "
              f"{np.median(steady) * 1e3:.0f} ms, p90 {np.percentile(steady, 90) * 1e3:.0f} ms per 320 ms hop")
        return
    args.out.mkdir(parents=True, exist_ok=True)
    t_all = time.perf_counter()
    for name, mode, user, agent in segments(args.limit):
        path = args.out / f"{name}-{mode}.npz"
        if path.exists():
            continue
        timings: list[float] = []
        hu, ha, act = run(encode, 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:.0f} ms, "
              f"p90 {np.percentile(timings, 90) * 1e3:.0f} ms", flush=True)
    print(f"done in {(time.perf_counter() - t_all) / 60:.1f} min", flush=True)


if __name__ == "__main__":
    main()