Download scripts/export.py from matthiastl/gepard-onnx: direct link, hf CLI and curl.
- Browser
- Download file 2.26 kB
-
https://huggingface.co/matthiastl/gepard-onnx/resolve/main/scripts/export.py
- Command line
-
hf download hf://matthiastl/gepard-onnx/scripts/export.py
-
curl -L -o export.py https://huggingface.co/matthiastl/gepard-onnx/resolve/main/scripts/export.py
2.26 kB
| """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() | |