Skip to content

Commit abe6aae

Browse files
harimkangcih9088jaegukhyunJihwanEom
authored
Move mpa.deploy to otx.algorithms.common (#1903)
* Move deploy modules to otx * test: fix mmdeploy api replacement error * Fix pre-commit issues * Update otx/mpa/det/exporter.py Co-authored-by: Jaeguk Hyun <[email protected]> * Update otx/mpa/exporter_mixin.py Co-authored-by: Jaeguk Hyun <[email protected]> * Update otx/mpa/seg/exporter.py Co-authored-by: Jaeguk Hyun <[email protected]> * Update otx/mpa/cls/exporter.py Co-authored-by: Jaeguk Hyun <[email protected]> * Update otx/algorithms/common/adapters/mmdeploy/utils/mmdeploy.py Co-authored-by: Jaeguk Hyun <[email protected]> * Update otx/algorithms/common/adapters/mmdeploy/utils/operations_domain.py Co-authored-by: Jihwan Eom <[email protected]> --------- Co-authored-by: Inhyuk Andy Cho <[email protected]> Co-authored-by: Jaeguk Hyun <[email protected]> Co-authored-by: Jihwan Eom <[email protected]>
1 parent e7325d5 commit abe6aae

33 files changed

+110
-100
lines changed

docs/source/guide/reference/mpa/deploy.rst

Lines changed: 0 additions & 34 deletions
This file was deleted.

docs/source/guide/reference/mpa/index.rst

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,4 @@ Model Preparation Algorithm
88
classification
99
detection
1010
segmentation
11-
deploy
1211
utils
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
"""Adapters for mmdeploy."""
2+
# Copyright (C) 2023 Intel Corporation
3+
#
4+
# SPDX-License-Identifier: MIT
5+
6+
from .utils.mmdeploy import is_mmdeploy_enabled
7+
8+
__all__ = [
9+
"is_mmdeploy_enabled",
10+
]

otx/mpa/deploy/apis.py renamed to otx/algorithms/common/adapters/mmdeploy/apis.py

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
"""API of otx.algorithms.common.adapters.mmdeploy."""
12
# Copyright (C) 2022 Intel Corporation
23
# SPDX-License-Identifier: Apache-2.0
34
#
@@ -12,20 +13,23 @@
1213

1314
import mmcv
1415
import numpy as np
15-
import onnx
1616
import torch
1717
from mmcv.parallel import collate, scatter
1818

19-
from .utils import numpy_2_list
2019
from .utils.mmdeploy import (
2120
is_mmdeploy_enabled,
2221
mmdeploy_init_model_helper,
2322
update_deploy_cfg,
2423
)
2524
from .utils.onnx import prepare_onnx_for_openvino
25+
from .utils.utils import numpy_2_list
26+
27+
# pylint: disable=too-many-locals
2628

2729

2830
class NaiveExporter:
31+
"""NaiveExporter for non-mmdeploy export."""
32+
2933
@staticmethod
3034
def export2openvino(
3135
output_dir: str,
@@ -38,13 +42,15 @@ def export2openvino(
3842
input_names: Optional[List[str]] = None,
3943
output_names: Optional[List[str]] = None,
4044
opset_version: int = 11,
41-
dynamic_axes: Dict[Any, Any] = {},
45+
dynamic_axes: Optional[Dict[Any, Any]] = None,
4246
mo_transforms: str = "",
4347
):
48+
"""Function for exporting to openvino."""
4449
input_data = scatter(collate([input_data], samples_per_gpu=1), [-1])[0]
4550

4651
model = model_builder(cfg)
4752
model = model.cpu().eval()
53+
dynamic_axes = dynamic_axes if dynamic_axes else dict()
4854

4955
onnx_path = NaiveExporter.torch2onnx(
5056
output_dir,
@@ -108,17 +114,19 @@ def torch2onnx(
108114
input_names: Optional[List[str]] = None,
109115
output_names: Optional[List[str]] = None,
110116
opset_version: int = 11,
111-
dynamic_axes: Dict[Any, Any] = {},
117+
dynamic_axes: Optional[Dict[Any, Any]] = None,
112118
verbose: bool = False,
113119
**onnx_options,
114120
) -> str:
121+
"""Function for torch to onnx exporting."""
115122

116123
img_metas = input_data.get("img_metas")
117124
numpy_2_list(img_metas)
118125
imgs = input_data.get("img")
119126
model.forward = partial(model.forward, img_metas=img_metas, return_loss=False)
120127

121128
onnx_file_name = model_name + ".onnx"
129+
dynamic_axes = dynamic_axes if dynamic_axes else dict()
122130
torch.onnx.export(
123131
model,
124132
imgs,
@@ -143,6 +151,7 @@ def onnx2openvino(
143151
model_name: str = "model",
144152
**openvino_options,
145153
) -> Tuple[str, str]:
154+
"""Function for onnx to openvino exporting."""
146155
from otx.mpa.utils import mo_wrapper
147156

148157
mo_args = {
@@ -163,17 +172,15 @@ def onnx2openvino(
163172

164173
if is_mmdeploy_enabled():
165174
import mmdeploy.apis.openvino as openvino_api
166-
from mmdeploy.apis import (
167-
build_task_processor,
168-
extract_model,
169-
get_predefined_partition_cfg,
170-
torch2onnx,
171-
)
175+
from mmdeploy.apis import build_task_processor, extract_model, torch2onnx
172176
from mmdeploy.apis.openvino import get_input_info_from_cfg, get_mo_options_from_cfg
173-
from mmdeploy.core import FUNCTION_REWRITER
174-
from mmdeploy.utils import get_backend_config, get_ir_config, get_partition_config
177+
178+
# from mmdeploy.core import FUNCTION_REWRITER
179+
from mmdeploy.utils import get_ir_config, get_partition_config
175180

176181
class MMdeployExporter:
182+
"""MMdeployExporter for mmdeploy exporting."""
183+
177184
@staticmethod
178185
def export2openvino(
179186
output_dir: str,
@@ -183,6 +190,7 @@ def export2openvino(
183190
*,
184191
model_name: str = "model",
185192
):
193+
"""Function for exporting to openvino."""
186194

187195
task_processor = build_task_processor(cfg, deploy_cfg, "cpu")
188196

@@ -248,6 +256,7 @@ def torch2onnx(
248256
*,
249257
model_name: str = "model",
250258
) -> str:
259+
"""Function for torch to onnx exporting."""
251260
onnx_file_name = model_name + ".onnx"
252261
torch2onnx(
253262
input_data,
@@ -266,6 +275,7 @@ def partition_onnx(
266275
onnx_path: str,
267276
partition_cfgs: Union[mmcv.ConfigDict, List[mmcv.ConfigDict]],
268277
) -> Tuple[str, ...]:
278+
"""Function for parition onnx."""
269279
partitioned_paths = []
270280

271281
if not isinstance(partition_cfgs, list):
@@ -290,6 +300,7 @@ def onnx2openvino(
290300
*,
291301
model_name: Optional[str] = None,
292302
) -> Tuple[str, str]:
303+
"""Function for onnx to openvino exporting."""
293304

294305
input_info = get_input_info_from_cfg(deploy_cfg)
295306
output_names = get_ir_config(deploy_cfg).output_names

otx/mpa/deploy/utils/__init__.py renamed to otx/algorithms/common/adapters/mmdeploy/utils/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
"""Init file for otx.algorithms.common.adapters.mmdeploy.utils."""
12
# Copyright (C) 2022 Intel Corporation
23
# SPDX-License-Identifier: Apache-2.0
34
#

otx/mpa/deploy/utils/mmdeploy.py renamed to otx/algorithms/common/adapters/mmdeploy/utils/mmdeploy.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,29 @@
1+
"""Functions for mmdeploy adapters."""
12
# Copyright (C) 2022 Intel Corporation
23
# SPDX-License-Identifier: Apache-2.0
34
#
45

56
import importlib
67

78
import onnx
8-
from mmcv.utils import ConfigDict
99

1010

1111
def is_mmdeploy_enabled():
12+
"""Checks if the 'mmdeploy' Python module is installed and available for use.
13+
14+
Returns:
15+
bool: True if 'mmdeploy' is installed, False otherwise.
16+
17+
Example:
18+
>>> is_mmdeploy_enabled()
19+
True
20+
"""
1221
return importlib.util.find_spec("mmdeploy") is not None
1322

1423

1524
def mmdeploy_init_model_helper(ctx, model_checkpoint=None, cfg_options=None, **kwargs):
25+
"""Helper function for initializing a model for inference using the 'mmdeploy' library."""
26+
1627
model_builder = kwargs.pop("model_builder")
1728
model = model_builder(
1829
ctx.model_cfg,
@@ -31,12 +42,14 @@ def mmdeploy_init_model_helper(ctx, model_checkpoint=None, cfg_options=None, **k
3142
return model
3243

3344

34-
def update_deploy_cfg(onnx_path, deploy_cfg, mo_options={}):
45+
def update_deploy_cfg(onnx_path, deploy_cfg, mo_options=None):
46+
"""Update the 'deploy_cfg' configuration file based on the ONNX model specified by 'onnx_path'."""
47+
3548
from mmdeploy.utils import get_backend_config, get_ir_config
3649

3750
onnx_model = onnx.load(onnx_path)
3851
ir_config = get_ir_config(deploy_cfg)
39-
backend_config = get_backend_config(deploy_cfg)
52+
get_backend_config(deploy_cfg)
4053

4154
# update input
4255
input_names = [i.name for i in onnx_model.graph.input]
@@ -47,6 +60,7 @@ def update_deploy_cfg(onnx_path, deploy_cfg, mo_options={}):
4760
ir_config["output_names"] = output_names
4861

4962
# update mo options
63+
mo_options = mo_options if mo_options else dict()
5064
deploy_cfg.merge_from_dict({"backend_config": {"mo_options": mo_options}})
5165

5266

otx/mpa/deploy/utils/onnx.py renamed to otx/algorithms/common/adapters/mmdeploy/utils/onnx.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
"""Functions for onnx adapters."""
12
# Copyright (C) 2022 Intel Corporation
23
# SPDX-License-Identifier: Apache-2.0
34
#
@@ -6,6 +7,7 @@
67

78

89
def remove_nodes_by_op_type(onnx_model, op_type):
10+
"""Remove all nodes of a specified op type from the ONNX model."""
911
# TODO: support more nodes
1012

1113
supported_op_types = ["Mark", "Conv", "Gemm"]
@@ -42,6 +44,7 @@ def remove_nodes_by_op_type(onnx_model, op_type):
4244

4345

4446
def prepare_onnx_for_openvino(in_path, out_path):
47+
"""Modify the specified ONNX model to be compatible with OpenVINO by removing 'Mark' op nodes."""
4548
onnx_model = onnx.load(in_path)
4649
onnx_model = remove_nodes_by_op_type(onnx_model, "Mark")
4750
onnx.checker.check_model(onnx_model)

otx/mpa/deploy/utils/operations_domain.py renamed to otx/algorithms/common/adapters/mmdeploy/utils/operations_domain.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
"""Add domain function."""
12
# Copyright (C) 2022 Intel Corporation
23
# SPDX-License-Identifier: Apache-2.0
34
#
@@ -6,4 +7,5 @@
67

78

89
def add_domain(name_operator: str) -> str:
10+
"""Function for adding to DOMAIN_CUSTOM_OPS_NAME."""
911
return DOMAIN_CUSTOM_OPS_NAME + "::" + name_operator

otx/mpa/deploy/utils/utils.py renamed to otx/algorithms/common/adapters/mmdeploy/utils/utils.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
"""Util functions of otx.algorithms.common.adapters.mmdeploy."""
12
# Copyright (C) 2022 Intel Corporation
23
# SPDX-License-Identifier: Apache-2.0
34
#
@@ -9,6 +10,7 @@
910

1011

1112
def sync_batchnorm_2_batchnorm(module, dim=2):
13+
"""Syncs the BatchNorm layers in a model to use regular BatchNorm layers."""
1214
if dim == 1:
1315
bn = torch.nn.BatchNorm1d
1416
elif dim == 2:
@@ -48,6 +50,7 @@ def sync_batchnorm_2_batchnorm(module, dim=2):
4850

4951

5052
def numpy_2_list(data):
53+
"""Converts NumPy arrays to Python lists."""
5154

5255
if isinstance(data, np.ndarray):
5356
return data.tolist()

otx/algorithms/detection/adapters/mmdet/models/detectors/custom_atss_detector.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@
99
from mmdet.models.builder import DETECTORS
1010
from mmdet.models.detectors.atss import ATSS
1111

12+
from otx.algorithms.common.adapters.mmdeploy.utils import is_mmdeploy_enabled
1213
from otx.algorithms.detection.adapters.mmdet.hooks.det_saliency_map_hook import (
1314
DetSaliencyMapHook,
1415
)
15-
from otx.mpa.deploy.utils import is_mmdeploy_enabled
1616
from otx.mpa.modules.hooks.recording_forward_hooks import FeatureVectorHook
1717
from otx.mpa.modules.utils.task_adapt import map_class_names
1818
from otx.mpa.utils.logger import get_logger

0 commit comments

Comments
 (0)