Phonon-2 Core ML: encoder windows of 5 to 35 seconds, exact five-value weights
Browse filesFiles changed (10)
19 unmodified lines202122232425262719 unmodified linesthe TDT decoder, the tokenizer and the feature-extractor configuration derivefrom that model and remain under CC-BY-4.0. This package converts the sameweights to Core ML programs for the Apple Neural Engine (encoder weights storedas 8-bit integers with one scale per output channel, activations in 16-bitfloating point) and carries the decoder tables unchanged.These weights are therefore distributed under CC-BY-4.0. The Fermion code inthis repository (the Swift package, the command-line tool and the export19 unmodified lines2021222324252627282919 unmodified linesthe TDT decoder, the tokenizer and the feature-extractor configuration derivefrom that model and remain under CC-BY-4.0. This package converts the sameweights to Core ML programs for the Apple Neural Engine (encoder weights storedexactly as five-value palettes: a 1-bit zero mask and 16-bit floating-pointlookup tables shared by groups of 16 output rows; activations in 16-bitfloating point) and carries the decoder's 6-bit tables unchanged, packed fourcodes to three bytes.These weights are therefore distributed under CC-BY-4.0. The Fermion code inthis repository (the Swift package, the command-line tool and the export
123version https://git-lfs.github.com/spec/v1oid sha256:a7781ac4033de600195a97279614eb58da9094abb44a5f83fdf8c8bb8a7ca739size 2153753123version https://git-lfs.github.com/spec/v1oid sha256:4f6790ec94fe4429b10397c013563d0a51119953ff6d3da466bbcb23a25dee2asize 2500482
123version https://git-lfs.github.com/spec/v1oid sha256:50045d0eeccfaf6680608e54bc58a232dd6e7ea6a016fd28012c8ec73d59da4dsize 611151616123version https://git-lfs.github.com/spec/v1oid sha256:93aa991318a00ed492fdbb724e7bca4e6a69c6cf671ab4f14a14ef6101e7648bsize 329186560
123456789101112131415161718{"fileFormatVersion": "1.0.0","itemInfoEntries": {"854E4CCA-EAC4-48FA-A519-84FC0846FC9A": {"author": "com.apple.CoreML","description": "CoreML Model Weights","name": "weights","path": "com.apple.CoreML/weights"},"860FA034-2F1F-4B5F-A6E5-B25A069881BE": {"author": "com.apple.CoreML","description": "CoreML Model Specification","name": "model.mlmodel","path": "com.apple.CoreML/model.mlmodel"}},"rootModelIdentifier": "860FA034-2F1F-4B5F-A6E5-B25A069881BE"}123456789101112131415161718{"fileFormatVersion": "1.0.0","itemInfoEntries": {"1452a30d-8602-4850-a916-b49abad83b36": {"author": "com.apple.CoreML","description": "CoreML Model Weights","name": "weights","path": "com.apple.CoreML/weights"},"94878592-565f-4730-b8bb-303214f197c5": {"author": "com.apple.CoreML","description": "CoreML Model Specification","name": "model.mlmodel","path": "com.apple.CoreML/model.mlmodel"}},"rootModelIdentifier": "94878592-565f-4730-b8bb-303214f197c5"}
19 unmodified lines202122232425262728293031323334353637383940414243444 unmodified lines49505152535455565758596061626364656667686970717273747576777879803 unmodified lines8485868788899091929394959697989910010110210310410510610710819 unmodified lines# Phonon-2 Core MLPhonon-2 for the Apple Neural Engine. One 613 MB Core ML package holds the Phonon-2 encoder for four input lengths with a singleshared set of weights, and the decoder is an 18 MB table file. On an M5 MacBook Air an hour of audio becomes text in about 17seconds, the GPU stays free, and the seven-set word error rate is the same 5.21 % as the Phonon-2 MLX engine.## Run itPhonon-2 is the model inside [Detta](https://www.fermionresearch.com/products/detta), the dictation app for the Mac. Thisrepository runs it on the Neural Engine from Swift or Python.**Swift**, on macOS 15 or iOS 18 and later. The Swift package is in `phonon-coreml-src.tgz`, under Apache 2.0.```swiftimport PhononCoreMLlet phonon = try Transcriber(bundle: URL(fileURLWithPath: "Phonon-2-CoreML")) // the folder this repository downloads tolet text = try phonon.transcribe(samples) // mono Float32 at 16 kHz``````bashphonon-coreml-cli Phonon-2-CoreML recording.wav # prints the transcript; --json out.json adds timing```**Python**, with coremltools, numpy and soundfile.4 unmodified linespython Phonon-2-CoreML/phonon_coreml.py Phonon-2-CoreML recording.wav```Both runners take mono 16 kHz audio. The first run compiles the package for the Neural Engine once, in under a minute on an M5,and keeps the compiled copy, so later loads take under a second.Phonon-2 also runs through the `fermion` command line on Apple silicon, Linux, Windows and NVIDIA GPUs. See the[Phonon-2 card](https://huggingface.co/FermionResearch/Phonon-2).## Long audioPhonon-2 is built to run through its own segmenter, which cuts audio at pauses into windows of 25 seconds or more. The fermion command line and Detta both use it, so long recordings need no preparation.If you split audio yourself, cut at pauses rather than at fixed times, use windows of 30 seconds or more, and never pad a window with silence. A window that starts in the middle of speech loses words at its start. On a 19-minute talk, fixed 30-second chunks add about 5 points of word error compared with the segmenter, 0.5 seconds of real audio before each chunk wins back about 2 of them, and fixed 20-second chunks add about 10.Both runners in this repository use the same segmenter, so audio of any length can be passed to them whole.## AccuracyEvery utterance of the seven English test sets, scored with the Open ASR Leaderboard's own code, with the Core ML encoder besidethe Phonon-2 MLX engine.| Set | Core ML, Neural Engine | Phonon-2 MLX engine ||---|---:|---:|| LibriSpeech clean | 1.74 | 1.72 || LibriSpeech other | 3.91 | 3.92 || AMI | 9.33 | 9.37 || Earnings-22 | 6.99 | 6.96 || GigaSpeech | 8.34 | 8.35 || SPGISpeech | 3.70 | 3.70 || VoxPopuli | 2.46 | 2.46 || **Mean of seven** | **5.21** | **5.21** |3 unmodified lines## SpeedOne stream at a time, with the model loaded once, the encoder on the Neural Engine and the decoder on the CPU.| Mac | Audio | Times realtime ||---|---|---:|| M5 MacBook Air | 20 recordings of 2 seconds to 2 minutes (797 s) | 212× || M5 MacBook Air | 40 LibriSpeech utterances of 3 to 24 seconds | 278× || M5 MacBook Air | 158 hours of test-set audio | 183× |The encoder takes 9 ms for a 5-second window, 21 ms for 15 seconds and 97 ms for 35 seconds on the M5.## Files| File | Size | Contents ||---|---:|---|| `Phonon-2.mlpackage` | 613 MB | the encoder for 5, 10, 15 and 35 second windows, with one shared weight set (8-bit integer weights, 16-bit float activations); audio is masked to its true length inside the window || `decoder.bin` | 18 MB | the prediction network, joint and vocabulary || `manifest.json` | | source checksum, window lengths and input contract || `phonon_coreml.py` | | the Python runner || `phonon-coreml-src.tgz` | | the Swift package and command-line tool || `SHA256SUMS` | | a checksum for every file above |## Licence19 unmodified lines202122232425262728293031323334353637383940414243444546474849505152534 unmodified lines5859606162636465666768697071727374757677787980818283848586873 unmodified lines91929394959697989910010110210310410510610710810911011111211311411519 unmodified lines# Phonon-2 Core MLPhonon-2 for the Apple Neural Engine. The Core ML package reads with the accuracy of the Phonon-2 reference engine: on the OpenASR Leaderboard's seven English test sets, run with the leaderboard's own code on the full sets, it averages 5.21 % word error,with LibriSpeech test-clean at 1.73 % and test-other at 3.91 %.One 332 MB package holds the encoder's five-value weights exactly, for every utterance up to 35 seconds, over a single set ofweights; the decoder is a 13 MB table file. On an M5 MacBook Air an hour of speech becomes text in 6 seconds (606 times realtime), a few seconds of audio returns its text in about 11 milliseconds once the model is loaded, every word carries its startand end time, and the GPU stays free.## Run itPhonon-2 is the model inside [Detta](https://www.fermionresearch.com/products/detta), the dictation app for the Mac. Thisrepository runs it on the Neural Engine from Swift or Python.**Swift**, on macOS 15 or iOS 18 and later, with the package at [github.com/fermionresearch/phonon-coreml](https://github.com/fermionresearch/phonon-coreml)(also in `phonon-coreml-src.tgz`).```swiftimport PhononCoreMLlet transcriber = try Transcriber(bundle: URL(fileURLWithPath: "Phonon-2-CoreML")) // the folder this repository downloads tolet result = try transcriber.transcribe(url: URL(fileURLWithPath: "recording.wav"))print(result.text)for word in result.words { print(word.start, word.end, word.text) }``````bashphonon-coreml-cli Phonon-2-CoreML recording.wav --words```**Python**, with coremltools, numpy and soundfile.4 unmodified linespython Phonon-2-CoreML/phonon_coreml.py Phonon-2-CoreML recording.wav```Both runners take mono 16 kHz audio of any length. The first run prepares the package for the Neural Engine once and gives itsfirst transcript in under a minute; the compiled copy is kept, so later loads take under a second.Phonon-2 also runs through the `fermion` command line on Apple silicon, Linux, Windows and NVIDIA GPUs. See the[Phonon-2 card](https://huggingface.co/FermionResearch/Phonon-2).## Long audioAn utterance of up to 35 seconds is read in one pass by the smallest encoder window that holds it. Longer recordings are cut atpauses into windows of up to 15 seconds and their words are joined, so no word is split at a boundary. Pass recordings whole;both runners do the cutting.## AccuracyEvery utterance of the seven English test sets, scored with the Open ASR Leaderboard's own code, with the Core ML package besidethe Phonon-2 MLX engine.| Set | Core ML, Neural Engine | Phonon-2 MLX engine ||---|---:|---:|| LibriSpeech clean | 1.73 | 1.72 || LibriSpeech other | 3.91 | 3.92 || AMI | 9.33 | 9.37 || Earnings-22 | 6.99 | 6.96 || GigaSpeech | 8.33 | 8.35 || SPGISpeech | 3.70 | 3.70 || VoxPopuli | 2.46 | 2.46 || **Mean of seven** | **5.21** | **5.21** |3 unmodified lines## SpeedOn an M5 MacBook Air, with the model loaded once, the encoder on the Neural Engine and the decoder on the CPU.| Audio | Time | Times real time ||---|---:|---:|| One hour of LibriSpeech read as a single file | 6.0 s | 606× || 158 hours of test-set audio, utterance by utterance | 31 min | 305× || 20 recordings of 2 seconds to 2 minutes (797 s) | 2.0 s | 400× || A recording of 3 to 5 seconds, model loaded (median of 20) | 11 ms | |## Files| File | Size | Contents ||---|---:|---|| `Phonon-2.mlpackage` | 332 MB | the encoder for 5, 10, 15 and 35 second windows over one shared weight set (five-value weights stored exactly, 16-bit float activations); audio is masked to its true length inside the window || `decoder.bin` | 13 MB | the prediction network, joint and vocabulary || `manifest.json` | | source checksum, window lengths and input contract || `phonon_coreml.py` | | the Python runner, with `frontend.py` and `segmenter_np.py` || `phonon-coreml-src.tgz` | | the Swift package and command-line tool || `ci/` | | three LibriSpeech clips and their transcripts, for a quick check || `SHA256SUMS` | | a checksum for every file above |## Licence
12345678910111213141516178a1ef729ee065dfb09d5b9630425b6f7c0ea4baa95831b3cf2e78b31f8dae727 README.md1c2debc9e81ff4cee6a1f0313a87784893c7095ed51e280122a0aa47c19e0519 NOTICE9ba9550ad48438d0836ddab3da480b3b69ffa0aac7b7878b5a0039e7ab429411 LICENSE-WEIGHTS-CC-BY-4.0.txtcfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE-CODE-Apache-2.0.txt8e2f8e012b86bd35cd77068dea84e27e2ae5bb35d18d613a4f540eee8742d77e manifest.jsonfe289e3f061bdb71c628ddc6ce30edfe0b2c0915413423234bc3096457ecba1e decoder.bin7073b62dcccf612245154ddba6dc1088ddd9467771f6826d260b292db7124e1f phonon_coreml.pya85dc4abab44b785333e338f22ac7bee2ac624425e0d2160e041b80022993bd7 frontend.pye56182a557f5bae30fe37bc8333cf9d0caf323aaae42b1e4465ad9270bf048f6 segmenter_np.py7fe41177ca4698508fcb153675c6b8f3d1aad3b06ffc61e65269836663470eff phonon-coreml-src.tgz695c112e2bbf6aa04b67e95a631e269d9643f7bb840f67313ab471cf7d8b242c ci/expected_texts.json30885601173f96b0d8ddd020dc959b055c6c1582b85a33e3fcab8c4b08ed94c2 ci/clips/1089-134686-0000.flac66277a3fa3df407261dc2a3ce685a7ceef19999ab0c10531bee5257cb64cb59d ci/clips/1089-134686-0002.flacc65e16be3ef92c11a31a9c2c4c570542eb2ed66153150a7c4cca00c01b30a4e2 ci/clips/1089-134686-0011.flaca7781ac4033de600195a97279614eb58da9094abb44a5f83fdf8c8bb8a7ca739 Phonon-2.mlpackage/Data/com.apple.CoreML/model.mlmodel50045d0eeccfaf6680608e54bc58a232dd6e7ea6a016fd28012c8ec73d59da4d Phonon-2.mlpackage/Data/com.apple.CoreML/weights/weight.bin46a518f850b3bcd518213026bd693b276f6d0bf9682ad7250f55b6366e699616 Phonon-2.mlpackage/Manifest.json123456789101112131415161730885601173f96b0d8ddd020dc959b055c6c1582b85a33e3fcab8c4b08ed94c2 ./ci/clips/1089-134686-0000.flac66277a3fa3df407261dc2a3ce685a7ceef19999ab0c10531bee5257cb64cb59d ./ci/clips/1089-134686-0002.flacc65e16be3ef92c11a31a9c2c4c570542eb2ed66153150a7c4cca00c01b30a4e2 ./ci/clips/1089-134686-0011.flac695c112e2bbf6aa04b67e95a631e269d9643f7bb840f67313ab471cf7d8b242c ./ci/expected_texts.json36fa7202dda85c603af60d930ab88d7e9f0d2a619490aff46f5384db924cfa70 ./decoder.bina85dc4abab44b785333e338f22ac7bee2ac624425e0d2160e041b80022993bd7 ./frontend.pycfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 ./LICENSE-CODE-Apache-2.0.txt9ba9550ad48438d0836ddab3da480b3b69ffa0aac7b7878b5a0039e7ab429411 ./LICENSE-WEIGHTS-CC-BY-4.0.txtab3fb5dfd3fc07b1d8a24379d04418f458d0443ba6359d3a5ab2f098a7d64089 ./manifest.jsonb468a23a1ce2c5181ea4050432bb68713a6468ce2e452927228d24f3d56226be ./NOTICEc7f88ad0c2a41d975e59fd522a53b443078a21ab68de1e575f103d4c02aee037 ./phonon_coreml.py4f6790ec94fe4429b10397c013563d0a51119953ff6d3da466bbcb23a25dee2a ./Phonon-2.mlpackage/Data/com.apple.CoreML/model.mlmodel93aa991318a00ed492fdbb724e7bca4e6a69c6cf671ab4f14a14ef6101e7648b ./Phonon-2.mlpackage/Data/com.apple.CoreML/weights/weight.bin6ebc9309aea0e16bda9c7558521fef6307fac0afba9a5b4959fea45ed7cd0429 ./Phonon-2.mlpackage/Manifest.json59e8df6143b4c24e09df1e1bca544c75593718cdd0aabbd5cef2737de182edb3 ./phonon-coreml-src.tgz66520a544c6d45290b8ba2f754480f7c7a7773578066f956db671af87d8c8c8e ./README.mde56182a557f5bae30fe37bc8333cf9d0caf323aaae42b1e4465ad9270bf048f6 ./segmenter_np.py
123version https://git-lfs.github.com/spec/v1oid sha256:fe289e3f061bdb71c628ddc6ce30edfe0b2c0915413423234bc3096457ecba1esize 17664492123version https://git-lfs.github.com/spec/v1oid sha256:36fa7202dda85c603af60d930ab88d7e9f0d2a619490aff46f5384db924cfa70size 13301279
1234567891 unmodified line1112131415161718192021{"name": "Phonon-2 Core ML","version": "1.0","container_sha256": "4b6bfa3a12cc3c4e0a54f2ab3ec4ca7a842b09e5c7ecfc8e7ca0ac6cc8c11468","multifunction": "Phonon-2.mlpackage","buckets_s": [5,10,15,1 unmodified line],"program_prefix": "enc_","frames_rule": "hf","residual_scale": 64.0,"weights": "int8 per output channel (the five-value encoder's one-dot values), 16-bit float activations; one weight blob shared by the four functions","inputs": "mel [1,128,T] fp32 normalised log-mel, zero-padded to the function's length; m1/m2/m3 frame masks after each stride-2 conv; kmask additive key mask over encoder tokens (0 / -1e4); pos [1,2*T3-1,1024] relative-position table","output": "enc [1,T3,640] = encoder output after the projector; greedy TDT (durations 0-4, blank 8192, at most 10 symbols per frame) with decoder.bin","decoder_bin": "prediction network, joint and vocabulary: 6-bit tables stored as int8 codes with 16-bit float row scales","min_os": "macOS 15 / iOS 18","compute_units": "cpuAndNeuralEngine"}1234567891 unmodified line1112131415161718192021222324252627282930313233{"name": "Phonon-2 Core ML","version": "3.0","container_sha256": "4b6bfa3a12cc3c4e0a54f2ab3ec4ca7a842b09e5c7ecfc8e7ca0ac6cc8c11468","multifunction": "Phonon-2.mlpackage","functions_s": [5,10,15,1 unmodified line],"program_prefix": "enc_","frames_rule": "hf","pos_input": {"5": false,"10": false,"15": false,"35": true},"io": "float32","long_audio": "windows15","window_s": 15,"band_min_s": 10,"overlap_s": 2.0,"single_shot_max_s": 35,"residual_scale": 64.0,"weights": "exact five-value palettes (sparse-g16-6b: 1-bit zero mask + 64-entry fp16 LUT per 16 output rows), 16-bit float activations; one weight blob shared by all functions; relative keys constant-folded for the 15 s function and sliced from that one table for the 5 s and 10 s functions","inputs": "mel [1,128,T] normalised log-mel, zero-padded to the function's length; m1/m2/m3 frame masks after each stride-2 conv; kmask additive key mask over encoder frames (0 / -1e4); pos [1,2*T3-1,1024] relative-position table (functions with pos_input only)","output": "enc [1,T3,640] = encoder output after the projector; greedy TDT (durations 0-4, blank 8192, at most 10 symbols per frame) with decoder.bin","decoder_bin": "prediction network, joint and vocabulary: 6-bit tables packed 4 codes per 3 bytes (format v2) with 16-bit float row scales","min_os": "macOS 15 / iOS 18","compute_units": "cpuAndNeuralEngine"}
123version https://git-lfs.github.com/spec/v1oid sha256:7fe41177ca4698508fcb153675c6b8f3d1aad3b06ffc61e65269836663470effsize 21933123version https://git-lfs.github.com/spec/v1oid sha256:59e8df6143b4c24e09df1e1bca544c75593718cdd0aabbd5cef2737de182edb3size 44549
123456789101112131415161718191 unmodified line212223242526276 unmodified lines343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121#!/usr/bin/env python3"""Phonon-2 Core ML reference runner (Python): wav/PCM in, text out. Needs coremltools, numpy, soundfile (no torch).python phonon_coreml.py <bundle-dir> file.wav [more.wav ...] [--json out.json] [--frames pip|hf] [--compute CPU_AND_NE|ALL|CPU_AND_GPU]bundle-dir holds manifest.json, decoder.bin and the Core ML package(s) named in the manifest. The encoder runs on the Neural Engine;the greedy TDT decoder runs here in numpy. Audio longer than 35 s is cut at quiet points into 25-35 s windows and the windows arejoined, the same rule as the other Phonon-2 engines. Nothing is padded with silence: shorter audio is masked inside its program."""import json, os, sys, timeimport numpy as npHERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)from frontend import log_mel, HOPfrom segmenter_np import plan, is_silentBLANK = 8192; DUR = [0, 1, 2, 3, 4]; MAXSYM = 10def _sig(x): return 1.0 / (1.0 + np.exp(-x))class DecoderBin:1 unmodified linedef __init__(self, path):d = open(path, "rb").read(); hl = int.from_bytes(d[:4], "little"); self.h = json.loads(d[4:4 + hl]); blob = d[4 + hl:]A = {}for a in self.h["arrays"]: A[a["name"]] = np.frombuffer(blob, dtype=np.dtype(a["dtype"]), count=int(np.prod(a["shape"])), offset=a["offset"]).reshape(a["shape"])def W(n): return A[n + ".q"].astype(np.float32) * A[n + ".scale"].astype(np.float32)[:, None]self.emb = W("decoder.embedding.weight").copy(); self.emb[BLANK] = 0self.L = [(W(f"decoder.lstm.weight_ih_l{l}"), W(f"decoder.lstm.weight_hh_l{l}"), A[f"decoder.lstm.bias_ih_l{l}"].astype(np.float32) + A[f"decoder.lstm.bias_hh_l{l}"].astype(np.float32)) for l in range(2)]6 unmodified linesg = Wi @ x + Wh @ h[l] + b; i, f, gg, o = np.split(g, 4); c2[l] = _sig(f) * c[l] + _sig(i) * np.tanh(gg); h2[l] = _sig(o) * np.tanh(c2[l]); x = h2[l]return self.Pw @ x + self.Pb, h2, c2def decode(self, enc):T3 = enc.shape[0]; h = np.zeros((2, 640), np.float32); c = np.zeros((2, 640), np.float32); d, h, c = self.step(BLANK, h, c); toks = []; t = 0; nsym = 0while t < T3:j = np.maximum(enc[t] + d, 0.0); pred = int(np.argmax(self.Ht @ j + self.bt)); dur = DUR[int(np.argmax(self.Hd @ j + self.bd))]if pred != BLANK: toks.append(pred); d, h, c = self.step(pred, h, c)t += dur; nsym += 1if dur != 0: nsym = 0elif nsym >= MAXSYM: t += 1; nsym = 0return toksdef text(self, toks):def special(p): return (p.startswith("<|") and p.endswith("|>")) or p in ("<unk>", "<pad>")return "".join(self.vocab[t] for t in toks if not special(self.vocab[t])).replace("▁", " ").strip()class Phonon2CoreML:def __init__(self, bundle, compute="CPU_AND_NE", frames=None):import coremltools as ctself.m = json.load(open(os.path.join(bundle, "manifest.json"))); self.dec = DecoderBin(os.path.join(bundle, "decoder.bin"))assert self.dec.container_sha256 == self.m["container_sha256"], "decoder.bin and manifest come from different containers"self.frames = frames or self.m.get("frames_rule", "hf"); self.cu = getattr(ct.ComputeUnit, compute); self.bundle = bundle; self.ct = ctself.buckets = sorted(self.m["buckets_s"]); self.progs = {}; self.pos = {}; self.load_s = 0.0# functions load lazily on first use (a short utterance needs only the 5 s function); the compiled copy is made once and kept# P2_NO_COMPILED=1 skips the compiled-model path (loads the .mlpackage directly; useful where CompiledMLModel misbehaves, e.g. VMs without a Neural Engine)self._comp = None if os.environ.get("P2_NO_COMPILED") else (self._compiled(os.path.join(bundle, self.m["multifunction"]), self.cu) if self.m.get("multifunction") else None)def prog(self, s):if s not in self.progs:t0 = time.perf_counter(); fn = f"{self.m['program_prefix']}{int(s)}s"if self.m.get("multifunction"):pkg = os.path.join(self.bundle, self.m["multifunction"])self.progs[s] = self.ct.models.CompiledMLModel(self._comp, compute_units=self.cu, function_name=fn) if self._comp else self.ct.models.MLModel(pkg, function_name=fn, compute_units=self.cu)else: self.progs[s] = self.ct.models.MLModel(os.path.join(self.bundle, fn + ".mlpackage"), compute_units=self.cu)self.load_s += time.perf_counter() - t0return self.progs[s]def _compiled(self, pkg, cu):import coremltools as ct, shutilname = os.path.splitext(os.path.basename(pkg))[0] + ".mlmodelc"for d in (os.path.dirname(pkg), os.path.join(os.path.expanduser("~/Library/Caches/phonon-coreml"), self.m["container_sha256"][:16])):c = os.path.join(d, name)if os.path.isdir(c): return ctry:tmp = ct.models.utils.compile_model(pkg); d = os.path.join(os.path.expanduser("~/Library/Caches/phonon-coreml"), self.m["container_sha256"][:16]); os.makedirs(d, exist_ok=True)c = os.path.join(d, name); shutil.move(tmp, c); return cexcept Exception: return None@staticmethoddef frames_for(sec): return 1 + int(round(sec * 16000)) // HOP@staticmethoddef sub(n):for _ in range(3): n = (n - 1) // 2 + 1return ndef pos_table(self, T3):if T3 not in self.pos:P = 2 * T3 - 1; p = np.arange(T3 - 1, -T3, -1, dtype=np.float64)[:, None]; invf = 1.0 / (10000.0 ** (np.arange(0, 1024, 2) / 1024.0)); f = p * invf[None, :]t = np.zeros((1, P, 1024), np.float32); t[0, :, 0::2] = np.sin(f); t[0, :, 1::2] = np.cos(f); self.pos[T3] = treturn self.pos[T3]def encode(self, wave):feats = log_mel(wave, self.frames); n = feats.shape[1]; sec = n * HOP / 16000s = next((b for b in self.buckets if sec <= b + 0.02), None); assert s is not None, f"window of {sec:.1f}s exceeds the largest program"T = self.frames_for(s); mel = np.zeros((1, 128, T), np.float32); mel[0, :, :n] = featslens = [n]; Ts = [T]for _ in range(3): lens.append((lens[-1] - 1) // 2 + 1); Ts.append((Ts[-1] - 1) // 2 + 1)feed = {"mel": mel}for i, name in enumerate(("m1", "m2", "m3")):m = np.zeros((1, 1, Ts[i + 1], 1), np.float32); m[:, :, :lens[i + 1]] = 1; feed[name] = mkm = np.full((1, 1, 1, Ts[3]), -1e4, np.float32); km[..., :lens[3]] = 0; feed["kmask"] = km; feed["pos"] = self.pos_table(Ts[3])y = np.asarray(self.prog(s).predict(feed)["enc"], np.float32)[0, :lens[3]]return ydef transcribe_window(self, w):if is_silent(w): return ""return self.dec.text(self.dec.decode(self.encode(w)))def transcribe(self, wave):wave = np.asarray(wave, np.float32).reshape(-1); parts = [self.transcribe_window(wave[a:b]) for a, b in plan(wave)]return " ".join(p for p in parts if p)def main():import argparse, soundfile as sfap = argparse.ArgumentParser(); ap.add_argument("bundle"); ap.add_argument("wavs", nargs="+"); ap.add_argument("--json"); ap.add_argument("--frames", choices=["pip", "hf"]); ap.add_argument("--compute", default="CPU_AND_NE")a = ap.parse_args(); m = Phonon2CoreML(a.bundle, a.compute, a.frames); rows = []; ta = tw = 0.0for p in a.wavs:w, sr = sf.read(p, dtype="float32")if w.ndim > 1: w = w.mean(1)if sr != 16000:import scipy.signal as ss; w = ss.resample_poly(w, 16000, sr)t0 = time.perf_counter(); text = m.transcribe(w); dt = time.perf_counter() - t0; ta += len(w) / 16000; tw += dtprint(text); rows.append({"path": os.path.basename(p), "audio_s": round(len(w) / 16000, 2), "wall_s": round(dt, 4), "text": text})if a.json: json.dump({"runtime": "phonon_coreml.py (Core ML encoder, numpy TDT)", "frames_rule": m.frames, "compute": a.compute, "load_s": round(m.load_s, 2), "audio_s": round(ta, 2), "decode_wall_s": round(tw, 3), "x_realtime": round(ta / tw, 1) if tw else None, "rows": rows}, open(a.json, "w"), indent=1)if __name__ == "__main__": main()12345678910111213141516171819201 unmodified line2223242526272829303132336 unmodified lines404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244#!/usr/bin/env python3"""Phonon-2 Core ML reference runner (Python example): wav in, text + words out. Needs coremltools, numpy, soundfile (no torch).python phonon_coreml.py <bundle-dir> file.wav [more.wav ...] [--json out.json] [--reference] [--frames hf|pip]bundle-dir holds manifest.json, decoder.bin and Phonon-2.mlpackage (encoder functions enc_5s ... enc_35s over one weight blob; each windowruns the smallest function that holds it). The encoder runs onthe Neural Engine; the greedy TDT decoder runs here in numpy (slow but exact in structure; the Swift package uses the C loop). Audio up to35 s is one window; longer audio is cut into windows of at most 15 s at quiet points, with a 2 s overlap and a word-level stitch whenthere is no quiet point. `words` is one {text, start, end} per word in seconds from the start of the file, the pip engine's shape."""import json, os, sys, timeimport numpy as npHERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)from frontend import log_mel, HOPfrom segmenter_np import plan as reference_plan, is_silentBLANK = 8192; DUR = [0, 1, 2, 3, 4]; MAXSYM = 10; FRAME_S = 0.08; SR = 16000def _sig(x): return 1.0 / (1.0 + np.exp(-x))class DecoderBin:1 unmodified linedef __init__(self, path):d = open(path, "rb").read(); hl = int.from_bytes(d[:4], "little"); self.h = json.loads(d[4:4 + hl]); blob = d[4 + hl:]A = {}for a in self.h["arrays"]:n = int(np.prod(a["shape"]))if a["dtype"] == "int6p": # v2: 6-bit codes, 4 per 3 bytes (little-endian bit order), two's complementb = np.frombuffer(blob, np.uint8, count=a["bytes"], offset=a["offset"]).reshape(-1, 3).astype(np.uint32); w = b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16)u = np.stack([(w >> (6 * k)) & 63 for k in range(4)], 1).reshape(-1)[:n].astype(np.int16); A[a["name"]] = np.where(u >= 32, u - 64, u).astype(np.int8).reshape(a["shape"])else: A[a["name"]] = np.frombuffer(blob, dtype=np.dtype(a["dtype"]), count=n, offset=a["offset"]).reshape(a["shape"])def W(n): return A[n + ".q"].astype(np.float32) * A[n + ".scale"].astype(np.float32)[:, None]self.emb = W("decoder.embedding.weight").copy(); self.emb[BLANK] = 0self.L = [(W(f"decoder.lstm.weight_ih_l{l}"), W(f"decoder.lstm.weight_hh_l{l}"), A[f"decoder.lstm.bias_ih_l{l}"].astype(np.float32) + A[f"decoder.lstm.bias_hh_l{l}"].astype(np.float32)) for l in range(2)]6 unmodified linesg = Wi @ x + Wh @ h[l] + b; i, f, gg, o = np.split(g, 4); c2[l] = _sig(f) * c[l] + _sig(i) * np.tanh(gg); h2[l] = _sig(o) * np.tanh(c2[l]); x = h2[l]return self.Pw @ x + self.Pb, h2, c2def decode(self, enc):"""-> [(token, frame, duration)]: greedy TDT, the same control flow as the C loop and the MLX engine."""T3 = enc.shape[0]; h = np.zeros((2, 640), np.float32); c = np.zeros((2, 640), np.float32); d, h, c = self.step(BLANK, h, c); toks = []; t = 0; nsym = 0while t < T3:j = np.maximum(enc[t] + d, 0.0); pred = int(np.argmax(self.Ht @ j + self.bt)); dur = DUR[int(np.argmax(self.Hd @ j + self.bd))]if pred == BLANK and dur == 0: dur = 1if pred != BLANK: toks.append((pred, t, dur)); d, h, c = self.step(pred, h, c)if dur == 0:nsym += 1if nsym >= MAXSYM: dur = 1; nsym = 0else: nsym = 0t += durreturn toksdef pieces(self, toks):"""(piece with the word marker as a leading space, start s, duration s) per token, specials dropped."""out = []for tok, fr, du in toks:p = self.vocab[tok]if (p.startswith("<|") and p.endswith("|>")) or p in ("<unk>", "<pad>"): continueout.append((p.replace("▁", " "), fr * FRAME_S, du * FRAME_S))return outdef _is_punct(s): return bool(s) and not any(ch.isalnum() for ch in s)def words_from_tokens(tokens, offset=0.0, limit=None):"""pip rule (fermion._speech.segment.words_from_tokens)."""words = []; cur = []def flush():if not cur: returntext = "".join(t[0] for t in cur).strip()if text:end = cur[-1][1] + cur[-1][2]if limit is not None: end = min(end, limit)words.append({"text": text, "start": round(cur[0][1] + offset, 3), "end": round(max(end, cur[0][1]) + offset, 3)})cur.clear()for piece, start, dur in tokens:if piece.startswith(" ") and cur and (not piece.strip() or not _is_punct(piece.strip())): flush()cur.append((piece, start, dur))flush(); return wordsdef stitch(kept, incoming, split, jitter=0.25):"""word-level stitch at an overlapped boundary (see Words.swift)."""while kept and kept[-1]["start"] >= split: kept.pop()seam = [w for w in kept if w["end"] > split - jitter - 0.5]for w in incoming:if w["start"] < split - jitter: continuedup = Falsefor a in seam:ov = min(a["end"], w["end"]) - max(a["start"], w["start"])if ov <= 1e-9: continueif a["text"].lower() == w["text"].lower() or ov > 0.5 * min(a["end"] - a["start"], w["end"] - w["start"]): dup = True; breakif not dup: kept.append(w)def plan_windows(audio, window_s=15.0, band_min_s=10.0, overlap_s=2.0, single_shot_max_s=35.0):"""-> [(start, end, split_or_None)] samples; the Swift Windower, line for line."""n = audio.sizeif n <= int(single_shot_max_s * SR): return [(0, n, None)]block = int(0.05 * SR); nb = -(-n // block); padded = np.zeros(nb * block, np.float32); padded[:n] = audiorms = np.sqrt(np.mean(padded.reshape(nb, block) ** 2, axis=1))W = int(window_s * SR) - 400; overlap = int(overlap_s * SR); out = []; start = 0; split = Nonewhile n - start > W:lo, hi = start + int(band_min_s * SR), start + Wb0, b1, bs = -(-lo // block), min(hi // block, nb), start // blockcut = Noneif b0 < b1 and b1 > bs:gate = max(0.004, 0.18 * float(rms[bs:b1].max())); best = None; i = b0while i < b1:if rms[i] > gate: i += 1; continuej = iwhile j < b1 and rms[j] <= gate: j += 1cand = (j - i, -abs((i + j) * block // 2 - hi), (i + j) * block // 2)if best is None or cand > best: best = candi = jif best: cut = best[2]if cut is not None: out.append((start, cut, split)); start = cut; split = Noneelse:out.append((start, hi, split)); s_lo, s_hi = hi - overlap + int(0.3 * SR), hi - int(0.3 * SR)b = -(-s_lo // block); bestb, bestv = -1, np.infwhile (b + 1) * block <= s_hi and b < nb:if rms[b] < bestv: bestv, bestb = rms[b], bb += 1split = bestb * block + block // 2 if bestb >= 0 else hi - overlap // 2; start = hi - overlapout.append((start, n, split)); return outdef speech_blocks(x, block=800):"""50 ms blocks above the reference gate (max(0.004, 0.18 x peak RMS of the window))."""n = x.size // blockif n == 0: return np.zeros(0, bool)rms = np.sqrt((x[:n * block].reshape(n, block) ** 2).mean(1)); return rms > max(0.004, 0.18 * float(rms.max()))def worst_gap(speech, words):"""longest run of 50 ms blocks no word covers -> (start s, end s, speech s) or None"""covered = np.zeros(speech.size, bool)for w in words: covered[max(0, int(w["start"] / 0.05)):min(speech.size, int(w["end"] / 0.05) + 1)] = Truebest = None; i = 0while i < speech.size:if covered[i]: i += 1; continuej = iwhile j < speech.size and not covered[j]: j += 1sp = int(speech[i:j].sum())if best is None or sp > best[2]: best = (i, j, sp)i = jreturn None if best is None else (best[0] * 0.05, best[1] * 0.05, best[2] * 0.05)class Phonon2CoreML:RESCUE_GAP_S = 1.5; RESCUE_MIN_DENSITY = 2.4def rescue(self, x, toks, depth=0):"""long-audio windows only: >= RESCUE_GAP_S of speech energy with no word (or a very sparse window) -> re-decode as two halvessplit at the gap's quietest block; keep the halves when they give more words. Returns new token triples or None."""secs = x.size / SRif secs < 3.0 or depth >= 2: return Nonespeech = speech_blocks(x); speech_s = float(speech.sum()) * 0.05if speech_s < 2.0: return Nonewords = words_from_tokens(toks, 0.0, secs); gap = worst_gap(speech, words)if gap is None or not (gap[2] >= self.RESCUE_GAP_S or len(words) / speech_s < self.RESCUE_MIN_DENSITY): return Nonecut = (gap[0] + gap[1]) / 2if gap[1] - gap[0] > 0.4:b0 = int(gap[0] / 0.05) + 1; b1 = int(gap[1] / 0.05); e = [(float((x[b * 800:(b + 1) * 800] ** 2).sum()), b) for b in range(b0, b1)]if e: cut = min(e)[1] * 0.05 + 0.025cut = min(max(cut, 1.0), secs - 1.0); m = int(cut * SR); out = []for a, b in ((0, m), (m, x.size)):part = x[a:b]; t = [] if is_silent(part) else self.dec.pieces(self.dec.decode(self.encode(part)))deeper = self.rescue(part, t, depth + 1)if deeper is not None: t = deeperout.extend((pc, st + a / SR, du) for pc, st, du in t)return out if len(words_from_tokens(out, 0.0, secs)) > len(words) else Nonedef __init__(self, bundle, compute="CPU_AND_NE", frames=None, long_audio=None):import coremltools as ctself.m = json.load(open(os.path.join(bundle, "manifest.json"))); self.dec = DecoderBin(os.path.join(bundle, "decoder.bin"))assert self.dec.container_sha256 == self.m["container_sha256"], "decoder.bin and manifest come from different containers"self.frames = frames or self.m.get("frames_rule", "hf"); self.cu = getattr(ct.ComputeUnit, compute); self.bundle = bundle; self.ct = ctself.long_audio = long_audio or self.m.get("long_audio", "windows15"); self.functions = sorted(self.m["functions_s"]); self.progs = {}; self.pos = {}; self.load_s = 0.0self._comp = self._compiled(os.path.join(bundle, self.m["multifunction"]))def cache_key(self, pkg):"""Same key as the Swift package (Transcriber.cacheKey): container + FNV-1a 64 of the program spec + the weight blob's size, so twopackages of the same weights never share a compiled model, and Swift and Python share one compiled copy."""d = os.path.join(pkg, "Data", "com.apple.CoreML"); h = 0xcbf29ce484222325for b in open(os.path.join(d, "model.mlmodel"), "rb").read() + os.path.getsize(os.path.join(d, "weights", "weight.bin")).to_bytes(8, "little"):h = ((h ^ b) * 0x100000001b3) & 0xFFFFFFFFFFFFFFFFreturn self.m["container_sha256"][:16] + "-" + format(h, "016x")def _compiled(self, pkg):import shutilname = os.path.splitext(os.path.basename(pkg))[0] + ".mlmodelc"root = os.environ.get("P2_COMPILE_DIR", os.path.expanduser("~/Library/Caches/phonon-coreml")); key = self.cache_key(pkg)for d in (os.path.dirname(pkg), os.path.join(root, key)):c = os.path.join(d, name)if os.path.isdir(c): return ctmp = self.ct.models.utils.compile_model(pkg); d = os.path.join(root, key); os.makedirs(d, exist_ok=True); c = os.path.join(d, name); shutil.move(tmp, c); return cdef prog(self, s):if s not in self.progs:t0 = time.perf_counter(); self.progs[s] = self.ct.models.CompiledMLModel(self._comp, compute_units=self.cu, function_name=f"{self.m['program_prefix']}{int(s)}s"); self.load_s += time.perf_counter() - t0return self.progs[s]@staticmethoddef frames_for(sec): return 1 + int(round(sec * SR)) // HOPdef pos_table(self, T3):if T3 not in self.pos:P = 2 * T3 - 1; p = np.arange(T3 - 1, -T3, -1, dtype=np.float64)[:, None]; invf = 1.0 / (10000.0 ** (np.arange(0, 1024, 2) / 1024.0)); f = p * invf[None, :]t = np.zeros((1, P, 1024), np.float32); t[0, :, 0::2] = np.sin(f); t[0, :, 1::2] = np.cos(f); self.pos[T3] = treturn self.pos[T3]def encode(self, wave):feats = log_mel(wave, self.frames); n = feats.shape[1]; sec = n * HOP / SR + 0.02s = next((b for b in self.functions if sec <= b), None); assert s is not None, f"window of {sec:.1f}s exceeds the largest function"T = self.frames_for(s); mel = np.zeros((1, 128, T), np.float32); mel[0, :, :n] = feats; lens = [n]; Ts = [T]for _ in range(3): lens.append((lens[-1] - 1) // 2 + 1); Ts.append((Ts[-1] - 1) // 2 + 1)feed = {"mel": mel}for i, name in enumerate(("m1", "m2", "m3")):m = np.zeros((1, 1, Ts[i + 1], 1), np.float32); m[:, :, :lens[i + 1]] = 1; feed[name] = mkm = np.full((1, 1, 1, Ts[3]), -1e4, np.float32); km[..., :lens[3]] = 0; feed["kmask"] = kmp = self.prog(s)pi = self.m.get("pos_input", True); pi = pi.get(str(int(s)), True) if isinstance(pi, dict) else pi # per function or one flagif pi: feed["pos"] = self.pos_table(Ts[3])if self.m.get("io") == "float16": feed = {k: v.astype(np.float16) for k, v in feed.items()} # bundles with 16-bit float inputsreturn np.asarray(p.predict(feed)["enc"], np.float32)[0, :lens[3]]def transcribe(self, wave):"""-> {"text", "words", "segments"}"""wave = np.asarray(wave, np.float32).reshape(-1)wins = [(a, b, None) for a, b in reference_plan(wave)] if self.long_audio == "reference" else plan_windows(wave)words = []; segments = []for i, (a, b, split) in enumerate(wins):w = wave[a:b]; toks = [] if is_silent(w) else self.dec.pieces(self.dec.decode(self.encode(w)))if len(wins) > 1 and self.long_audio != "reference":r = self.rescue(w, toks)if r is not None: toks = rws = words_from_tokens(toks, a / SR, (b - a) / SR)if split is not None: stitch(words, ws, split / SR)else: words.extend(ws)segments.append({"id": i, "start": round(a / SR, 3), "end": round(b / SR, 3), "text": " ".join(x["text"] for x in ws)})return {"text": " ".join(x["text"] for x in words), "words": words, "segments": segments}def main():import argparse, soundfile as sfap = argparse.ArgumentParser(); ap.add_argument("bundle"); ap.add_argument("wavs", nargs="+"); ap.add_argument("--json"); ap.add_argument("--frames", choices=["pip", "hf"]); ap.add_argument("--compute", default="CPU_AND_NE"); ap.add_argument("--reference", action="store_true")a = ap.parse_args(); m = Phonon2CoreML(a.bundle, a.compute, a.frames, "reference" if a.reference else None); rows = []; ta = tw = 0.0for p in a.wavs:w, sr = sf.read(p, dtype="float32")if w.ndim > 1: w = w.mean(1)if sr != SR:import scipy.signal as ss; w = ss.resample_poly(w, SR, sr)t0 = time.perf_counter(); r = m.transcribe(w); dt = time.perf_counter() - t0; ta += len(w) / SR; tw += dtprint(r["text"]); rows.append({"path": os.path.basename(p), "audio_s": round(len(w) / SR, 2), "wall_s": round(dt, 4), **r})if a.json: json.dump({"runtime": "phonon_coreml.py (Core ML encoder, numpy TDT)", "frames_rule": m.frames, "compute": a.compute, "long_audio": m.long_audio, "load_s": round(m.load_s, 2), "audio_s": round(ta, 2), "decode_wall_s": round(tw, 3), "x_realtime": round(ta / tw, 1) if tw else None, "rows": rows}, open(a.json, "w"), indent=1)if __name__ == "__main__": main()
NOTICE+4-2
Phonon-2.mlpackage/Data/com.apple.CoreML/model.mlmodel+2-2
Phonon-2.mlpackage/Data/com.apple.CoreML/weights/weight.bin+2-2
Phonon-2.mlpackage/Manifest.json+3-3
README.md+35-28
SHA256SUMS+17-17
decoder.bin+2-2
manifest.json+17-5
phonon-coreml-src.tgz+2-2
phonon_coreml.py+184-61