File size: 3,985 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
"""Export tyger's CPU port: the encoder to layer 15 (`l15.onnx`, any window length) and the turn-taker GRU, one frame
per call (`turn_taker.onnx`). Also writes the mel filterbank (`mel_filters.npy`), and the GRU's and the 15 layers'
weights alone (`data/turn_taker.safetensors`, `data/l15.safetensors`) for `turns.py` and `stream.py`.

    ../parakeet-eou/.venv/bin/python -I export.py --out export
    ../sava-onnx/.venv/bin/python -I export.py --quantize export      # -> l15.int8.onnx
"""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

HERE = Path(__file__).parent
sys.path.insert(0, str(HERE))


class Step:
    """TurnTaker for one frame: (user, agent features, energy dB, previous state, GRU state) -> (8 outputs, state).
    The energy normalisation is gru_batch.py's: clip((dB + 50) / 25, -3, 3)."""

    @staticmethod
    def module(turn_taker):
        import torch

        class _Step(torch.nn.Module):
            def __init__(self):
                super().__init__()
                self.tt = turn_taker

            def forward(self, hu, ha, db, prev, state):
                act = ((db + 50) / 25).clamp(-3, 3)
                out, state = self.tt(hu[:, None], ha[:, None], act[:, None], prev[:, None], state)
                return out[:, 0], state

        return _Step().eval()


def export(out: Path) -> None:
    import torch
    from safetensors.torch import save_file

    import l15
    import tyger_ref

    out.mkdir(parents=True, exist_ok=True)
    encoder, _, turn_taker, _ = tyger_ref.load()
    model = l15.L15.from_hf(encoder)
    with torch.no_grad():
        torch.onnx.export(model, (torch.zeros(1, 801, 128),), str(out / "l15.onnx"), dynamo=False,
                          input_names=["mel"], output_names=["l15"],
                          dynamic_axes={"mel": {1: "frames"}, "l15": {1: "encoder_frames"}}, opset_version=17)
        step = Step.module(turn_taker)
        args = (torch.zeros(1, 1024), torch.zeros(1, 1024), torch.zeros(1), torch.zeros(1, dtype=torch.long),
                torch.zeros(3, 1, 768))
        torch.onnx.export(step, args, str(out / "turn_taker.onnx"), dynamo=False,
                          input_names=["user", "agent", "energy_db", "previous_state", "state_in"],
                          output_names=["outputs", "state_out"], opset_version=17)
    save_file({k: v.contiguous() for k, v in turn_taker.state_dict().items()}, str(HERE / "data" / "turn_taker.safetensors"))
    save_file({k: v.contiguous() for k, v in model.state_dict().items()}, str(HERE / "data" / "l15.safetensors"))
    import numpy as np

    _, proc, _, _ = tyger_ref.load(check=False)
    filters = proc.feature_extractor.mel_filters.numpy().astype(np.float32)        # (128, 257)
    for folder in (out, HERE / "data"):
        np.save(folder / "mel_filters.npy", filters)
    print("exported", sorted(p.name for p in out.iterdir()))


def quantize(folder: Path) -> None:
    """8-bit weights for the learned linear layers only (MatMul with a constant weight), per output channel; the
    convolutions, attention products, norms and everything else stay fp32."""
    from onnxruntime.quantization import QuantType, quantize_dynamic

    quantize_dynamic(str(folder / "l15.onnx"), str(folder / "l15.int8.onnx"), weight_type=QuantType.QInt8,
                     per_channel=True, op_types_to_quantize=["MatMul"], extra_options={"MatMulConstBOnly": True})
    for p in sorted(folder.glob("*.onnx")):
        size = p.stat().st_size + sum(q.stat().st_size for q in folder.glob(p.name + ".data"))
        print(f"{p.name}: {size / 1e6:.0f} MB")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--out", type=Path)
    parser.add_argument("--quantize", type=Path)
    args = parser.parse_args()
    if args.out:
        export(args.out)
    if args.quantize:
        quantize(args.quantize)


if __name__ == "__main__":
    main()