Spaces:
Sleeping
Sleeping
Download export_onnx.py from neonforestmist/AutoSprite: direct link, hf CLI and curl.
- Browser
- Download file 1.63 kB
-
https://huggingface.co/spaces/neonforestmist/AutoSprite/resolve/main/export_onnx.py
- Command line
-
hf download hf://spaces/neonforestmist/AutoSprite/export_onnx.py
-
curl -L -o export_onnx.py https://huggingface.co/spaces/neonforestmist/AutoSprite/resolve/main/export_onnx.py
1.63 kB
| """Export a trained checkpoint to ONNX so the app only needs onnxruntime on CPU. | |
| python export_onnx.py weights/autosprite.pt weights/autosprite.onnx | |
| """ | |
| from __future__ import annotations | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import onnxruntime as ort | |
| import torch | |
| from autosprite import CANVAS, MAX_PALETTE | |
| from autosprite.features import IN_CHANNELS | |
| from autosprite.model import AutoSpriteNet | |
| def main(src: Path, dst: Path) -> None: | |
| ckpt = torch.load(src, map_location="cpu") | |
| model = AutoSpriteNet(width=ckpt["width"]).eval() | |
| model.load_state_dict(ckpt["model"]) | |
| inputs = ( | |
| torch.zeros(1, IN_CHANNELS, CANVAS, CANVAS), | |
| torch.zeros(1, MAX_PALETTE, CANVAS, CANVAS), | |
| torch.zeros(1, MAX_PALETTE, 3), | |
| torch.ones(1, MAX_PALETTE), | |
| ) | |
| dst.parent.mkdir(parents=True, exist_ok=True) | |
| torch.onnx.export( | |
| model, | |
| inputs, | |
| str(dst), | |
| input_names=["x", "palmask", "palrgb", "palvalid"], | |
| output_names=["logits"], | |
| opset_version=17, | |
| dynamo=False, | |
| ) | |
| rng = np.random.default_rng(0) | |
| feeds = [rng.random(t.shape, dtype=np.float32) for t in inputs] | |
| with torch.no_grad(): | |
| expected = model(*map(torch.from_numpy, feeds)).numpy() | |
| session = ort.InferenceSession(str(dst), providers=["CPUExecutionProvider"]) | |
| got = session.run(None, dict(zip(["x", "palmask", "palrgb", "palvalid"], feeds)))[0] | |
| print(f"exported {dst} ({dst.stat().st_size / 1e6:.1f} MB), max abs diff {np.abs(got - expected).max():.2e}") | |
| if __name__ == "__main__": | |
| main(Path(sys.argv[1]), Path(sys.argv[2])) | |