Download export_streaming.py from mahmud71/muaalem-streaming: direct link, hf CLI and curl.
- Browser
- Download file 6.1 kB
-
https://huggingface.co/mahmud71/muaalem-streaming/resolve/main/export_streaming.py
- Command line
-
hf download hf://mahmud71/muaalem-streaming/export_streaming.py
-
curl -L -o export_streaming.py https://huggingface.co/mahmud71/muaalem-streaming/resolve/main/export_streaming.py
6.1 kB
| """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 | |
| 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() | |