1# Copyright (c) ONNX Project Contributors
2
3# SPDX-License-Identifier: Apache-2.0
4"""onnx version converter
5
6This enables users to convert their models between different opsets within the
7default domain ("" or "ai.onnx").
8"""
9
10from __future__ import annotations
11
12import onnx
13import onnx.onnx_cpp2py_export.version_converter as C # noqa: N812
14from onnx import ModelProto
15
16
17def convert_version(model: ModelProto, target_version: int) -> ModelProto:
18 """Convert opset version of the ModelProto.
19
20 Arguments:
21 model: Model.
22 target_version: Target opset version.
23
24 Returns:
25 Converted model.
26
27 Raises:
28 RuntimeError when some necessary conversion is not supported.
29 """
30 if not isinstance(model, ModelProto):
31 raise TypeError(
32 f"VersionConverter only accepts ModelProto as model, incorrect type: {type(model)}"
33 )
34 if not isinstance(target_version, int):
35 raise TypeError(
36 f"VersionConverter only accepts int as target_version, incorrect type: {type(target_version)}"
37 )
38 model_str = model.SerializeToString()
39 converted_model_str = C.convert_version(model_str, target_version)
40 return onnx.load_from_string(converted_model_str)
41
42
43ConvertError = C.ConvertError