Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[PyOV][Linter] Change max line length to 120 (#32987)

Przemyslaw Wysocki77ccf552e10d
diff --git a/src/bindings/python/setup.cfg b/src/bindings/python/setup.cfg
index c932db80ccd..899047fee0d 100644
--- a/src/bindings/python/setup.cfg
+++ b/src/bindings/python/setup.cfg
@@ -59,7 +59,7 @@ deps = -rrequirements.txt
ignore=A001,A002,A004,CCE001,D100,D101,D102,D103,D104,D105,D107,D412,E402,F401,N803,RST301,TAE002,T001,W503,PT007,PT012
inline-quotes = double
filename = *.py
-max-line-length = 160
+max-line-length = 120
max-parameters-amount = 8
show_source = True
docstring-convention = google
diff --git a/src/bindings/python/src/openvino/_op_base.py b/src/bindings/python/src/openvino/_op_base.py
index d7fda51bff0..f2d8c1baacb 100644
--- a/src/bindings/python/src/openvino/_op_base.py
+++ b/src/bindings/python/src/openvino/_op_base.py
@@ -9,7 +9,14 @@ from openvino._pyopenvino import Node, Output
class Op(OpBase):
- def __init__(self, py_obj: "Op", inputs: Optional[Union[list[Union[Node, Output]], tuple[Union[Node, Output, list[Union[Node, Output]]]]]] = None) -> None:
+ def __init__(
+ self,
+ py_obj: "Op",
+ inputs: Optional[Union[
+ list[Union[Node, Output]],
+ tuple[Union[Node, Output, list[Union[Node, Output]]]]
+ ]] = None
+ ) -> None:
super().__init__(py_obj)
self._update_type_info()
if isinstance(inputs, tuple):
diff --git a/src/bindings/python/src/openvino/_ov_api.py b/src/bindings/python/src/openvino/_ov_api.py
index cf06667483c..f0f1568e12e 100644
--- a/src/bindings/python/src/openvino/_ov_api.py
+++ b/src/bindings/python/src/openvino/_ov_api.py
@@ -78,7 +78,12 @@ class Model(object, metaclass=ModelMeta):
def __enter__(self) -> "Model":
return self
- def __exit__(self, exc_type: type[BaseException], exc_value: BaseException, traceback: TracebackType) -> None: # noqa: F811
+ def __exit__(
+ self,
+ exc_type: type[BaseException],
+ exc_value: BaseException,
+ traceback: TracebackType, # noqa: F811
+ ) -> None:
del self.__model
self.__model = None
@@ -86,7 +91,15 @@ class Model(object, metaclass=ModelMeta):
return self.__model.__repr__()
def __dir__(self) -> list:
- wrapper_methods = ["__copy__", "__deepcopy__", "__dict__", "__enter__", "__exit__", "__getattr__", "__weakref__"]
+ wrapper_methods = [
+ "__copy__",
+ "__deepcopy__",
+ "__dict__",
+ "__enter__",
+ "__exit__",
+ "__getattr__",
+ "__weakref__",
+ ]
return dir(self.__model) + wrapper_methods
def evaluate(
@@ -142,13 +155,19 @@ class InferRequest(_InferRequestWrapper):
If set to `True` the data dispatcher tries to provide "zero-copy"
Tensors for every input in form of:
- * `numpy.ndarray` and all the types that are castable to it, e.g. `torch.Tensor`
+
+ * `numpy.ndarray` and all the types that are castable to it,
+ e.g. `torch.Tensor`
+
Data that is going to be copied:
- * `numpy.ndarray` which are not C contiguous and/or not writable (WRITEABLE flag is set to False)
+
+ * `numpy.ndarray` which are not C contiguous and/or not writable
+ (WRITEABLE flag is set to False)
* inputs which data types are mismatched from Infer Request's inputs
* inputs that should be in `BF16` data type
* scalar inputs (i.e. `np.float_`/`str`/`bytes`/`int`/`float`)
* lists of simple data types (i.e. `str`/`bytes`/`int`/`float`)
+
Keeps Tensor inputs "as-is".
Note: Use with extra care, shared data can be modified during runtime!
@@ -226,13 +245,19 @@ class InferRequest(_InferRequestWrapper):
If set to `True` the data dispatcher tries to provide "zero-copy"
Tensors for every input in form of:
- * `numpy.ndarray` and all the types that are castable to it, e.g. `torch.Tensor`
+
+ * `numpy.ndarray` and all the types that are castable to it,
+ e.g. `torch.Tensor`
+
Data that is going to be copied:
- * `numpy.ndarray` which are not C contiguous and/or not writable (WRITEABLE flag is set to False)
+
+ * `numpy.ndarray` which are not C contiguous and/or not writable
+ (WRITEABLE flag is set to False)
* inputs which data types are mismatched from Infer Request's inputs
* inputs that should be in `BF16` data type
* scalar inputs (i.e. `np.float_`/`str`/`bytes`/`int`/`float`)
* lists of simple data types (i.e. `str`/`bytes`/`int`/`float`)
+
Keeps Tensor inputs "as-is".
Note: Use with extra care, shared data can be modified during runtime!
@@ -395,13 +420,19 @@ class CompiledModel(CompiledModelBase):
If set to `True` the data dispatcher tries to provide "zero-copy"
Tensors for every input in form of:
- * `numpy.ndarray` and all the types that are castable to it, e.g. `torch.Tensor`
+
+ * `numpy.ndarray` and all the types that are castable to it,
+ e.g. `torch.Tensor`
+
Data that is going to be copied:
- * `numpy.ndarray` which are not C contiguous and/or not writable (WRITEABLE flag is set to False)
+
+ * `numpy.ndarray` which are not C contiguous and/or not writable
+ (WRITEABLE flag is set to False)
* inputs which data types are mismatched from Infer Request's inputs
* inputs that should be in `BF16` data type
* scalar inputs (i.e. `np.float_`/`str`/`bytes`/`int`/`float`)
* lists of simple data types (i.e. `str`/`bytes`/`int`/`float`)
+
Keeps Tensor inputs "as-is".
Note: Use with extra care, shared data can be modified during runtime!
@@ -514,13 +545,19 @@ class AsyncInferQueue(AsyncInferQueueBase):
If set to `True` the data dispatcher tries to provide "zero-copy"
Tensors for every input in form of:
- * `numpy.ndarray` and all the types that are castable to it, e.g. `torch.Tensor`
+
+ * `numpy.ndarray` and all the types that are castable to it,
+ e.g. `torch.Tensor`
+
Data that is going to be copied:
- * `numpy.ndarray` which are not C contiguous and/or not writable (WRITEABLE flag is set to False)
+
+ * `numpy.ndarray` which are not C contiguous and/or not writable
+ (WRITEABLE flag is set to False)
* inputs which data types are mismatched from Infer Request's inputs
* inputs that should be in `BF16` data type
* scalar inputs (i.e. `np.float_`/`str`/`bytes`/`int`/`float`)
* lists of simple data types (i.e. `str`/`bytes`/`int`/`float`)
+
Keeps Tensor inputs "as-is".
Note: Use with extra care, shared data can be modified during runtime!
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
index 417bac5db83..0c604a7bd68 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py
@@ -384,7 +384,10 @@ class TorchFXPythonDecoder (BaseFXDecoder):
return self._raw_outputs()[index]
def _raw_inputs(self):
- return [self._nodes[x] if not isinstance(x, InlinedInput) and x < len(self._nodes) else x.data for x in self._inputs]
+ return [
+ self._nodes[x] if not isinstance(x, InlinedInput) and x < len(self._nodes) else x.data
+ for x in self._inputs
+ ]
def _raw_input(self, index):
return self._raw_inputs()[index]
@@ -415,7 +418,9 @@ class TorchFXPythonDecoder (BaseFXDecoder):
return ov_const.outputs()
def input_is_none(self, index):
- if index >= len(self._inputs) or (isinstance(self._inputs[index], InlinedInput) and self._inputs[index].data is None):
+ if index >= len(self._inputs) or (
+ isinstance(self._inputs[index], InlinedInput) and self._inputs[index].data is None
+ ):
return True
else:
r_input = self._raw_input(index)
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/gptq.py b/src/bindings/python/src/openvino/frontend/pytorch/gptq.py
index 86d3f78f88c..cee37d22f66 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/gptq.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/gptq.py
@@ -144,12 +144,17 @@ def patch_model(model):
module.qweight = module.qweight.view(dtype=torch.uint8)
module.qzeros = module.qzeros.view(dtype=torch.uint8)
- # TODO: Redundant tensor copy? Try to remove module.qweight and module.qzeros after keeping modified values as submodules
+ # TODO: Redundant tensor copy? Try to remove module.qweight and module.qzeros
+ # after keeping modified values as submodules
module.add_module(
- "_openvino_u4_compression_submodule_qweights", KeepWeight(module.qweight))
- # Adding 17 to move zp+1 step from after unpacking to before to have correct decompression pattern. Can it overflow?
- module.add_module("_openvino_u4_compression_submodule_qzeros",
- KeepWeight(module.qzeros + torch.tensor(17, dtype=torch.uint8)))
+ "_openvino_u4_compression_submodule_qweights", KeepWeight(module.qweight)
+ )
+ # Adding 17 to move zp+1 step from after unpacking to before
+ # to have correct decompression pattern. Can it overflow?
+ module.add_module(
+ "_openvino_u4_compression_submodule_qzeros",
+ KeepWeight(module.qzeros + torch.tensor(17, dtype=torch.uint8)),
+ )
module.scales = module.scales.view(-1, 1, module.width)
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/compile.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/compile.py
index 27cbd8076cb..ef9c9de59d6 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/compile.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/compile.py
@@ -15,7 +15,12 @@ from torch.fx import GraphModule
from openvino.frontend import FrontEndManager
from openvino.frontend.pytorch.fx_decoder import TorchFXPythonDecoder
from openvino import Core, Type, PartialShape, serialize
-from openvino.frontend.pytorch.torchdynamo.backend_utils import _get_cache_dir, _get_device, _get_config, _is_cache_dir_in_config
+from openvino.frontend.pytorch.torchdynamo.backend_utils import (
+ _get_cache_dir,
+ _get_device,
+ _get_config,
+ _is_cache_dir_in_config,
+)
logger = logging.getLogger(__name__)
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py
index c3d5b46dd37..c32470dfac3 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py
@@ -29,12 +29,24 @@ def convolution_backward(
# Compute the gradient of the input tensor
grad_input = torch.nn.functional.conv_transpose2d(
- grad_output, weight, stride=stride, padding=padding, dilation=dilation, groups=groups, output_padding=output_padding
+ grad_output,
+ weight,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ groups=groups,
+ output_padding=output_padding,
)
# Compute the gradient of the weight tensor
grad_weight = torch.nn.functional.conv_transpose2d(
- inp, weight.transpose(0, 1), stride=stride, padding=padding, dilation=dilation, groups=groups, output_padding=output_padding
+ inp,
+ weight.transpose(0, 1),
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ groups=groups,
+ output_padding=output_padding,
)
# Compute the gradient of the bias tensor
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/execute.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/execute.py
index 8a523f859a1..ebc8c407acc 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/execute.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/execute.py
@@ -52,11 +52,16 @@ def execute(
options: Optional[Any] = None,
):
if executor == "openvino":
- return openvino_execute_partitioned(gm, *args, executor_parameters=executor_parameters, options=options)
+ return openvino_execute_partitioned(
+ gm, *args, executor_parameters=executor_parameters, options=options
+ )
elif executor == "strictly_openvino":
return openvino_execute(gm, *args, executor_parameters=executor_parameters)
- msg = "Received unexpected value for 'executor': {0}. Allowed values are: openvino, strictly_openvino.".format(executor)
+ msg = (
+ "Received unexpected value for 'executor': {0}. "
+ "Allowed values are: openvino, strictly_openvino."
+ ).format(executor)
raise ValueError(msg)
@@ -132,10 +137,18 @@ class OpenVINOGraphModule(torch.nn.Module):
return self.gm(*args)
try:
- result = openvino_execute(self.gm, *args, executor_parameters=self.executor_parameters, partition_id=self.partition_id, options=self.options)
+ result = openvino_execute(
+ self.gm,
+ *args,
+ executor_parameters=self.executor_parameters,
+ partition_id=self.partition_id,
+ options=self.options,
+ )
logger.debug("OpenVINO graph execution successful")
except Exception as e:
- logger.debug(f"OpenVINO execution failed with {e}. Falling back to native PyTorch execution.")
+ logger.debug(
+ f"OpenVINO execution failed with {e}. Falling back to native PyTorch execution."
+ )
self.perm_fallback = True
return self.gm(*args)
@@ -177,13 +190,31 @@ def openvino_execute_partitioned(gm: GraphModule, *args, executor_parameters=Non
if (not _get_aot_autograd(options)):
for idx, input_data in enumerate(args):
if isinstance(input_data, torch.Tensor):
- signature = signature + "_" + str(idx) + ":" + str(input_data.type())[6:] + ":" + str(input_data.size())[11:-1].replace(" ", "")
+ signature = (
+ signature
+ + "_"
+ + str(idx)
+ + ":"
+ + str(input_data.type())[6:]
+ + ":"
+ + str(input_data.size())[11:-1].replace(" ", "")
+ )
else:
- signature = signature + "_" + str(idx) + ":" + type(input_data).__name__ + ":val(" + str(input_data) + ")"
+ signature = (
+ signature
+ + "_"
+ + str(idx)
+ + ":"
+ + type(input_data).__name__
+ + ":val("
+ + str(input_data)
+ + ")"
+ )
if signature not in partitioned_modules:
- partitioned_modules[signature] = partition_graph(gm, use_python_fusion_cache=use_python_fusion_cache,
- model_hash_str=model_hash_str, options=options)
+ partitioned_modules[signature] = partition_graph(
+ gm, use_python_fusion_cache=use_python_fusion_cache, model_hash_str=model_hash_str, options=options
+ )
return partitioned_modules[signature](*args)
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py
index 1464a94598d..5d84c332ae7 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/partition.py
@@ -95,7 +95,10 @@ class Partitioner:
unsqueeze_1_node = PatternNode
unsqueeze_1_node.op_types["call_function:aten.unsqueeze.default"] = [const_1_node]
bitwise_right_shift_node = PatternNode
- bitwise_right_shift_node.op_types["call_function:aten.bitwise_right_shift.Tensor"] = [expand_node, unsqueeze_1_node]
+ bitwise_right_shift_node.op_types["call_function:aten.bitwise_right_shift.Tensor"] = [
+ expand_node,
+ unsqueeze_1_node,
+ ]
to_copy_node = PatternNode
to_copy_node.op_types["call_function:aten._to_copy.default"] = [bitwise_right_shift_node]
add_or_to_copy_node = PatternNode
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
index fb615da9243..4d51b0217b8 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
@@ -419,7 +419,8 @@ class TorchScriptPythonDecoder(Decoder):
self.graph_element, self.pt_module)
assert pt_value is not None, "Couldn't retrieve value from prim::GetAttr"
if isinstance(pt_value, torch.ScriptObject):
- # We assume this is __torch__.torch.classes.quantized.Conv2dPackedParamsBase or __torch__.torch.classes.quantized.LinearPackedParamsBase
+ # We assume this is __torch__.torch.classes.quantized.Conv2dPackedParamsBase
+ # or __torch__.torch.classes.quantized.LinearPackedParamsBase
# TODO: but can be anything. Figure a better way to distinguish
weight, bias = pt_value.unpack()
w_name = name + ".weight"
@@ -550,13 +551,24 @@ class TorchScriptPythonDecoder(Decoder):
return False
def may_produce_alias(self, in_index: int, out_index: int) -> bool:
- if self.get_op_type() in ["aten::conv1d", "aten::conv2d", "aten::conv3d", "aten::_convolution", "aten::matmul", "aten::clone"]:
- # AliasDB::may_contain_alias sometimes return True for tensors produced by convolution or matmul, we have to workaround that
+ if self.get_op_type() in [
+ "aten::conv1d",
+ "aten::conv2d",
+ "aten::conv3d",
+ "aten::_convolution",
+ "aten::matmul",
+ "aten::clone",
+ ]:
+ # AliasDB::may_contain_alias sometimes return True for tensors produced
+ # by convolution or matmul, we have to workaround that
return False
try:
- return self.alias_db.may_contain_alias(self._raw_input(in_index), self._raw_output(out_index))
+ return self.alias_db.may_contain_alias(
+ self._raw_input(in_index), self._raw_output(out_index)
+ )
except Exception as e:
- # Sometimes pytorch fails to get result with IndexError exception while these indexes exist in node
+ # Sometimes pytorch fails to get result with IndexError exception
+ # while these indexes exist in node
logging.debug("Failed to get alias information", exc_info=e)
return False
@@ -574,9 +586,12 @@ class TorchScriptPythonDecoder(Decoder):
def get_rt_info(self):
rt_info = {}
- if self.config is not None and "quantization_config" in self.config and "sym" in self.config["quantization_config"]:
- rt_info["symmetric_quantization"] = OVAny(
- self.config["quantization_config"]["sym"])
+ if (
+ self.config is not None
+ and "quantization_config" in self.config
+ and "sym" in self.config["quantization_config"]
+ ):
+ rt_info["symmetric_quantization"] = OVAny(self.config["quantization_config"]["sym"])
return rt_info
@staticmethod
diff --git a/src/bindings/python/src/openvino/opset10/ops.py b/src/bindings/python/src/openvino/opset10/ops.py
index ec4e5f012cf..263463ca3b3 100644
--- a/src/bindings/python/src/openvino/opset10/ops.py
+++ b/src/bindings/python/src/openvino/opset10/ops.py
@@ -75,7 +75,11 @@ def interpolate(
attrs["pads_begin"] = [] if pads_begin is None else pads_begin
attrs["pads_end"] = [] if pads_end is None else pads_end
- inputs = as_nodes(image, output_shape, scales, name=name) if axes is None else as_nodes(image, output_shape, scales, axes, name=name)
+ inputs = (
+ as_nodes(image, output_shape, scales, name=name)
+ if axes is None
+ else as_nodes(image, output_shape, scales, axes, name=name)
+ )
# This is an update of the operator version, so even though this is opset 10,
# the operator is taken from opset 4.
diff --git a/src/bindings/python/src/openvino/opset11/ops.py b/src/bindings/python/src/openvino/opset11/ops.py
index e8038200559..e8c30bd6bf4 100644
--- a/src/bindings/python/src/openvino/opset11/ops.py
+++ b/src/bindings/python/src/openvino/opset11/ops.py
@@ -72,7 +72,11 @@ def interpolate(
attrs["pads_begin"] = [] if pads_begin is None else pads_begin
attrs["pads_end"] = [] if pads_end is None else pads_end
- inputs = as_nodes(image, scales_or_sizes, name=name) if axes is None else as_nodes(image, scales_or_sizes, axes, name=name)
+ inputs = (
+ as_nodes(image, scales_or_sizes, name=name)
+ if axes is None
+ else as_nodes(image, scales_or_sizes, axes, name=name)
+ )
return _get_node_factory_opset11().create("Interpolate", inputs, attrs)
diff --git a/src/bindings/python/src/openvino/opset13/ops.py b/src/bindings/python/src/openvino/opset13/ops.py
index 155726ec288..8faddc18a2e 100644
--- a/src/bindings/python/src/openvino/opset13/ops.py
+++ b/src/bindings/python/src/openvino/opset13/ops.py
@@ -41,7 +41,8 @@ def bitwise_and(
:param left_node: Tensor of integer or boolean datatype providing data.
:param right_node: Tensor of integer or boolean datatype providing data.
- :param auto_broadcast: The type of broadcasting specifies rules used for auto-broadcasting of input tensors. Defaults to “NUMPY”.
+ :param auto_broadcast: The type of broadcasting specifies rules used for
+ auto-broadcasting of input tensors. Defaults to "NUMPY".
:param name: The optional new name for output node.
:return: The node performing bitwise AND operation on input nodes corresponding elements.
"""
@@ -84,7 +85,8 @@ def bitwise_or(
:param left_node: Tensor of integer or boolean datatype providing data.
:param right_node: Tensor of integer or boolean datatype providing data.
- :param auto_broadcast: The type of broadcasting specifies rules used for auto-broadcasting of input tensors. Defaults to “NUMPY”.
+ :param auto_broadcast: The type of broadcasting specifies rules used for
+ auto-broadcasting of input tensors. Defaults to "NUMPY".
:param name: The optional new name for output node.
:return: The node performing bitwise OR operation on input nodes corresponding elements.
"""
@@ -108,7 +110,8 @@ def bitwise_xor(
:param left_node: Tensor of integer or boolean datatype providing data.
:param right_node: Tensor of integer or boolean datatype providing data.
- :param auto_broadcast: The type of broadcasting specifies rules used for auto-broadcasting of input tensors. Defaults to “NUMPY”.
+ :param auto_broadcast: The type of broadcasting specifies rules used for
+ auto-broadcasting of input tensors. Defaults to "NUMPY".
:param name: The optional new name for output node.
:return: The node performing bitwise XOR operation on input nodes corresponding elements.
"""
@@ -209,20 +212,26 @@ def nms_rotated(
) -> Node:
"""Return a node which performs NMSRotated.
- :param boxes: Tensor with box coordinates of floating point type and shape [num_batches, num_boxes, 5],
- where the last dimension is defined as [x_ctr, y_ctr, width, height, angle_radians].
- :param scores: Tensor with box scores of floating point type and shape [num_batches, num_classes, num_boxes].
- :param max_output_boxes_per_class: Tensor (scalar or 1D) of integer type, specifying maximum number of boxes
- to be selected per class.
- :param iou_threshold: Tensor (scalar or 1D) of floating point type, specifying intersection over union threshold
- :param score_threshold: Tensor (scalar or 1D) of floating point type, specifying minimum score to consider box for the processing.
- :param sort_result_descending: Flag that specifies whenever it is necessary to sort selected
- boxes across batches or not.
+ :param boxes: Tensor with box coordinates of floating point type and shape
+ [num_batches, num_boxes, 5], where the last dimension is defined as
+ [x_ctr, y_ctr, width, height, angle_radians].
+ :param scores: Tensor with box scores of floating point type and shape
+ [num_batches, num_classes, num_boxes].
+ :param max_output_boxes_per_class: Tensor (scalar or 1D) of integer type, specifying
+ maximum number of boxes to be selected per class.
+ :param iou_threshold: Tensor (scalar or 1D) of floating point type, specifying
+ intersection over union threshold
+ :param score_threshold: Tensor (scalar or 1D) of floating point type, specifying
+ minimum score to consider box for the processing.
+ :param sort_result_descending: Flag that specifies whenever it is necessary to sort
+ selected boxes across batches or not.
:param output_type: Output element type.
:param clockwise: Flag that specifies direction of the box rotation.
:return: The new node which performs NMSRotated
"""
- inputs = as_nodes(boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, name=name)
+ inputs = as_nodes(
+ boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, name=name
+ )
attributes = {
"sort_result_descending": sort_result_descending,
@@ -261,7 +270,9 @@ def scaled_dot_product_attention(
if attention_mask is not None:
inputs.append(as_node(attention_mask, name=name))
elif scale is not None:
- inputs.append(as_node(convert_like(constant(np.array(0, np.int32)), inputs[0]), name=name))
+ inputs.append(
+ as_node(convert_like(constant(np.array(0, np.int32)), inputs[0]), name=name)
+ )
if scale is not None:
inputs.append(as_node(scale, name=name))
@@ -271,7 +282,12 @@ def scaled_dot_product_attention(
return _get_node_factory_opset13().create("ScaledDotProductAttention", inputs, attributes)
-@overloading(Union[NumericData, np.number, bool, np.bool_, list], Union[NumericType, Type], Optional[str], bool) # type: ignore
+@overloading(
+ Union[NumericData, np.number, bool, np.bool_, list],
+ Union[NumericType, Type],
+ Optional[str],
+ bool,
+) # type: ignore
@nameable_op
def constant(
value: Union[NumericData, np.number, bool, np.bool_, list],
@@ -303,7 +319,10 @@ def constant(
def display_shared_memory_warning(warning_message: str) -> None:
if shared_memory:
- log.warning(f"{warning_message}. Memory sharing is disabled by default. Set shared_memory=False to hide this warning.")
+ log.warning(
+ f"{warning_message}. Memory sharing is disabled by default. "
+ "Set shared_memory=False to hide this warning."
+ )
if isinstance(value, np.ndarray):
_value, _shared_memory = value, shared_memory
diff --git a/src/bindings/python/src/openvino/opset14/ops.py b/src/bindings/python/src/openvino/opset14/ops.py
index a2f3d5cec8b..0a823e8e79b 100644
--- a/src/bindings/python/src/openvino/opset14/ops.py
+++ b/src/bindings/python/src/openvino/opset14/ops.py
@@ -31,9 +31,12 @@ def convert_promote_types(
:param left_node: input node with type to be promoted to common one.
:param right_node: input node with type to be promoted to common one.
- :param promote_unsafe: Bool attribute whether to allow promotions that might result in bit-widening, precision loss and undefined behaviors.
- :param pytorch_scalar_promotion: Bool attribute whether to promote scalar input to type provided by non-scalar input when number format is matching.
- :param u64_integer_promotion_target: Element type attribute to select promotion result when inputs are u64 and signed integer.
+ :param promote_unsafe: Bool attribute whether to allow promotions that might result
+ in bit-widening, precision loss and undefined behaviors.
+ :param pytorch_scalar_promotion: Bool attribute whether to promote scalar input to type
+ provided by non-scalar input when number format is matching.
+ :param u64_integer_promotion_target: Element type attribute to select promotion result
+ when inputs are u64 and signed integer.
:param name: Optional name for the new output node.
:return: The new node performing ConvertPromoteTypes operation.
diff --git a/src/bindings/python/src/openvino/opset15/ops.py b/src/bindings/python/src/openvino/opset15/ops.py
index d6cc8b2d251..106b2a7874c 100644
--- a/src/bindings/python/src/openvino/opset15/ops.py
+++ b/src/bindings/python/src/openvino/opset15/ops.py
@@ -119,7 +119,9 @@ def embedding_bag_offsets(
if per_sample_weights is not None:
inputs.append(per_sample_weights)
- return _get_node_factory_opset15().create("EmbeddingBagOffsets", as_nodes(*inputs, name=name), {"reduction": reduction})
+ return _get_node_factory_opset15().create(
+ "EmbeddingBagOffsets", as_nodes(*inputs, name=name), {"reduction": reduction}
+ )
@nameable_op
@@ -143,7 +145,9 @@ def embedding_bag_packed(
if per_sample_weights is not None:
inputs.append(per_sample_weights)
- return _get_node_factory_opset15().create("EmbeddingBagPacked", as_nodes(*inputs, name=name), {"reduction": reduction})
+ return _get_node_factory_opset15().create(
+ "EmbeddingBagPacked", as_nodes(*inputs, name=name), {"reduction": reduction}
+ )
@nameable_op
diff --git a/src/bindings/python/src/openvino/opset16/ops.py b/src/bindings/python/src/openvino/opset16/ops.py
index 07940788863..587994d778d 100644
--- a/src/bindings/python/src/openvino/opset16/ops.py
+++ b/src/bindings/python/src/openvino/opset16/ops.py
@@ -80,8 +80,10 @@ def segment_max(
:param data: ND tensor of type T, the numerical data on which SegmentMax operation will be performed.
:param segment_ids: 1D Tensor of sorted non-negative numbers, representing the segments.
- :param num_segments: An optional scalar value representing the segments count. If not provided, it is inferred from segment_ids.
- :param fill_mode: Responsible for the value assigned to segments which are empty. Can be "ZERO" or "LOWEST".
+ :param num_segments: An optional scalar value representing the segments count.
+ If not provided, it is inferred from segment_ids.
+ :param fill_mode: Responsible for the value assigned to segments which are empty.
+ Can be "ZERO" or "LOWEST".
:param name: Optional name for the node.
:return: The new node performing SegmentMax operation.
diff --git a/src/bindings/python/src/openvino/opset2/ops.py b/src/bindings/python/src/openvino/opset2/ops.py
index 4dd6d686297..216814f7d0f 100644
--- a/src/bindings/python/src/openvino/opset2/ops.py
+++ b/src/bindings/python/src/openvino/opset2/ops.py
@@ -153,7 +153,9 @@ def roi_pooling(
if spatial_scale is None:
raise AttributeError("The following arguments must be defined: `spatial_scale`!")
- def _deprecated_output_size_arg(output_roi: Optional[TensorShape], output_size: Optional[TensorShape]) -> Optional[TensorShape]:
+ def _deprecated_output_size_arg(
+ output_roi: Optional[TensorShape], output_size: Optional[TensorShape]
+ ) -> Optional[TensorShape]:
if output_size is not None:
warnings.warn(
"`output_size` is deprecated and will be removed in future. "
diff --git a/src/bindings/python/src/openvino/opset6/ops.py b/src/bindings/python/src/openvino/opset6/ops.py
index f83230b878a..abd623447fd 100644
--- a/src/bindings/python/src/openvino/opset6/ops.py
+++ b/src/bindings/python/src/openvino/opset6/ops.py
@@ -152,12 +152,19 @@ def read_value(init_value: Union[Node, Output, int, float, np.ndarray],
return _read_value(new_value=as_node(init_value, name=name), variable=var_from_info)
-@overloading(str, Optional[Union[type, np.dtype, Type, str]], Optional[Union[TensorShape, Shape, PartialShape]], Optional[str]) # type: ignore
+@overloading(
+ str,
+ Optional[Union[type, np.dtype, Type, str]],
+ Optional[Union[TensorShape, Shape, PartialShape]],
+ Optional[str],
+) # type: ignore
@nameable_op
-def read_value(variable_id: str, # noqa: F811
- variable_type: Optional[Union[type, np.dtype, Type, str]] = None,
- variable_shape: Optional[Union[TensorShape, Shape, PartialShape]] = None,
- name: Optional[str] = None) -> Node:
+def read_value( # noqa: F811
+ variable_id: str,
+ variable_type: Optional[Union[type, np.dtype, Type, str]] = None,
+ variable_shape: Optional[Union[TensorShape, Shape, PartialShape]] = None,
+ name: Optional[str] = None,
+) -> Node:
"""Return a node which produces the Assign operation.
:param variable_id: Id of a variable to be read.
diff --git a/src/bindings/python/src/openvino/opset9/ops.py b/src/bindings/python/src/openvino/opset9/ops.py
index 249ca9ebc09..4e93b552bf6 100644
--- a/src/bindings/python/src/openvino/opset9/ops.py
+++ b/src/bindings/python/src/openvino/opset9/ops.py
@@ -78,12 +78,20 @@ def non_max_suppression(
:param output_type: Output element type.
:return: The new node which performs NonMaxSuppression
"""
- max_output_boxes_per_class = max_output_boxes_per_class if max_output_boxes_per_class is not None else make_constant_node(0, np.int64)
+ max_output_boxes_per_class = (
+ max_output_boxes_per_class
+ if max_output_boxes_per_class is not None
+ else make_constant_node(0, np.int64)
+ )
iou_threshold = iou_threshold if iou_threshold is not None else make_constant_node(0, np.float32)
- score_threshold = score_threshold if score_threshold is not None else make_constant_node(0, np.float32)
+ score_threshold = (
+ score_threshold if score_threshold is not None else make_constant_node(0, np.float32)
+ )
soft_nms_sigma = soft_nms_sigma if soft_nms_sigma is not None else make_constant_node(0, np.float32)
- inputs = as_nodes(boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, soft_nms_sigma, name=name)
+ inputs = as_nodes(
+ boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, soft_nms_sigma, name=name
+ )
attributes = {
"box_encoding": box_encoding,
@@ -286,9 +294,12 @@ def generate_proposals(
:param nms_threshold: Specifies threshold to be used in the NMS stage.
:param pre_nms_count: Specifies number of top-n proposals before NMS.
:param post_nms_count: Specifies number of top-n proposals after NMS.
- :param normalized: Specifies whether proposal bboxes are normalized or not. Optional attribute, default value is `True`.
- :param nms_eta: Specifies eta parameter for adaptive NMS., must be in range `[0.0, 1.0]`. Optional attribute, default value is `1.0`.
- :param roi_num_type: Specifies the element type of the third output `rpnroisnum`. Optional attribute, range of values: `i64` (default) or `i32`.
+ :param normalized: Specifies whether proposal bboxes are normalized or not.
+ Optional attribute, default value is `True`.
+ :param nms_eta: Specifies eta parameter for adaptive NMS., must be in range `[0.0, 1.0]`.
+ Optional attribute, default value is `1.0`.
+ :param roi_num_type: Specifies the element type of the third output `rpnroisnum`.
+ Optional attribute, range of values: `i64` (default) or `i32`.
:param name: The optional name for the output node.
:return: New node performing GenerateProposals operation.
"""
diff --git a/src/bindings/python/src/openvino/package_utils.py b/src/bindings/python/src/openvino/package_utils.py
index dbb3bfcfd19..a959cb4e956 100644
--- a/src/bindings/python/src/openvino/package_utils.py
+++ b/src/bindings/python/src/openvino/package_utils.py
@@ -24,9 +24,13 @@ def _add_openvino_libs_to_search_path() -> None:
if os.path.isdir(os.path.join(os.path.dirname(__file__), "libs")):
# looking for the libs in the pip installation path.
openvino_libs.append(os.path.join(os.path.dirname(__file__), "libs"))
- elif os.path.isdir(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, "Library", "bin")):
+ elif os.path.isdir(
+ os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, "Library", "bin")
+ ):
# looking for the libs in the conda installation path
- openvino_libs.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, "Library", "bin"))
+ openvino_libs.append(
+ os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, "Library", "bin")
+ )
else:
# setupvars.bat script set all libs paths to OPENVINO_LIB_PATHS environment variable.
openvino_libs_installer = os.getenv("OPENVINO_LIB_PATHS")
@@ -58,8 +62,12 @@ def get_cmake_path() -> str:
return ""
-def deprecated(name: Any = None, version: str = "", message: str = "", stacklevel: int = 2) -> Callable[..., Any]:
- """Prints deprecation warning "{function_name} is deprecated and will be removed in version {version}. {message}" and runs the function.
+def deprecated(
+ name: Any = None, version: str = "", message: str = "", stacklevel: int = 2
+) -> Callable[..., Any]:
+ """Prints deprecation warning and runs the function.
+
+ "{function_name} is deprecated and will be removed in version {version}. {message}"
:param version: The version in which the code will be removed.
:param message: A message explaining why the function is deprecated and/or what to use instead.
@@ -97,7 +105,9 @@ def classproperty(func: Any) -> _ClassPropertyDescriptor:
return _ClassPropertyDescriptor(func) # type: ignore
-def deprecatedclassproperty(name: Any = None, version: str = "", message: str = "", stacklevel: int = 2) -> Callable[[Any], _ClassPropertyDescriptor]:
+def deprecatedclassproperty(
+ name: Any = None, version: str = "", message: str = "", stacklevel: int = 2
+) -> Callable[[Any], _ClassPropertyDescriptor]:
def decorator(wrapped: Any) -> _ClassPropertyDescriptor:
func = classproperty(wrapped)
@@ -130,7 +140,8 @@ class LazyLoader:
# Import the module and update sys.modules with the loaded module
self._module = importlib.import_module(self.module_name)
# Update the LazyLoader instance's __dict__ with the module's __dict__
- # This ensures that subsequent attribute accesses use the module's attributes directly (by __getattribute__() )
+ # This ensures that subsequent attribute accesses use the module's
+ # attributes directly (by __getattribute__() )
self.__dict__.update(self._module.__dict__)
def __getattr__(self, item: str) -> Any:
diff --git a/src/bindings/python/src/openvino/preprocess/torchvision/torchvision_preprocessing.py b/src/bindings/python/src/openvino/preprocess/torchvision/torchvision_preprocessing.py
index f452a817420..eb2eef0ae0e 100644
--- a/src/bindings/python/src/openvino/preprocess/torchvision/torchvision_preprocessing.py
+++ b/src/bindings/python/src/openvino/preprocess/torchvision/torchvision_preprocessing.py
@@ -270,8 +270,16 @@ class _(TransformConverterBase):
top_right.append(min(bottom_left[0] + target_size[0], source_size[0] - 1))
top_right.append(min(bottom_left[1] + target_size[1], source_size[1] - 1))
- bottom_left = [0] * len(input_shape[:-2]) + bottom_left if meta["layout"] == Layout("NCHW") else [0] + bottom_left + [0] # noqa ECE001
- top_right = input_shape[:-2] + top_right if meta["layout"] == Layout("NCHW") else input_shape[:1] + top_right + input_shape[-1:]
+ is_nchw = meta["layout"] == Layout("NCHW")
+ if is_nchw:
+ bottom_left = [0] * len(input_shape[:-2]) + bottom_left
+ else:
+ bottom_left = [0] + bottom_left + [0]
+
+ if is_nchw:
+ top_right = input_shape[:-2] + top_right
+ else:
+ top_right = input_shape[:1] + top_right + input_shape[-1:]
ppp.input(input_idx).preprocess().crop(bottom_left, top_right)
meta["image_dimensions"] = (target_size[-2], target_size[-1])
@@ -313,15 +321,22 @@ class _(TransformConverterBase):
meta["image_dimensions"] = (target_h, target_w)
-def _from_torchvision(model: Model, transform: Callable, input_example: Any, input_name: Union[str, None] = None) -> Model:
+def _from_torchvision(
+ model: Model, transform: Callable, input_example: Any, input_name: Union[str, None] = None
+) -> Model:
if input_name is not None:
- input_idx = next((i for i, p in enumerate(model.get_parameters()) if p.get_friendly_name() == input_name), None)
+ input_idx = next(
+ (i for i, p in enumerate(model.get_parameters()) if p.get_friendly_name() == input_name), None
+ )
else:
if len(model.get_parameters()) == 1:
input_idx = 0
else:
- raise ValueError("Model contains multiple inputs. Please specify the name of the input to which prepocessing is added.")
+ raise ValueError(
+ "Model contains multiple inputs. Please specify the name of the input "
+ "to which prepocessing is added."
+ )
if input_idx is None:
raise ValueError(f"Input with name {input_name} is not found")
diff --git a/src/bindings/python/src/openvino/utils/data_helpers/data_dispatcher.py b/src/bindings/python/src/openvino/utils/data_helpers/data_dispatcher.py
index fe2610f0a37..400cc3b97d7 100644
--- a/src/bindings/python/src/openvino/utils/data_helpers/data_dispatcher.py
+++ b/src/bindings/python/src/openvino/utils/data_helpers/data_dispatcher.py
@@ -148,10 +148,19 @@ def to_c_style(value: Any, is_shared: bool = False) -> Any:
if not isinstance(value, np.ndarray):
if hasattr(value, "__array__"):
if np.lib.NumpyVersion(np.__version__) >= "2.0.0":
- # https://numpy.org/devdocs/numpy_2_0_migration_guide.html#adapting-to-changes-in-the-copy-keyword
- return to_c_style(np.asarray(value), is_shared) if is_shared else np.asarray(value, copy=True) # type: ignore
+ # https://numpy.org/devdocs/numpy_2_0_migration_guide.html
+ # #adapting-to-changes-in-the-copy-keyword
+ return (
+ to_c_style(np.asarray(value), is_shared)
+ if is_shared
+ else np.asarray(value, copy=True) # type: ignore
+ )
else:
- return to_c_style(np.array(value, copy=False), is_shared) if is_shared else np.array(value, copy=True)
+ return (
+ to_c_style(np.array(value, copy=False), is_shared)
+ if is_shared
+ else np.array(value, copy=True)
+ )
return value
return value if value.flags["C_CONTIGUOUS"] else np.ascontiguousarray(value)
@@ -167,10 +176,19 @@ def normalize_arrays(
# Check the special case of the array-interface
if hasattr(inputs, "__array__"):
if np.lib.NumpyVersion(np.__version__) >= "2.0.0":
- # https://numpy.org/devdocs/numpy_2_0_migration_guide.html#adapting-to-changes-in-the-copy-keyword
- return to_c_style(np.asarray(inputs), is_shared) if is_shared else np.asarray(inputs, copy=True) # type: ignore
+ # https://numpy.org/devdocs/numpy_2_0_migration_guide.html
+ # #adapting-to-changes-in-the-copy-keyword
+ return (
+ to_c_style(np.asarray(inputs), is_shared)
+ if is_shared
+ else np.asarray(inputs, copy=True) # type: ignore
+ )
else:
- return to_c_style(np.array(inputs, copy=False), is_shared) if is_shared else np.array(inputs, copy=True)
+ return (
+ to_c_style(np.array(inputs, copy=False), is_shared)
+ if is_shared
+ else np.array(inputs, copy=True)
+ )
# Error should be raised if type does not match any dispatchers
raise TypeError(f"Incompatible inputs of type: {type(inputs)}")
@@ -249,7 +267,9 @@ def _(
) -> dict:
# If list is passed to single input model and consists only of simple types
# i.e. str/bytes/float/int, wrap around it and pass into the dispatcher.
- request._inputs_data = normalize_arrays([inputs] if request._is_single_input() and is_list_simple_type(inputs) else inputs, is_shared=True)
+ request._inputs_data = normalize_arrays(
+ [inputs] if request._is_single_input() and is_list_simple_type(inputs) else inputs, is_shared=True
+ )
return {k: value_to_tensor(v, request=request, is_shared=True, key=k) for k, v in request._inputs_data.items()}
@@ -409,7 +429,12 @@ def _(
) -> dict:
# If list is passed to single input model and consists only of simple types
# i.e. str/bytes/float/int, wrap around it and pass into the dispatcher.
- return update_inputs(normalize_arrays([inputs] if request._is_single_input() and is_list_simple_type(inputs) else inputs, is_shared=False), request)
+ return update_inputs(
+ normalize_arrays(
+ [inputs] if request._is_single_input() and is_list_simple_type(inputs) else inputs, is_shared=False
+ ),
+ request,
+ )
@create_copied.register(np.ndarray)
diff --git a/src/bindings/python/src/openvino/utils/postponed_constant.py b/src/bindings/python/src/openvino/utils/postponed_constant.py
index cb58ee5b840..e4a5ec6cffd 100644
--- a/src/bindings/python/src/openvino/utils/postponed_constant.py
+++ b/src/bindings/python/src/openvino/utils/postponed_constant.py
@@ -9,24 +9,37 @@ from openvino import Op, Type, Shape, Tensor, PartialShape, TensorVector
class PostponedConstant(Op):
- """Postponed Constant is a way to materialize a big constant only when it is going to be serialized to IR and then immediately dispose."""
+ """Postponed Constant is a way to materialize a big constant.
+
+ This class materializes a big constant only when it is going to be serialized
+ to IR and then immediately disposes of it.
+ """
+
@overload
- def __init__(self, element_type: Type, shape: Shape, maker: Callable[[], Tensor], name: Optional[str] = None) -> None:
+ def __init__(
+ self, element_type: Type, shape: Shape, maker: Callable[[], Tensor], name: Optional[str] = None
+ ) -> None:
...
@overload
- def __init__(self, element_type: Type, shape: Shape, maker: Callable[[Tensor], None], name: Optional[str] = None) -> None:
+ def __init__(
+ self, element_type: Type, shape: Shape, maker: Callable[[Tensor], None], name: Optional[str] = None
+ ) -> None:
...
- def __init__(self, element_type: Type, shape: Shape, maker: Callable, name: Optional[str] = None) -> None:
+ def __init__(
+ self, element_type: Type, shape: Shape, maker: Callable, name: Optional[str] = None
+ ) -> None:
"""Creates a PostponedConstant.
:param element_type: Element type of the constant.
:type element_type: openvino.Type
:param shape: Shape of the constant.
:type shape: openvino.Shape
- :param maker: A callable that returns a Tensor or modifies the provided Tensor to represent the constant.
- Note: It's recommended to use a callable without arguments (returns Tensor) to avoid unnecessary tensor data copies.
+ :param maker: A callable that returns a Tensor or modifies the provided Tensor to
+ represent the constant.
+ Note: It's recommended to use a callable without arguments (returns Tensor)
+ to avoid unnecessary tensor data copies.
:type maker: Union[Callable[[], Tensor], Callable[[Tensor], None]]
:param name: Optional name for the constant.
:type name: Optional[str]
@@ -48,13 +61,19 @@ class PostponedConstant(Op):
if name is not None:
self.friendly_name = name
- if callable(self.m_maker) and hasattr(self.m_maker.__call__, "__code__") and self.m_maker.__call__.__code__.co_argcount > 1:
+ if (
+ callable(self.m_maker)
+ and hasattr(self.m_maker.__call__, "__code__")
+ and self.m_maker.__call__.__code__.co_argcount > 1
+ ):
from openvino._pyopenvino.util import deprecation_warning
+
deprecation_warning(
"PostponedConstant.__init__ with Callable[[Tensor], None]",
"2026.0",
- "Please use PostponedConstant's 'maker' argument as Callable[[], Tensor] instead of Callable[[Tensor], None].",
- 3
+ "Please use PostponedConstant's 'maker' argument as Callable[[], Tensor] "
+ "instead of Callable[[Tensor], None].",
+ 3,
)
self.constructor_validate_and_infer_types()
diff --git a/src/bindings/python/src/openvino/utils/types.py b/src/bindings/python/src/openvino/utils/types.py
index 034269dfe6a..b888bc02a54 100644
--- a/src/bindings/python/src/openvino/utils/types.py
+++ b/src/bindings/python/src/openvino/utils/types.py
@@ -145,7 +145,9 @@ def get_shape(data: NumericData) -> TensorShape:
return []
-def make_constant_node(value: NumericData, dtype: Union[NumericType, Type] = None, *, name: Optional[str] = None) -> Constant:
+def make_constant_node(
+ value: NumericData, dtype: Union[NumericType, Type] = None, *, name: Optional[str] = None
+) -> Constant:
"""Return an openvino Constant node with the specified value."""
ndarray = get_ndarray(value)
if dtype is not None:
diff --git a/src/bindings/python/tests/test_graph/test_basic.py b/src/bindings/python/tests/test_graph/test_basic.py
index eaeddb29138..723574d1c27 100644
--- a/src/bindings/python/tests/test_graph/test_basic.py
+++ b/src/bindings/python/tests/test_graph/test_basic.py
@@ -565,7 +565,9 @@ def test_sink_model_ctors():
sinks = model.get_sinks()
assert ["Assign", "Assign"] == [sink.get_type_name() for sink in sinks]
assert model.sinks[0].get_output_shape(0) == Shape([2, 2])
- assert op_types == ["Parameter", "Constant", "ReadValue", "Assign", "Constant", "ReadValue", "Add", "Assign", "Result"]
+ assert op_types == [
+ "Parameter", "Constant", "ReadValue", "Assign", "Constant", "ReadValue", "Add", "Assign", "Result"
+ ]
assert len(model.get_ops()) == 9
assert model.get_output_size() == 1
assert model.get_output_op(0).get_type_name() == "Result"
diff --git a/src/bindings/python/tests/test_graph/test_constant.py b/src/bindings/python/tests/test_graph/test_constant.py
index c36b527794f..a64146ea1c4 100644
--- a/src/bindings/python/tests/test_graph/test_constant.py
+++ b/src/bindings/python/tests/test_graph/test_constant.py
@@ -318,9 +318,11 @@ OPSETS = [ov.opset12, ov.opset13]
],
)
def test_float_to_f8e5m2_constant(ov_type, numpy_dtype, opset):
- data = np.array([4.75, 4.5, -5.25, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5,
- 0.6, 0.7, 0.8, 0.9, 1, -0.0, -0.1, -0.2, -0.3,
- -0.4, -0.5, -0.6, -0.7, -0.8, -0.9, -1.0, 0.0000152587890625, 448, 500, 512, 57344], dtype=numpy_dtype)
+ data = np.array([
+ 4.75, 4.5, -5.25, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5,
+ 0.6, 0.7, 0.8, 0.9, 1, -0.0, -0.1, -0.2, -0.3,
+ -0.4, -0.5, -0.6, -0.7, -0.8, -0.9, -1.0, 0.0000152587890625, 448, 500, 512, 57344
+ ], dtype=numpy_dtype)
compressed_const = opset.constant(data, dtype=ov.Type.f8e5m2, name="f8e5m2_constant")
convert = opset.convert(compressed_const, data.dtype)
@@ -475,9 +477,11 @@ def test_float_to_f8e8m0_constant(ov_type, numpy_dtype, opset):
],
)
def test_float_to_f8e5m2_convert(ov_type, numpy_dtype, opset):
- data = np.array([4.75, 4.5, -5.25, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5,
- 0.6, 0.7, 0.8, 0.9, 1, -0.0, -0.1, -0.2, -0.3,
- -0.4, -0.5, -0.6, -0.7, -0.8, -0.9, -1.0, 0.0000152587890625, 448, 500, 512, 57344], dtype=numpy_dtype)
+ data = np.array([
+ 4.75, 4.5, -5.25, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5,
+ 0.6, 0.7, 0.8, 0.9, 1, -0.0, -0.1, -0.2, -0.3,
+ -0.4, -0.5, -0.6, -0.7, -0.8, -0.9, -1.0, 0.0000152587890625, 448, 500, 512, 57344
+ ], dtype=numpy_dtype)
compressed_const = opset.constant(data, dtype=ov_type, name="fx_constant")
convert_to_fp8 = opset.convert(compressed_const, Type.f8e5m2)
diff --git a/src/bindings/python/tests/test_graph/test_convert_promote_types.py b/src/bindings/python/tests/test_graph/test_convert_promote_types.py
index 668f3acb69d..32d8da1f4fa 100644
--- a/src/bindings/python/tests/test_graph/test_convert_promote_types.py
+++ b/src/bindings/python/tests/test_graph/test_convert_promote_types.py
@@ -10,7 +10,10 @@ from openvino import Type
@pytest.mark.parametrize(
- ("lhs", "rhs", "promote_unsafe", "pytorch_scalar_promotion", "u64_integer_promotion_target", "expected_output_type"),
+ (
+ "lhs", "rhs", "promote_unsafe", "pytorch_scalar_promotion",
+ "u64_integer_promotion_target", "expected_output_type"
+ ),
[
(([], np.float32), ([2], np.float16), False, False, "f32", Type.f32),
(([], np.float32), ([2], np.float16), True, True, Type.f32, Type.f16),
@@ -18,11 +21,15 @@ from openvino import Type
(([], np.uint64), ([2], np.int8), True, False, "f64", Type.f64),
],
)
-def test_convert_promote_types_param_inputs(lhs, rhs, promote_unsafe, pytorch_scalar_promotion, u64_integer_promotion_target, expected_output_type):
+def test_convert_promote_types_param_inputs(
+ lhs, rhs, promote_unsafe, pytorch_scalar_promotion, u64_integer_promotion_target, expected_output_type
+):
lhs_param = ops.parameter(*lhs)
rhs_param = ops.parameter(*rhs)
- op = ops.convert_promote_types(lhs_param, rhs_param, promote_unsafe, pytorch_scalar_promotion, u64_integer_promotion_target)
+ op = ops.convert_promote_types(
+ lhs_param, rhs_param, promote_unsafe, pytorch_scalar_promotion, u64_integer_promotion_target
+ )
attrs = op.get_attributes()
assert attrs.get("promote_unsafe") == promote_unsafe
assert attrs.get("pytorch_scalar_promotion") == pytorch_scalar_promotion
@@ -38,7 +45,10 @@ def test_convert_promote_types_param_inputs(lhs, rhs, promote_unsafe, pytorch_sc
@pytest.mark.parametrize(
- ("lhs", "rhs", "promote_unsafe", "pytorch_scalar_promotion", "u64_integer_promotion_target", "expected_output_type"),
+ (
+ "lhs", "rhs", "promote_unsafe", "pytorch_scalar_promotion",
+ "u64_integer_promotion_target", "expected_output_type"
+ ),
[
((1, np.float32), ([2], np.float16), False, False, "f32", Type.f32),
((1, np.float32), ([2], np.float16), True, True, "f32", Type.f16),
@@ -46,11 +56,15 @@ def test_convert_promote_types_param_inputs(lhs, rhs, promote_unsafe, pytorch_sc
((1, np.uint64), ([2], np.int8), True, False, Type.f64, Type.f64),
],
)
-def test_convert_promote_types_const_inputs(lhs, rhs, promote_unsafe, pytorch_scalar_promotion, u64_integer_promotion_target, expected_output_type):
+def test_convert_promote_types_const_inputs(
+ lhs, rhs, promote_unsafe, pytorch_scalar_promotion, u64_integer_promotion_target, expected_output_type
+):
lhs_param = ops.constant(*lhs)
rhs_param = ops.constant(*rhs)
- op = ops.convert_promote_types(lhs_param, rhs_param, promote_unsafe, pytorch_scalar_promotion, u64_integer_promotion_target)
+ op = ops.convert_promote_types(
+ lhs_param, rhs_param, promote_unsafe, pytorch_scalar_promotion, u64_integer_promotion_target
+ )
attrs = op.get_attributes()
assert attrs.get("promote_unsafe") == promote_unsafe
assert attrs.get("pytorch_scalar_promotion") == pytorch_scalar_promotion
diff --git a/src/bindings/python/tests/test_graph/test_create_op.py b/src/bindings/python/tests/test_graph/test_create_op.py
index 5a3a12adfe1..79e72c4f120 100644
--- a/src/bindings/python/tests/test_graph/test_create_op.py
+++ b/src/bindings/python/tests/test_graph/test_create_op.py
@@ -600,7 +600,10 @@ def test_roi_pooling_deprecation():
@pytest.mark.parametrize(
- ("data_shape", "rois", "batch_indices", "pooled_h", "pooled_w", "sampling_ratio", "spatial_scale", "mode", "aligned_mode", "expected_shape"),
+ (
+ "data_shape", "rois", "batch_indices", "pooled_h", "pooled_w", "sampling_ratio",
+ "spatial_scale", "mode", "aligned_mode", "expected_shape"
+ ),
[
([2, 3, 5, 6], [7, 4], [7], 2, 2, 1, 1.0, "avg", "asymmetric", [7, 3, 2, 2]),
([10, 3, 5, 5], [7, 4], [7], 3, 4, 1, 1.0, "avg", "half_pixel_for_nn", [7, 3, 3, 4]),
@@ -608,7 +611,10 @@ def test_roi_pooling_deprecation():
([10, 3, 5, 5], [3, 4], [3], 3, 4, 1, float(1), "avg", "half_pixel", [3, 3, 3, 4]),
],
)
-def test_roi_align(data_shape, rois, batch_indices, pooled_h, pooled_w, sampling_ratio, spatial_scale, mode, aligned_mode, expected_shape):
+def test_roi_align(
+ data_shape, rois, batch_indices, pooled_h, pooled_w, sampling_ratio,
+ spatial_scale, mode, aligned_mode, expected_shape
+):
data_parameter = ov.parameter(data_shape, name="Data", dtype=np.float32)
rois_parameter = ov.parameter(rois, name="Rois", dtype=np.float32)
batch_indices_parameter = ov.parameter(batch_indices, name="Batch_indices", dtype=np.int32)
@@ -632,7 +638,10 @@ def test_roi_align(data_shape, rois, batch_indices, pooled_h, pooled_w, sampling
@pytest.mark.parametrize(
- ("data_shape", "rois", "batch_indices", "pooled_h", "pooled_w", "sampling_ratio", "spatial_scale", "clockwise_mode", "expected_shape"),
+ (
+ "data_shape", "rois", "batch_indices", "pooled_h", "pooled_w", "sampling_ratio",
+ "spatial_scale", "clockwise_mode", "expected_shape"
+ ),
[
([2, 3, 5, 6], [7, 5], [7], 2, 2, 1, 1.0, True, [7, 3, 2, 2]),
([10, 3, 5, 5], [7, 5], [7], 3, 4, 1, 1.0, True, [7, 3, 3, 4]),
@@ -640,7 +649,9 @@ def test_roi_align(data_shape, rois, batch_indices, pooled_h, pooled_w, sampling
([10, 3, 5, 5], [3, 5], [3], 3, 4, 1, float(1), False, [3, 3, 3, 4]),
],
)
-def test_roi_align_rotated(data_shape, rois, batch_indices, pooled_h, pooled_w, sampling_ratio, spatial_scale, clockwise_mode, expected_shape):
+def test_roi_align_rotated(
+ data_shape, rois, batch_indices, pooled_h, pooled_w, sampling_ratio, spatial_scale, clockwise_mode, expected_shape
+):
data_parameter = ov.parameter(data_shape, name="Data", dtype=np.float32)
rois_parameter = ov.parameter(rois, name="Rois", dtype=np.float32)
batch_indices_parameter = ov.parameter(batch_indices, name="Batch_indices", dtype=np.int32)
@@ -1720,9 +1731,18 @@ def test_matrix_nms():
@pytest.mark.parametrize(
("boxes_shape", "scores_shape", "max_output_boxes", "expected_shape"),
[
- ([1, 1000, 4], [1, 1, 1000], [1000], [PartialShape([Dimension(0, 1000), Dimension(3)]), PartialShape([Dimension(0, 1000), Dimension(3)])]),
- ([1, 700, 4], [1, 1, 700], [600], [PartialShape([Dimension(0, 600), Dimension(3)]), PartialShape([Dimension(0, 600), Dimension(3)])]),
- ([1, 300, 4], [1, 1, 300], [300], [PartialShape([Dimension(0, 300), Dimension(3)]), PartialShape([Dimension(0, 300), Dimension(3)])]),
+ (
+ [1, 1000, 4], [1, 1, 1000], [1000],
+ [PartialShape([Dimension(0, 1000), Dimension(3)]), PartialShape([Dimension(0, 1000), Dimension(3)])]
+ ),
+ (
+ [1, 700, 4], [1, 1, 700], [600],
+ [PartialShape([Dimension(0, 600), Dimension(3)]), PartialShape([Dimension(0, 600), Dimension(3)])]
+ ),
+ (
+ [1, 300, 4], [1, 1, 300], [300],
+ [PartialShape([Dimension(0, 300), Dimension(3)]), PartialShape([Dimension(0, 300), Dimension(3)])]
+ ),
],
)
@pytest.mark.parametrize("op_name", ["NonMaxSuppression", "NonMaxSuppressionV3"])
@@ -1730,7 +1750,9 @@ def test_non_max_suppression(boxes_shape, scores_shape, max_output_boxes, expect
boxes_parameter = ov.parameter(boxes_shape, name="Boxes", dtype=np.float32)
scores_parameter = ov.parameter(scores_shape, name="Scores", dtype=np.float32)
- node = ov.non_max_suppression(boxes_parameter, scores_parameter, make_constant_node(max_output_boxes, np.int64), name=op_name)
+ node = ov.non_max_suppression(
+ boxes_parameter, scores_parameter, make_constant_node(max_output_boxes, np.int64), name=op_name
+ )
assert node.get_type_name() == "NonMaxSuppression"
assert node.get_friendly_name() == op_name
assert node.get_output_size() == 3
@@ -1740,16 +1762,29 @@ def test_non_max_suppression(boxes_shape, scores_shape, max_output_boxes, expect
@pytest.mark.parametrize(
- ("boxes_shape", "scores_shape", "max_output_boxes", "iou_threshold", "score_threshold", "soft_nms_sigma", "expected_shape"),
+ (
+ "boxes_shape", "scores_shape", "max_output_boxes", "iou_threshold",
+ "score_threshold", "soft_nms_sigma", "expected_shape"
+ ),
[
- ([1, 100, 4], [1, 1, 100], [100], 0.1, 0.4, 0.5, [PartialShape([Dimension(0, 100), Dimension(3)]), PartialShape([Dimension(0, 100), Dimension(3)])]),
- ([1, 700, 4], [1, 1, 700], [600], 0.1, 0.4, 0.5, [PartialShape([Dimension(0, 600), Dimension(3)]), PartialShape([Dimension(0, 600), Dimension(3)])]),
- ([1, 300, 4], [1, 1, 300], [300], 0.1, 0.4, 0.5, [PartialShape([Dimension(0, 300), Dimension(3)]), PartialShape([Dimension(0, 300), Dimension(3)])]),
+ (
+ [1, 100, 4], [1, 1, 100], [100], 0.1, 0.4, 0.5,
+ [PartialShape([Dimension(0, 100), Dimension(3)]), PartialShape([Dimension(0, 100), Dimension(3)])]
+ ),
+ (
+ [1, 700, 4], [1, 1, 700], [600], 0.1, 0.4, 0.5,
+ [PartialShape([Dimension(0, 600), Dimension(3)]), PartialShape([Dimension(0, 600), Dimension(3)])]
+ ),
+ (
+ [1, 300, 4], [1, 1, 300], [300], 0.1, 0.4, 0.5,
+ [PartialShape([Dimension(0, 300), Dimension(3)]), PartialShape([Dimension(0, 300), Dimension(3)])]
+ ),
],
)
@pytest.mark.parametrize("op_name", ["NonMaxSuppression", "NonMaxSuppressionV3"])
-def test_non_max_suppression_non_default_args(boxes_shape, scores_shape, max_output_boxes, iou_threshold,
- score_threshold, soft_nms_sigma, expected_shape, op_name):
+def test_non_max_suppression_non_default_args(
+ boxes_shape, scores_shape, max_output_boxes, iou_threshold, score_threshold, soft_nms_sigma, expected_shape, op_name
+):
boxes_parameter = ov.parameter(boxes_shape, name="Boxes", dtype=np.float32)
scores_parameter = ov.parameter(scores_shape, name="Scores", dtype=np.float32)
@@ -1758,7 +1793,10 @@ def test_non_max_suppression_non_default_args(boxes_shape, scores_shape, max_out
score_threshold = make_constant_node(score_threshold, np.float32)
soft_nms_sigma = make_constant_node(soft_nms_sigma, np.float32)
- node = ov.non_max_suppression(boxes_parameter, scores_parameter, max_output_boxes, iou_threshold, score_threshold, soft_nms_sigma, name=op_name)
+ node = ov.non_max_suppression(
+ boxes_parameter, scores_parameter, max_output_boxes, iou_threshold,
+ score_threshold, soft_nms_sigma, name=op_name
+ )
assert node.get_type_name() == "NonMaxSuppression"
assert node.get_friendly_name() == op_name
assert node.get_output_size() == 3
diff --git a/src/bindings/python/tests/test_graph/test_custom_op.py b/src/bindings/python/tests/test_graph/test_custom_op.py
index ab993c07523..cd6a5af8fb1 100644
--- a/src/bindings/python/tests/test_graph/test_custom_op.py
+++ b/src/bindings/python/tests/test_graph/test_custom_op.py
@@ -136,7 +136,11 @@ def prepared_paths(request, tmp_path):
({"body": Model(ops.constant([1]), [])}, does_not_raise(), ""),
({"dim": Dimension(2)}, does_not_raise(), ""),
({"wrong_list": [{}]}, pytest.raises(TypeError), "Unsupported attribute type in provided list: <class 'dict'>"),
- ({"wrong_np": np.array([1.5, 2.5], dtype="complex128")}, pytest.raises(TypeError), "Unsupported NumPy array dtype: complex128"),
+ (
+ {"wrong_np": np.array([1.5, 2.5], dtype="complex128")},
+ pytest.raises(TypeError),
+ "Unsupported NumPy array dtype: complex128"
+ ),
({"wrong": {}}, pytest.raises(TypeError), "Unsupported attribute type: <class 'dict'>")
])
def test_visit_attributes_custom_op(device, prepared_paths, attributes, expectation, raise_msg):
diff --git a/src/bindings/python/tests/test_graph/test_multinomial.py b/src/bindings/python/tests/test_graph/test_multinomial.py
index ccd8bca7f99..f47299ef2e6 100644
--- a/src/bindings/python/tests/test_graph/test_multinomial.py
+++ b/src/bindings/python/tests/test_graph/test_multinomial.py
@@ -10,15 +10,20 @@ from openvino import PartialShape, Type
@pytest.mark.parametrize(
- ("probs_shape", "num_samples_shape", "convert_type", "with_replacement", "log_probs", "global_seed", "op_seed", "expected_out_shape"),
+ (
+ "probs_shape", "num_samples_shape", "convert_type", "with_replacement",
+ "log_probs", "global_seed", "op_seed", "expected_out_shape"
+ ),
[
([4, 16], [], "i32", False, True, 7461, 1546, PartialShape([4, -1])),
([1, 8], [1], "i64", True, False, 0, 0, PartialShape([1, -1])),
],
)
@pytest.mark.parametrize("op_name", ["multinomial", "multinomialOpset13"])
-def test_multinomial_param_inputs(probs_shape, num_samples_shape, convert_type,
- with_replacement, log_probs, global_seed, op_seed, expected_out_shape, op_name):
+def test_multinomial_param_inputs(
+ probs_shape, num_samples_shape, convert_type, with_replacement,
+ log_probs, global_seed, op_seed, expected_out_shape, op_name
+):
probs = ops.parameter(probs_shape, dtype=np.float32)
num_samples = ops.parameter(num_samples_shape, dtype=np.int32)
@@ -37,15 +42,20 @@ def test_multinomial_param_inputs(probs_shape, num_samples_shape, convert_type,
@pytest.mark.parametrize(
- ("probs_array", "num_samples_val", "convert_type", "with_replacement", "log_probs", "global_seed", "op_seed", "expected_out_shape"),
+ (
+ "probs_array", "num_samples_val", "convert_type", "with_replacement",
+ "log_probs", "global_seed", "op_seed", "expected_out_shape"
+ ),
[
(np.array([[0.7, 0.3, 0.6, 0.5]]), 3, "i32", False, True, 111, 222, PartialShape([1, 3])),
(np.array([[0.7, 0.3], [0.6, 0.5]]), 2, "i64", True, False, 111, 222, PartialShape([2, 2])),
],
)
@pytest.mark.parametrize("op_name", ["multinomial", "multinomialOpset13"])
-def test_multinomial_const_inputs(probs_array, num_samples_val, convert_type,
- with_replacement, log_probs, global_seed, op_seed, expected_out_shape, op_name):
+def test_multinomial_const_inputs(
+ probs_array, num_samples_val, convert_type, with_replacement,
+ log_probs, global_seed, op_seed, expected_out_shape, op_name
+):
probs = ops.constant(probs_array, dtype=np.float32)
num_samples = ops.constant(num_samples_val, dtype=np.int32)
diff --git a/src/bindings/python/tests/test_graph/test_nms_rotated.py b/src/bindings/python/tests/test_graph/test_nms_rotated.py
index 0fce952d9da..da3f806340a 100644
--- a/src/bindings/python/tests/test_graph/test_nms_rotated.py
+++ b/src/bindings/python/tests/test_graph/test_nms_rotated.py
@@ -14,13 +14,24 @@ from openvino.utils.types import make_constant_node
@pytest.mark.parametrize(
("boxes_shape", "scores_shape", "max_output_boxes", "iou_threshold", "score_threshold", "expected_shape"),
[
- ([1, 100, 5], [1, 1, 100], [100], 0.1, 0.4, [PartialShape([Dimension(0, 100), Dimension(3)]), PartialShape([Dimension(0, 100), Dimension(3)])]),
- ([1, 700, 5], [1, 1, 700], [600], 0.1, 0.4, [PartialShape([Dimension(0, 600), Dimension(3)]), PartialShape([Dimension(0, 600), Dimension(3)])]),
- ([1, 300, 5], [1, 1, 300], [300], 0.1, 0.4, [PartialShape([Dimension(0, 300), Dimension(3)]), PartialShape([Dimension(0, 300), Dimension(3)])]),
+ (
+ [1, 100, 5], [1, 1, 100], [100], 0.1, 0.4,
+ [PartialShape([Dimension(0, 100), Dimension(3)]), PartialShape([Dimension(0, 100), Dimension(3)])]
+ ),
+ (
+ [1, 700, 5], [1, 1, 700], [600], 0.1, 0.4,
+ [PartialShape([Dimension(0, 600), Dimension(3)]), PartialShape([Dimension(0, 600), Dimension(3)])]
+ ),
+ (
+ [1, 300, 5], [1, 1, 300], [300], 0.1, 0.4,
+ [PartialShape([Dimension(0, 300), Dimension(3)]), PartialShape([Dimension(0, 300), Dimension(3)])]
+ ),
],
)
@pytest.mark.parametrize("op_name", ["nms_rotated", "nmsRotated", "nmsRotatedOpset13"])
-def test_nms_rotated_default_attrs(boxes_shape, scores_shape, max_output_boxes, iou_threshold, score_threshold, expected_shape, op_name):
+def test_nms_rotated_default_attrs(
+ boxes_shape, scores_shape, max_output_boxes, iou_threshold, score_threshold, expected_shape, op_name
+):
boxes_parameter = ov_opset13.parameter(boxes_shape, name="Boxes", dtype=np.float32)
scores_parameter = ov_opset13.parameter(scores_shape, name="Scores", dtype=np.float32)
diff --git a/src/bindings/python/tests/test_graph/test_ops_embedding.py b/src/bindings/python/tests/test_graph/test_ops_embedding.py
index 409e0ce1b9b..42655ea9f4e 100644
--- a/src/bindings/python/tests/test_graph/test_ops_embedding.py
+++ b/src/bindings/python/tests/test_graph/test_ops_embedding.py
@@ -44,7 +44,9 @@ def test_embedding_bag_offsets_15_per_sample_weights():
offsets = opset15.parameter([3], name="offsets", dtype=np.int64)
per_sample_weights = opset15.parameter([4], name="per_sample_weights", dtype=np.float32)
- node = opset15.embedding_bag_offsets(emb_table, indices, offsets, per_sample_weights=per_sample_weights, reduction="SUM")
+ node = opset15.embedding_bag_offsets(
+ emb_table, indices, offsets, per_sample_weights=per_sample_weights, reduction="SUM"
+ )
assert node.get_type_name() == "EmbeddingBagOffsets"
assert node.get_output_size() == 1
@@ -60,7 +62,9 @@ def test_embedding_bag_offsets_15_default_index_per_sample_weights():
default_index = opset15.parameter([], name="default_index", dtype=np.int64)
per_sample_weights = opset15.parameter([4], name="per_sample_weights", dtype=np.float32)
- node = opset15.embedding_bag_offsets(emb_table, indices, offsets, default_index, per_sample_weights, "sum")
+ node = opset15.embedding_bag_offsets(
+ emb_table, indices, offsets, default_index, per_sample_weights, "sum"
+ )
assert node.get_type_name() == "EmbeddingBagOffsets"
assert node.get_output_size() == 1
diff --git a/src/bindings/python/tests/test_graph/test_preprocess.py b/src/bindings/python/tests/test_graph/test_preprocess.py
index 1074c60b973..df3114da0e9 100644
--- a/src/bindings/python/tests/test_graph/test_preprocess.py
+++ b/src/bindings/python/tests/test_graph/test_preprocess.py
@@ -732,7 +732,10 @@ def test_graph_set_layout_by_layout_class_thow_exception():
assert "Layout name is invalid" in str(e.value)
[email protected](("pads_begin", "pads_end", "values", "mode"), [([0, 0, 0, 0], [0, 0, 1, 1], 0, PaddingMode.CONSTANT)])
+ ("pads_begin", "pads_end", "values", "mode"),
+ [([0, 0, 0, 0], [0, 0, 1, 1], 0, PaddingMode.CONSTANT)]
+)
def test_pad_vector_constant_layout(pads_begin, pads_end, values, mode):
shape = [1, 3, 200, 200]
parameter_a = ops.parameter(shape, dtype=np.float32, name="RGB_input")
@@ -746,7 +749,10 @@ def test_pad_vector_constant_layout(pads_begin, pads_end, values, mode):
assert list(new_model.get_output_shape(0)) == shape
[email protected](("pads_begin", "pads_end", "values", "mode"), [([0, 0, -2, 0], [0, 0, -4, 1], 0, PaddingMode.CONSTANT)])
+ ("pads_begin", "pads_end", "values", "mode"),
+ [([0, 0, -2, 0], [0, 0, -4, 1], 0, PaddingMode.CONSTANT)]
+)
def test_pad_vector_out_of_range(pads_begin, pads_end, values, mode):
shape = [1, 3, 5, 5]
parameter_a = ops.parameter(shape, dtype=np.float32, name="A")
@@ -759,7 +765,10 @@ def test_pad_vector_out_of_range(pads_begin, pads_end, values, mode):
assert "not aligned with original parameter's shape" in str(e.value)
[email protected](("pads_begin", "pads_end", "values", "mode"), [([0, 0, 2, 0, 1], [0, 0, 4, 1, 1], 0, PaddingMode.CONSTANT)])
+ ("pads_begin", "pads_end", "values", "mode"),
+ [([0, 0, 2, 0, 1], [0, 0, 4, 1, 1], 0, PaddingMode.CONSTANT)]
+)
def test_pad_vector_dim_mismatch(pads_begin, pads_end, values, mode):
shape = [1, 3, 5, 5]
parameter_a = ops.parameter(shape, dtype=np.float32, name="A")
@@ -772,7 +781,10 @@ def test_pad_vector_dim_mismatch(pads_begin, pads_end, values, mode):
assert "mismatches with rank of input" in str(e.value)
[email protected](("pads_begin", "pads_end", "values", "mode"), [([0, 0, 0, 0], [0, 0, 1, 1], 0, PaddingMode.CONSTANT)])
+ ("pads_begin", "pads_end", "values", "mode"),
+ [([0, 0, 0, 0], [0, 0, 1, 1], 0, PaddingMode.CONSTANT)]
+)
def test_pad_vector_type_and_ops(pads_begin, pads_end, values, mode):
shape = [1, 3, 200, 200]
parameter_a = ops.parameter(shape, dtype=np.float32, name="RGB_input")
diff --git a/src/bindings/python/tests/test_graph/test_sequence_processing.py b/src/bindings/python/tests/test_graph/test_sequence_processing.py
index f5aee41e19b..22b65f661c2 100644
--- a/src/bindings/python/tests/test_graph/test_sequence_processing.py
+++ b/src/bindings/python/tests/test_graph/test_sequence_processing.py
@@ -58,7 +58,9 @@ def test_range_4(destination_type, expected_type):
(3, 1, 0, -1, "normalize", [3, 3]),
(4, 5, 10, 1, "normalize", [3, 4]),
])
-def test_one_hot_opset16_with_negative_indices_mode(depth, on_value, off_value, axis, negative_indices_mode, expected_shape):
+def test_one_hot_opset16_with_negative_indices_mode(
+ depth, on_value, off_value, axis, negative_indices_mode, expected_shape
+):
param = ov.opset11.parameter([3], dtype=np.int32)
node = ov16.one_hot(param, depth, on_value, off_value, axis, negative_indices_mode)
assert node.get_output_size() == 1
diff --git a/src/bindings/python/tests/test_graph/test_utils.py b/src/bindings/python/tests/test_graph/test_utils.py
index b25e08fdceb..a2a57628a34 100644
--- a/src/bindings/python/tests/test_graph/test_utils.py
+++ b/src/bindings/python/tests/test_graph/test_utils.py
@@ -13,5 +13,8 @@ def test_deprecation_warning():
deprecation_warning("function2", "2025.4")
with pytest.warns(DeprecationWarning, match="function3 is deprecated. Use another function instead"):
deprecation_warning("function3", message="Use another function instead")
- with pytest.warns(DeprecationWarning, match="function4 is deprecated and will be removed in version 2025.4. Use another function instead"):
+ with pytest.warns(
+ DeprecationWarning,
+ match="function4 is deprecated and will be removed in version 2025.4. Use another function instead"
+ ):
deprecation_warning("function4", version="2025.4", message="Use another function instead")
diff --git a/src/bindings/python/tests/test_runtime/test_async_infer_request.py b/src/bindings/python/tests/test_runtime/test_async_infer_request.py
index 060da2393e2..7b0896abb03 100644
--- a/src/bindings/python/tests/test_runtime/test_async_infer_request.py
+++ b/src/bindings/python/tests/test_runtime/test_async_infer_request.py
@@ -327,7 +327,9 @@ def test_start_async(device, share_inputs):
])
@pytest.mark.parametrize("share_inputs", [True, False])
def test_async_mixed_values(device, ov_type, numpy_dtype, share_inputs):
- request, tensor1, array1 = generate_concat_compiled_model_with_data(device=device, ov_type=ov_type, numpy_dtype=numpy_dtype)
+ request, tensor1, array1 = generate_concat_compiled_model_with_data(
+ device=device, ov_type=ov_type, numpy_dtype=numpy_dtype
+ )
request.start_async([tensor1, array1], share_inputs=share_inputs)
request.wait()
diff --git a/src/bindings/python/tests/test_runtime/test_compiled_model.py b/src/bindings/python/tests/test_runtime/test_compiled_model.py
index 634e72de2ac..5264207daa5 100644
--- a/src/bindings/python/tests/test_runtime/test_compiled_model.py
+++ b/src/bindings/python/tests/test_runtime/test_compiled_model.py
@@ -43,7 +43,10 @@ def test_export_import_stream(device):
core = Core()
if props.device.Capability.EXPORT_IMPORT not in core.get_property(device, props.device.capabilities):
- pytest.skip(f"{core.get_property(device, props.device.full_name)} plugin due-to export, import model API isn't implemented.")
+ pytest.skip(
+ f"{core.get_property(device, props.device.full_name)} plugin "
+ "due-to export, import model API isn't implemented."
+ )
compiled_model = generate_relu_compiled_model(device)
@@ -61,7 +64,10 @@ def test_export_import_tensor(device):
core = Core()
if props.device.Capability.EXPORT_IMPORT not in core.get_property(device, props.device.capabilities):
- pytest.skip(f"{core.get_property(device, props.device.full_name)} plugin due-to export, import model API isn't implemented.")
+ pytest.skip(
+ f"{core.get_property(device, props.device.full_name)} plugin "
+ "due-to export, import model API isn't implemented."
+ )
compiled_model = generate_relu_compiled_model(device)
@@ -80,7 +86,10 @@ def test_export_import_with_encryption(device):
core = Core()
if props.device.Capability.EXPORT_IMPORT not in core.get_property(device, props.device.capabilities):
- pytest.skip(f"{core.get_property(device, props.device.full_name)} plugin due-to export, import model API isn't implemented.")
+ pytest.skip(
+ f"{core.get_property(device, props.device.full_name)} plugin "
+ "due-to export, import model API isn't implemented."
+ )
config = {}
config["CACHE_ENCRYPTION_CALLBACKS"] = [encrypt_base64, decrypt_base64]
@@ -103,7 +112,10 @@ def test_export_import_advanced(device):
core = Core()
if props.device.Capability.EXPORT_IMPORT not in core.get_property(device, props.device.capabilities):
- pytest.skip(f"{core.get_property(device, props.device.full_name)} plugin due-to export, import model API isn't implemented.")
+ pytest.skip(
+ f"{core.get_property(device, props.device.full_name)} plugin "
+ "due-to export, import model API isn't implemented."
+ )
compiled_model = generate_relu_compiled_model(device)
@@ -135,7 +147,10 @@ def test_export_import_via_file(prepare_blob_path, device):
core = Core()
if props.device.Capability.EXPORT_IMPORT not in core.get_property(device, props.device.capabilities):
- pytest.skip(f"{core.get_property(device, props.device.full_name)} plugin due-to export, import model API isn't implemented.")
+ pytest.skip(
+ f"{core.get_property(device, props.device.full_name)} plugin "
+ "due-to export, import model API isn't implemented."
+ )
compiled_model = generate_relu_compiled_model(device)
@@ -321,7 +336,10 @@ def test_compiled_model_after_core_destroyed(request, tmp_path, device):
del core
del model
# check compiled and infer request can work properly after core object is destroyed
- compiled([np.random.normal(size=list(input.shape)).astype(dtype=input.get_element_type().to_dtype()) for input in compiled.inputs])
+ compiled([
+ np.random.normal(size=list(input.shape)).astype(dtype=input.get_element_type().to_dtype())
+ for input in compiled.inputs
+ ])
def test_compiled_model_from_buffer_in_memory(request, tmp_path, device):
@@ -336,7 +354,10 @@ def test_compiled_model_from_buffer_in_memory(request, tmp_path, device):
compiled = core.compile_model(model=xml, weights=weights, device_name=device)
assert isinstance(compiled.outputs[0], ConstOutput)
- _ = compiled([np.random.normal(size=list(input.shape)).astype(dtype=input.get_element_type().to_dtype()) for input in compiled.inputs])
+ _ = compiled([
+ np.random.normal(size=list(input.shape)).astype(dtype=input.get_element_type().to_dtype())
+ for input in compiled.inputs
+ ])
def test_memory_release(device):
diff --git a/src/bindings/python/tests/test_runtime/test_core.py b/src/bindings/python/tests/test_runtime/test_core.py
index cd07e978f63..c4bb6b8f3ae 100644
--- a/src/bindings/python/tests/test_runtime/test_core.py
+++ b/src/bindings/python/tests/test_runtime/test_core.py
@@ -52,7 +52,10 @@ def test_compact_api_wrong_path():
return "test class"
with pytest.raises(RuntimeError) as e:
compile_model(TestClass())
- assert "Path: 'test class' does not exist. Please provide valid model's path either as a string, bytes or pathlib.Path" in str(e.value)
+ assert (
+ "Path: 'test class' does not exist. Please provide valid model's path either as a string, bytes or pathlib.Path"
+ in str(e.value)
+ )
def test_core_class(device):
diff --git a/src/bindings/python/tests/test_runtime/test_deprecated_runtime.py b/src/bindings/python/tests/test_runtime/test_deprecated_runtime.py
index fa9749d720b..0ff9859a8a5 100644
--- a/src/bindings/python/tests/test_runtime/test_deprecated_runtime.py
+++ b/src/bindings/python/tests/test_runtime/test_deprecated_runtime.py
@@ -10,7 +10,10 @@ import warnings
import operator
import sysconfig
-with pytest.warns(DeprecationWarning, match="The `openvino.runtime` module is deprecated and will be removed in the 2026.0 release."):
+with pytest.warns(
+ DeprecationWarning,
+ match="The `openvino.runtime` module is deprecated and will be removed in the 2026.0 release."
+):
import openvino.runtime as ov
import openvino.runtime.opset13 as ops
diff --git a/src/bindings/python/tests/test_runtime/test_model.py b/src/bindings/python/tests/test_runtime/test_model.py
index 97b6a116555..ff28a01d55e 100644
--- a/src/bindings/python/tests/test_runtime/test_model.py
+++ b/src/bindings/python/tests/test_runtime/test_model.py
@@ -160,10 +160,13 @@ def test_get_result_index_invalid():
assert model.get_result_index(invalid_output) == -1
[email protected](("shapes", "relu_names", "model_name", "expected_outputs_length", "is_invalid", "expected_result_index"), [
- ([PartialShape([1])], ["relu"], "TestModel", 1, False, 0),
- ([PartialShape([1]), PartialShape([4])], ["relu1", "relu2"], "TestModel1", 1, True, -1)
-])
+ ("shapes", "relu_names", "model_name", "expected_outputs_length", "is_invalid", "expected_result_index"),
+ [
+ ([PartialShape([1])], ["relu"], "TestModel", 1, False, 0),
+ ([PartialShape([1]), PartialShape([4])], ["relu1", "relu2"], "TestModel1", 1, True, -1)
+ ]
+)
def test_result_index(shapes, relu_names, model_name, expected_outputs_length, is_invalid, expected_result_index):
params = [ops.parameter(shape, dtype=np.float32, name=f"data{i + 1}") for i, shape in enumerate(shapes)]
relus = [ops.relu(param, name=relu_name) for param, relu_name in zip(params, relu_names)]
@@ -270,14 +273,19 @@ def test_model_sink_ctors():
# Model(list[openvino._pyopenvino.op.Result], list[ov::Output<ov::Node>],
# list[openvino._pyopenvino.op.Parameter], list[openvino._pyopenvino.op.util.Variable], str = '')
- model = Model(results=[res], sinks=[assign.output(0)], parameters=[input_data], variables=[variable_1], name="TestModel")
+ model = Model(
+ results=[res], sinks=[assign.output(0)], parameters=[input_data], variables=[variable_1], name="TestModel"
+ )
model.validate_nodes_and_infer_types()
assert model.sinks[0].get_output_shape(0) == Shape([2, 2])
assert sinks == [sink.get_type_name() for sink in model.get_sinks()]
# Model(list[ov::Output<ov::Node>, list[ov::Output<ov::Node>],
# list[openvino._pyopenvino.op.Parameter], list[openvino._pyopenvino.op.util.Variable], str = '')
- model = Model(results=[res.output(0)], sinks=[assign.output(0)], parameters=[input_data], variables=[variable_1], name="TestModel")
+ model = Model(
+ results=[res.output(0)], sinks=[assign.output(0)], parameters=[input_data],
+ variables=[variable_1], name="TestModel"
+ )
model.validate_nodes_and_infer_types()
assert model.sinks[0].get_output_shape(0) == Shape([2, 2])
assert sinks == [sink.get_type_name() for sink in model.get_sinks()]
@@ -693,15 +701,26 @@ def test_serialize_complex_rt_info(request, tmp_path):
assert model.get_rt_info(["config", "type_of_model"]).astype(str) == "classification"
assert model.get_rt_info(["config", "converter_type"]).astype(str) == "classification"
- assert math.isclose(model.get_rt_info(["config", "model_parameters", "threshold"]).astype(float), 13.23, rel_tol=0.0001)
- assert math.isclose(model.get_rt_info(["config", "model_parameters", "min"]).astype(float), -3.24543, rel_tol=0.0001)
- assert math.isclose(model.get_rt_info(["config", "model_parameters", "max"]).astype(float), 3.234223, rel_tol=0.0001)
+ assert math.isclose(
+ model.get_rt_info(["config", "model_parameters", "threshold"]).astype(float), 13.23, rel_tol=0.0001
+ )
+ assert math.isclose(
+ model.get_rt_info(["config", "model_parameters", "min"]).astype(float), -3.24543, rel_tol=0.0001
+ )
+ assert math.isclose(
+ model.get_rt_info(["config", "model_parameters", "max"]).astype(float), 3.234223, rel_tol=0.0001
+ )
assert model.get_rt_info(["config", "model_parameters", "labels", "label_tree", "type"]).astype(str) == "tree"
- assert model.get_rt_info(["config", "model_parameters", "labels", "label_tree", "directed"]).astype(bool) is True
+ assert (
+ model.get_rt_info(["config", "model_parameters", "labels", "label_tree", "directed"]).astype(bool) is True
+ )
assert model.get_rt_info(["config", "model_parameters", "labels", "label_tree", "float_empty"]).aslist() == []
assert model.get_rt_info(["config", "model_parameters", "labels", "label_tree", "nodes"]).aslist() == []
- assert model.get_rt_info(["config", "model_parameters", "labels", "label_groups", "ids"]).aslist(str) == ["sasd", "fdfdfsdf"]
+ assert (
+ model.get_rt_info(["config", "model_parameters", "labels", "label_groups", "ids"]).aslist(str)
+ == ["sasd", "fdfdfsdf"]
+ )
assert model.get_rt_info(["config", "model_parameters", "mean_values"]).aslist(float) == [22.3, 33.11, 44.0]
assert model.get_rt_info("enum_info_int").astype(int) == 1
assert model.get_rt_info("enum_info_str").astype(str) == "info_str"
diff --git a/src/bindings/python/tests/test_runtime/test_properties.py b/src/bindings/python/tests/test_runtime/test_properties.py
index b7abd73194a..e41c2d6e15c 100644
--- a/src/bindings/python/tests/test_runtime/test_properties.py
+++ b/src/bindings/python/tests/test_runtime/test_properties.py
@@ -617,7 +617,10 @@ def test_single_property_setting(device):
assert isinstance(core.get_property(device, streams.num()), int)
[email protected](os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test")
+ os.environ.get("TEST_DEVICE", "CPU") != "CPU",
+ reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test"
+)
@pytest.mark.parametrize(
"properties_to_set",
[
diff --git a/src/bindings/python/tests/test_runtime/test_stateful.py b/src/bindings/python/tests/test_runtime/test_stateful.py
index 2c31854c6dc..09b66187a7c 100644
--- a/src/bindings/python/tests/test_runtime/test_stateful.py
+++ b/src/bindings/python/tests/test_runtime/test_stateful.py
@@ -93,4 +93,6 @@ def test_query_state_write_buffer(device, base_class, input_shape, data_type, mo
res = caller.call({0: np.full(input_shape, 1, dtype=data_type)})
expected_res = np.full(input_shape, i, dtype=data_type)
- assert np.allclose(res[list(res)[0]], expected_res, atol=1e-6), f"Expected values: {expected_res} \n Actual values: {res} \n"
+ assert np.allclose(
+ res[list(res)[0]], expected_res, atol=1e-6
+ ), f"Expected values: {expected_res} \n Actual values: {res} \n"
diff --git a/src/bindings/python/tests/test_runtime/test_sync_infer_request.py b/src/bindings/python/tests/test_runtime/test_sync_infer_request.py
index 995401a95cd..fee1c1bbf09 100644
--- a/src/bindings/python/tests/test_runtime/test_sync_infer_request.py
+++ b/src/bindings/python/tests/test_runtime/test_sync_infer_request.py
@@ -312,7 +312,9 @@ def test_infer_mixed_keys(device, share_inputs):
])
@pytest.mark.parametrize("share_inputs", [True, False])
def test_infer_mixed_values(device, ov_type, numpy_dtype, share_inputs):
- request, tensor1, array1 = generate_concat_compiled_model_with_data(device=device, ov_type=ov_type, numpy_dtype=numpy_dtype)
+ request, tensor1, array1 = generate_concat_compiled_model_with_data(
+ device=device, ov_type=ov_type, numpy_dtype=numpy_dtype
+ )
request.infer([tensor1, array1], share_inputs=share_inputs)
diff --git a/src/bindings/python/tests/test_runtime/test_tensor_string.py b/src/bindings/python/tests/test_runtime/test_tensor_string.py
index 168a649b573..b2f1753f819 100644
--- a/src/bindings/python/tests/test_runtime/test_tensor_string.py
+++ b/src/bindings/python/tests/test_runtime/test_tensor_string.py
@@ -26,14 +26,20 @@ def check_bytes_based(tensor, string_data, to_flat=False):
tensor_data = tensor.bytes_data
encoded_data = string_data if string_data.dtype.kind == "S" else np.char.encode(string_data)
assert tensor_data.dtype.kind == "S"
- _check_tensor_string(tensor_data.flatten() if to_flat else tensor_data, encoded_data.flatten() if to_flat else encoded_data)
+ _check_tensor_string(
+ tensor_data.flatten() if to_flat else tensor_data,
+ encoded_data.flatten() if to_flat else encoded_data
+ )
def check_string_based(tensor, string_data, to_flat=False):
tensor_data = tensor.str_data
decoded_data = string_data if string_data.dtype.kind == "U" else np.char.decode(string_data)
assert tensor_data.dtype.kind == "U"
- _check_tensor_string(tensor_data.flatten() if to_flat else tensor_data, decoded_data.flatten() if to_flat else decoded_data)
+ _check_tensor_string(
+ tensor_data.flatten() if to_flat else tensor_data,
+ decoded_data.flatten() if to_flat else decoded_data
+ )
def test_string_tensor_shared_memory_fails():
diff --git a/src/bindings/python/tests/test_runtime/test_type.py b/src/bindings/python/tests/test_runtime/test_type.py
index ca11736a800..970ef206c39 100644
--- a/src/bindings/python/tests/test_runtime/test_type.py
+++ b/src/bindings/python/tests/test_runtime/test_type.py
@@ -91,7 +91,10 @@ def test_basic_ovtypes(ovtype,
def test_undefined_ovtype():
- with pytest.warns(DeprecationWarning, match="openvino.Type.undefined is deprecated and will be removed in version 2026.0") as w:
+ with pytest.warns(
+ DeprecationWarning,
+ match="openvino.Type.undefined is deprecated and will be removed in version 2026.0"
+ ) as w:
ov_type = Type.undefined
assert issubclass(w[0].category, DeprecationWarning)
assert "openvino.Type.undefined is deprecated and will be removed in version 2026.0" in str(w[0].message)
diff --git a/src/bindings/python/tests/test_transformations/test_compression_4bit.py b/src/bindings/python/tests/test_transformations/test_compression_4bit.py
index 2f26075dc64..e97288b84f8 100644
--- a/src/bindings/python/tests/test_transformations/test_compression_4bit.py
+++ b/src/bindings/python/tests/test_transformations/test_compression_4bit.py
@@ -94,6 +94,8 @@ def test_float_to_f4e2m1_convert(ov_type, numpy_dtype):
tensor = np.zeros(data.shape, dtype=numpy_dtype)
result = compiled_model(tensor)[0]
- expected = np.array([-6.0, -4.0, -3.0, -2.0, -1.5, -1.0, -0.0, 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], dtype=numpy_dtype)
+ expected = np.array(
+ [-6.0, -4.0, -3.0, -2.0, -1.5, -1.0, -0.0, 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], dtype=numpy_dtype
+ )
assert np.allclose(result, expected)
diff --git a/src/bindings/python/tests/test_transformations/test_offline_api.py b/src/bindings/python/tests/test_transformations/test_offline_api.py
index 58d78206255..a987e5665f9 100644
--- a/src/bindings/python/tests/test_transformations/test_offline_api.py
+++ b/src/bindings/python/tests/test_transformations/test_offline_api.py
@@ -44,7 +44,9 @@ def get_lstm_sequence_model():
const_r = ov.opset9.constant(value=r_val, dtype=np.float32)
const_b = ov.opset9.constant(value=b_val, dtype=np.float32)
- lstm_sequence = ov.opset9.lstm_sequence(parameter_x, parameter_y, parameter_z, seq_lengths, const_w, const_r, const_b, 128, "FORWARD")
+ lstm_sequence = ov.opset9.lstm_sequence(
+ parameter_x, parameter_y, parameter_z, seq_lengths, const_w, const_r, const_b, 128, "FORWARD"
+ )
y_out = ov.opset9.result(lstm_sequence.output(0))
ho = ov.opset9.result(lstm_sequence.output(1))
co = ov.opset9.result(lstm_sequence.output(2))
@@ -66,7 +68,9 @@ def get_rnn_sequence_model():
const_r = ov.opset9.constant(value=r_val, dtype=np.float32)
const_b = ov.opset9.constant(value=b_val, dtype=np.float32)
- rnn_sequence = ov.opset9.rnn_sequence(parameter_x, parameter_y, seq_lengths, const_w, const_r, const_b, 128, "FORWARD")
+ rnn_sequence = ov.opset9.rnn_sequence(
+ parameter_x, parameter_y, seq_lengths, const_w, const_r, const_b, 128, "FORWARD"
+ )
y_out = ov.opset9.result(rnn_sequence.output(0))
model = Model([y_out], [parameter_x, parameter_y])
@@ -86,7 +90,9 @@ def get_gru_sequence_model():
const_r = ov.opset9.constant(value=r_val, dtype=np.float32)
const_b = ov.opset9.constant(value=b_val, dtype=np.float32)
- gru_sequence = ov.opset9.gru_sequence(parameter_x, parameter_y, seq_lengths, const_w, const_r, const_b, 128, "FORWARD")
+ gru_sequence = ov.opset9.gru_sequence(
+ parameter_x, parameter_y, seq_lengths, const_w, const_r, const_b, 128, "FORWARD"
+ )
y_out = ov.opset9.result(gru_sequence.output(0))
ho = ov.opset9.result(gru_sequence.output(1))
model = Model([y_out, ho], [parameter_x, parameter_y])
@@ -206,7 +212,9 @@ def compare_models_and_finalize_after_test(model, xml_path, bin_path):
)
@pytest.mark.parametrize("path_suffix", [r"test", r"晚安_пут"])
def test_serialize_pass_v2(request, tmp_path, is_path_xml, is_path_bin, path_suffix):
- model, xml_path, bin_path = prepare_test_model_for_serialize(request, tmp_path / path_suffix, is_path_xml, is_path_bin)
+ model, xml_path, bin_path = prepare_test_model_for_serialize(
+ request, tmp_path / path_suffix, is_path_xml, is_path_bin
+ )
serialize(model, xml_path, bin_path)
compare_models_and_finalize_after_test(model, xml_path, bin_path)
@@ -223,7 +231,9 @@ def test_serialize_pass_v2_path_as_bytes(request, tmp_path, path_suffix):
@pytest.mark.parametrize("is_path_bin", [True, False])
@pytest.mark.parametrize("path_suffix", [r"test", r"晚安_пут"])
def test_save_model(request, tmp_path, is_path_xml, is_path_bin, path_suffix):
- model, xml_path, bin_path = prepare_test_model_for_serialize(request, tmp_path / path_suffix, is_path_xml, is_path_bin)
+ model, xml_path, bin_path = prepare_test_model_for_serialize(
+ request, tmp_path / path_suffix, is_path_xml, is_path_bin
+ )
save_model(model, xml_path, compress_to_fp16=False)
compare_models_and_finalize_after_test(model, xml_path, bin_path)
@@ -413,7 +423,8 @@ def test_flush_fp32_subnormals_to_zero():
result = ov.opset10.result(add_node)
model = Model([result], [parameter])
- apply_moc_transformations(model, cf=False, smart_reshape=True) # apply_flush_fp32_subnormals_to_zero is called inside
+ # apply_flush_fp32_subnormals_to_zero is called inside
+ apply_moc_transformations(model, cf=False, smart_reshape=True)
new_weights = add_node.input_value(1).get_node()
assert np.all(new_weights.data[4:8] != subnorm_val)
diff --git a/src/bindings/python/tests/test_transformations/test_pattern_ops.py b/src/bindings/python/tests/test_transformations/test_pattern_ops.py
index 6a381a749c1..dfb0b3f2cad 100644
--- a/src/bindings/python/tests/test_transformations/test_pattern_ops.py
+++ b/src/bindings/python/tests/test_transformations/test_pattern_ops.py
@@ -347,8 +347,12 @@ def test_optional_with_input_and_predicate():
pattern_add = ops.add(AnyInput(), AnyInput())
- assert Matcher(Optional(["opset13.Relu"], pattern_add.output(0), lambda x: True), "TestInputPredicate").match(model_relu)
- assert not Matcher(Optional(["opset13.Relu"], pattern_add.output(0), lambda x: False), "TestInputPredicate").match(model_relu)
+ assert Matcher(
+ Optional(["opset13.Relu"], pattern_add.output(0), lambda x: True), "TestInputPredicate"
+ ).match(model_relu)
+ assert not Matcher(
+ Optional(["opset13.Relu"], pattern_add.output(0), lambda x: False), "TestInputPredicate"
+ ).match(model_relu)
def test_optional_with_input_node():
@@ -365,8 +369,12 @@ def test_optional_with_input_node_and_predicate():
model_add = ops.add(model_input, model_input)
model_relu = ops.relu(model_add.output(0))
- assert Matcher(Optional(["opset13.Relu"], model_add, lambda x: True), "TestInputNodePredicate").match(model_relu)
- assert not Matcher(Optional(["opset13.Relu"], model_add, lambda x: False), "TestInputNodePredicate").match(model_relu)
+ assert Matcher(
+ Optional(["opset13.Relu"], model_add, lambda x: True), "TestInputNodePredicate"
+ ).match(model_relu)
+ assert not Matcher(
+ Optional(["opset13.Relu"], model_add, lambda x: False), "TestInputNodePredicate"
+ ).match(model_relu)
assert not Matcher(Optional(["opset13.Cos"], model_add, lambda x: True), "TestInputNodePredicate").match(model_relu)
@@ -381,8 +389,12 @@ def test_optional_with_multi_input_node():
assert not Matcher(Optional(["opset13.Add"], [model_relu, model_input_1]), "MultiInNode").match(model_input_1)
assert not Matcher(Optional(["opset13.Add"], [model_relu, model_input_1]), "MultiInNode").match(model_input_0)
- assert not Matcher(Optional(["opset13.Add"], [model_relu, model_input_1], lambda x: False), "MultiInNodePredicate").match(model_add)
- assert Matcher(Optional(["opset13.Add"], [model_relu, model_input_1], lambda x: True), "MultiInNodePredicate").match(model_add)
+ assert not Matcher(
+ Optional(["opset13.Add"], [model_relu, model_input_1], lambda x: False), "MultiInNodePredicate"
+ ).match(model_add)
+ assert Matcher(
+ Optional(["opset13.Add"], [model_relu, model_input_1], lambda x: True), "MultiInNodePredicate"
+ ).match(model_add)
def test_all_predicates():
diff --git a/src/bindings/python/tests/test_utils/test_utils.py b/src/bindings/python/tests/test_utils/test_utils.py
index ec4f12b5098..0e283df6b53 100644
--- a/src/bindings/python/tests/test_utils/test_utils.py
+++ b/src/bindings/python/tests/test_utils/test_utils.py
@@ -56,11 +56,17 @@ def test_deprecation_decorator():
with pytest.warns(DeprecationWarning, match="deprecated_function1 is deprecated"):
deprecated_function1("param1")
- with pytest.warns(DeprecationWarning, match="deprecated_function2 is deprecated and will be removed in version 2025.4"):
+ with pytest.warns(
+ DeprecationWarning,
+ match="deprecated_function2 is deprecated and will be removed in version 2025.4"
+ ):
deprecated_function2(param1=1)
with pytest.warns(DeprecationWarning, match="deprecated_function3 is deprecated. Use another function instead"):
deprecated_function3()
- with pytest.warns(DeprecationWarning, match="deprecated_function4 is deprecated and will be removed in version 2025.4. Use another function instead"):
+ with pytest.warns(
+ DeprecationWarning,
+ match="deprecated_function4 is deprecated and will be removed in version 2025.4. Use another function instead"
+ ):
deprecated_function4()
@@ -196,7 +202,10 @@ def test_serialize_postponned_constant_maker_tensor_copy(prepare_ir_paths):
) as w:
model = create_model(maker)
assert issubclass(w[0].category, DeprecationWarning)
- assert "Please use PostponedConstant's 'maker' argument as Callable[[], Tensor] instead of Callable[[Tensor], None]" in str(w[0].message)
+ assert (
+ "Please use PostponedConstant's 'maker' argument as Callable[[], Tensor] "
+ "instead of Callable[[Tensor], None]"
+ ) in str(w[0].message)
assert maker.called_times() == 0
model_export_file_name, weights_export_file_name = prepare_ir_paths
diff --git a/src/bindings/python/tests/utils/helpers.py b/src/bindings/python/tests/utils/helpers.py
index 9185bdf6594..e74ec15d9be 100644
--- a/src/bindings/python/tests/utils/helpers.py
+++ b/src/bindings/python/tests/utils/helpers.py
@@ -19,7 +19,8 @@ from openvino import Model, Core, Shape, Tensor, Type
import openvino.opset13 as ops
-def _compare_models(model_one: Model, model_two: Model, compare_names: bool = True) -> tuple[bool, str]: # noqa: C901 the function is too complex
+# noqa: C901 the function is too complex
+def _compare_models(model_one: Model, model_two: Model, compare_names: bool = True) -> tuple[bool, str]:
"""Function to compare OpenVINO model (ops names, types and shapes).
Note that the functions uses get_ordered_ops, so the topological order of ops should be also preserved.
@@ -280,7 +281,9 @@ def generate_concat_compiled_model(device, input_shape: list[int] = None, ov_typ
return core.compile_model(model, device)
-def generate_concat_compiled_model_with_data(device, input_shape: list[int] = None, ov_type=Type.f32, numpy_dtype=np.float32):
+def generate_concat_compiled_model_with_data(
+ device, input_shape: list[int] = None, ov_type=Type.f32, numpy_dtype=np.float32
+):
if input_shape is None:
input_shape = [5]