File size: 2,258 Bytes
2d4936d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | """ONNX exports: decoder (any number of new positions with a memory), frame embedding, heads, voice
compressor, text table; the codec's decoder and encoder. Opset 17, fp32."""
import sys
from pathlib import Path
import numpy as np
import torch
from torch import nn
sys.path.insert(0, str(Path(__file__).parent))
import gepard_model as gm # noqa: E402
OUT = Path(__file__).resolve().parents[1] / "export"
class Frame(nn.Module):
def __init__(s, g):
super().__init__()
s.g = g
def forward(s, codes):
return s.g.embed_frame(codes)[0]
class Heads(nn.Module):
def __init__(s, g):
super().__init__()
s.g = g
def forward(s, h):
logits, stop = s.g.outputs(h)
return logits, stop
def ex(mod, args, name, ins, outs, dyn):
with torch.no_grad():
torch.onnx.export(mod, args, str(OUT / name), dynamo=False, opset_version=17, input_names=ins, output_names=outs, dynamic_axes=dyn)
print(name, round((OUT / name).stat().st_size / 1e6), "MB", flush=True)
def main():
OUT.mkdir(exist_ok=True)
g, comp, emb = gm.load()
s, p = 3, 5
cos, sin = gm.rope(p, s)
z = torch.zeros(gm.L, gm.KV, p, gm.HD)
ex(g.decoder, (torch.zeros(1, s, gm.D), z, z, cos, sin, torch.zeros(s, p + s)), "decoder.onnx",
["x", "past_k", "past_v", "cos", "sin", "mask"], ["hidden", "new_k", "new_v"],
{"x": {1: "S"}, "past_k": {2: "P"}, "past_v": {2: "P"}, "cos": {0: "S"}, "sin": {0: "S"}, "mask": {0: "S", 1: "T"},
"hidden": {1: "S"}, "new_k": {2: "S"}, "new_v": {2: "S"}})
ex(Frame(g), (torch.zeros(1, 32, dtype=torch.long),), "frame.onnx", ["codes"], ["x"], {"codes": {0: "S"}, "x": {0: "S"}})
ex(Heads(g), (torch.zeros(1, gm.D),), "heads.onnx", ["hidden"], ["logits", "stop"], {"hidden": {0: "S"}, "logits": {0: "S"}, "stop": {0: "S"}})
ex(comp, (torch.zeros(1, 60, 32, dtype=torch.long),), "compressor.onnx", ["codes"], ["prefix"], {"codes": {1: "T"}})
np.save(OUT / "text_embedding.f16.npy", emb.numpy().astype(np.float16))
print("text table", (OUT / "text_embedding.f16.npy").stat().st_size // 10 ** 6, "MB; fp16 max error", float(np.abs(emb.numpy() - emb.numpy().astype(np.float16)).max()))
if __name__ == "__main__":
main()
|