Download scripts/coreml_export.py from matthiastl/tyger-coreml: direct link, hf CLI and curl.
- Browser
- Download file 8.27 kB
-
https://huggingface.co/matthiastl/tyger-coreml/resolve/main/scripts/coreml_export.py
- Command line
-
hf download hf://matthiastl/tyger-coreml/scripts/coreml_export.py
-
curl -L -o coreml_export.py https://huggingface.co/matthiastl/tyger-coreml/resolve/main/scripts/coreml_export.py
8.27 kB
| """RULE-coreml.md: the encoder to layer 15 with a fixed 801-frame input, written with the operations ONNX Runtime's | |
| Core ML provider takes, in 16-bit floats (`l15.static.fp16.onnx`) or 32-bit (`l15.static.fp32.onnx`), for one window | |
| or (`--batch 2`, `l15.static.b2.fp16.onnx`) both streams' windows at once. | |
| Same function as l15.L15, checked here against it: | |
| - shapes are fixed; the position terms of every layer and the attention mask are constants; | |
| - padding on the left and right of the convolutions is written as symmetric padding plus a slice; | |
| - the mask is added (-1e4) instead of filled with -inf. | |
| A window shorter than 8 s is padded on the right with zero log-mels; every stage is causal, so frames before the | |
| padding don't change. | |
| python -I -B coreml_export.py --out export | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from torch import nn | |
| HERE = Path(__file__).parent | |
| sys.path[:0] = [str(HERE), str(HERE.parent)] # vendor/ is one level up | |
| import l15 # noqa: E402 | |
| MELS, T_MEL, D = 128, 801, 1024 | |
| T = (T_MEL - 1) // 8 + 1 # 101 | |
| def gate_sigmoid(x): | |
| return torch.sigmoid(x) | |
| def gate_tanh(x): | |
| """sigmoid(x), written so the Neural Engine doesn't use its imprecise one.""" | |
| return 0.5 + 0.5 * torch.tanh(0.5 * x) | |
| def silu_relu(x): | |
| """x * sigmoid(x) = relu(x) - |x| sigmoid(-|x|): the approximated part stays small.""" | |
| a = torch.relu(x) + torch.relu(-x) | |
| return torch.relu(x) - a * torch.sigmoid(-a) | |
| # How SiLU and the GLU's gate are written, by place (RULE-coreml.md allows rewriting as long as the function is the same) | |
| FORMS = {"conv": lambda x: x * gate_tanh(x), "ffn": lambda x: x * gate_sigmoid(x), "glu": gate_tanh} | |
| class StaticAttention(nn.Module): | |
| def __init__(self, src: l15.Attention, pos: torch.Tensor, b: int): | |
| super().__init__() | |
| self.b = b | |
| self.h, self.dk = src.h, src.dk | |
| self.q_proj, self.k_proj, self.v_proj, self.o_proj = src.q_proj, src.k_proj, src.v_proj, src.o_proj | |
| self.register_buffer("bias_u", src.bias_u.detach().view(1, self.h, 1, self.dk)) | |
| self.register_buffer("bias_v", src.bias_v.detach().view(1, self.h, 1, self.dk)) | |
| with torch.no_grad(): | |
| p = src.relative_k_proj(pos).view(1, -1, self.h, self.dk).permute(0, 2, 3, 1) | |
| self.register_buffer("p", p.contiguous() * self.dk ** -0.5) # (1, h, dk, 2T-1), scale folded in | |
| self.register_buffer("zero", torch.zeros(b, self.h, T, 1)) | |
| self.scale = self.dk ** -0.5 | |
| def split(self, x): | |
| return x.reshape(self.b, T, self.h, self.dk).transpose(1, 2) | |
| def forward(self, x, mask): | |
| q, k, v = self.split(self.q_proj(x)), self.split(self.k_proj(x)), self.split(self.v_proj(x)) | |
| bd = torch.matmul(q + self.bias_v, self.p) # (1, h, T, 2T-1) | |
| bd = torch.cat([self.zero, bd], dim=-1).reshape(self.b, self.h, 2 * T, T) | |
| bd = bd[:, :, 1:, :].reshape(self.b, self.h, T, 2 * T - 1)[:, :, :, :T] | |
| ac = torch.matmul((q + self.bias_u) * self.scale, k.transpose(2, 3)) | |
| w = torch.softmax(ac + bd + mask, dim=-1) | |
| return self.o_proj(torch.matmul(w, v).transpose(1, 2).reshape(self.b, T, D)) | |
| class StaticConv(nn.Module): | |
| def __init__(self, src: l15.ConvModule): | |
| super().__init__() | |
| self.pointwise_conv1, self.pointwise_conv2, self.norm = src.pointwise_conv1, src.pointwise_conv2, src.norm | |
| self.depthwise = nn.Conv1d(D, D, src.kernel, groups=D, bias=False, padding=src.kernel - 1) | |
| self.depthwise.weight = src.depthwise_conv.weight | |
| def forward(self, x): | |
| a, b = self.pointwise_conv1(x).split(D, dim=-1) | |
| x = self.depthwise((a * FORMS["glu"](b)).transpose(1, 2))[:, :, :T].transpose(1, 2) | |
| x = self.norm(x) | |
| return self.pointwise_conv2(FORMS["conv"](x)) | |
| class StaticBlock(nn.Module): | |
| def __init__(self, src: l15.Block, pos, b: int): | |
| super().__init__() | |
| self.ff1, self.ff2 = src.feed_forward1, src.feed_forward2 | |
| self.attn, self.conv = StaticAttention(src.self_attn, pos, b), StaticConv(src.conv) | |
| self.n1, self.n2, self.n3, self.n4, self.n5 = (src.norm_feed_forward1, src.norm_self_att, src.norm_conv, | |
| src.norm_feed_forward2, src.norm_out) | |
| def ffn(m, x): | |
| return m.linear2(FORMS["ffn"](m.linear1(x))) | |
| def forward(self, x, mask): | |
| x = x + 0.5 * self.ffn(self.ff1, self.n1(x)) | |
| x = x + self.attn(self.n2(x), mask) | |
| x = x + self.conv(self.n3(x)) | |
| x = x + 0.5 * self.ffn(self.ff2, self.n4(x)) | |
| return self.n5(x) | |
| class StaticL15(nn.Module): | |
| """log-mel (b, 801, 128) -> (b, 101, 1024).""" | |
| def __init__(self, src: l15.L15, b: int = 1): | |
| super().__init__() | |
| self.b = b | |
| s = src.subsampling | |
| self.convs = nn.ModuleList() | |
| for conv in [s.conv_in, *s.dw]: | |
| c = nn.Conv2d(conv.in_channels, conv.out_channels, 3, stride=2, groups=conv.groups, padding=2) | |
| c.weight, c.bias = conv.weight, conv.bias | |
| self.convs.append(c) | |
| self.pw, self.linear = s.pw, s.linear | |
| pos = l15.positions(T, D) | |
| self.layers = nn.ModuleList(StaticBlock(block, pos, b) for block in src.layers) | |
| idx = torch.arange(T) | |
| diff = idx[:, None] - idx[None, :] | |
| allowed = (diff >= 0) & (diff <= l15.LEFT) | |
| self.register_buffer("mask", torch.where(allowed, 0.0, -1e4).view(1, 1, T, T)) | |
| def forward(self, mel): | |
| x = mel.reshape(self.b, 1, T_MEL, MELS) | |
| for i, (conv, t, f) in enumerate(zip(self.convs, (401, 201, 101), (65, 33, 17))): | |
| x = conv(x)[:, :, :t, :f] | |
| x = torch.relu(x if i == 0 else self.pw[i - 1](x)) | |
| x = self.linear(x.transpose(1, 2).reshape(self.b, T, 256 * 17)) | |
| for layer in self.layers: | |
| x = layer(x, self.mask) | |
| return x | |
| def load(b: int = 1) -> tuple[l15.L15, StaticL15]: | |
| from safetensors.torch import load_file | |
| ref = l15.L15() | |
| ref.load_state_dict(load_file(str(HERE / "data" / "l15.safetensors")), strict=True) | |
| ref.eval() | |
| return ref, StaticL15(ref, b).eval() | |
| def check(ref, static) -> None: | |
| """The static module against l15.L15 in PyTorch fp32, on Open Yap log-mels: full and right-padded windows.""" | |
| import openyap as pb | |
| user, agent = pb.audio() | |
| mel = l15.LogMel(np.load(HERE / "data" / "mel_filters.npy")) | |
| for n in (5120, 40960, 128000): | |
| ms = [mel(wav[:n]) for wav in (user, agent)[:static.b]] | |
| padded = np.zeros((static.b, T_MEL, MELS), np.float32) | |
| for i, m in enumerate(ms): | |
| padded[i, :len(m)] = m | |
| with torch.no_grad(): | |
| b = static(torch.from_numpy(padded)).numpy() | |
| for i, m in enumerate(ms): | |
| a = ref(torch.from_numpy(m)[None])[0].numpy() | |
| print(f"stream {i}, {n} samples: {len(a)} frames, largest difference {np.abs(a - b[i, :len(a)]).max():.2e} " | |
| f"(largest value {np.abs(a).max():.2f})") | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument("--out", type=Path, required=True) | |
| parser.add_argument("--fp32", action="store_true") | |
| parser.add_argument("--batch", type=int, default=1, choices=[1, 2]) | |
| args = parser.parse_args() | |
| ref, static = load(args.batch) | |
| with torch.no_grad(): | |
| check(ref, static) | |
| x = torch.zeros(args.batch, T_MEL, MELS) | |
| if not args.fp32: | |
| static, x = static.half(), x.half() | |
| name = f"l15.static{'.b2' if args.batch == 2 else ''}.{'fp32' if args.fp32 else 'fp16'}.onnx" | |
| torch.onnx.export(static, (x,), str(args.out / name), dynamo=False, input_names=["mel"], output_names=["l15"], | |
| opset_version=17) | |
| import collections | |
| import onnx | |
| m = onnx.load(str(args.out / name), load_external_data=False) | |
| print(name, f"{(args.out / name).stat().st_size / 1e6:.0f} MB", | |
| dict(collections.Counter(n.op_type for n in m.graph.node if n.op_type != "Constant"))) | |
| if __name__ == "__main__": | |
| main() | |