Export an ONNX model from a TorchVision classification model. Args: model: PyTorch model to export. output: Path to the output ONNX model. input_shape: Shape of the input tensor. verbose: Whether to print the verbose output.
(
model: "torch.nn.Module", # noqa: F821
output: Path,
input_shape: tuple[int, ...],
*,
verbose: bool | None = None,
)
| 250 | |
| 251 | |
| 252 | def export_classifier_onnx( |
| 253 | model: "torch.nn.Module", # noqa: F821 |
| 254 | output: Path, |
| 255 | input_shape: tuple[int, ...], |
| 256 | *, |
| 257 | verbose: bool | None = None, |
| 258 | ) -> None: |
| 259 | """ |
| 260 | Export an ONNX model from a TorchVision classification model. |
| 261 | |
| 262 | Args: |
| 263 | model: PyTorch model to export. |
| 264 | output: Path to the output ONNX model. |
| 265 | input_shape: Shape of the input tensor. |
| 266 | verbose: Whether to print the verbose output. |
| 267 | """ |
| 268 | import torch |
| 269 | import onnx |
| 270 | import onnxslim |
| 271 | |
| 272 | class ClassifierEnd2End(torch.nn.Module): |
| 273 | def __init__(self, model): |
| 274 | super().__init__() |
| 275 | self.model = model |
| 276 | |
| 277 | def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 278 | softmax = torch.nn.functional.softmax(self.model(x), dim=1) |
| 279 | return softmax |
| 280 | |
| 281 | model = ClassifierEnd2End(model) |
| 282 | model.eval() |
| 283 | |
| 284 | torch.onnx.export( |
| 285 | model, |
| 286 | args=(torch.randn(1, *input_shape),), |
| 287 | f=output, |
| 288 | export_params=True, |
| 289 | opset_version=13, |
| 290 | do_constant_folding=True, |
| 291 | input_names=["input"], |
| 292 | output_names=["output"], |
| 293 | verbose=verbose, |
| 294 | ) |
| 295 | onnx_model = onnx.load(output) |
| 296 | slim_onnx_model = onnxslim.slim(onnx_model) |
| 297 | onnx.save(slim_onnx_model, output) |
| 298 | |
| 299 | |
| 300 | def export_segmentation_onnx( |
no test coverage detected