Skip to content

Commit 8af421d

Browse files
author
pfinashx
committed
Merge branch 'develop' into pf/adding_anomaly_training_tests
2 parents 26ad5d1 + 2bbc890 commit 8af421d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+1040
-720
lines changed

external/anomaly/ote_anomalib/openvino.py

+31-60
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,15 @@
1616
# See the License for the specific language governing permissions
1717
# and limitations under the License.
1818

19-
import inspect
19+
import io
2020
import json
2121
import os
22-
import subprocess # nosec
23-
import sys
2422
import tempfile
25-
from shutil import copyfile, copytree
2623
from typing import Any, Dict, List, Optional
2724
from zipfile import ZipFile
2825

2926
import numpy as np
27+
import ote_anomalib.exportable_code
3028
from addict import Dict as ADDict
3129
from anomalib.deploy import OpenVINOInferencer
3230
from anomalib.post_processing import anomaly_map_to_color_map
@@ -41,12 +39,6 @@
4139
contains_anomalous_images,
4240
split_local_global_resultset,
4341
)
44-
from ote_anomalib.exportable_code import (
45-
AnomalyBase,
46-
AnomalyClassification,
47-
AnomalyDetection,
48-
AnomalySegmentation,
49-
)
5042
from ote_anomalib.logging import get_logger
5143
from ote_sdk.entities.datasets import DatasetEntity
5244
from ote_sdk.entities.inference_parameters import (
@@ -307,11 +299,17 @@ def optimize(
307299
if get_nodes_by_type(model, ["FakeQuantize"]):
308300
raise RuntimeError("Model is already optimized by POT")
309301

302+
if optimization_parameters is not None:
303+
optimization_parameters.update_progress(10)
304+
310305
engine = IEEngine(config=ADDict({"device": "CPU"}), data_loader=data_loader, metric=None)
311306
pipeline = create_pipeline(algo_config=self._get_optimization_algorithms_configs(), engine=engine)
312307
compressed_model = pipeline.run(model)
313308
compress_model_weights(compressed_model)
314309

310+
if optimization_parameters is not None:
311+
optimization_parameters.update_progress(90)
312+
315313
with tempfile.TemporaryDirectory() as tempdir:
316314
save_model(compressed_model, tempdir, model_name="model")
317315
self.__load_weights(path=os.path.join(tempdir, "model.xml"), output_model=output_model, key="openvino.xml")
@@ -330,6 +328,10 @@ def optimize(
330328
self.task_environment.model = output_model
331329
self.inferencer = self.load_inferencer()
332330

331+
if optimization_parameters is not None:
332+
optimization_parameters.update_progress(100)
333+
logger.info("POT optimization completed")
334+
333335
def load_inferencer(self) -> OpenVINOInferencer:
334336
"""
335337
Create the OpenVINO inferencer object
@@ -422,57 +424,26 @@ def deploy(self, output_model: ModelEntity) -> None:
422424

423425
task_type = str(self.task_type).lower()
424426

425-
if self.task_type == TaskType.ANOMALY_CLASSIFICATION:
426-
selected_class = AnomalyClassification
427-
elif self.task_type == TaskType.ANOMALY_DETECTION:
428-
selected_class = AnomalyDetection
429-
elif self.task_type == TaskType.ANOMALY_SEGMENTATION:
430-
selected_class = AnomalySegmentation
431-
else:
432-
raise ValueError(
433-
f"{self.task_type} is not supported. "
434-
"Only Anomaly <Classification, Detection, Segmentation> are supported"
435-
)
436-
437427
parameters["type_of_model"] = task_type
438428
parameters["converter_type"] = task_type.upper()
439429
parameters["model_parameters"] = self._get_openvino_configuration()
440-
name_of_package = "demo_package"
441-
442-
with tempfile.TemporaryDirectory() as tempdir:
443-
copyfile(os.path.join(work_dir, "setup.py"), os.path.join(tempdir, "setup.py"))
444-
copyfile(os.path.join(work_dir, "requirements.txt"), os.path.join(tempdir, "requirements.txt"))
445-
copytree(os.path.join(work_dir, name_of_package), os.path.join(tempdir, name_of_package))
446-
config_path = os.path.join(tempdir, name_of_package, "config.json")
447-
with open(config_path, "w", encoding="utf-8") as file:
448-
json.dump(parameters, file, ensure_ascii=False, indent=4)
449-
450-
copyfile(inspect.getfile(selected_class), os.path.join(tempdir, name_of_package, "model.py"))
451-
copyfile(inspect.getfile(AnomalyBase), os.path.join(tempdir, name_of_package, "base.py"))
452-
453-
# create wheel package
454-
subprocess.run(
455-
[
456-
sys.executable,
457-
os.path.join(tempdir, "setup.py"),
458-
"bdist_wheel",
459-
"--dist-dir",
460-
tempdir,
461-
"clean",
462-
"--all",
463-
],
464-
check=True,
465-
)
466-
wheel_file_name = [f for f in os.listdir(tempdir) if f.endswith(".whl")][0]
467-
468-
with ZipFile(os.path.join(tempdir, "openvino.zip"), "w") as arch:
469-
arch.writestr(os.path.join("model", "model.xml"), self.task_environment.model.get_data("openvino.xml"))
470-
arch.writestr(os.path.join("model", "model.bin"), self.task_environment.model.get_data("openvino.bin"))
471-
arch.write(os.path.join(tempdir, "requirements.txt"), os.path.join("python", "requirements.txt"))
472-
arch.write(os.path.join(work_dir, "README.md"), os.path.join("python", "README.md"))
473-
arch.write(os.path.join(work_dir, "LICENSE"), os.path.join("python", "LICENSE"))
474-
arch.write(os.path.join(work_dir, "demo.py"), os.path.join("python", "demo.py"))
475-
arch.write(os.path.join(tempdir, wheel_file_name), os.path.join("python", wheel_file_name))
476-
with open(os.path.join(tempdir, "openvino.zip"), "rb") as output_arch:
477-
output_model.exportable_code = output_arch.read()
430+
zip_buffer = io.BytesIO()
431+
with ZipFile(zip_buffer, "w") as arch:
432+
# model files
433+
arch.writestr(os.path.join("model", "model.xml"), self.task_environment.model.get_data("openvino.xml"))
434+
arch.writestr(os.path.join("model", "model.bin"), self.task_environment.model.get_data("openvino.bin"))
435+
arch.writestr(os.path.join("model", "config.json"), json.dumps(parameters, ensure_ascii=False, indent=4))
436+
# model_wrappers files
437+
for root, _, files in os.walk(os.path.dirname(ote_anomalib.exportable_code.__file__)):
438+
for file in files:
439+
file_path = os.path.join(root, file)
440+
arch.write(
441+
file_path, os.path.join("python", "model_wrappers", file_path.split("exportable_code/")[1])
442+
)
443+
# other python files
444+
arch.write(os.path.join(work_dir, "requirements.txt"), os.path.join("python", "requirements.txt"))
445+
arch.write(os.path.join(work_dir, "LICENSE"), os.path.join("python", "LICENSE"))
446+
arch.write(os.path.join(work_dir, "README.md"), os.path.join("python", "README.md"))
447+
arch.write(os.path.join(work_dir, "demo.py"), os.path.join("python", "demo.py"))
448+
output_model.exportable_code = zip_buffer.getvalue()
478449
logger.info("Deployment completed.")

external/anomaly/requirements.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
anomalib @ git+https://github.com/openvinotoolkit/anomalib.git@834d45ab1761841ba4041eb4472f01fb63d344a6
2-
openmodelzoo-modelapi @ git+https://github.com/openvinotoolkit/open_model_zoo/@releases/2021/SCMVP#egg=openmodelzoo-modelapi&subdirectory=demos/common/python
2+
openmodelzoo-modelapi @ git+https://github.com/openvinotoolkit/open_model_zoo/@releases/2022/SCv1.1#egg=openmodelzoo-modelapi&subdirectory=demos/common/python
33
openvino==2022.1.0
44
openvino-dev==2022.1.0
55
onnx==1.10.1

external/anomaly/tests/ote_cli/test_anomaly_classification.py

+1
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ def test_nncf_export(self, template):
128128

129129
@e2e_pytest_component
130130
@pytest.mark.parametrize("template", templates, ids=templates_ids)
131+
@pytest.mark.xfail(reason="CVS-83124")
131132
def test_nncf_eval(self, template):
132133
if template.entrypoints.nncf is None:
133134
pytest.skip("nncf entrypoint is none")

external/anomaly/tests/ote_cli/test_anomaly_detection.py

+1
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ def test_nncf_export(self, template):
127127

128128
@e2e_pytest_component
129129
@pytest.mark.parametrize("template", templates, ids=templates_ids)
130+
@pytest.mark.xfail(reason="CVS-83124")
130131
def test_nncf_eval(self, template):
131132
if template.entrypoints.nncf is None:
132133
pytest.skip("nncf entrypoint is none")

external/anomaly/tests/ote_cli/test_anomaly_segmentation.py

+1
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ def test_nncf_export(self, template):
128128

129129
@e2e_pytest_component
130130
@pytest.mark.parametrize("template", templates, ids=templates_ids)
131+
@pytest.mark.xfail(reason="CVS-83124")
131132
def test_nncf_eval(self, template):
132133
if template.entrypoints.nncf is None:
133134
pytest.skip("nncf entrypoint is none")
+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
nncf @ git+https://github.com/openvinotoolkit/nncf@464244204fc2c5e80c8164c17d8d266ccae50062#egg=nncf
22
openvino==2022.1.0
33
openvino-dev==2022.1.0
4-
openmodelzoo-modelapi @ git+https://github.com/openvinotoolkit/open_model_zoo/@releases/2021/SCMVP#egg=openmodelzoo-modelapi&subdirectory=demos/common/python
4+
openmodelzoo-modelapi @ git+https://github.com/openvinotoolkit/open_model_zoo/@releases/2022/SCv1.1#egg=openmodelzoo-modelapi&subdirectory=demos/common/python

external/deep-object-reid/tests/ote_cli/test_classification.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def test_nncf_eval(self, template):
151151
pytest.skip("nncf entrypoint is none")
152152

153153
nncf_eval_testing(template, root, ote_dir, args, threshold=0.001)
154-
154+
155155
@e2e_pytest_component
156156
@pytest.mark.parametrize("template", templates, ids=templates_ids)
157157
def test_nncf_eval_openvino(self, template):

external/deep-object-reid/torchreid_tasks/model_wrappers/classification.py

+3
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ def _check_io_number(self, inp, outp):
4545

4646
def _get_outputs(self):
4747
layer_name = 'logits'
48+
for name, meta in self.outputs.items():
49+
if 'logits' in meta.names:
50+
layer_name = name
4851
layer_shape = self.outputs[layer_name].shape
4952

5053
if len(layer_shape) != 2 and len(layer_shape) != 4:

external/deep-object-reid/torchreid_tasks/openvino_task.py

+32-34
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,17 @@
1212
# See the License for the specific language governing permissions
1313
# and limitations under the License.
1414

15-
import inspect
15+
import io
1616
import json
1717
import logging
1818
import os
19-
import subprocess # nosec
20-
import sys
2119
import tempfile
22-
from shutil import copyfile, copytree
2320
from typing import Any, Dict, Optional, Tuple, Union
2421

2522
from addict import Dict as ADDict
2623

2724
import numpy as np
28-
25+
import torchreid_tasks.model_wrappers as model_wrappers
2926
from ote_sdk.usecases.exportable_code import demo
3027
from ote_sdk.entities.annotation import AnnotationSceneEntity
3128
from ote_sdk.entities.datasets import DatasetEntity
@@ -72,7 +69,6 @@
7269
from torchreid_tasks.utils import get_multihead_class_info
7370

7471
from zipfile import ZipFile
75-
from . import model_wrappers
7672

7773
logger = logging.getLogger(__name__)
7874

@@ -204,39 +200,31 @@ def deploy(self,
204200
logger.info('Deploying the model')
205201

206202
work_dir = os.path.dirname(demo.__file__)
207-
model_file = inspect.getfile(type(self.inferencer.model))
208203
parameters = {}
209204
parameters['type_of_model'] = 'ote_classification'
210205
parameters['converter_type'] = 'CLASSIFICATION'
211206
parameters['model_parameters'] = self.inferencer.configuration
212207
parameters['model_parameters']['labels'] = LabelSchemaMapper.forward(self.task_environment.label_schema)
213-
name_of_package = "demo_package"
214-
with tempfile.TemporaryDirectory() as tempdir:
215-
copyfile(os.path.join(work_dir, "setup.py"), os.path.join(tempdir, "setup.py"))
216-
copyfile(os.path.join(work_dir, "requirements.txt"), os.path.join(tempdir, "requirements.txt"))
217-
copytree(os.path.join(work_dir, name_of_package), os.path.join(tempdir, name_of_package))
218-
config_path = os.path.join(tempdir, name_of_package, "config.json")
219-
with open(config_path, "w", encoding='utf-8') as f:
220-
json.dump(parameters, f, ensure_ascii=False, indent=4)
221-
# generate model.py
222-
if (inspect.getmodule(self.inferencer.model) in
223-
[module[1] for module in inspect.getmembers(model_wrappers, inspect.ismodule)]):
224-
copyfile(model_file, os.path.join(tempdir, name_of_package, "model.py"))
225-
# create wheel package
226-
subprocess.run([sys.executable, os.path.join(tempdir, "setup.py"), 'bdist_wheel',
227-
'--dist-dir', tempdir, 'clean', '--all'], check=True)
228-
wheel_file_name = [f for f in os.listdir(tempdir) if f.endswith('.whl')][0]
229-
230-
with ZipFile(os.path.join(tempdir, "openvino.zip"), 'w') as zip_f:
231-
zip_f.writestr(os.path.join("model", "model.xml"), self.model.get_data("openvino.xml"))
232-
zip_f.writestr(os.path.join("model", "model.bin"), self.model.get_data("openvino.bin"))
233-
zip_f.write(os.path.join(tempdir, "requirements.txt"), os.path.join("python", "requirements.txt"))
234-
zip_f.write(os.path.join(work_dir, "README.md"), os.path.join("python", "README.md"))
235-
zip_f.write(os.path.join(work_dir, "LICENSE"), os.path.join("python", "LICENSE"))
236-
zip_f.write(os.path.join(work_dir, "demo.py"), os.path.join("python", "demo.py"))
237-
zip_f.write(os.path.join(tempdir, wheel_file_name), os.path.join("python", wheel_file_name))
238-
with open(os.path.join(tempdir, "openvino.zip"), "rb") as file:
239-
output_model.exportable_code = file.read()
208+
209+
zip_buffer = io.BytesIO()
210+
with ZipFile(zip_buffer, 'w') as arch:
211+
# model files
212+
arch.writestr(os.path.join("model", "model.xml"), self.model.get_data("openvino.xml"))
213+
arch.writestr(os.path.join("model", "model.bin"), self.model.get_data("openvino.bin"))
214+
arch.writestr(
215+
os.path.join("model", "config.json"), json.dumps(parameters, ensure_ascii=False, indent=4)
216+
)
217+
# model_wrappers files
218+
for root, dirs, files in os.walk(os.path.dirname(model_wrappers.__file__)):
219+
for file in files:
220+
file_path = os.path.join(root, file)
221+
arch.write(file_path, os.path.join("python", "model_wrappers", file_path.split("model_wrappers/")[1]))
222+
# other python files
223+
arch.write(os.path.join(work_dir, "requirements.txt"), os.path.join("python", "requirements.txt"))
224+
arch.write(os.path.join(work_dir, "LICENSE"), os.path.join("python", "LICENSE"))
225+
arch.write(os.path.join(work_dir, "README.md"), os.path.join("python", "README.md"))
226+
arch.write(os.path.join(work_dir, "demo.py"), os.path.join("python", "demo.py"))
227+
output_model.exportable_code = zip_buffer.getvalue()
240228
logger.info('Deploying completed')
241229

242230
def optimize(self,
@@ -269,6 +257,9 @@ def optimize(self,
269257
if get_nodes_by_type(model, ["FakeQuantize"]):
270258
raise RuntimeError("Model is already optimized by POT")
271259

260+
if optimization_parameters is not None:
261+
optimization_parameters.update_progress(10)
262+
272263
engine_config = ADDict({
273264
'device': 'CPU'
274265
})
@@ -296,6 +287,9 @@ def optimize(self,
296287

297288
compress_model_weights(compressed_model)
298289

290+
if optimization_parameters is not None:
291+
optimization_parameters.update_progress(90)
292+
299293
with tempfile.TemporaryDirectory() as tempdir:
300294
save_model(compressed_model, tempdir, model_name="model")
301295
with open(os.path.join(tempdir, "model.xml"), "rb") as f:
@@ -313,3 +307,7 @@ def optimize(self,
313307

314308
self.model = output_model
315309
self.inferencer = self.load_inferencer()
310+
311+
if optimization_parameters is not None:
312+
optimization_parameters.update_progress(100)
313+
logger.info('POT optimization completed')

0 commit comments

Comments
 (0)