|
| 1 | +import json |
| 2 | +import zipfile |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from pathlib import Path |
| 5 | +from typing import Dict, Any |
| 6 | + |
| 7 | +import torch |
| 8 | +import torch.nn as nn |
| 9 | + |
| 10 | + |
| 11 | +class BaseModel(nn.Module, ABC): |
| 12 | + """ |
| 13 | + A base abstract class for all models, providing utility methods for metadata handling, |
| 14 | + model saving in ONNX format, and enforcing standard PyTorch model behavior. |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__(self): |
| 18 | + super().__init__() |
| 19 | + |
| 20 | + @property |
| 21 | + @abstractmethod |
| 22 | + def description(self) -> str: |
| 23 | + """Abstract property for a description of the model's purpose.""" |
| 24 | + pass |
| 25 | + |
| 26 | + @property |
| 27 | + def metadata(self) -> Dict[str, Any]: |
| 28 | + """ |
| 29 | + Constructs metadata with the basic attributes required for all models. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + dict: Metadata containing model_type and description. |
| 33 | + """ |
| 34 | + return { |
| 35 | + 'model_type': self.__class__.__name__, |
| 36 | + 'description': self.description |
| 37 | + } |
| 38 | + |
| 39 | + @abstractmethod |
| 40 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 41 | + """ |
| 42 | + Abstract method that must be implemented to define the forward pass for the model. |
| 43 | + Args: |
| 44 | + x (torch.Tensor): Input tensor. |
| 45 | + Returns: |
| 46 | + torch.Tensor: Output tensor after passing through the model. |
| 47 | + """ |
| 48 | + pass |
| 49 | + |
| 50 | + @abstractmethod |
| 51 | + def onnx_export(self) -> Dict[str, Any]: |
| 52 | + """ |
| 53 | + Constructs the parameters needed for torch.onnx.export(). |
| 54 | +
|
| 55 | + Returns: |
| 56 | + dict: A dictionary containing the parameters needed for ONNX export. |
| 57 | + """ |
| 58 | + pass |
| 59 | + |
| 60 | + def save(self, path: str) -> None: |
| 61 | + """ |
| 62 | + Saves the model in ONNX format and stores it in a zip file along with metadata. |
| 63 | +
|
| 64 | + Args: |
| 65 | + path (str): The path to save the model. |
| 66 | + """ |
| 67 | + # Gather ONNX export parameters |
| 68 | + onnx_params = self.onnx_export() |
| 69 | + onnx_path = Path(path).with_suffix(".onnx") |
| 70 | + metadata_path = Path(path + "_metadata.json") |
| 71 | + |
| 72 | + # Perform the ONNX export using the current model (`self`) |
| 73 | + torch.onnx.export( |
| 74 | + self, |
| 75 | + onnx_params['example_input'], |
| 76 | + str(onnx_path), # This is the required third argument - file path |
| 77 | + export_params=onnx_params.get('export_params', True), |
| 78 | + opset_version=onnx_params.get('opset_version', 17), |
| 79 | + input_names=onnx_params.get('input_names', ['input']), |
| 80 | + output_names=onnx_params.get('output_names', ['output']), |
| 81 | + # dynamic_axes=onnx_params.get('dynamic_axes', {'input': {0: 'batch_size'}}), |
| 82 | + ) |
| 83 | + |
| 84 | + # onnx_program.save(str(onnx_path)) # Saves a file called onnx_path.onnx |
| 85 | + |
| 86 | + # Save metadata to a JSON file |
| 87 | + metadata = self.metadata |
| 88 | + metadata_path.write_text(json.dumps(metadata)) |
| 89 | + |
| 90 | + # Zip ONNX model and metadata file |
| 91 | + zip_path = Path(path).with_suffix(".zip") |
| 92 | + with zipfile.ZipFile(zip_path, 'w') as model_zip: |
| 93 | + model_zip.write(onnx_path, onnx_path.name) |
| 94 | + model_zip.write(metadata_path, metadata_path.name) |
| 95 | + |
| 96 | + # Clean up temporary files |
| 97 | + onnx_path.unlink() |
| 98 | + metadata_path.unlink() |
0 commit comments