"""Step 1. Trace Parakeet TDT v3 into four TorchScript pieces plus reference tensors. Usage: python export.py <16 kHz wav> Runs wherever NeMo is installed. build.py converts the traced pieces to Core ML on a Mac, and check.py compares them with the reference tensors saved here. """ import json, os, sys import numpy as np, soundfile as sf, torch import nemo.collections.asr as nemo_asr from huggingface_hub import hf_hub_download OUT = sys.argv[1] SAMPLE = sys.argv[2] # a public 16 kHz utterance used for the reference tensors WINDOW_S = 15 # fixed encoder window, padded SAMPLES = 16_000 * WINDOW_S REPO, REVISION = "nvidia/parakeet-tdt-0.6b-v3", "541d1f99c6b0c3cd0b11a95167540bb8edefd82b" os.makedirs(OUT, exist_ok=True) nemo_path = hf_hub_download(REPO, "parakeet-tdt-0.6b-v3.nemo", revision=REVISION) model = nemo_asr.models.ASRModel.restore_from(nemo_path, map_location="cpu").eval() model.preprocessor.featurizer.dither = 0.0 model.preprocessor.featurizer.pad_to = 0 class Preprocessor(torch.nn.Module): def __init__(self, m): super().__init__(); self.m = m def forward(self, audio, length): return self.m(input_signal=audio, length=length) class Encoder(torch.nn.Module): def __init__(self, m): super().__init__(); self.m = m def forward(self, mel, length): return self.m(audio_signal=mel, length=length) class Decoder(torch.nn.Module): """One prediction-net step: last token and LSTM state in, embedding and state out.""" def __init__(self, m): super().__init__(); self.m = m def forward(self, token, h, c): g, (h2, c2) = self.m.predict(token, state=[h, c], add_sos=False, batch_size=None) return g, h2, c2 class Joint(torch.nn.Module): """One encoder frame against one prediction step: token logits then duration logits.""" def __init__(self, m): super().__init__(); self.m = m def forward(self, enc, g): return self.m.joint(enc, g) audio, rate = sf.read(SAMPLE, dtype="float32") assert rate == 16_000, rate n = min(len(audio), SAMPLES) padded = np.zeros(SAMPLES, dtype=np.float32); padded[:n] = audio[:n] x = torch.from_numpy(padded)[None] xl = torch.tensor([n], dtype=torch.int64) with torch.inference_mode(): pre, enc, dec, joint = Preprocessor(model.preprocessor), Encoder(model.encoder), Decoder(model.decoder), Joint(model.joint) mel, mel_len = pre(x, xl) encoded, enc_len = enc(mel, mel_len) hidden = model.cfg.decoder.prednet.pred_hidden layers = model.cfg.decoder.prednet.pred_rnn_layers blank = model.decoder.blank_idx token = torch.tensor([[blank]], dtype=torch.int64) h = torch.zeros(layers, 1, hidden); c = torch.zeros(layers, 1, hidden) g, h2, c2 = dec(token, h, c) frame = encoded[:, :, :1].transpose(1, 2) # [1, 1, 1024] logits = joint(frame, g) # [1, 1, 1, V+1+D] # A trace records whatever runs while it watches. With any submodule in training mode it records # dropout and batch statistics, and the encoder scores 0.74 against NeMo instead of 1.0. # NeMo's transcribe() leaves the encoder in training mode, so it runs only after tracing. assert not any(m.training for m in model.modules()), "trace in evaluation mode" with torch.no_grad(): for name, module, args in [("preprocessor", pre, (x, xl)), ("encoder", enc, (mel, mel_len)), ("decoder", dec, (token, h, c)), ("joint", joint, (frame, g))]: torch.jit.trace(module, args, check_trace=False).save(f"{OUT}/{name}.pt") print("[MS] traced", name, flush=True) np.savez(f"{OUT}/reference.npz", audio=padded, audio_len=np.array([n]), mel=mel.numpy(), mel_len=mel_len.numpy(), encoded=encoded.numpy(), enc_len=enc_len.numpy(), token=token.numpy(), h=h.numpy(), c=c.numpy(), g=g.numpy(), h2=h2.numpy(), c2=c2.numpy(), frame=frame.numpy(), logits=logits.numpy()) reference = model.transcribe([SAMPLE], batch_size=1)[0] tok = model.tokenizer meta = { "source": REPO, "nemo": os.path.basename(nemo_path), "revision": REVISION, "window_samples": SAMPLES, "mel_frames": int(mel.shape[-1]), "encoder_frames": int(encoded.shape[-1]), "blank": int(blank), "durations": list(model.cfg.model_defaults.tdt_durations), "pred_hidden": hidden, "pred_layers": layers, "vocab_size": int(tok.vocab_size), "reference_text": reference.text if hasattr(reference, "text") else str(reference), } json.dump(meta, open(f"{OUT}/meta.json", "w"), indent=1) json.dump([tok.ids_to_tokens([i])[0] for i in range(tok.vocab_size)], open(f"{OUT}/vocab.json", "w"), ensure_ascii=False) print("[MS] shapes mel", tuple(mel.shape), "encoded", tuple(encoded.shape), "logits", tuple(logits.shape), flush=True) print("[MS] done", flush=True)