File size: 6,657 Bytes
547c405
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Export SAVA's one-frame streaming step to ONNX.

The graph takes one 40 ms frame and the stream's memory, and returns the frame's logits and the
new memory:

    pcm    [1, 640]   float32, 16 kHz mono samples in [-1, 1]
    state  [1, S]     float32, all zeros at the start of a stream
    ->
    speech     [1, 1]  logit of P(speech at this frame)
    lookahead  [1, 1]  logit of P(speech at the frame 3 back); -30 for a stream's first 3 frames
    turn       [1, 1, 4]  logits of P(the turn has ended), horizons 0, 5, 10 and 20 frames
    new_state  [1, S]

The memory is SAVA's own streaming state packed into one tensor, so a caller carries a single
array between frames. The frame counter rides in its last slot as a float, which is exact for the
first 2**24 frames (186 hours) of a stream.
"""

from __future__ import annotations

import argparse
import math
from pathlib import Path

import onnx
import torch
from inworld import sava
from inworld.sava import config
from inworld.sava import model as model_lib
from inworld.sava import modules
from onnx import numpy_helper


def _tensors(state: model_lib.StreamState) -> list[torch.Tensor]:
    """The state's float tensors in a fixed order. Offsets are left out: they equal the frame count."""
    out = [state.frontend, state.mixer.tail]
    for block in [*state.trunk, state.vad, state.turn]:
        if isinstance(block, modules.MambaState):
            out += [block.conv_tail, block.ssm]
        else:
            out += [block.keys, block.values]
    return [*out, state.prev_speech]


class Step(torch.nn.Module):
    """``SavaModel.step`` for one frame of one stream, with the state as a flat tensor."""

    def __init__(self, model: model_lib.SavaModel):
        super().__init__()
        self.model = model
        self.template = model.init_state(1, torch.device("cpu"), torch.float32)
        self.shapes = [tuple(t.shape) for t in _tensors(self.template)]
        self.state_size = sum(t.numel() for t in _tensors(self.template)) + 1

    def _unpack(self, flat: torch.Tensor) -> model_lib.StreamState:
        frames = flat[0, -1].round().long()
        parts, start = [], 0
        for shape in self.shapes:
            size = math.prod(shape)
            parts.append(flat[:, start : start + size].reshape(shape))
            start += size
        parts = iter(parts)

        def like(block):
            if isinstance(block, modules.MambaState):
                return modules.MambaState(conv_tail=next(parts), ssm=next(parts))
            return modules.AttentionState(keys=next(parts), values=next(parts), offset=frames)

        template = self.template
        return model_lib.StreamState(
            frontend=next(parts),
            mixer=modules.MixerState(tail=next(parts)),
            trunk=[like(block) for block in template.trunk],
            vad=like(template.vad),
            turn=like(template.turn),
            prev_speech=next(parts),
            frames=frames,
        )

    def forward(self, pcm: torch.Tensor, state: torch.Tensor):
        out, new = self.model.step(pcm, self._unpack(state))
        flat = [t.reshape(1, -1).float() for t in _tensors(new)]
        new_state = torch.cat([*flat, new.frames.float().reshape(1, 1)], dim=1)
        return out.speech, out.lookahead, out.turn, new_state


def name_linear_nodes(path: Path, model: torch.nn.Module) -> int:
    """Rename each MatMul that applies an ``nn.Linear`` weight to ``linear:<module path>``.

    The export leaves every matrix product as an anonymous MatMul, including the mel front end's
    DFT and filterbank and the attention products. Naming the learned layers lets a quantizer pick
    exactly those and leave the rest in full precision.
    """
    by_weight = {
        module.weight.detach().T.contiguous().numpy().tobytes(): name
        for name, module in model.named_modules()
        if isinstance(module, torch.nn.Linear)
    }
    graph = onnx.load(path)
    weights = {i.name: i for i in graph.graph.initializer}
    named = 0
    for node in graph.graph.node:
        if node.op_type == "MatMul" and node.input[1] in weights:
            module = by_weight.get(numpy_helper.to_array(weights[node.input[1]]).tobytes())
            if module is not None:
                node.name = f"linear:{module}"
                named += 1
    onnx.save(graph, path)
    return named


def strip_metadata(path: Path) -> int:
    """Remove the exporter's per-node metadata; returns how many nodes carried any.

    ``torch.onnx.export`` records for every node the Python stack trace that produced it, which
    spells out the full paths of the source files on the machine that ran the export, user name
    included. Nothing in it is needed to run the graph, and it must not be published.
    """
    graph = onnx.load(path)
    nodes = list(graph.graph.node) + [node for function in graph.functions for node in function.node]
    stripped = sum(bool(node.metadata_props) or bool(node.doc_string) for node in nodes)
    for node in nodes:
        del node.metadata_props[:]
        node.doc_string = ""
    onnx.save(graph, path)
    if str(Path.home()).encode() in path.read_bytes():
        raise RuntimeError(f"{path} still contains this machine's home path")
    return stripped


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--model", default="inworld/sava")
    parser.add_argument("--out", type=Path, default=Path("build/sava.onnx"))
    parser.add_argument("--strip", type=Path, nargs="+", help="only remove the metadata of these existing ONNX files")
    args = parser.parse_args()
    if args.strip:
        for path in args.strip:
            print(f"{path}: metadata removed from {strip_metadata(path)} nodes")
        return

    model = sava.load(args.model).eval()
    step = Step(model)
    args.out.parent.mkdir(parents=True, exist_ok=True)
    example = (torch.zeros(1, config.FRAME_SAMPLES), torch.zeros(1, step.state_size))
    program = torch.onnx.export(
        step,
        example,
        input_names=["pcm", "state"],
        output_names=["speech", "lookahead", "turn", "new_state"],
        dynamo=True,
    )
    program.save(str(args.out))
    linears = sum(isinstance(m, torch.nn.Linear) for m in model.modules())
    named = name_linear_nodes(args.out, model)
    if named != linears:
        raise RuntimeError(f"found {named} of the model's {linears} linear layers in the graph")
    strip_metadata(args.out)
    print(f"{args.out}: {args.out.stat().st_size / 1e6:.1f} MB, state size {step.state_size}, {named} linear layers")


if __name__ == "__main__":
    main()