ZONOS3-Mini / desktop /speak.py
mlboydaisuke's picture
Add ZONOS3-Mini as three float32 LiteRT graphs with an Android runner
2e0d354 verified
Raw History Blame Contribute Delete
9.94 kB
"""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="<f4", count=n)
if noise.size != n or not np.isfinite(noise).all() or np.any(noise <= 0):
raise ValueError(f"missing or invalid kit draws at sampled row {self.rows}")
self.rows += 1
return (probs / torch.from_numpy(noise).view_as(probs)).argmax(1, keepdim=True)
def clip_embedding(path, model, graph):
rate, pcm = wavfile.read(path)
if pcm.dtype == np.uint8:
wave = (pcm.astype(np.float32) - 128) / 128
elif pcm.dtype.kind == "i":
wave = pcm.astype(np.float32) / float(1 << (pcm.dtype.itemsize * 8 - 1))
elif pcm.dtype.kind == "f":
wave = pcm.astype(np.float32)
else:
raise ValueError(f"unsupported WAV encoding: {pcm.dtype}")
front = SpeakerHost(model, sys.modules[type(model).__module__])
# A 10 s bucket contains 998 complete 25 ms windows at a 10 ms hop.
mono = front.wav16k(wave.T.copy(), rate)[:160000]
if len(mono) < front.size or not np.isfinite(mono).all():
raise ValueError("speaker WAV requires at least one finite 25 ms frame")
fb = front.fbank_np(mono)[:998]
embedding, = graph.run(front.inputs(fb))
return torch.from_numpy(embedding.reshape(-1))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("sentence")
parser.add_argument("--model", required=True, type=Path, help="local Zyphra/ZONOS3-Mini-hf snapshot at e39d30df")
parser.add_argument("--graphs", required=True, type=Path, help="directory containing the fp32 language model, decoder, and speaker encoder graphs")
parser.add_argument("--out", required=True, type=Path, help="new output folder")
parser.add_argument("--draws", type=Path, help="optional kit takes/<tag>/draws.f32")
parser.add_argument("--speaker-wav", type=Path, help="condition on a recording instead of Savannah reference codes")
parser.add_argument("--seed", type=int, default=1000)
args = parser.parse_args()
if not args.sentence.strip() or args.out.exists():
parser.error("supply a nonempty sentence and a new output directory")
torch.set_num_threads(4)
model = AutoModel.from_pretrained(str(args.model.resolve()), trust_remote_code=True,
local_files_only=True, dtype=torch.float32).to("cpu").eval()
environment = cm.Environment.create(options=cm.EnvironmentOptions(runtime_path=str(Path(cm.__file__).parent)))
files = {"lm":"lm_step_p768.tflite", "codec":"codec_dec_f150.tflite", "speaker":"spk_enc_t998.tflite"}
with contextlib.ExitStack() as resources, torch.no_grad():
graphs = {key: CpuGraph(args.graphs / name, environment, resources) for key, name in files.items()}
if args.speaker_wav:
voice = {"speaker_embedding": clip_embedding(args.speaker_wav, model, graphs["speaker"]),
"speaker_mode": "embedding"}
else:
voice = {"voice":"Savannah"}
model.lm = StepLM(model, graphs["lm"])
codec = CodecHost(model, 150)
def decode(codes):
frames = len(codes)
if frames > 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("<i4")
record = {"text": args.sentence, "language":"en_us", "seed":args.seed,
"voice":"recording" if args.speaker_wav else "Savannah", "threads":torch.get_num_threads(),
"sampling":"kit" if draws is not None else "seeded PyTorch",
"kit_draw_rows":draws.rows if draws is not None else 0,
"graph_calls":{key:g.calls for key,g in graphs.items()}, "frames":len(codes),
"samples":len(wave),"sample_rate_hz":take.sampling_rate}
args.out.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=args.out.parent) as tmp:
stage = Path(tmp) / "audio"
stage.mkdir()
np.save(stage / "codes.npy", codes)
np.save(stage / "waveform.npy", wave)
wavfile.write(stage / "speech.wav", take.sampling_rate, (np.clip(wave, -1, 1)*32767).round().astype("<i2"))
(stage / "run.json").write_text(json.dumps(record, indent=2)+"\n")
stage.rename(args.out)
print(json.dumps(record))
if __name__ == "__main__":
main()