Download source/shruti_coreml/runtime.py from bingokingooo/shruti-coreml: direct link, hf CLI and curl.
- Browser
- Download file 5.4 kB
-
https://huggingface.co/bingokingooo/shruti-coreml/resolve/main/source/shruti_coreml/runtime.py
- Command line
-
hf download hf://bingokingooo/shruti-coreml/source/shruti_coreml/runtime.py
-
curl -L -o runtime.py https://huggingface.co/bingokingooo/shruti-coreml/resolve/main/source/shruti_coreml/runtime.py
5.4 kB
| """Run the Core ML port through the pinned upstream portable beam search.""" | |
| import argparse | |
| import importlib.util | |
| import json | |
| import subprocess | |
| from pathlib import Path | |
| import coremltools as ct | |
| import numpy as np | |
| from .sources import CATALOG, ROOT | |
| def upstream_module(): | |
| checkout = ROOT / ".upstream/shruti" | |
| expected = CATALOG["shruti_source"]["revision"] | |
| revision = subprocess.check_output(["git", "-C", str(checkout), "rev-parse", "HEAD"], text=True).strip() | |
| if revision != expected: | |
| raise ValueError(f"Unexpected upstream checkout: {revision}") | |
| path = checkout / "onnx/python/shruti_onnx/__init__.py" | |
| spec = importlib.util.spec_from_file_location("upstream_shruti_onnx", path) | |
| module = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(module) | |
| return module | |
| _upstream = upstream_module() | |
| def indices_from_history(history, tokens, cfg): | |
| """Compute the original unsigned 32-bit Engram hash on the host.""" | |
| history = np.concatenate((history, tokens), axis=1).astype(np.uint32) | |
| columns = [] | |
| for order in cfg["orders"]: | |
| for _ in range(cfg["hashes"]): | |
| seed = (0x9E3779B9 * (len(columns) + 1)) & 0xFFFFFFFF | |
| value = np.full(len(tokens), seed, np.uint32) | |
| for previous in range(order): | |
| value = (value ^ history[:, -1 - previous]) * np.uint32(0x01000193) | |
| columns.append((value ^ (value >> 15)) % cfg["slots"]) | |
| return np.stack(columns, axis=-1).astype(np.int32)[:, None, :] | |
| class CoreMLShruti(_upstream.Shruti): | |
| def __init__(self, folder, units=ct.ComputeUnit.CPU_ONLY): | |
| folder = Path(folder) | |
| self.meta = meta = json.loads((folder / "model.json").read_text()) | |
| self.vocab, self.cfg = meta["vocab"], meta["config"] | |
| self.text, self.bos, self.eos = (self.cfg[key] for key in ("text", "bos", "eos")) | |
| self.tags = {tag: self.text + i for i, tag in enumerate(self.cfg["languages"])} | |
| self.languages = (meta["language"], "en") | |
| self.state_names = tuple(meta["states"]) | |
| def load(name): | |
| compiled = folder / "assets" / f"{name}.mlmodelc" | |
| if compiled.is_dir(): | |
| return ct.models.CompiledMLModel(str(compiled), compute_units=units) | |
| return ct.models.MLModel(str(folder / "packages" / f"{name}.mlpackage"), compute_units=units) | |
| self.frontend = load("ShrutiAudioFrontend") | |
| self.stem = load("SplitStem") | |
| self.blocks = [load(f"SplitBlock{i}") for i in range(self.cfg["enc_layers"])] | |
| self.head = load("SplitHead") | |
| self.decoder = load("StaticDecoder") | |
| def init_state(self, batch): | |
| return { | |
| name: np.zeros(pin["shape"] if name == "pos" else (batch, *pin["shape"][1:]), pin["dtype"]) | |
| for name, pin in self.meta["states"].items() | |
| } | |
| def encode(self, waveform): | |
| valid_samples = len(waveform) | |
| hop = self.cfg["hop"] | |
| if not hop <= valid_samples <= self.meta["max_audio_samples"]: | |
| raise ValueError("Expected one analysis window between 10 milliseconds and 30 seconds") | |
| features = self.frontend.predict({"audio": waveform[None].astype(np.float32)})["features"] | |
| target = self.meta["max_audio_samples"] // hop + 1 | |
| features = np.pad(features, ((0, 0), (0, target - features.shape[1]), (0, 0))) | |
| stem = self.stem.predict({"features": features, "frames": np.array([valid_samples // hop], np.int32)}) | |
| hidden = stem["hidden"] | |
| for block in self.blocks: | |
| hidden = block.predict({"hidden": hidden, "length": stem["length"]})["encoded"] | |
| return self.head.predict({"hidden": hidden})["cross"][:, :int(stem["length"][0])].copy() | |
| def step(self, tokens, cross, state): | |
| batch = len(tokens) | |
| padded_batch = self.meta["beams"] | |
| if not 1 <= batch <= padded_batch: | |
| raise ValueError(f"This package supports at most {padded_batch} beams") | |
| def pad(array): | |
| padding = [(0, padded_batch - batch)] + [(0, 0)] * (array.ndim - 1) | |
| return np.pad(array, padding) | |
| for offset in range(tokens.shape[1]): | |
| current = tokens[:, offset : offset + 1].astype(np.int32) | |
| indices = indices_from_history(state["hist"], current, self.cfg) | |
| inputs = {name: array if name == "pos" else pad(array) for name, array in state.items()} | |
| result = self.decoder.predict({**inputs, "tokens": pad(current), "cross": cross, "indices": pad(indices)}) | |
| state = { | |
| name: result[f"new_{name}"] if name == "pos" else result[f"new_{name}"][:batch] | |
| for name in self.state_names | |
| } | |
| return result["logits"][:batch, 0].copy(), state | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("model", type=Path) | |
| parser.add_argument("audio", nargs="+", type=Path) | |
| parser.add_argument("--language") | |
| parser.add_argument("--compute", default="CPU_ONLY", choices=["CPU_ONLY", "CPU_AND_GPU", "CPU_AND_NE", "ALL"]) | |
| args = parser.parse_args() | |
| model = CoreMLShruti(args.model, getattr(ct.ComputeUnit, args.compute)) | |
| for path in args.audio: | |
| print(json.dumps({"audio": str(path), **model.transcribe(str(path), language=args.language)}, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |