Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update OV / NNCF/ ModelAPI / Datumaro #2090

Merged
merged 118 commits into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from 117 commits
Commits
Show all changes
118 commits
Select commit Hold shift + click to select a range
247e8f3
Update ov to a pre-release version
sovrasov Apr 28, 2023
83f21e2
Update OV to 2023 release
sovrasov Jun 1, 2023
3b4e8c5
dummy fix for unit tests
sovrasov Jun 1, 2023
64786e2
Update
sovrasov Jun 1, 2023
43b77a1
Apply a workaround for OV 23 bug
sovrasov Jun 2, 2023
b1b55f0
Fix getting rt info
sovrasov Jun 2, 2023
0bbfa84
Tmp update of NNCF
sovrasov Jun 2, 2023
d4faa4c
Changes for supporting NNCF 2.5 (WIP)
nikita-savelyevv May 26, 2023
9c2dfb0
Add new model api to reqs
sovrasov Jun 2, 2023
0b015af
Integration for classification
sovrasov Jun 2, 2023
c5fc5e3
Update model contaner
sovrasov Jun 6, 2023
4f0983b
Fix OTX segm wrapper
sovrasov Jun 6, 2023
5648e90
Fix linter
sovrasov Jun 6, 2023
9462d54
Update detection inference
sovrasov Jun 6, 2023
f57c4d9
Fix MRCNN inference
sovrasov Jun 6, 2023
11007f1
Fix tiling inference
sovrasov Jun 6, 2023
c79554b
Fix cls unit tests
sovrasov Jun 6, 2023
0295c18
Fix detection unit tests
sovrasov Jun 6, 2023
0c97432
Fix semantic segmentation UT
sovrasov Jun 6, 2023
bfdb054
Fix datumaro tests
sovrasov Jun 6, 2023
1331845
Ugrade mapi in action and anomaly
sovrasov Jun 6, 2023
56fbd8e
Update exp code commit ver
sovrasov Jun 6, 2023
6c07ee8
Add raw scores to cls config
sovrasov Jun 6, 2023
25f1de7
Revert changes in graph parsing test
sovrasov Jun 6, 2023
a660a7b
Fix model creation in modelAdapter
sovrasov Jun 7, 2023
52d432a
Fix metadata shape in ModelAdapter
sovrasov Jun 7, 2023
e02a9f3
Fix tile classifier config
sovrasov Jun 7, 2023
f58aab2
Update exportable code reqs
sovrasov Jun 7, 2023
1a6f25c
Fix model container
sovrasov Jun 7, 2023
cc3504a
Del unused import
sovrasov Jun 7, 2023
17137af
Update NNCF to release version
sovrasov Jun 7, 2023
2853fe6
Xfail movinet inference
sovrasov Jun 7, 2023
02eaf1e
Updatemapi
sovrasov Jun 7, 2023
b41b812
Update exportable code commit
sovrasov Jun 7, 2023
02a8153
Fix act test xfail
sovrasov Jun 7, 2023
a33e2e7
Fix tiling inference
sovrasov Jun 7, 2023
4398844
Fix imports
sovrasov Jun 7, 2023
a526482
Fix exports in unit tests
sovrasov Jun 7, 2023
39dce04
Fix tiling test
sovrasov Jun 8, 2023
54878f5
Swithc classification to PTQ
sovrasov Jun 8, 2023
055dc80
Extract quantization check
sovrasov Jun 8, 2023
2ec137a
Move transform to dataset
sovrasov Jun 8, 2023
98ad837
Switch to ptq in segmentation
sovrasov Jun 8, 2023
b803b69
Fix mypy
sovrasov Jun 8, 2023
256d0c6
Fix ptq naming
sovrasov Jun 12, 2023
72aaa56
Switch to PTQ in action task
sovrasov Jun 12, 2023
2fd5e77
Fix cls optimize test
sovrasov Jun 12, 2023
ce2bf72
Fix segmentation ptq test
sovrasov Jun 12, 2023
737b0c7
Fix action tests
sovrasov Jun 12, 2023
14006a5
PTQ for detection task
sovrasov Jun 12, 2023
303b99e
Use ignored_scope in segm pqt
sovrasov Jun 13, 2023
d85d82a
Extract OV data loader to a standalone class
sovrasov Jun 13, 2023
9542fb5
PTQ for anomaly
sovrasov Jun 13, 2023
abf4830
Shuffler for action PTQ dataset
sovrasov Jun 13, 2023
d65c4ea
Fix det unit tests
sovrasov Jun 13, 2023
790144f
Del unused import
sovrasov Jun 13, 2023
ccc4199
Update exportable code deps
sovrasov Jun 13, 2023
b94772c
Fix exportable code tiling
sovrasov Jun 13, 2023
f80d5f7
Update exportable code reqs
sovrasov Jun 13, 2023
867b3f7
Fix tiling in exportable code
sovrasov Jun 14, 2023
6babcc0
Use py configs for PTQ segmentation
sovrasov Jun 15, 2023
78664f6
Add py style PTQ configs
sovrasov Jun 15, 2023
827b09e
Del outdated pot segm configs
sovrasov Jun 15, 2023
31b5c04
Update ptq configs for anomaly
sovrasov Jun 15, 2023
5d09640
Fix cls explain inference
sovrasov Jun 15, 2023
70841e8
Fix activation cls wrapper
sovrasov Jun 16, 2023
c776790
PArtially fix OMZ plugin
sovrasov Jun 17, 2023
8d5f300
Fix opset version collisions
sovrasov Jun 19, 2023
2efdd27
Partially fix nncf ckpt
sovrasov Jun 19, 2023
54d5e35
Fix MRCNN wrapper
sovrasov Jun 19, 2023
3f1668a
Fix softmax opset ver
sovrasov Jun 20, 2023
0bb9873
Update changelog
sovrasov Jun 20, 2023
bf1651d
Update exportable code reqs
sovrasov Jun 20, 2023
943213c
Update ov related imports
sovrasov Jun 20, 2023
258a2c9
Update fq num refs for semantic segmentation
sovrasov Jun 20, 2023
30f3adb
Update fq refs for classification
sovrasov Jun 20, 2023
56a1c41
Add update mode for FQ refs
sovrasov Jun 20, 2023
c65ad93
Update fq refs for detection
sovrasov Jun 20, 2023
49660bf
Xfaail e2e for movinet
sovrasov Jun 20, 2023
818fa38
Update sses fqs pt2
sovrasov Jun 20, 2023
fbbfdd3
Upgrade nncf anomalib integration
sovrasov Jun 20, 2023
c1c31bb
Upgrade nncf weights loading workaround in anomaly task
sovrasov Jun 20, 2023
7f778ea
Update FQ refs for anomaly
sovrasov Jun 20, 2023
96e85da
Bypass PTQ for tile classifier
sovrasov Jun 20, 2023
1d25453
Update IS FQ refs
sovrasov Jun 21, 2023
08dae30
Update detection FQ refs
sovrasov Jun 21, 2023
8ae49fe
Fix tiling classifier PTQ bypass
sovrasov Jun 21, 2023
2dfc285
Minor updates in tests
sovrasov Jun 21, 2023
b0c5d2b
Fix ruff
sovrasov Jun 21, 2023
b4a2533
Fix tile classifier PTQ bypass condition
sovrasov Jun 21, 2023
341896f
Fix a typo
sovrasov Jun 21, 2023
bace62e
Update det ut
sovrasov Jun 21, 2023
70e5c5a
Update fq refs for tiling iseg
sovrasov Jun 21, 2023
6f7768e
Fix tiling inference configuration
sovrasov Jun 21, 2023
f3da463
Fix readme
sovrasov Jun 22, 2023
0020b11
Update datumaro commit
sovrasov Jun 27, 2023
b71faf7
Update datumaro commit
sovrasov Jun 27, 2023
0add9e6
Update masks postprocessing in OV wrapper
sovrasov Jun 28, 2023
48f37d2
Update mrcnn unit tests
sovrasov Jun 28, 2023
eeabbca
Fix yolox inference config
sovrasov Jun 28, 2023
bdddd6d
Update docs for NNCF state dict hooks
sovrasov Jun 28, 2023
58b3b7d
Fix comments formatting
sovrasov Jun 28, 2023
5f7a87f
Skip action det ov e2e tests
sovrasov Jun 29, 2023
675b34b
Update IS tests skips
sovrasov Jul 3, 2023
f8f3d67
Skip some of SS PTQ tests
sovrasov Jul 3, 2023
aac0adf
Fix a type in skip comment
sovrasov Jul 3, 2023
14ffe33
Fix data pipeline for tiling yolox
sovrasov Jul 3, 2023
b2ee3e0
Revert ss PTQ->POT
sovrasov Jul 4, 2023
f01604f
Re-enable POT tests for sseg
sovrasov Jul 4, 2023
9fec926
Fix ptq config managing
sovrasov Jul 4, 2023
cdfa1c0
Fix black
sovrasov Jul 4, 2023
b77dcee
Fix merge conflicts
sovrasov Jul 4, 2023
20b8157
Update refs to PTQ configs in docs
sovrasov Jul 4, 2023
deea851
Update changelog
sovrasov Jul 4, 2023
a6f098d
Update FQs refs for anomaly
sovrasov Jul 5, 2023
9000caa
Update FQ refs for SS models
sovrasov Jul 5, 2023
84418cb
Merge remote-tracking branch 'origin/develop' into vs/upd_ov
sovrasov Jul 6, 2023
a2cc7e2
Merge branch 'develop' into vs/upd_ov
jaegukhyun Jul 7, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ All notable changes to this project will be documented in this file.
- Set persistent_workers and pin_memory as True in detection task (<https://github.com/openvinotoolkit/training_extensions/pull/2224>)
- New algorithm for Semi-SL semantic segmentation based on metric lerning via class prototypes (https://github.com/openvinotoolkit/training_extensions/pull/2156)
- Self-SL for classification now can recieve just folder with any images to start contrastive pretraining (https://github.com/openvinotoolkit/training_extensions/pull/2219)
- Update OpenVINO version to 2023.0, and NNCF verion to 2.5 (<https://github.com/openvinotoolkit/training_extensions/pull/2090>)
- Improve XAI saliency map generation for tiling detection and tiling instance segmentation (https://github.com/openvinotoolkit/training_extensions/pull/2240)

### Bug fixes
Expand All @@ -30,7 +31,7 @@ All notable changes to this project will be documented in this file.

### Known issues

- OpenVINO(==2022.3) IR inference is not working well on 2-stage models (e.g. Mask-RCNN) exported from torch==1.13.1
- OpenVINO(==2023.0) IR inference is not working well on 2-stage models (e.g. Mask-RCNN) exported from torch==1.13.1
goodsong81 marked this conversation as resolved.
Show resolved Hide resolved

## \[v1.3.1\]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ Models Optimization
OpenVINO™ Training Extensions provides two types of optimization algorithms: `Post-training Optimization Tool (POT) <https://docs.openvino.ai/latest/pot_introduction.html#doxid-pot-introduction>`_ and `Neural Network Compression Framework (NNCF) <https://github.com/openvinotoolkit/nncf>`_.

*******************************
Post-training Optimization Tool
Post-training Optimization Tool
*******************************

POT is designed to optimize the inference of models by applying post-training methods that do not require model retraining or fine-tuning. If you want to know more details about how POT works and to be more familiar with model optimization methods, please refer to `documentation <https://docs.openvino.ai/latest/pot_introduction.html#doxid-pot-introduction>`_.

To run Post-training optimization it is required to convert the model to OpenVINO™ intermediate representation (IR) first. To perform fast and accurate quantization we use ``DefaultQuantization Algorithm`` for each task. Please, see the `DefaultQuantization Parameters <https://docs.openvino.ai/latest/pot_compression_algorithms_quantization_default_README.html#doxid-pot-compression-algorithms-quantization-default-r-e-a-d-m-e>`_ for further information about configuring the optimization.

POT parameters can be found and configured in ``template.yaml`` and ``configuration.yaml`` for each task. For Anomaly and Semantic Segmentation tasks, we have separate configuration files for POT, that can be found in the same directory with ``template.yaml``, for example for `PaDiM <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/anomaly/configs/classification/padim/pot_optimization_config.json>`_, `OCR-Lite-HRNe-18-mod2 <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/segmentation/configs/ocr_lite_hrnet_18_mod2/pot_optimization_config.json>`_ model.
POT parameters can be found and configured in ``template.yaml`` and ``configuration.yaml`` for each task. For Anomaly and Semantic Segmentation tasks, we have separate configuration files for POT, that can be found in the same directory with ``template.yaml``, for example for `PaDiM <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/anomaly/configs/classification/padim/ptq_optimization_config.py>`_, `OCR-Lite-HRNe-18-mod2 <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/segmentation/configs/ocr_lite_hrnet_18_mod2/ptq_optimization_config.py>`_ model.

************************************
Neural Network Compression Framework
Expand All @@ -23,8 +23,8 @@ The process of optimization is controlled by the NNCF configuration file. A JSON
You can refer to configuration files for default templates for each task accordingly: `Classification <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/classification/configs/efficientnet_b0_cls_incr/compression_config.json>`_, `Object Detection <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/detection/configs/detection/mobilenetv2_atss/compression_config.json>`_, `Semantic segmentation <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/segmentation/configs/ocr_lite_hrnet_18_mod2/compression_config.json>`_, `Instance segmentation <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/detection/configs/instance_segmentation/efficientnetb2b_maskrcnn/compression_config.json>`_, `Anomaly classification <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/anomaly/configs/classification/padim/compression_config.json>`_, `Anomaly Detection <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/anomaly/configs/detection/padim/compression_config.json>`_, `Anomaly segmentation <https://github.com/openvinotoolkit/training_extensions/blob/develop/src/otx/algorithms/anomaly/configs/segmentation/padim/compression_config.json>`_. Configs for other templates can be found in the same directory.


NNCF tends to provide better quality in terms of preserving accuracy as it uses training compression approaches.
Compression results achievable with the NNCF can be found `here <https://github.com/openvinotoolkit/nncf#nncf-compressed-model-zoo>`_ .
NNCF tends to provide better quality in terms of preserving accuracy as it uses training compression approaches.
Compression results achievable with the NNCF can be found `here <https://github.com/openvinotoolkit/nncf#nncf-compressed-model-zoo>`_ .
Meanwhile, the POT is faster but can degrade accuracy more than the training-enabled approach.

.. note::
Expand Down
2 changes: 1 addition & 1 deletion requirements/base.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ natsort>=6.0.0
prettytable
protobuf>=3.20.0
pyyaml
datumaro==1.3.2
datumaro@ git+https://github.com/openvinotoolkit/datumaro@3e77b3138d063db68a4efba3c03a6bac7df086b1#egg=datumaro
psutil
scipy>=1.8
bayesian-optimization>=1.2.0
Expand Down
8 changes: 4 additions & 4 deletions requirements/openvino.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# OpenVINO Requirements. #
nncf==2.4.0
nncf==2.5.0
onnx==1.13.0
openmodelzoo-modelapi==2022.3.0
openvino==2022.3.0
openvino-dev==2022.3.0
openvino-model-api==0.1.2
openvino==2023.0
openvino-dev==2023.0
openvino-telemetry>=2022.1.0
9 changes: 4 additions & 5 deletions src/otx/algorithms/action/adapters/openvino/dataloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,12 @@
from typing import Dict, List

import numpy as np
from compression.api import DataLoader

from otx.api.entities.annotation import AnnotationSceneEntity
from otx.api.entities.datasets import DatasetEntity, DatasetItemEntity


def get_ovdataloader(dataset: DatasetEntity, task_type: str, clip_len: int, width: int, height: int) -> DataLoader:
def get_ovdataloader(dataset: DatasetEntity, task_type: str, clip_len: int, width: int, height: int):
"""Find proper dataloader for dataset and task type.

If dataset has only a single video, this returns DataLoader for online demo
Expand All @@ -49,7 +48,7 @@ def _is_multi_video(dataset: DatasetEntity) -> bool:
return False


class ActionOVDemoDataLoader(DataLoader):
class ActionOVDemoDataLoader:
"""DataLoader for online demo purpose.

Since it is for online demo purpose it selects background frames from neighbor of key frame
Expand Down Expand Up @@ -91,7 +90,7 @@ def add_prediction(self, data: List[DatasetItemEntity], prediction: AnnotationSc
dataset_item.append_annotations(prediction.annotations)


class ActionOVClsDataLoader(DataLoader):
class ActionOVClsDataLoader:
"""DataLoader for evaluation of action classification models.

It iterates through clustered video, and it samples frames from given video
Expand Down Expand Up @@ -151,7 +150,7 @@ def add_prediction(self, dataset: DatasetEntity, data: List[DatasetItemEntity],
dataset_item.append_labels(prediction.annotations[0].get_labels())


class ActionOVDetDataLoader(DataLoader):
class ActionOVDetDataLoader:
"""DataLoader for evaluation of spatio-temporal action detection models.

It iterates through DatasetEntity, which only contains non-empty frame(frame with actor annotation)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,16 @@
from typing import Any, Dict, List

import numpy as np
from openvino.model_api.adapters import OpenvinoAdapter
from openvino.model_api.models.model import Model
from openvino.model_api.models.utils import (
RESIZE_TYPES,
Detection,
InputTransform,
)

from otx.api.entities.datasets import DatasetItemEntity

try:
from openvino.model_zoo.model_api.adapters import OpenvinoAdapter
from openvino.model_zoo.model_api.models.model import Model
from openvino.model_zoo.model_api.models.utils import (
RESIZE_TYPES,
Detection,
InputTransform,
)
except ImportError as e:
import warnings

warnings.warn(f"{e}, ModelAPI was not found.")


def softmax_numpy(x: np.ndarray):
"""Softmax numpy."""
Expand Down
87 changes: 36 additions & 51 deletions src/otx/algorithms/action/adapters/openvino/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,26 @@
import json
import logging
import os
import random
import tempfile
from typing import Any, Dict, List, Optional, Tuple, Union
from zipfile import ZipFile

import nncf
import numpy as np
from addict import Dict as ADDict
from compression.api import DataLoader
from compression.engines.ie_engine import IEEngine
from compression.graph import load_model, save_model
from compression.graph.model_utils import compress_model_weights, get_nodes_by_type
from compression.pipeline.initializer import create_pipeline
import openvino.runtime as ov
from mmcv.utils import ProgressBar
from nncf.common.quantization.structs import QuantizationPreset
from openvino.model_api.adapters import OpenvinoAdapter, create_core
from openvino.model_api.models import Model

from otx.algorithms.action.adapters.openvino import (
ActionOVClsDataLoader,
get_ovdataloader,
model_wrappers,
)
from otx.algorithms.action.configs.base import ActionConfig
from otx.algorithms.common.utils.ir import check_if_quantized
from otx.api.entities.annotation import AnnotationSceneEntity
from otx.api.entities.datasets import DatasetEntity, DatasetItemEntity
from otx.api.entities.inference_parameters import (
Expand All @@ -53,6 +54,7 @@
)
from otx.api.entities.optimization_parameters import OptimizationParameters
from otx.api.entities.resultset import ResultSetEntity
from otx.api.entities.subset import Subset
from otx.api.entities.task_environment import TaskEnvironment
from otx.api.serialization.label_mapper import LabelSchemaMapper, label_schema_to_bytes
from otx.api.usecases.evaluation.metrics_helper import MetricsHelper
Expand All @@ -71,14 +73,6 @@
OptimizationType,
)

try:
from openvino.model_zoo.model_api.adapters import OpenvinoAdapter, create_core
from openvino.model_zoo.model_api.models import Model
except ImportError:
import warnings

warnings.warn("ModelAPI was not found.")

logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -115,7 +109,7 @@ def __init__(
create_core(), model_file, weight_file, device=device, max_num_requests=num_requests
)
self.configuration: Dict[Any, Any] = {}
self.model = Model.create_model(self.task_type, model_adapter, self.configuration, preload=True)
self.model = Model.create_model(model_adapter, self.task_type, self.configuration, preload=True)
self.converter: IPredictionToAnnotationConverter
if self.task_type == "ACTION_CLASSIFICATION":
self.converter = ClassificationToAnnotationConverter(self.label_schema)
Expand Down Expand Up @@ -147,20 +141,26 @@ def forward(self, image: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
return self.model.infer_sync(image)


class DataLoaderWrapper(DataLoader):
class DataLoaderWrapper:
"""DataLoader implementation for ActionOpenVINOTask."""

def __init__(self, dataloader: DataLoader, inferencer: BaseInferencer):
super().__init__(config=None)
def __init__(self, dataloader: Any, inferencer: BaseInferencer, shuffle: bool = True):
self.dataloader = dataloader
self.inferencer = inferencer
self.shuffler = None
if shuffle:
self.shuffler = list(range(len(dataloader)))
random.shuffle(self.shuffler)

def __getitem__(self, index: int):
"""Get item from dataset."""
if self.shuffler is not None:
index = self.shuffler[index]

item = self.dataloader[index]
annotation = item[len(item) // 2].annotation_scene
inputs, metadata = self.inferencer.pre_process(item)
return (index, annotation), inputs, metadata
inputs, _ = self.inferencer.pre_process(item)
return inputs, annotation

def __len__(self):
"""Get length of dataset."""
Expand Down Expand Up @@ -272,13 +272,15 @@ def optimize(
"""Optimize function of OpenVINOTask."""

if optimization_type is not OptimizationType.POT:
raise ValueError("POT is the only supported optimization type for OpenVino models")
raise ValueError("PTQ is the only supported optimization type for OpenVino models")

clip_len = self.inferencer.model.t
width = self.inferencer.model.w
height = self.inferencer.model.h
dataset = dataset.get_subset(Subset.TRAINING)
data_loader = get_ovdataloader(dataset, self.task_type, clip_len, width, height)
data_loader = DataLoaderWrapper(data_loader, self.inferencer)
quantization_dataset = nncf.Dataset(data_loader, lambda data: data[0])

if self.model is None:
raise RuntimeError("optimize failed, model is None")
Expand All @@ -291,47 +293,30 @@ def optimize(
with open(bin_path, "wb") as f:
f.write(self.model.get_data("openvino.bin"))

model_config = ADDict({"model_name": "openvino_model", "model": xml_path, "weights": bin_path})

model = load_model(model_config)

if get_nodes_by_type(model, ["FakeQuantize"]):
raise RuntimeError("Model is already optimized by POT")
ov_model = ov.Core().read_model(xml_path)
if check_if_quantized(ov_model):
raise RuntimeError("Model is already optimized by PTQ")

if optimization_parameters is not None:
optimization_parameters.update_progress(10, None)

engine_config = ADDict({"device": "CPU"})

stat_subset_size = self.hparams.pot_parameters.stat_subset_size
preset = self.hparams.pot_parameters.preset.name.lower()
preset = QuantizationPreset(self.hparams.pot_parameters.preset.name.lower())

algorithms = [
{
"name": "DefaultQuantization",
"params": {
"target_device": "ANY",
"preset": preset,
"stat_subset_size": min(stat_subset_size, len(data_loader)),
"shuffle_data": True,
},
}
]

engine = IEEngine(config=engine_config, data_loader=data_loader, metric=None)

pipeline = create_pipeline(algorithms, engine)

compressed_model = pipeline.run(model)

compress_model_weights(compressed_model)
compressed_model = nncf.quantize(
ov_model,
quantization_dataset,
subset_size=min(stat_subset_size, len(data_loader)),
preset=preset,
)

if optimization_parameters is not None:
optimization_parameters.update_progress(90, None)

with tempfile.TemporaryDirectory() as tempdir:
save_model(compressed_model, tempdir, model_name="model")
with open(os.path.join(tempdir, "model.xml"), "rb") as f:
xml_path = os.path.join(tempdir, "model.xml")
ov.serialize(compressed_model, xml_path)
with open(xml_path, "rb") as f:
output_model.set_data("openvino.xml", f.read())
with open(os.path.join(tempdir, "model.bin"), "rb") as f:
output_model.set_data("openvino.bin", f.read())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
from typing import Union

import numpy as np
from openvino.model_zoo.model_api.models import SegmentationModel
from openvino.model_zoo.model_api.models.types import DictValue, NumericalValue
from openvino.model_api.models import SegmentationModel
from openvino.model_api.models.types import DictValue, NumericalValue


class AnomalyBase(SegmentationModel):
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""PTQ config file."""
from nncf import IgnoredScope
from nncf.common.quantization.structs import QuantizationPreset
from nncf.quantization.advanced_parameters import AdvancedQuantizationParameters
from nncf.quantization.range_estimator import (
AggregatorType,
RangeEstimatorParameters,
StatisticsCollectorParameters,
StatisticsType,
)

advanced_parameters = AdvancedQuantizationParameters(
activations_range_estimator_params=RangeEstimatorParameters(
min=StatisticsCollectorParameters(
statistics_type=StatisticsType.QUANTILE, aggregator_type=AggregatorType.MIN, quantile_outlier_prob=1e-4
),
max=StatisticsCollectorParameters(
statistics_type=StatisticsType.QUANTILE, aggregator_type=AggregatorType.MAX, quantile_outlier_prob=1e-4
),
)
)

preset = QuantizationPreset.MIXED

ignored_scope = IgnoredScope(names=["/anomaly_map_generator/Mul", "/anomaly_map_generator/Sqrt"])

This file was deleted.

Loading