bingokingooo's picture
Record Hindi FLEURS and verify all packages compile on iOS
01e140f verified
Raw History Blame Contribute Delete
10.6 kB
"""Export Core ML packages from a pinned, released Shruti CQ4 archive."""
import argparse
import json
import shutil
import subprocess
import types
from .archive import archive_weights
from .sources import CATALOG, ROOT, compiled_assets, fetch, model_inputs, verify
from pathlib import Path
import coremltools as ct
import numpy as np
import onnx
import torch
from coremltools.converters.mil import Builder as mb, get_new_symbol
from onnx import numpy_helper
SAMPLES = 480_000
FRAMES = SAMPLES // 160
CROSS_FRAMES = (FRAMES + 7) // 8
CACHE_LENGTH = 320
BEAMS = 5
def reference_module(path):
source = path.read_text()
# Make the encoder traceable at a fixed shape and hold the decoder cache at
# a fixed capacity. Swift supplies indexes for the unsigned n-gram hash.
edits = (
("padding=self.dw.shape[-1] // 2, groups=h.shape[-1]",
"padding=int(self.dw.shape[-1]) // 2, groups=int(h.shape[-1])"),
('k = torch.cat([st["k"], k], 2)\n v = torch.cat([st["v"], v], 2)',
'slots = torch.arange(st["k"].shape[2])\n'
' update = (slots == pos[0])[None, None, :, None]\n'
' k = torch.where(update, k, st["k"])\n'
' v = torch.where(update, v, st["v"])'),
("ok = torch.arange(P)[None, :] <= (torch.arange(S)[:, None] + (P - S))",
"ok = slots[None, :] <= pos[:, None]"),
("def forward(self, tokens, cross, *state):", "def forward(self, tokens, cross, indices, *state):"),
('idx = engram_indices(st["hist"], tok, self.orders, self.hashes, self.slots)', "idx = indices"),
("z(B, self.kv, 0, self.qk)", f"z(B, self.kv, {CACHE_LENGTH}, self.qk)"),
("z(B, self.kv, 0, self.vd)", f"z(B, self.kv, {CACHE_LENGTH}, self.vd)"),
)
for old, new in edits:
if source.count(old) != 1:
raise ValueError(f"Expected one reference match for {old}")
source = source.replace(old, new)
module = types.ModuleType("shruti_benchmark_reference")
exec(compile(source, str(path), "exec"), module.__dict__)
return module
def frontend_program(path):
graph = onnx.load(str(path)).graph
weights = {tensor.name: numpy_helper.to_array(tensor) for tensor in graph.initializer}
@mb.program(input_specs=[mb.TensorSpec(shape=(1, get_new_symbol()))], opset_version=ct.target.iOS17)
def preprocess(audio):
signal = mb.expand_dims(x=audio, axes=[1])
spectrum = mb.conv(x=signal, weight=weights["fe.basis"], strides=[160], pad_type="custom", pad=[200, 200])
real, imaginary = mb.split(x=spectrum, axis=1, split_sizes=[257, 257])
power = mb.add(x=mb.square(x=real), y=mb.square(x=imaginary))
mel = mb.matmul(x=mb.transpose(x=power, perm=[0, 2, 1]), y=weights["fe.mel"])
logmel = mb.log(x=mb.add(x=mel, y=np.float32(2**-24)), epsilon=np.float32(0))
samples = mb.gather(x=mb.shape(x=audio), indices=1, axis=0)
frames = mb.gather(x=mb.shape(x=logmel), indices=1, axis=0)
valid = mb.floor_div(x=samples, y=160)
positions = mb.range_1d(start=0, end=frames, step=1)
mask = mb.expand_dims(x=mb.cast(x=mb.less(x=positions, y=valid), dtype="fp32"), axes=[0, 2])
valid_float = mb.cast(x=valid, dtype="fp32")
mean = mb.real_div(x=mb.reduce_sum(x=mb.mul(x=logmel, y=mask), axes=[1], keep_dims=True),
y=mb.maximum(x=valid_float, y=np.float32(1)))
centered = mb.mul(x=mb.sub(x=logmel, y=mean), y=mask)
variance = mb.real_div(x=mb.reduce_sum(x=mb.square(x=centered), axes=[1], keep_dims=True),
y=mb.maximum(x=mb.sub(x=valid_float, y=np.float32(1)), y=np.float32(1)))
normalized = mb.real_div(x=centered, y=mb.add(x=mb.sqrt(x=variance), y=np.float32(1e-5)))
peak = mb.reduce_max(x=mb.abs(x=audio), axes=[0, 1])
audible = mb.cast(x=mb.greater_equal(x=peak, y=np.float32(1e-4)), dtype="fp32")
return mb.mul(x=normalized, y=audible, name="features")
return ct.convert(
preprocess, minimum_deployment_target=ct.target.iOS17, convert_to="mlprogram",
inputs=[ct.TensorType(name="audio", shape=(1, ct.RangeDim(160, SAMPLES, default=16_000)))],
compute_precision=ct.precision.FLOAT32, skip_model_load=True,
)
class Stem(torch.nn.Module):
def __init__(self, network, lanes):
super().__init__()
self.network = network
self.lanes = lanes
def forward(self, features, frames):
x, length = self.network.stem(features, frames)
x = torch.nn.functional.pad(x, (0, 0, 0, int(x.shape[1]) % 2))
return x[:, :, None, :].expand(-1, -1, self.lanes, -1), length
class EncoderBlock(torch.nn.Module):
def __init__(self, block, mix):
super().__init__()
self.block = block
self.mix = mix
def forward(self, x, length):
positions = torch.arange(x.shape[1])
seen = positions[None, :] < length
return self.mix(x, lambda u: self.block(u, seen, seen[..., None].to(u.dtype), positions.float()))
class Head(torch.nn.Module):
def __init__(self, network, norm):
super().__init__()
self.network = network
self.norm = norm
def forward(self, x):
net = self.network
encoded = self.norm(x.mean(2), net.final_norm)
memory = net.memory(encoded)[:, :CROSS_FRAMES]
keys = (memory @ net.ck).reshape(1, CROSS_FRAMES, net.L, net.heads, net.qk)
values = (memory @ net.cv).reshape(1, CROSS_FRAMES, net.L, net.heads, net.vd)
keys = self.norm(keys, net.ck_norm)
return torch.cat((keys.flatten(3), values.flatten(3)), dim=-1).reshape(1, CROSS_FRAMES, -1)
def convert(module, values, input_names, output_names, shapes=None):
trace = torch.jit.trace(module.eval(), values, check_trace=False)
return ct.convert(
trace, minimum_deployment_target=ct.target.iOS18, compute_precision=ct.precision.FLOAT32,
inputs=[ct.TensorType(name=name, shape=(shapes or {}).get(name, tuple(value.shape)), dtype=value.numpy().dtype)
for name, value in zip(input_names, values)],
outputs=[ct.TensorType(name=name) for name in output_names],
skip_model_load=True,
)
def export(code, output, reference_path, compile_platform=None):
data = model_inputs(code)
onnx = CATALOG["onnx_source"]
name, pin = next(iter(onnx["frontend"].items()))
frontend = fetch(f"https://huggingface.co/{onnx['repo']}/resolve/{onnx['revision']}/{name}",
ROOT / "data/shared/preprocess.onnx", pin)
expected = CATALOG["shruti_source"]["reference_sha256"]
verify(reference_path, {"bytes": reference_path.stat().st_size, "sha256": expected})
module = reference_module(reference_path)
v = json.loads((data / "shruti.json").read_text())
config = v["config"]
archive = next(data.glob("*.cact"))
weights = archive_weights(archive, config)
encoder = module.Encoder(weights, config).eval()
decoder = module.Decoder(weights, config, mask_tags=False).eval()
packages = output / "packages"
packages.mkdir(parents=True, exist_ok=True)
assets = compiled_assets(output, compile_platform)
if compile_platform:
assets.mkdir(exist_ok=True)
def save(model, name):
package = packages / f"{name}.mlpackage"
model.short_description = f"Shruti {code} from the released CQ4 archive, adapted to Core ML"
model.license = "Apache-2.0"
model.author = "Udgam Labs; based on Cactus Whistle by Cactus Compute"
model.save(package)
if compile_platform:
subprocess.run(
["xcrun", "coremlcompiler", "compile", str(package), str(assets),
"--platform", compile_platform, "--deployment-target", "26.0"], check=True
)
save(frontend_program(frontend), "ShrutiAudioFrontend")
features = torch.zeros(1, FRAMES + 1, 80)
frames = torch.tensor([FRAMES], dtype=torch.int32)
stem = Stem(encoder, config["enc_lanes"]).eval()
hidden, length = stem(features, frames)
save(convert(stem, (features, frames), ["features", "frames"], ["hidden", "length"]), "SplitStem")
for index, (block, mix) in enumerate(zip(encoder.blocks, encoder.mix)):
save(convert(EncoderBlock(block, mix), (hidden, length), ["hidden", "length"], ["encoded"]),
f"SplitBlock{index}")
head = Head(encoder, module.zc_norm)
cross = head(hidden)
save(convert(head, (hidden,), ["hidden"], ["cross"]), "SplitHead")
names = decoder.state_names()
state = tuple(value.to(torch.int32) if value.dtype == torch.int64 else value
for value in decoder.init_state(BEAMS).values())
token = torch.full((BEAMS, 1), config["bos"], dtype=torch.int32)
indices = torch.zeros(BEAMS, 1, config["hashes"] * len(config["orders"]), dtype=torch.int32)
width = cross.shape[-1]
save(convert(
decoder, (token, cross, indices, *state), ["tokens", "cross", "indices", *names],
["logits", *["new_" + name for name in names]],
shapes={"cross": (1, ct.RangeDim(1, CROSS_FRAMES, default=CROSS_FRAMES), width)},
), "StaticDecoder")
manifest = {
**v, "language": code, "beams": BEAMS, "max_audio_samples": SAMPLES,
"cache_length": CACHE_LENGTH, "cross_frames": CROSS_FRAMES,
"states": {name: {"shape": list(value.shape), "dtype": str(value.numpy().dtype)}
for name, value in zip(names, state)},
"source": CATALOG["models"][code],
"semantics": "CQ4 dequantized; fp32 graph arithmetic; upstream Torch port",
}
(output / "model.json").write_text(json.dumps(manifest, ensure_ascii=False) + "\n")
shutil.copyfile(data / "LICENSE", output / "LICENSE")
notice = (data / "NOTICE").read_text()
(output / "NOTICE").write_text(notice + "\nConverted to Core ML from the released CQ4 archive.\n")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("language", choices=sorted(CATALOG["models"]))
parser.add_argument("--reference", type=Path,
default=ROOT / ".upstream/shruti/onnx/export/shruti_torch.py")
parser.add_argument("--output", type=Path, default=ROOT / "build")
parser.add_argument("--compile", choices=("macos", "ios", "iossimulator"))
args = parser.parse_args()
torch.set_num_threads(2)
with torch.no_grad():
export(args.language, args.output / args.language, args.reference, args.compile)
if __name__ == "__main__":
main()