"""Synthesize one English request using three fp32 LiteRT graphs and four Mac CPU threads.""" import argparse import contextlib import json import math import mmap import os from pathlib import Path import sys import tempfile os.environ["OMP_NUM_THREADS"] = "4" os.environ["HF_HUB_OFFLINE"] = "1" os.environ["HF_HUB_DISABLE_XET"] = "1" os.environ.setdefault("HF_HOME", str(Path.cwd() / ".zonos-cache" / "hf")) sys.path.insert(0, str(Path(__file__).resolve().parent)) import numpy as np import torch from ai_edge_litert import compiled_model as cm, schema_py_generated as schema from scipy.io import wavfile from transformers import AutoModel from host import CodecHost, LMHost, SpeakerHost def graph_layout(path): """Read signature names and shapes, leaving external weight buffers mapped.""" with path.open("rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as data: model = schema.Model.GetRootAsModel(data, 0) sig = model.SignatureDefs(0) sg = model.Subgraphs(sig.SubgraphIndex()) layout = {} for role in ("Inputs", "Outputs"): items = {} for i in range(getattr(sig, role + "Length")()): mapping = getattr(sig, role)(i) tensor = sg.Tensors(mapping.TensorIndex()) if tensor.Type() != schema.TensorType.FLOAT32: raise ValueError(f"{path.name}: graph signature inputs and outputs must use float32") items[mapping.Name().decode()] = tuple(map(int, tensor.ShapeAsNumpy())) layout[role] = items return layout class CpuGraph: def __init__(self, path, environment, resources): layout = graph_layout(path) options = cm.Options(hardware_accelerators=cm.HardwareAccelerator.CPU, cpu_options=cm.CpuOptions(num_threads=4)) self.model = cm.CompiledModel.from_file(str(path), options=options, environment=environment) resources.callback(self.model.close) signature = self.model.get_signature_by_index(0) self.inputs = self.model.create_input_buffers(0) self.outputs = self.model.create_output_buffers(0) for buffer in self.inputs + self.outputs: resources.callback(buffer.destroy) self.input_layout = [(int(n.removeprefix("args_")), layout["Inputs"][n]) for n in signature["inputs"]] self.output_layout = [(int(n.removeprefix("output_")), layout["Outputs"][n]) for n in signature["outputs"]] self.calls = 0 def run(self, args): for buffer, (index, shape) in zip(self.inputs, self.input_layout, strict=True): x = np.ascontiguousarray(args[index], dtype=np.float32) if x.shape != shape: raise ValueError(f"args_{index} has shape {x.shape}, expected {shape}") buffer.write(x) self.model.run_by_index(0, self.inputs, self.outputs) self.calls += 1 result = [None] * len(self.outputs) for buffer, (index, shape) in zip(self.outputs, self.output_layout, strict=True): result[index] = buffer.read(math.prod(shape), np.float32).reshape(shape) return result class StepLM(torch.nn.Module): def __init__(self, model, graph): super().__init__() self.multi_output = model.lm.multi_output self.host = LMHost(model, 768) self.graph = graph def forward(self, ids, cache, *, speaker_rows=None, condition_rows=None, logits_to_keep=0): if not hasattr(cache, "_lrt"): cache._lrt = self.host.fresh() state = cache._lrt if state["pos"] != cache.position: raise ValueError("inconsistent LM cache position") if state["pos"] + len(ids) > 768: raise ValueError("CapacityReached: LM step position must be below 768") results = [] for r, row in enumerate(ids.cpu().numpy()): x = self.host.row(row, state["pos"], speaker_rows, condition_rows) logits = self.host.step(self.graph.run, state, x) if logits_to_keep <= 0 or r >= len(ids) - logits_to_keep: results.append(logits) cache.position = state["pos"] return torch.from_numpy(np.stack(results)) class KitDraws(torch.overrides.TorchFunctionMode): """Use the kit variates for the author's final multinomial operation only.""" def __init__(self, stream): super().__init__() self.stream = stream self.rows = 0 def __torch_function__(self, func, types, args=(), kwargs=None): kwargs = kwargs or {} if func is not torch.multinomial: return func(*args, **kwargs) probs, = args if probs.shape != (10, 4098) or kwargs.get("num_samples") != 1: raise ValueError("unexpected multinomial call from the model") n = probs.numel() noise = np.fromfile(self.stream, dtype=" codec.frames: raise ValueError(f"BucketExceeded: {frames} frames exceed decoder bucket 150") head, = graphs["codec"].run(codec.inputs(codes.cpu().numpy())) audio = codec.audio_np(*codec.split(head, frames)) return torch.from_numpy(np.ascontiguousarray(audio, dtype=np.float32)) model.decode_codes = decode draws = KitDraws(resources.enter_context(args.draws.open("rb"))) if args.draws else None with draws if draws is not None else contextlib.nullcontext(): take = model.generate(args.sentence, language="en_us", seed=args.seed, **voice) wave = take.waveform.detach().cpu().numpy().reshape(-1) if not wave.size or not np.isfinite(wave).all(): raise ValueError("empty or nonfinite output") codes = take.codes.cpu().numpy().astype("