Upload convert_to_onnx.py with huggingface_hub
Browse files- convert_to_onnx.py +47 -0
convert_to_onnx.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from src.s01_config import ModelConfig
|
| 4 |
+
from src.s02_tokenizer import MusicTokenizer
|
| 5 |
+
from src.s04_model import MusicTransformer
|
| 6 |
+
|
| 7 |
+
def export_onnx():
|
| 8 |
+
# 1. Initialize tokenizer and model configuration
|
| 9 |
+
tokenizer = MusicTokenizer()
|
| 10 |
+
model_config = ModelConfig(vocab_size=tokenizer.vocab_size)
|
| 11 |
+
model = MusicTransformer.from_config(model_config)
|
| 12 |
+
|
| 13 |
+
# 2. Load model weights from the PyTorch checkpoint
|
| 14 |
+
checkpoint_path = Path("checkpoints/best.pt")
|
| 15 |
+
if not checkpoint_path.exists():
|
| 16 |
+
print(f"Error: Checkpoint not found at {checkpoint_path}")
|
| 17 |
+
return
|
| 18 |
+
|
| 19 |
+
print("Loading PyTorch model weights...")
|
| 20 |
+
checkpoint = torch.load(checkpoint_path, map_location="cpu")
|
| 21 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
| 22 |
+
model.eval()
|
| 23 |
+
|
| 24 |
+
# 3. Prepare dummy inputs (batch_size=1, sequence_length=10)
|
| 25 |
+
dummy_input_ids = torch.zeros((1, 10), dtype=torch.long)
|
| 26 |
+
|
| 27 |
+
# 4. Export to ONNX format with dynamic axes
|
| 28 |
+
onnx_output_path = Path("checkpoints/model.onnx")
|
| 29 |
+
print(f"Exporting model to ONNX format: {onnx_output_path}...")
|
| 30 |
+
|
| 31 |
+
torch.onnx.export(
|
| 32 |
+
model,
|
| 33 |
+
(dummy_input_ids,),
|
| 34 |
+
str(onnx_output_path),
|
| 35 |
+
input_names=["input_ids"],
|
| 36 |
+
output_names=["logits"],
|
| 37 |
+
dynamic_axes={
|
| 38 |
+
"input_ids": {0: "batch_size", 1: "sequence_length"},
|
| 39 |
+
"logits": {0: "batch_size", 1: "sequence_length"}
|
| 40 |
+
},
|
| 41 |
+
opset_version=15,
|
| 42 |
+
do_constant_folding=True
|
| 43 |
+
)
|
| 44 |
+
print("ONNX export completed successfully!")
|
| 45 |
+
|
| 46 |
+
if __name__ == "__main__":
|
| 47 |
+
export_onnx()
|