trioskosmos commited on
Commit
37004b0
·
verified ·
1 Parent(s): 653786d

Upload ai/models/export_onnx.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. ai/models/export_onnx.py +61 -0
ai/models/export_onnx.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+
5
+ import torch
6
+
7
+ # Add project root to path
8
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
9
+
10
+ from ai.models.training_config import INPUT_SIZE, POLICY_SIZE
11
+ from ai.training.train import AlphaNet
12
+
13
+
14
+ def export_model(model_path, output_path):
15
+ device = torch.device("cpu") # ONNX export usually done on CPU to be safe
16
+
17
+ print(f"Loading checkpoint from {model_path}...")
18
+ checkpoint = torch.load(model_path, map_location=device)
19
+
20
+ # Handle dictionary checkpoint
21
+ if isinstance(checkpoint, dict) and "model_state" in checkpoint:
22
+ state_dict = checkpoint["model_state"]
23
+ else:
24
+ state_dict = checkpoint
25
+
26
+ # Detect policy size from weights to support different versions
27
+ if "policy_head_fc.bias" in state_dict:
28
+ detected_size = state_dict["policy_head_fc.bias"].shape[0]
29
+ print(f"Detected Policy Size: {detected_size}")
30
+ else:
31
+ detected_size = POLICY_SIZE
32
+ print(f"Using Default Policy Size: {detected_size}")
33
+
34
+ model = AlphaNet(policy_size=detected_size).to(device)
35
+ model.load_state_dict(state_dict)
36
+ model.eval()
37
+
38
+ dummy_input = torch.randn(1, INPUT_SIZE, device=device)
39
+
40
+ print(f"Exporting to {output_path}...")
41
+ torch.onnx.export(
42
+ model,
43
+ dummy_input,
44
+ output_path,
45
+ export_params=True,
46
+ opset_version=17, # Use modern opset for better compatibility
47
+ do_constant_folding=True,
48
+ input_names=["input"],
49
+ output_names=["policy", "value"],
50
+ dynamic_axes={"input": {0: "batch_size"}, "policy": {0: "batch_size"}, "value": {0: "batch_size"}},
51
+ )
52
+ print("Export complete.")
53
+
54
+
55
+ if __name__ == "__main__":
56
+ parser = argparse.ArgumentParser()
57
+ parser.add_argument("--model", type=str, required=True, help="Path to .pt checkpoint")
58
+ parser.add_argument("--output", type=str, required=True, help="Path to .onnx output")
59
+ args = parser.parse_args()
60
+
61
+ export_model(args.model, args.output)