File size: 6,097 Bytes
21f5301 | 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 | """Exports the trained streaming Muaalem to ONNX for the app, shrinks it to
8 bits, and checks both against PyTorch chunk by chunk.
One call of the exported model is one streaming step:
in: features (1, CHUNK, 160) rescaled log-mel pairs (features.py)
attn (24, 1, LEFT, 448)
conv (24, 1, 30, 448)
a_res (1, 1, 448)
a_att (1, 1, 448)
a_attn (1, LEFT/2, 448)
seen () int64, frames (50/s) processed before this chunk
out: logits (1, CHUNK/2, 43)
the same six state tensors, updated (names prefixed "next_")
python export_streaming.py --checkpoint best.pt --stats norm_stats.json \\
[--chunk 32] [--clips local/test_clips] [--out export]
Writes OUT/muaalem_streaming.int8.onnx, norm_stats.json, phoneme_vocab.json,
config.json (chunk, left, norm window/prior), LICENSE and NOTICE.md.
"""
from __future__ import annotations
import argparse
import json
import shutil
from pathlib import Path
import numpy as np
import onnxruntime as ort
import torch
from onnxruntime.quantization import QuantType, quantize_dynamic
from features import Fbank, NormStats, running_normalize, stack_pairs
from streaming_model import StreamingMuaalem, download, load_muaalem, vocab
from units import edit_distance, split_units
STATE = ["attn", "conv", "a_res", "a_att", "a_attn", "seen"]
class Step(torch.nn.Module):
"""StreamingMuaalem.step with plain tensors in and out, for export."""
def __init__(self, model: StreamingMuaalem):
super().__init__()
self.model = model
def forward(self, features, attn, conv, a_res, a_att, a_attn, seen):
from streaming_model import State
logits, s = self.model.step(
features, State(attn, conv, a_res, a_att, a_attn, seen)
)
return (logits, *s.tensors())
def load_trained(checkpoint: Path, chunk: int) -> StreamingMuaalem:
saved = torch.load(checkpoint, map_location="cpu", weights_only=False)
model = StreamingMuaalem(load_muaalem(download()), chunk=chunk, left=saved.get("left", 192))
weights = saved.get("ema", saved.get("model", saved))
model.load_state_dict({k: v.float() for k, v in weights.items()})
return model.eval()
def letters(ids, chars, previous=None):
out = []
for i in ids:
i = int(i)
if i != previous and i != 0:
out.append(chars[i])
previous = i
return "".join(out), previous
@torch.no_grad()
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--checkpoint", type=Path, required=True)
parser.add_argument("--stats", type=Path, required=True)
parser.add_argument("--chunk", type=int, default=32)
parser.add_argument("--clips", type=Path, default=Path("local/test_clips"))
parser.add_argument("--out", type=Path, default=Path("export"))
args = parser.parse_args()
args.out.mkdir(parents=True, exist_ok=True)
snapshot = download()
chars = vocab(snapshot)
model = load_trained(args.checkpoint, args.chunk)
step = Step(model).eval()
state = model.initial_state()
example = (torch.randn(1, args.chunk, 160), *state.tensors())
fp32 = args.out / "muaalem_streaming.fp32.onnx"
int8 = args.out / "muaalem_streaming.int8.onnx"
torch.onnx.export(
step,
example,
fp32,
input_names=["features", *STATE],
output_names=["logits", *[f"next_{n}" for n in STATE]],
opset_version=17,
dynamo=False,
)
quantize_dynamic(fp32, int8, weight_type=QuantType.QInt8)
print(f"wrote {int8} ({int8.stat().st_size / 1e6:.0f} MB)")
# Check: torch step, ONNX fp32 and ONNX int8, chunk by chunk, on real clips.
stats = NormStats.load(args.stats)
fbank = Fbank()
sessions = {
name: ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
for name, path in (("fp32", fp32), ("int8", int8))
}
clips = sorted(args.clips.glob("*.pcm"))
totals = {"fp32": [0, 0], "int8": [0, 0]}
for clip in clips:
pcm = np.fromfile(clip, dtype=np.int16)[: 30 * 16000]
raw = fbank(torch.from_numpy(pcm.astype(np.float32) / 32768)[None])
n = raw.shape[1] // (2 * args.chunk) * (2 * args.chunk)
feats = stack_pairs(running_normalize(raw[:, :n], torch.tensor([n]), 2 * args.chunk, stats))
reference = {"torch": [], "fp32": [], "int8": []}
states = {k: [t.numpy() for t in model.initial_state().tensors()] for k in sessions}
s = model.initial_state()
for start in range(0, feats.shape[1], args.chunk):
x = feats[:, start : start + args.chunk]
logits, s = model.step(x, s)
reference["torch"].extend(logits[0].argmax(-1).tolist())
for name, sess in sessions.items():
out = sess.run(None, {"features": x.numpy(), **dict(zip(STATE, states[name]))})
reference[name].extend(out[0][0].argmax(-1).tolist())
states[name] = out[1:]
want = split_units(letters(reference["torch"], chars)[0])
for name in sessions:
got = split_units(letters(reference[name], chars)[0])
totals[name][0] += edit_distance(want, got)
totals[name][1] += len(want)
print(f"{clip.stem}: {len(want)} units")
for name, (errors, total) in totals.items():
print(f"ONNX {name} vs torch, chunk by chunk: {100 * (1 - errors / max(1, total)):.2f}% of {total} units")
# What the app needs beside the model.
shutil.copy(args.stats, args.out / "norm_stats.json")
for name in ("phoneme_vocab.json", "LICENSE", "NOTICE.md"):
shutil.copy(snapshot / name, args.out / name)
(args.out / "config.json").write_text(
json.dumps({"chunk": args.chunk, "left": model.left, "norm_window": 1000, "norm_prior": 100, "conv_cache": model.kernel - 1})
)
fp32.unlink()
for extra in args.out.glob("*.onnx.data"):
extra.unlink()
if __name__ == "__main__":
main()
|