Spaces:
Running
Running
Upload ai/utils/export_onnx.py with huggingface_hub
Browse files- ai/utils/export_onnx.py +41 -0
ai/utils/export_onnx.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
# Add project root to path
|
| 7 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 8 |
+
|
| 9 |
+
from ai.models.training_config import INPUT_SIZE, POLICY_SIZE
|
| 10 |
+
from ai.training.train import AlphaNet
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def export_to_onnx(model_path, output_path):
|
| 14 |
+
device = torch.device("cpu")
|
| 15 |
+
checkpoint = torch.load(model_path, map_location=device)
|
| 16 |
+
state_dict = (
|
| 17 |
+
checkpoint["model_state"] if isinstance(checkpoint, dict) and "model_state" in checkpoint else checkpoint
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
model = AlphaNet(policy_size=POLICY_SIZE).to(device)
|
| 21 |
+
model.load_state_dict(state_dict)
|
| 22 |
+
model.eval()
|
| 23 |
+
|
| 24 |
+
dummy_input = torch.randn(1, INPUT_SIZE)
|
| 25 |
+
|
| 26 |
+
torch.onnx.export(
|
| 27 |
+
model,
|
| 28 |
+
dummy_input,
|
| 29 |
+
output_path,
|
| 30 |
+
export_params=True,
|
| 31 |
+
opset_version=14,
|
| 32 |
+
do_constant_folding=True,
|
| 33 |
+
input_names=["input"],
|
| 34 |
+
output_names=["policy", "value"],
|
| 35 |
+
dynamic_axes={"input": {0: "batch_size"}, "policy": {0: "batch_size"}, "value": {0: "batch_size"}},
|
| 36 |
+
)
|
| 37 |
+
print(f"Model successfully exported to {output_path}")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if __name__ == "__main__":
|
| 41 |
+
export_to_onnx("ai/models/alphanet_best.pt", "ai/models/alphanet.onnx")
|