Coverage for src/bioimageio/core/weight_converters/pytorch_to_onnx.py: 86%
12 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 09:46 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 09:46 +0000
1from __future__ import annotations
3from collections.abc import Sequence
4from pathlib import Path
6from bioimageio.spec.model.v0_5 import ModelDescr, OnnxWeightsDescr
8from ..backends.pytorch_backend import load_torch_model
9from ._utils_torch_onnx import export_to_onnx
12def convert(
13 model_descr: ModelDescr,
14 output_path: Path,
15 *,
16 verbose: bool = False,
17 opset_version: int = 18,
18 devices: Sequence[str] | None = None,
19) -> OnnxWeightsDescr:
20 """
21 Convert model weights from the Torchscript state_dict format to the ONNX format.
23 Args:
24 model_descr:
25 The model description object that contains the model and its weights.
26 output_path:
27 The file path where the ONNX model will be saved.
28 verbose:
29 If True, will print out detailed information during the ONNX export process. Defaults to False.
30 opset_version:
31 The ONNX opset version to use for the export. Defaults to 18.
33 Raises:
34 ValueError:
35 If the provided model does not have weights in the PyTorch state_dict format.
37 Returns:
38 A description of the exported ONNX weights.
39 """
41 state_dict_weights_descr = model_descr.weights.pytorch_state_dict
42 if state_dict_weights_descr is None: 42 ↛ 43line 42 didn't jump to line 43 because the condition on line 42 was never true
43 raise ValueError(
44 "The provided model does not have weights in the pytorch state dict format"
45 )
47 model = load_torch_model(
48 state_dict_weights_descr, load_state=True, devices=devices
49 ).eval()
51 return export_to_onnx(
52 model_descr,
53 model,
54 output_path,
55 verbose,
56 opset_version,
57 parent="pytorch_state_dict",
58 )