Export an ONNX model from a TorchVision segmentation 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,
)
| 298 | |
| 299 | |
| 300 | def export_segmentation_onnx( |
| 301 | model: "torch.nn.Module", # noqa: F821 |
| 302 | output: Path, |
| 303 | input_shape: tuple[int, ...], |
| 304 | *, |
| 305 | verbose: bool | None = None, |
| 306 | ) -> None: |
| 307 | """ |
| 308 | Export an ONNX model from a TorchVision segmentation model. |
| 309 | |
| 310 | Args: |
| 311 | model: PyTorch model to export. |
| 312 | output: Path to the output ONNX model. |
| 313 | input_shape: Shape of the input tensor. |
| 314 | verbose: Whether to print the verbose output. |
| 315 | """ |
| 316 | import torch |
| 317 | import onnx |
| 318 | import onnxslim |
| 319 | |
| 320 | class SegmentationEnd2End(torch.nn.Module): |
| 321 | def __init__(self, model): |
| 322 | super().__init__() |
| 323 | self.model = model |
| 324 | |
| 325 | def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 326 | softmax = torch.nn.functional.softmax(self.model(x)["out"], dim=1) |
| 327 | return softmax |
| 328 | |
| 329 | model = SegmentationEnd2End(model) |
| 330 | model.eval() |
| 331 | |
| 332 | torch.onnx.export( |
| 333 | model, |
| 334 | args=(torch.randn(1, *input_shape),), |
| 335 | f=output, |
| 336 | export_params=True, |
| 337 | opset_version=13, |
| 338 | do_constant_folding=True, |
| 339 | input_names=["input"], |
| 340 | output_names=["output"], |
| 341 | verbose=verbose, |
| 342 | ) |
| 343 | onnx_model = onnx.load(output) |
| 344 | slim_onnx_model = onnxslim.slim(onnx_model) |
| 345 | onnx.save(slim_onnx_model, output) |
| 346 | |
| 347 | |
| 348 | def export_retinanet_onnx( |
no test coverage detected