145 lines · 6.2 KB · PythonRaw
#!/usr/bin/env python3"""Convert one AI4Bharat IndicConformer language to sherpa-onnx (NeMo CTC, int8). convert_indicconformer.py <out-dir> <lang> [--check audio.wav]Source: ai4bharat/indicconformer_stt_<lang>_hybrid_ctc_rnnt_large on Hugging Face(MIT; gated: accept its terms once and set HF_TOKEN). It is a hybrid CTC/RNNT modelover one tokenizer shared by 22 languages, 256 pieces each. The steps, each checked: 1. load the .nemo with AI4Bharat's NeMo fork (branch nemo-v2), CTC head chosen; 2. export to ONNX (opset 16, legacy TorchScript exporter: the dynamo exporter fails on this architecture) with every piece but this language's 256 and the blank masked to -inf inside the graph, so a plain CTC decoder emits only them; 3. dynamic int8 on MatMul only, per channel (full-graph int8 and fp16 both damaged the output); 4. tokens.txt from the shared vocabulary plus <blk>, and the metadata sherpa-onnx reads (vocab_size, normalize_type per_feature, subsampling_factor 4, model_type EncDecCTCModelBPE).Writes <out-dir>/model.int8.onnx and <out-dir>/tokens.txt. With --check it alsodecodes the file through NeMo and through sherpa-onnx and refuses to finish whenthey differ by more than a character or two.Environment: Python 3.10, torch (CPU), AI4Bharat's NeMo fork; scripts/voice/requirements-convert.txt pins them. Run it on a machine with ~16 GB free memory."""import argparseimport osimport sysfrom pathlib import PathLANG_SIZE = 256BLANK_ID = 5632def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("out", type=Path) ap.add_argument("lang") ap.add_argument("--check", type=Path) a = ap.parse_args() a.out.mkdir(parents=True, exist_ok=True) if not os.environ.get("HF_TOKEN"): sys.exit("HF_TOKEN is not set: the AI4Bharat repos are gated (accept the terms on the model page once)") # NeMo's fork imports names newer libraries dropped; stand them in before import. import numpy as np if not hasattr(np, "sctypes"): np.sctypes = {"int": [np.int8, np.int16, np.int32, np.int64], "uint": [np.uint8, np.uint16, np.uint32, np.uint64], "float": [np.float16, np.float32, np.float64], "complex": [np.complex64, np.complex128]} import pytorch_lightning.loggers as pll if not hasattr(pll, "NeptuneLogger"): pll.NeptuneLogger = type("NeptuneLogger", (), {}) import functools import torch import torch.nn as nn import nemo.collections.asr as nemo_asr model = nemo_asr.models.ASRModel.from_pretrained(f"ai4bharat/indicconformer_stt_{a.lang}_hybrid_ctc_rnnt_large", map_location="cpu") model.eval() offset = model.tokenizer.token_id_offset[a.lang] vocab = model.tokenizer.vocab assert len(vocab) == BLANK_ID, f"vocabulary is {len(vocab)} pieces, expected {BLANK_ID}" model.cur_decoder = "ctc" model.set_export_config({"decoder_type": "ctc"}) original = torch.onnx.export @functools.wraps(original) def legacy(*args, **kwargs): kwargs.setdefault("dynamo", False) return original(*args, **kwargs) class Masked(nn.Module): def __init__(self, inner): super().__init__() self.inner = inner mask = torch.full((BLANK_ID + 1,), float("-inf")) mask[offset:offset + LANG_SIZE] = 0.0 mask[BLANK_ID] = 0.0 self.register_buffer("mask", mask) def forward(self, audio_signal, length): return self.inner.forward_for_export(input=audio_signal, length=length) + self.mask wrapper = Masked(model).eval() feats = torch.randn(1, 80, 400) length = torch.tensor([400]) fp32 = a.out / "model.fp32.onnx" legacy(wrapper, (feats, length), str(fp32), input_names=["audio_signal", "length"], output_names=["logprobs"], dynamic_axes={"audio_signal": {0: "batch", 2: "time"}, "length": {0: "batch"}, "logprobs": {0: "batch", 1: "time"}}, opset_version=16) from onnxruntime.quantization import QuantType, quantize_dynamic from onnxruntime.quantization.shape_inference import quant_pre_process pre = a.out / "model.pre.onnx" int8 = a.out / "model.int8.onnx" quant_pre_process(input_model=str(fp32), output_model_path=str(pre)) quantize_dynamic(model_input=str(pre), model_output=str(int8), per_channel=True, weight_type=QuantType.QUInt8, op_types_to_quantize=["MatMul"]) import onnx m = onnx.load(str(int8)) for k, v in {"vocab_size": str(BLANK_ID + 1), "normalize_type": "per_feature", "subsampling_factor": "4", "model_type": "EncDecCTCModelBPE", "version": "1", "model_author": "ai4bharat", "comment": f"ai4bharat indicconformer, {a.lang}, CTC-only, masked, int8 MatMul-only"}.items(): p = m.metadata_props.add() p.key, p.value = k, v onnx.save(m, str(int8)) with open(a.out / "tokens.txt", "w", encoding="utf-8") as fh: for i, tok in enumerate(vocab): fh.write(f"{tok} {i}\n") fh.write(f"<blk> {BLANK_ID}\n") fp32.unlink() pre.unlink() if a.check: import sherpa_onnx import soundfile as sf import soxr ref = model.transcribe([str(a.check)], batch_size=1, language_id=a.lang)[0] while isinstance(ref, list): ref = ref[0] ref = ref if isinstance(ref, str) else ref.text audio, sr = sf.read(str(a.check), dtype="float32") if audio.ndim > 1: audio = audio.mean(axis=1) if sr != 16000: audio = soxr.resample(audio, sr, 16000) rec = sherpa_onnx.OfflineRecognizer.from_nemo_ctc(str(int8), str(a.out / "tokens.txt"), num_threads=4) s = rec.create_stream() s.accept_waveform(16000, audio) rec.decode_stream(s) got = s.result.text.strip() print(f"nemo: {ref}\nsherpa: {got}") import difflib if difflib.SequenceMatcher(None, ref.strip(), got).ratio() < 0.97: sys.exit("the converted model does not read the check file as NeMo does") print(f"{a.lang}: {int8} ({int8.stat().st_size / 1e6:.0f} MB)")if __name__ == "__main__": main()