Merge branch 'openvinotoolkit:master' into smyk-mxnet

This commit is contained in:
Maciej Smyk 2022-06-14 07:53:56 +02:00 committed by GitHub
commit 30bf39a9b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
149 changed files with 2548 additions and 1944 deletions

View File

@ -0,0 +1,3 @@
[tool.black]
line-length = 160
include = '\.pyi?$'

View File

@ -33,7 +33,11 @@ deps = -rrequirements.txt
[flake8]
# ignore:
# A001 variable "var_name" is shadowing a python builtin
# A002 argument "..." is shadowing a python builtin
# CCE001 ClassName.method1 should be after ClassName.method2
# D100 - Missing docstring in public module
# D101 - Missing docstring in public class
# D102 - Missing docstring in public method
# D103 - Missing docstring in public function
# D104 - Missing docstring in public package
@ -41,8 +45,17 @@ deps = -rrequirements.txt
# D107 - Missing docstring in __init__
# D412 - No blank lines allowed between a section header and its content
# F401 - module imported but unused
# N803 - argument name '...' should be lowercase
# T001 - print found
# W503 - line break before binary operator (prefer line breaks before op, not after)
ignore=D100,D102,D103,D104,D105,D107,D412,F401,W503
# RST301 - Unexpected indentation
# TAE002 - too complex annotation
# PT007 - wrong values type @pytest.mark.parametrize, expected list of tuples
# PT012 - pytest.raises() block should contain a single simple statement
# VNE001 - single letter variable names like 'X' are not allowed
# VNE003 - variable names that shadow builtins are not allowed
ignore=A001,A002,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
@ -51,12 +64,9 @@ show_source = True
docstring-convention = google
enable-extensions = G
per-file-ignores =
# todo: will be fixed as part of 81803
tests/*: A001,C101,C812,C815,C816,C819,CCE001,D100,D101,D102,D103,D104,D105,D107,D212,E800,ECE001,N400,N802,N806,P101,P103,PT001,PT005,PT006,PT007,PT011,PT012,PT019,PT023,RST201,RST301,S001,T001,VNE001,VNE002,VNE003,W503
tests_compatibility/test_ngraph/*: A001,C101,C812,C815,C816,C819,CCE001,D100,D101,D102,D103,D104,D105,D107,D212,E800,ECE001,N400,N802,N806,P101,P103,PT001,PT005,PT006,PT007,PT011,PT012,PT019,PT023,RST201,RST301,S001,T001,VNE001,VNE002,VNE003,W503
src/compatibility/ngraph/*: A001,A002,C101,C812,C819,CCE001,E800,N803,N806,P101,RST201,RST202,RST203,RST206,RST301,T001,TAE002,VNE001,VNE003
# todo: will be fixed as part of 81803
src/openvino/*: A001,A002,C101,C812,C819,CCE001,E402,E800,N803,N806,P101,RST201,RST202,RST203,RST205,RST206,RST299,RST301,T001,TAE002,VNE001,VNE002,VNE003
src/openvino/runtime/*/ops.py: VNE001,VNE003
tests_compatibility/test_ngraph/*: C101,C812,C815,C816,C819,CCE001,D212,E800,ECE001,N400,N802,N806,P101,P103,PT001,PT005,PT006,PT011,PT019,PT023,RST201,S001,VNE002
src/compatibility/ngraph/*: C101,C812,C819,CCE001,E800,N806,P101,RST201,RST202,RST203,RST206,VNE001,VNE003
[pydocstyle]
convention = google

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -7,6 +8,7 @@
from openvino.utils import add_openvino_libs_to_path
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution("openvino-core").version
except DistributionNotFound:
@ -65,6 +67,7 @@ from openvino.pyopenvino import properties
from openvino.runtime.ie_api import tensor_from_file
from openvino.runtime.ie_api import compile_model
# Extend Node class to support binary operators
Node.__add__ = opset9.add
Node.__sub__ = opset9.subtract

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -22,9 +23,7 @@ def tensor_from_file(path: str) -> Tensor:
return Tensor(np.fromfile(path, dtype=np.uint8))
def set_scalar_tensor(
request: InferRequestBase, tensor: Tensor, key: Union[str, int, ConstOutput] = None
) -> None:
def set_scalar_tensor(request: InferRequestBase, tensor: Tensor, key: Union[str, int, ConstOutput] = None) -> None:
if key is None:
request.set_input_tensor(tensor)
elif isinstance(key, int):
@ -32,9 +31,7 @@ def set_scalar_tensor(
elif isinstance(key, (str, ConstOutput)):
request.set_tensor(key, tensor)
else:
raise TypeError(
"Unsupported key type: {} for Tensor under key: {}".format(type(key), key)
)
raise TypeError(f"Unsupported key type: {type(key)} for Tensor under key: {key}")
@singledispatch
@ -43,9 +40,7 @@ def update_tensor(
request: InferRequestBase,
key: Union[str, int, ConstOutput] = None,
) -> None:
raise TypeError(
"Incompatible input data of type {} under {} key!".format(type(inputs), key)
)
raise TypeError(f"Incompatible input data of type {type(inputs)} under {key} key!")
@update_tensor.register(np.ndarray)
@ -65,11 +60,7 @@ def _(
elif isinstance(key, (str, ConstOutput)):
tensor = request.get_tensor(key)
else:
raise TypeError(
"Unsupported key type: {} for Tensor under key: {}".format(
type(key), key
)
)
raise TypeError(f"Unsupported key type: {type(key)} for Tensor under key: {key}")
# Update shape if there is a mismatch
if tensor.shape != inputs.shape:
tensor.shape = inputs.shape
@ -86,7 +77,7 @@ def _(
key: Union[str, int, ConstOutput] = None,
) -> None:
set_scalar_tensor(
request, Tensor(np.ndarray([], type(inputs), np.array(inputs))), key
request, Tensor(np.ndarray([], type(inputs), np.array(inputs))), key,
)
@ -100,29 +91,25 @@ def normalize_inputs(request: InferRequestBase, inputs: dict) -> dict:
# new_inputs will be used to transfer data to inference calls,
# ensuring that original inputs are not overwritten with Tensors.
new_inputs: Dict[Union[str, int, ConstOutput], Tensor] = {}
for k, val in inputs.items():
if not isinstance(k, (str, int, ConstOutput)):
raise TypeError("Incompatible key type for input: {}".format(k))
for key, value in inputs.items():
if not isinstance(key, (str, int, ConstOutput)):
raise TypeError(f"Incompatible key type for input: {key}")
# Copy numpy arrays to already allocated Tensors.
if isinstance(val, (np.ndarray, np.number, int, float)):
update_tensor(val, request, k)
if isinstance(value, (np.ndarray, np.number, int, float)):
update_tensor(value, request, key)
# If value is of Tensor type, put it into temporary dictionary.
elif isinstance(val, Tensor):
new_inputs[k] = val
elif isinstance(value, Tensor):
new_inputs[key] = value
# Throw error otherwise.
else:
raise TypeError(
"Incompatible input data of type {} under {} key!".format(type(val), k)
)
raise TypeError(f"Incompatible input data of type {type(value)} under {key} key!")
return new_inputs
class InferRequest(InferRequestBase):
"""InferRequest class represents infer request which can be run in asynchronous or synchronous manners."""
def infer(
self, inputs: Union[dict, list, tuple, Tensor, np.ndarray] = None
) -> dict:
def infer(self, inputs: Union[dict, list, tuple, Tensor, np.ndarray] = None) -> dict:
"""Infers specified input(s) in synchronous mode.
Blocks all methods of InferRequest while request is running.
@ -158,10 +145,7 @@ class InferRequest(InferRequestBase):
# It is an extension of above branch with dict inputs.
elif isinstance(inputs, (list, tuple)):
return super().infer(
normalize_inputs(
self, {index: input for index, input in enumerate(inputs)}
)
)
normalize_inputs(self, {index: input for index, input in enumerate(inputs)}))
# If inputs are Tensor, call infer method directly.
elif isinstance(inputs, Tensor):
return super().infer(inputs)
@ -211,11 +195,7 @@ class InferRequest(InferRequestBase):
super().start_async(normalize_inputs(self, inputs), userdata)
elif isinstance(inputs, (list, tuple)):
super().start_async(
normalize_inputs(
self, {index: input for index, input in enumerate(inputs)}
),
userdata,
)
normalize_inputs(self, {index: input for index, input in enumerate(inputs)}), userdata)
elif isinstance(inputs, Tensor):
super().start_async(inputs, userdata)
elif isinstance(inputs, (np.ndarray, np.number, int, float)):
@ -242,9 +222,7 @@ class CompiledModel(CompiledModelBase):
"""
return InferRequest(super().create_infer_request())
def infer_new_request(
self, inputs: Union[dict, list, tuple, Tensor, np.ndarray] = None
) -> dict:
def infer_new_request(self, inputs: Union[dict, list, tuple, Tensor, np.ndarray] = None) -> dict:
"""Infers specified input(s) in synchronous mode.
Blocks all methods of CompiledModel while request is running.
@ -292,7 +270,6 @@ class AsyncInferQueue(AsyncInferQueueBase):
InferRequests and provides synchronization functions to control flow of
a simple pipeline.
"""
def __getitem__(self, i: int) -> InferRequest:
"""Gets InferRequest from the pool with given i id.
@ -334,7 +311,7 @@ class AsyncInferQueue(AsyncInferQueueBase):
super().start_async({}, userdata)
elif isinstance(inputs, dict):
super().start_async(
normalize_inputs(self[self.get_idle_request_id()], inputs), userdata
normalize_inputs(self[self.get_idle_request_id()], inputs), userdata,
)
elif isinstance(inputs, (list, tuple)):
super().start_async
@ -364,7 +341,7 @@ class Core(CoreBase):
"""
def compile_model(
self, model: Union[Model, str], device_name: str = None, config: dict = None
self, model: Union[Model, str], device_name: str = None, config: dict = None,
) -> CompiledModel:
"""Creates a compiled model.
@ -389,15 +366,15 @@ class Core(CoreBase):
"""
if device_name is None:
return CompiledModel(
super().compile_model(model, {} if config is None else config)
super().compile_model(model, {} if config is None else config),
)
return CompiledModel(
super().compile_model(model, device_name, {} if config is None else config)
super().compile_model(model, device_name, {} if config is None else config),
)
def import_model(
self, model_stream: bytes, device_name: str, config: dict = None
self, model_stream: bytes, device_name: str, config: dict = None,
) -> CompiledModel:
"""Imports a compiled model from a previously exported one.
@ -414,6 +391,7 @@ class Core(CoreBase):
:rtype: openvino.runtime.CompiledModel
:Example:
.. code-block:: python
user_stream = compiled.export_model()
@ -439,8 +417,8 @@ class Core(CoreBase):
"""
return CompiledModel(
super().import_model(
model_stream, device_name, {} if config is None else config
)
model_stream, device_name, {} if config is None else config,
),
)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -68,7 +69,7 @@ def add(
) -> Node:
"""Return node which applies f(x) = A+B to the input nodes element-wise."""
return _get_node_factory_opset1().create(
"Add", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Add", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -230,7 +231,7 @@ def broadcast(
if mode.upper() == "EXPLICIT":
inputs.append(as_node(axes_mapping))
return _get_node_factory_opset1().create(
"Broadcast", inputs, {"mode": mode.upper()}
"Broadcast", inputs, {"mode": mode.upper()},
)
@ -251,7 +252,7 @@ def ctc_greedy_decoder(
"""
node_inputs = as_nodes(data, sequence_mask)
return _get_node_factory_opset1().create(
"CTCGreedyDecoder", node_inputs, {"ctc_merge_repeated": merge_repeated}
"CTCGreedyDecoder", node_inputs, {"ctc_merge_repeated": merge_repeated},
)
@ -268,7 +269,10 @@ def ceiling(node: NodeInput, name: Optional[str] = None) -> Node:
@nameable_op
def clamp(
data: NodeInput, min_value: ScalarData, max_value: ScalarData, name: Optional[str] = None
data: NodeInput,
min_value: ScalarData,
max_value: ScalarData,
name: Optional[str] = None,
) -> Node:
"""Perform clamp element-wise on data from input node.
@ -295,7 +299,7 @@ def clamp(
data=max_value
"""
return _get_node_factory_opset1().create(
"Clamp", [as_node(data)], {"min": min_value, "max": max_value}
"Clamp", [as_node(data)], {"min": min_value, "max": max_value},
)
@ -329,7 +333,9 @@ def constant(
@nameable_op
def convert(
data: NodeInput, destination_type: Union[str, NumericType], name: Optional[str] = None
data: NodeInput,
destination_type: Union[str, NumericType],
name: Optional[str] = None,
) -> Node:
"""Return node which casts input node values to specified type.
@ -341,7 +347,7 @@ def convert(
if not isinstance(destination_type, str):
destination_type = get_element_type_str(destination_type)
return _get_node_factory_opset1().create(
"Convert", [as_node(data)], {"destination_type": destination_type.lower()}
"Convert", [as_node(data)], {"destination_type": destination_type.lower()},
)
@ -595,7 +601,9 @@ def depth_to_space(node: Node, mode: str, block_size: int = 1, name: str = None)
:return: The new node performing an DepthToSpace operation on its input tensor.
"""
return _get_node_factory_opset1().create(
"DepthToSpace", [node], {"mode": mode, "block_size": block_size},
"DepthToSpace",
[node],
{"mode": mode, "block_size": block_size},
)
@ -650,6 +658,7 @@ def detection_output(
* code_type The type of coding method for bounding boxes.
Range of values: {'caffe.PriorBoxParameter.CENTER_SIZE',
'caffe.PriorBoxParameter.CORNER'}
Default value: 'caffe.PriorBoxParameter.CORNER'
Required: no
@ -717,6 +726,7 @@ def detection_output(
'num_classes': 85,
'keep_top_k': [1, 2, 3],
'nms_threshold': 0.645,
}
attrs = {
@ -727,6 +737,7 @@ def detection_output(
'clip_before_nms': True,
'input_height': [32],
'input_width': [32],
}
Optional attributes which are absent from dictionary will be set with corresponding default.
@ -777,7 +788,7 @@ def divide(
:return: The node performing element-wise division.
"""
return _get_node_factory_opset1().create(
"Divide", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Divide", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -815,7 +826,7 @@ def equal(
:return: The node performing element-wise equality check.
"""
return _get_node_factory_opset1().create(
"Equal", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Equal", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -879,8 +890,7 @@ def fake_quantize(
\f[ output =
\dfrac{round( \dfrac{data - input\_low}{(input\_high - input\_low)\cdot (levels-1)})}
{(levels-1)\cdot (output\_high - output\_low)} + output\_low
\f]
{(levels-1)\cdot (output\_high - output\_low)} + output\_low \f]
"""
return _get_node_factory_opset1().create(
"FakeQuantize",
@ -916,13 +926,13 @@ def floor_mod(
:return: The node performing element-wise FloorMod operation.
"""
return _get_node_factory_opset1().create(
"FloorMod", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"FloorMod", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@nameable_op
def gather(
data: NodeInput, indices: NodeInput, axis: NodeInput, name: Optional[str] = None
data: NodeInput, indices: NodeInput, axis: NodeInput, name: Optional[str] = None,
) -> Node:
"""Return Gather node which takes slices from axis of data according to indices.
@ -991,7 +1001,7 @@ def greater(
:return: The node performing element-wise check whether left_node is greater than right_node.
"""
return _get_node_factory_opset1().create(
"Greater", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Greater", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -1009,11 +1019,13 @@ def greater_equal(
:param auto_broadcast: The type of broadcasting specifies rules used for
auto-broadcasting of input tensors.
:param name: The optional new name for output node.
:return: The node performing element-wise check whether left_node is greater than or equal
right_node.
:return: The node performing element-wise check whether left_node is greater than or equal right_node.
"""
return _get_node_factory_opset1().create(
"GreaterEqual", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"GreaterEqual",
[left_node, right_node],
{"auto_broadcast": auto_broadcast.upper()},
)
@ -1055,11 +1067,13 @@ def group_convolution(
:param auto_pad: Describes how to perform padding. Possible values:
EXPLICIT: Pad dimensions are explicity specified
SAME_LOWER: Pad dimensions computed to match input shape
Ceil(num_dims/2) at the beginning and
Floor(num_dims/2) at the end
Ceil(num_dims/2) at the beginning and
Floor(num_dims/2) at the end
SAME_UPPER: Pad dimensions computed to match input shape
Floor(num_dims/2) at the beginning and
Ceil(num_dims/2) at the end
VALID: No padding
:param name: Optional output node name.
:return: The new node performing a Group Convolution operation on tensor from input node.
@ -1104,12 +1118,15 @@ def group_convolution_backprop_data(
:param auto_pad: Describes how to perform padding. Possible values:
EXPLICIT: Pad dimensions are explicity specified
SAME_LOWER: Pad dimensions computed to match input shape
Ceil(num_dims/2) at the beginning and
Floor(num_dims/2) at the end
Ceil(num_dims/2) at the beginning and
Floor(num_dims/2) at the end
SAME_UPPER: Pad dimensions computed to match input shape
Floor(num_dims/2) at the beginning and
Ceil(num_dims/2) at the end
VALID: No padding
:param output_padding: The additional amount of paddings added per each spatial axis
in the output tensor.
:param name: Optional output node name.
@ -1143,7 +1160,9 @@ def group_convolution_backprop_data(
@nameable_op
def hard_sigmoid(data: Node, alpha: NodeInput, beta: NodeInput, name: Optional[str] = None) -> Node:
def hard_sigmoid(
data: Node, alpha: NodeInput, beta: NodeInput, name: Optional[str] = None,
) -> Node:
"""Perform Hard Sigmoid operation element-wise on data from input node.
:param data: The node with data tensor.
@ -1163,7 +1182,7 @@ def hard_sigmoid(data: Node, alpha: NodeInput, beta: NodeInput, name: Optional[s
@nameable_op
def interpolate(
image: Node, output_shape: NodeInput, attrs: dict, name: Optional[str] = None
image: Node, output_shape: NodeInput, attrs: dict, name: Optional[str] = None,
) -> Node:
"""Perform interpolation of independent slices in input tensor.
@ -1192,6 +1211,7 @@ def interpolate(
* antialias A flag that specifies whether to perform anti-aliasing.
Range of values: False - do not perform anti-aliasing
True - perform anti-aliasing
Default value: False
Required: no
@ -1221,6 +1241,7 @@ def interpolate(
'antialias': True,
'pads_begin': [2, 2, 2],
}
Optional attributes which are absent from dictionary will be set with corresponding default.
"""
requirements = [
@ -1254,7 +1275,7 @@ def less(
:return: The node performing element-wise check whether left_node is less than the right_node.
"""
return _get_node_factory_opset1().create(
"Less", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Less", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -1276,7 +1297,7 @@ def less_equal(
right_node.
"""
return _get_node_factory_opset1().create(
"LessEqual", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"LessEqual", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -1308,7 +1329,9 @@ def logical_and(
:return: The node performing logical and operation on input nodes corresponding elements.
"""
return _get_node_factory_opset1().create(
"LogicalAnd", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"LogicalAnd",
[left_node, right_node],
{"auto_broadcast": auto_broadcast.upper()},
)
@ -1340,7 +1363,7 @@ def logical_or(
:return: The node performing logical or operation on input nodes corresponding elements.
"""
return _get_node_factory_opset1().create(
"LogicalOr", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"LogicalOr", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -1361,7 +1384,9 @@ def logical_xor(
:return: The node performing logical or operation on input nodes corresponding elements.
"""
return _get_node_factory_opset1().create(
"LogicalXor", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"LogicalXor",
[left_node, right_node],
{"auto_broadcast": auto_broadcast.upper()},
)
@ -1428,15 +1453,22 @@ def lstm_cell(
if activations_beta is None:
activations_beta = []
node_inputs = as_nodes(X, initial_hidden_state, initial_cell_state, W, R, B)
node_inputs = as_nodes(
X,
initial_hidden_state,
initial_cell_state,
W,
R,
B,
)
# P - nGraph additional input, no such input in the OV spec
peepholes_count = 3 # nGraph default
peepholes_shape = [peepholes_count * hidden_size]
peepholes_array = np.zeros(peepholes_shape) # nGraph default
data_dtype = get_dtype(node_inputs[0].get_output_element_type(0))
default_P = make_constant_node(peepholes_array, dtype=data_dtype)
node_inputs.append(default_P)
default_p = make_constant_node(peepholes_array, dtype=data_dtype)
node_inputs.append(default_p)
weights_format = "fico" # IE LSTMWeightsFormat, no such attribute in the OV spec
input_forget = False # nGraph default, no such attribute in the OV spec
@ -1502,7 +1534,15 @@ def lstm_sequence(
if activations_beta is None:
activations_beta = []
node_inputs = as_nodes(X, initial_hidden_state, initial_cell_state, sequence_lengths, W, R, B)
node_inputs = as_nodes(
X,
initial_hidden_state,
initial_cell_state,
sequence_lengths,
W,
R,
B,
)
# P - nGraph additional input, no such input in the OV spec
peepholes_count = 3 # nGraph default
@ -1513,8 +1553,8 @@ def lstm_sequence(
peepholes_shape = [num_directions, peepholes_count * hidden_size]
peepholes_array = np.zeros(peepholes_shape) # nGraph default
data_dtype = get_dtype(node_inputs[0].get_output_element_type(0))
default_P = make_constant_node(peepholes_array, dtype=data_dtype)
node_inputs.append(default_P)
default_p = make_constant_node(peepholes_array, dtype=data_dtype)
node_inputs.append(default_p)
weights_format = "fico" # IE LSTMWeightsFormat, no such attribute in the OV spec
input_forget = False # nGraph default, no such attribute in the OV spec
@ -1549,7 +1589,9 @@ def matmul(
:return: MatMul operation node
"""
return _get_node_factory_opset1().create(
"MatMul", as_nodes(data_a, data_b), {"transpose_a": transpose_a, "transpose_b": transpose_b}
"MatMul",
as_nodes(data_a, data_b),
{"transpose_a": transpose_a, "transpose_b": transpose_b},
)
@ -1605,7 +1647,7 @@ def maximum(
) -> Node:
"""Return node which applies the maximum operation to input nodes elementwise."""
return _get_node_factory_opset1().create(
"Maximum", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Maximum", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -1618,7 +1660,7 @@ def minimum(
) -> Node:
"""Return node which applies the minimum operation to input nodes elementwise."""
return _get_node_factory_opset1().create(
"Minimum", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Minimum", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -1638,7 +1680,7 @@ def mod(
:return: The node performing element-wise Mod operation.
"""
return _get_node_factory_opset1().create(
"Mod", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Mod", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -1651,7 +1693,7 @@ def multiply(
) -> Node:
"""Return node which applies f(x) = A*B to the input nodes elementwise."""
return _get_node_factory_opset1().create(
"Multiply", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Multiply", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -1703,7 +1745,11 @@ def non_max_suppression(
@nameable_op
def normalize_l2(
data: NodeInput, axes: NodeInput, eps: float, eps_mode: str, name: Optional[str] = None
data: NodeInput,
axes: NodeInput,
eps: float,
eps_mode: str,
name: Optional[str] = None,
) -> Node:
"""Construct an NormalizeL2 operation.
@ -1714,7 +1760,7 @@ def normalize_l2(
:return: New node which performs the L2 normalization.
"""
return _get_node_factory_opset1().create(
"NormalizeL2", as_nodes(data, axes), {"eps": eps, "mode": eps_mode}
"NormalizeL2", as_nodes(data, axes), {"eps": eps, "mode": eps_mode},
)
@ -1735,7 +1781,7 @@ def not_equal(
:return: The node performing element-wise inequality check.
"""
return _get_node_factory_opset1().create(
"NotEqual", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"NotEqual", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -1762,7 +1808,7 @@ def one_hot(
:return: New node performing one-hot operation.
"""
return _get_node_factory_opset1().create(
"OneHot", as_nodes(indices, depth, on_value, off_value), {"axis": axis}
"OneHot", as_nodes(indices, depth, on_value, off_value), {"axis": axis},
)
@ -1795,13 +1841,15 @@ def pad(
@nameable_op
def parameter(
shape: TensorShape, dtype: Union[NumericType, Type] = np.float32, name: Optional[str] = None
shape: TensorShape,
dtype: Union[NumericType, Type] = np.float32,
name: Optional[str] = None,
) -> Parameter:
"""Return an openvino Parameter object."""
return Parameter(get_element_type(dtype)
if isinstance(dtype, (type, np.dtype))
else dtype,
PartialShape(shape))
return Parameter(
get_element_type(dtype) if isinstance(dtype, (type, np.dtype)) else dtype,
PartialShape(shape),
)
@binary_op
@ -1821,7 +1869,7 @@ def power(
:return: The new node performing element-wise exponentiation operation on input nodes.
"""
return _get_node_factory_opset1().create(
"Power", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Power", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -1848,7 +1896,7 @@ def prelu(data: NodeInput, slope: NodeInput, name: Optional[str] = None) -> Node
@nameable_op
def prior_box_clustered(
output_size: Node, image_size: NodeInput, attrs: dict, name: Optional[str] = None
output_size: Node, image_size: NodeInput, attrs: dict, name: Optional[str] = None,
) -> Node:
"""Generate prior boxes of specified sizes normalized to the input image size.
@ -1928,13 +1976,13 @@ def prior_box_clustered(
check_valid_attributes("PriorBoxClustered", attrs, requirements)
return _get_node_factory_opset1().create(
"PriorBoxClustered", [output_size, as_node(image_size)], attrs
"PriorBoxClustered", [output_size, as_node(image_size)], attrs,
)
@nameable_op
def prior_box(
layer_shape: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None
layer_shape: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None,
) -> Node:
"""Generate prior boxes of specified sizes and aspect ratios across all dimensions.
@ -1991,6 +2039,7 @@ def prior_box(
* scale_all_sizes The flag that denotes type of inference.
Range of values: False - max_size is ignored
True - max_size is used
Default value: True
Required: no
@ -2044,7 +2093,9 @@ def prior_box(
check_valid_attributes("PriorBox", attrs, requirements)
return _get_node_factory_opset1().create("PriorBox", [layer_shape, as_node(image_shape)], attrs)
return _get_node_factory_opset1().create(
"PriorBox", [layer_shape, as_node(image_shape)], attrs,
)
@nameable_op
@ -2062,6 +2113,7 @@ def proposal(
:param image_shape: The 1D input tensor with 3 or 4 elements describing image shape.
:param attrs: The dictionary containing key, value pairs for attributes.
:param name: Optional name for the output node.
:return: Node representing Proposal operation.
* base_size The size of the anchor to which scale and ratio attributes are applied.
@ -2137,6 +2189,7 @@ def proposal(
Range of values: "" (empty string) - calculate box coordinates like in Caffe*
tensorflow - calculate box coordinates like in the TensorFlow*
Object Detection API models
Default value: "" (empty string)
Required: no
@ -2157,6 +2210,7 @@ def proposal(
}
Optional attributes which are absent from dictionary will be set with corresponding default.
"""
requirements = [
("base_size", True, np.unsignedinteger, is_positive_value),
@ -2178,7 +2232,9 @@ def proposal(
check_valid_attributes("Proposal", attrs, requirements)
return _get_node_factory_opset1().create(
"Proposal", [class_probs, bbox_deltas, as_node(image_shape)], attrs
"Proposal",
[class_probs, bbox_deltas, as_node(image_shape)],
attrs,
)
@ -2222,7 +2278,12 @@ def psroi_pooling(
@nameable_op
def range(start: Node, stop: NodeInput, step: NodeInput, name: Optional[str] = None) -> Node:
def range(
start: Node,
stop: NodeInput,
step: NodeInput,
name: Optional[str] = None,
) -> Node:
"""Return a node which produces the Range operation.
:param start: The start value of the generated range.
@ -2247,7 +2308,10 @@ def relu(node: NodeInput, name: Optional[str] = None) -> Node:
@nameable_op
def reduce_logical_and(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
node: NodeInput,
reduction_axes: NodeInput,
keep_dims: bool = False,
name: Optional[str] = None,
) -> Node:
"""Logical AND reduction operation on input tensor, eliminating the specified reduction axes.
@ -2258,13 +2322,16 @@ def reduce_logical_and(
:return: The new node performing reduction operation.
"""
return _get_node_factory_opset1().create(
"ReduceLogicalAnd", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
"ReduceLogicalAnd", as_nodes(node, reduction_axes), {"keep_dims": keep_dims},
)
@nameable_op
def reduce_logical_or(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
node: NodeInput,
reduction_axes: NodeInput,
keep_dims: bool = False,
name: Optional[str] = None,
) -> Node:
"""Logical OR reduction operation on input tensor, eliminating the specified reduction axes.
@ -2275,13 +2342,16 @@ def reduce_logical_or(
:return: The new node performing reduction operation.
"""
return _get_node_factory_opset1().create(
"ReduceLogicalOr", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
"ReduceLogicalOr", as_nodes(node, reduction_axes), {"keep_dims": keep_dims},
)
@nameable_op
def reduce_max(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
node: NodeInput,
reduction_axes: NodeInput,
keep_dims: bool = False,
name: Optional[str] = None,
) -> Node:
"""Max-reduction operation on input tensor, eliminating the specified reduction axes.
@ -2291,13 +2361,16 @@ def reduce_max(
:param name: Optional name for output node.
"""
return _get_node_factory_opset1().create(
"ReduceMax", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
"ReduceMax", as_nodes(node, reduction_axes), {"keep_dims": keep_dims},
)
@nameable_op
def reduce_mean(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
node: NodeInput,
reduction_axes: NodeInput,
keep_dims: bool = False,
name: Optional[str] = None,
) -> Node:
"""Mean-reduction operation on input tensor, eliminating the specified reduction axes.
@ -2308,13 +2381,16 @@ def reduce_mean(
:return: The new node performing mean-reduction operation.
"""
return _get_node_factory_opset1().create(
"ReduceMean", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
"ReduceMean", as_nodes(node, reduction_axes), {"keep_dims": keep_dims},
)
@nameable_op
def reduce_min(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
node: NodeInput,
reduction_axes: NodeInput,
keep_dims: bool = False,
name: Optional[str] = None,
) -> Node:
"""Min-reduction operation on input tensor, eliminating the specified reduction axes.
@ -2324,13 +2400,16 @@ def reduce_min(
:param name: Optional name for output node.
"""
return _get_node_factory_opset1().create(
"ReduceMin", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
"ReduceMin", as_nodes(node, reduction_axes), {"keep_dims": keep_dims},
)
@nameable_op
def reduce_prod(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
node: NodeInput,
reduction_axes: NodeInput,
keep_dims: bool = False,
name: Optional[str] = None,
) -> Node:
"""Product-reduction operation on input tensor, eliminating the specified reduction axes.
@ -2341,13 +2420,16 @@ def reduce_prod(
:return: The new node performing product-reduction operation.
"""
return _get_node_factory_opset1().create(
"ReduceProd", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
"ReduceProd", as_nodes(node, reduction_axes), {"keep_dims": keep_dims},
)
@nameable_op
def reduce_sum(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
node: NodeInput,
reduction_axes: NodeInput,
keep_dims: bool = False,
name: Optional[str] = None,
) -> Node:
"""Perform element-wise sums of the input tensor, eliminating the specified reduction axes.
@ -2358,7 +2440,7 @@ def reduce_sum(
:return: The new node performing summation along `reduction_axes` element-wise.
"""
return _get_node_factory_opset1().create(
"ReduceSum", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
"ReduceSum", as_nodes(node, reduction_axes), {"keep_dims": keep_dims},
)
@ -2410,7 +2492,10 @@ def region_yolo(
@nameable_op
def reshape(
node: NodeInput, output_shape: NodeInput, special_zero: bool, name: Optional[str] = None
node: NodeInput,
output_shape: NodeInput,
special_zero: bool,
name: Optional[str] = None,
) -> Node:
"""Return reshaped node according to provided parameters.
@ -2425,7 +2510,7 @@ def reshape(
Range of values: False or True
"""
return _get_node_factory_opset1().create(
"Reshape", as_nodes(node, output_shape), {"special_zero": special_zero}
"Reshape", as_nodes(node, output_shape), {"special_zero": special_zero},
)
@ -2483,15 +2568,16 @@ def select(
"""
inputs = as_nodes(cond, then_node, else_node)
return _get_node_factory_opset1().create(
"Select",
inputs,
{"auto_broadcast": auto_broadcast.upper()}
"Select", inputs, {"auto_broadcast": auto_broadcast.upper()},
)
@nameable_op
def selu(
data: NodeInput, alpha: NodeInput, lambda_value: NodeInput, name: Optional[str] = None
data: NodeInput,
alpha: NodeInput,
lambda_value: NodeInput,
name: Optional[str] = None,
) -> Node:
"""Perform a Scaled Exponential Linear Unit (SELU) operation on input node element-wise.
@ -2501,7 +2587,9 @@ def selu(
:param name: The optional output node name.
:return: The new node performing relu operation on its input element-wise.
"""
return _get_node_factory_opset1().create("Selu", as_nodes(data, alpha, lambda_value))
return _get_node_factory_opset1().create(
"Selu", as_nodes(data, alpha, lambda_value),
)
@nameable_op
@ -2588,7 +2676,9 @@ def space_to_depth(data: Node, mode: str, block_size: int = 1, name: str = None)
:return: The new node performing a SpaceToDepth operation on input tensor.
"""
return _get_node_factory_opset1().create(
"SpaceToDepth", [data], {"mode": mode, "block_size": block_size},
"SpaceToDepth",
[data],
{"mode": mode, "block_size": block_size},
)
@ -2602,9 +2692,7 @@ def split(data: NodeInput, axis: NodeInput, num_splits: int, name: Optional[str]
:return: Split node
"""
return _get_node_factory_opset1().create(
"Split",
as_nodes(data, axis),
{"num_splits": num_splits}
"Split", as_nodes(data, axis), {"num_splits": num_splits},
)
@ -2621,7 +2709,10 @@ def sqrt(node: NodeInput, name: Optional[str] = None) -> Node:
@binary_op
def squared_difference(
x1: NodeInput, x2: NodeInput, auto_broadcast: str = "NUMPY", name: Optional[str] = None
x1: NodeInput,
x2: NodeInput,
auto_broadcast: str = "NUMPY",
name: Optional[str] = None,
) -> Node:
r"""Perform an element-wise squared difference between two tensors.
@ -2635,7 +2726,7 @@ def squared_difference(
:return: The new node performing a squared difference between two tensors.
"""
return _get_node_factory_opset1().create(
"SquaredDifference", [x1, x2], {"auto_broadcast": auto_broadcast.upper()}
"SquaredDifference", [x1, x2], {"auto_broadcast": auto_broadcast.upper()},
)
@ -2707,7 +2798,7 @@ def strided_slice(
}
return _get_node_factory_opset1().create(
"StridedSlice", as_nodes(data, begin, end, strides), attributes
"StridedSlice", as_nodes(data, begin, end, strides), attributes,
)
@ -2728,7 +2819,7 @@ def subtract(
:return: The new output node performing subtraction operation on both tensors element-wise.
"""
return _get_node_factory_opset1().create(
"Subtract", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
"Subtract", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()},
)
@ -2821,7 +2912,10 @@ def unsqueeze(data: NodeInput, axes: NodeInput, name: Optional[str] = None) -> N
@nameable_op
def variadic_split(
data: NodeInput, axis: NodeInput, split_lengths: NodeInput, name: Optional[str] = None
data: NodeInput,
axis: NodeInput,
split_lengths: NodeInput,
name: Optional[str] = None,
) -> Node:
"""Return a node which splits the input tensor into variadic length slices.
@ -2830,4 +2924,6 @@ def variadic_split(
:param split_lengths: Sizes of the output tensors along the split axis
:return: VariadicSplit node
"""
return _get_node_factory_opset1().create("VariadicSplit", as_nodes(data, axis, split_lengths))
return _get_node_factory_opset1().create(
"VariadicSplit", as_nodes(data, axis, split_lengths),
)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -57,7 +58,7 @@ def batch_to_space(
:return: The new node performing a BatchToSpace operation.
"""
return _get_node_factory_opset2().create(
"BatchToSpace", as_nodes(data, block_shape, crops_begin, crops_end)
"BatchToSpace", as_nodes(data, block_shape, crops_begin, crops_end),
)
@ -103,7 +104,11 @@ def mvn(
return _get_node_factory_opset2().create(
"MVN",
[data],
{"across_channels": across_channels, "normalize_variance": normalize_variance, "eps": eps},
{
"across_channels": across_channels,
"normalize_variance": normalize_variance,
"eps": eps,
},
)
@ -141,7 +146,11 @@ def roi_pooling(
return _get_node_factory_opset2().create(
"ROIPooling",
as_nodes(input, coords),
{"output_size": Shape(output_size), "spatial_scale": spatial_scale, "method": method},
{
"output_size": Shape(output_size),
"spatial_scale": spatial_scale,
"method": method,
},
)
@ -167,5 +176,5 @@ def space_to_batch(
:return: The new node performing a SpaceToBatch operation.
"""
return _get_node_factory_opset2().create(
"SpaceToBatch", as_nodes(data, block_shape, pads_begin, pads_end)
"SpaceToBatch", as_nodes(data, block_shape, pads_begin, pads_end),
)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -49,7 +50,7 @@ def assign(new_value: NodeInput, variable_id: str, name: Optional[str] = None) -
return _get_node_factory_opset3().create(
"Assign",
[as_node(new_value)],
{"variable_id": variable_id}
{"variable_id": variable_id},
)
@ -76,7 +77,7 @@ def broadcast(
if broadcast_spec.upper() == "EXPLICIT":
inputs.append(as_node(axes_mapping))
return _get_node_factory_opset3().create(
"Broadcast", inputs, {"mode": broadcast_spec.upper()}
"Broadcast", inputs, {"mode": broadcast_spec.upper()},
)
@ -122,7 +123,7 @@ def cum_sum(
:return: New node performing the operation
"""
return _get_node_factory_opset3().create(
"CumSum", as_nodes(arg, axis), {"exclusive": exclusive, "reverse": reverse}
"CumSum", as_nodes(arg, axis), {"exclusive": exclusive, "reverse": reverse},
)
@ -353,7 +354,7 @@ def non_max_suppression(
@nameable_op
def non_zero(data: NodeInput, output_type: str = "i64", name: Optional[str] = None,) -> Node:
def non_zero(data: NodeInput, output_type: str = "i64", name: Optional[str] = None) -> Node:
"""Return the indices of the elements that are non-zero.
:param data: Input data.
@ -364,7 +365,7 @@ def non_zero(data: NodeInput, output_type: str = "i64", name: Optional[str] = No
return _get_node_factory_opset3().create(
"NonZero",
[as_node(data)],
{"output_type": output_type}
{"output_type": output_type},
)
@ -380,7 +381,7 @@ def read_value(init_value: NodeInput, variable_id: str, name: Optional[str] = No
return _get_node_factory_opset3().create(
"ReadValue",
[as_node(init_value)],
{"variable_id": variable_id}
{"variable_id": variable_id},
)
@ -507,13 +508,13 @@ def scatter_elements_update(
"""
return _get_node_factory_opset3().create(
"ScatterElementsUpdate", as_nodes(data, indices, updates, axis)
"ScatterElementsUpdate", as_nodes(data, indices, updates, axis),
)
@nameable_op
def scatter_update(
data: Node, indices: NodeInput, updates: NodeInput, axis: NodeInput, name: Optional[str] = None
data: Node, indices: NodeInput, updates: NodeInput, axis: NodeInput, name: Optional[str] = None,
) -> Node:
"""Return a node which produces a ScatterUpdate operation.
@ -527,7 +528,7 @@ def scatter_update(
"""
return _get_node_factory_opset3().create(
"ScatterUpdate",
as_nodes(data, indices, updates, axis)
as_nodes(data, indices, updates, axis),
)
@ -542,7 +543,7 @@ def shape_of(data: NodeInput, output_type: str = "i64", name: Optional[str] = No
return _get_node_factory_opset3().create(
"ShapeOf",
[as_node(data)],
{"output_type": output_type}
{"output_type": output_type},
)
@ -571,7 +572,7 @@ def shuffle_channels(data: Node, axis: int, group: int, name: Optional[str] = No
For example:
.. code-block:: ipython
.. code-block:: python
Inputs: tensor of shape [1, 6, 2, 2]
@ -595,7 +596,7 @@ def shuffle_channels(data: Node, axis: int, group: int, name: Optional[str] = No
[[20., 21.], [22., 23.]]]]
"""
return _get_node_factory_opset3().create(
"ShuffleChannels", [as_node(data)], {"axis": axis, "group": group}
"ShuffleChannels", [as_node(data)], {"axis": axis, "group": group},
)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -129,7 +130,7 @@ def softplus(data: NodeInput, name: Optional[str] = None) -> Node:
@nameable_op
def mish(data: NodeInput, name: Optional[str] = None,) -> Node:
def mish(data: NodeInput, name: Optional[str] = None) -> Node:
"""Return a node which performs Mish.
:param data: Tensor with input data floating point type.
@ -139,7 +140,7 @@ def mish(data: NodeInput, name: Optional[str] = None,) -> Node:
@nameable_op
def hswish(data: NodeInput, name: Optional[str] = None,) -> Node:
def hswish(data: NodeInput, name: Optional[str] = None) -> Node:
"""Return a node which performs HSwish (hard version of Swish).
:param data: Tensor with input data floating point type.
@ -212,6 +213,7 @@ def proposal(
:param image_shape: The 1D input tensor with 3 or 4 elements describing image shape.
:param attrs: The dictionary containing key, value pairs for attributes.
:param name: Optional name for the output node.
* base_size The size of the anchor to which scale and ratio attributes are applied.
Range of values: a positive unsigned integer number
Default value: None
@ -272,6 +274,7 @@ def proposal(
Range of values: "" (empty string) - calculate box coordinates like in Caffe*
tensorflow - calculate box coordinates like in the TensorFlow*
Object Detection API models
Default value: "" (empty string)
Required: no
@ -314,13 +317,13 @@ def proposal(
check_valid_attributes("Proposal", attrs, requirements)
return _get_node_factory_opset4().create(
"Proposal", [class_probs, bbox_deltas, as_node(image_shape)], attrs
"Proposal", [class_probs, bbox_deltas, as_node(image_shape)], attrs,
)
@nameable_op
def reduce_l1(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None,
) -> Node:
"""L1-reduction operation on input tensor, eliminating the specified reduction axes.
@ -331,13 +334,13 @@ def reduce_l1(
:return: The new node performing mean-reduction operation.
"""
return _get_node_factory_opset4().create(
"ReduceL1", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
"ReduceL1", as_nodes(node, reduction_axes), {"keep_dims": keep_dims},
)
@nameable_op
def reduce_l2(
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None
node: NodeInput, reduction_axes: NodeInput, keep_dims: bool = False, name: Optional[str] = None,
) -> Node:
"""L2-reduction operation on input tensor, eliminating the specified reduction axes.
@ -348,7 +351,7 @@ def reduce_l2(
:return: The new node performing mean-reduction operation.
"""
return _get_node_factory_opset4().create(
"ReduceL2", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
"ReduceL2", as_nodes(node, reduction_axes), {"keep_dims": keep_dims},
)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -80,7 +81,7 @@ def gather_nd(
inputs = as_nodes(data, indices)
attributes = {
"batch_dims": batch_dims
"batch_dims": batch_dims,
}
return _get_node_factory_opset5().create("GatherND", inputs, attributes)
@ -133,11 +134,11 @@ def non_max_suppression(
score_threshold = make_constant_node(0, np.float32)
if soft_nms_sigma is None:
inputs = as_nodes(
boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold
boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold,
)
else:
inputs = as_nodes(
boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, soft_nms_sigma
boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, soft_nms_sigma,
)
attributes = {
@ -227,7 +228,7 @@ def lstm_sequence(
return _get_node_factory_opset5().create("LSTMSequence", node_inputs, attributes)
def hsigmoid(data: NodeInput, name: Optional[str] = None,) -> Node:
def hsigmoid(data: NodeInput, name: Optional[str] = None) -> Node:
"""Return a node which performs HSigmoid.
:param data: Tensor with input data floating point type.
@ -255,16 +256,16 @@ def gru_sequence(
) -> Node:
"""Return a node which performs GRUSequence operation.
:param X: The input tensor. Shape: [batch_size, seq_length, input_size].
:param inputs: The input tensor. Shape: [batch_size, seq_length, input_size].
:param initial_hidden_state: The hidden state tensor.
Shape: [batch_size, num_directions, hidden_size].
:param sequence_lengths: Specifies real sequence lengths for each batch element.
Shape: [batch_size]. Integer type.
:param W: Tensor with weights for matrix multiplication operation with input portion of data.
:param weights_w: Tensor with weights for matrix multiplication operation with input portion of data.
Shape: [num_directions, 3*hidden_size, input_size].
:param R: The tensor with weights for matrix multiplication operation with hidden state.
:param weights_r: The tensor with weights for matrix multiplication operation with hidden state.
Shape: [num_directions, 3*hidden_size, hidden_size].
:param B: The sum of biases (weight and recurrence).
:param biases: The sum of biases (weight and recurrence).
For linear_before_reset set True the shape is [num_directions, 4*hidden_size].
Otherwise the shape is [num_directions, 3*hidden_size].
:param hidden_size: Specifies hidden state size.

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -63,7 +64,7 @@ def ctc_greedy_decoder_seq_len(
attributes = {
"merge_repeated": merge_repeated,
"classes_index_type": classes_index_type,
"sequence_length_type": sequence_length_type
"sequence_length_type": sequence_length_type,
}
return _get_node_factory_opset6().create("CTCGreedyDecoderSeqLen", inputs, attributes)
@ -86,7 +87,7 @@ def gather_elements(
inputs = as_nodes(data, indices)
attributes = {
"axis": axis
"axis": axis,
}
return _get_node_factory_opset6().create("GatherElements", inputs, attributes)
@ -117,7 +118,7 @@ def mvn(
attributes = {
"normalize_variance": normalize_variance,
"eps": eps,
"eps_mode": eps_mode
"eps_mode": eps_mode,
}
return _get_node_factory_opset6().create("MVN", inputs, attributes)
@ -135,7 +136,7 @@ def assign(new_value: NodeInput, variable_id: str, name: Optional[str] = None) -
return _get_node_factory_opset6().create(
"Assign",
[as_node(new_value)],
{"variable_id": variable_id}
{"variable_id": variable_id},
)
@ -151,5 +152,5 @@ def read_value(init_value: NodeInput, variable_id: str, name: Optional[str] = No
return _get_node_factory_opset6().create(
"ReadValue",
[as_node(init_value)],
{"variable_id": variable_id}
{"variable_id": variable_id},
)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -40,7 +41,7 @@ _get_node_factory_opset7 = partial(_get_node_factory, "opset7")
@nameable_op
def einsum(
inputs: List[Node],
equation: str
equation: str,
) -> Node:
"""Return a node which performs Einsum operation.
@ -49,7 +50,7 @@ def einsum(
:return: The new node performing Einsum operation on the inputs
"""
attributes = {
"equation": equation
"equation": equation,
}
return _get_node_factory_opset7().create("Einsum", as_nodes(*inputs), attributes)
@ -71,7 +72,7 @@ def gelu(
inputs = as_nodes(data)
attributes = {
"approximation_mode": approximation_mode
"approximation_mode": approximation_mode,
}
return _get_node_factory_opset7().create("Gelu", inputs, attributes)
@ -112,7 +113,7 @@ def gather(
"""
inputs = as_nodes(data, indices, axis)
attributes = {
"batch_dims": batch_dims
"batch_dims": batch_dims,
}
return _get_node_factory_opset7().create("Gather", inputs, attributes)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -80,7 +81,7 @@ def deformable_convolution(
"auto_pad": auto_pad,
"group": group,
"deformable_group": deformable_group,
"bilinear_interpolation_pad": bilinear_interpolation_pad
"bilinear_interpolation_pad": bilinear_interpolation_pad,
},
)
@ -88,7 +89,7 @@ def deformable_convolution(
@nameable_op
def adaptive_avg_pool(
data: NodeInput,
output_shape: NodeInput
output_shape: NodeInput,
) -> Node:
"""Return a node which performs AdaptiveAvgPool operation.
@ -104,7 +105,7 @@ def adaptive_avg_pool(
def adaptive_max_pool(
data: NodeInput,
output_shape: NodeInput,
index_element_type: str = "i64"
index_element_type: str = "i64",
) -> Node:
"""Return a node which performs AdaptiveMaxPool operation.
@ -135,7 +136,7 @@ def multiclass_nms(
keep_top_k: int = -1,
background_class: int = -1,
nms_eta: float = 1.0,
normalized: bool = True
normalized: bool = True,
) -> Node:
"""Return a node which performs MulticlassNms.
@ -172,7 +173,7 @@ def multiclass_nms(
"keep_top_k": keep_top_k,
"background_class": background_class,
"nms_eta": nms_eta,
"normalized": normalized
"normalized": normalized,
}
return _get_node_factory_opset8().create("MulticlassNms", inputs, attributes)
@ -192,7 +193,7 @@ def matrix_nms(
decay_function: str = "linear",
gaussian_sigma: float = 2.0,
post_threshold: float = 0.0,
normalized: bool = True
normalized: bool = True,
) -> Node:
"""Return a node which performs MatrixNms.
@ -233,7 +234,7 @@ def matrix_nms(
"decay_function": decay_function,
"gaussian_sigma": gaussian_sigma,
"post_threshold": post_threshold,
"normalized": normalized
"normalized": normalized,
}
return _get_node_factory_opset8().create("MatrixNms", inputs, attributes)
@ -250,14 +251,14 @@ def gather(
:param data: N-D tensor with data for gathering
:param indices: N-D tensor with indices by which data is gathered. Negative indices
indicate reverse indexing from the end
indicate reverse indexing from the end
:param axis: axis along which elements are gathered
:param batch_dims: number of batch dimensions
:return: The new node which performs Gather
"""
inputs = as_nodes(data, indices, axis)
attributes = {
"batch_dims": batch_dims
"batch_dims": batch_dims,
}
return _get_node_factory_opset8().create("Gather", inputs, attributes)
@ -324,7 +325,7 @@ def random_uniform(
max_val: NodeInput,
output_type: str,
global_seed: int = 0,
op_seed: int = 0
op_seed: int = 0,
) -> Node:
"""Return a node which generates sequence of random values from uniform distribution.
@ -332,18 +333,19 @@ def random_uniform(
:param min_val: Tensor with the lower bound on the range of random values to generate.
:param max_val: Tensor with the upper bound on the range of random values to generate.
:param output_type: Specifies the output tensor type, possible values:
'i64', 'i32', 'f64', 'f32', 'f16', 'bf16'.
'i64', 'i32', 'f64', 'f32', 'f16', 'bf16'.
:param global_seed: Specifies global seed value. Required to be a positive integer or 0.
:param op_seed: Specifies operational seed value. Required to be a positive integer or 0.
:return: The new node which performs generation of random values from uniform distribution.
"""
inputs = as_nodes(output_shape, min_val, max_val)
if global_seed < 0:
raise RuntimeError("global_seed should be positive or 0. Got: {}".format(global_seed))
raise RuntimeError(f"global_seed should be positive or 0. Got: {global_seed}")
if op_seed < 0:
raise RuntimeError("op_seed should be positive or 0. Got: {}".format(op_seed))
raise RuntimeError(f"op_seed should be positive or 0. Got: {op_seed}")
attributes = {
"output_type": output_type,
@ -397,7 +399,7 @@ def gather_nd(
inputs = as_nodes(data, indices)
attributes = {
"batch_dims": batch_dims
"batch_dims": batch_dims,
}
return _get_node_factory_opset8().create("GatherND", inputs, attributes)
@ -405,7 +407,7 @@ def gather_nd(
@nameable_op
def prior_box(
layer_shape: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None
layer_shape: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None,
) -> Node:
"""Generate prior boxes of specified sizes and aspect ratios across all dimensions.
@ -414,11 +416,13 @@ def prior_box(
:param attrs: The dictionary containing key, value pairs for attributes.
:param name: Optional name for the output node.
:return: Node representing prior box operation.
Available attributes are:
* min_size The minimum box size (in pixels).
Range of values: positive floating point numbers
Default value: []
Required: no
* max_size The maximum box size (in pixels).
Range of values: positive floating point numbers
Default value: []
@ -452,6 +456,7 @@ def prior_box(
* scale_all_sizes The flag that denotes type of inference.
Range of values: False - max_size is ignored
True - max_size is used
Default value: True
Required: no
* fixed_ratio This is an aspect ratio of a box.
@ -469,10 +474,13 @@ def prior_box(
* min_max_aspect_ratios_order The flag that denotes the order of output prior box.
Range of values: False - the output prior box is in order of
[min, aspect_ratios, max]
True - the output prior box is in order of
[min, max, aspect_ratios]
Default value: True
Required: no
Example of attribute dictionary:
.. code-block:: python
@ -532,7 +540,7 @@ def i420_to_bgr(
inputs = as_nodes(arg, arg_u, arg_v)
else:
raise UserInputError(
"Operation I420toBGR must have one (single plane) or three (separate planes) inputs provided."
"Operation I420toBGR must have one (single plane) or three (separate planes) inputs provided.",
)
return _get_node_factory_opset8().create("I420toBGR", inputs)
@ -559,7 +567,7 @@ def i420_to_rgb(
inputs = as_nodes(arg, arg_u, arg_v)
else:
raise UserInputError(
"Operation I420toRGB must have one (single plane) or three (separate planes) inputs provided."
"Operation I420toRGB must have one (single plane) or three (separate planes) inputs provided.",
)
return _get_node_factory_opset8().create("I420toRGB", inputs)
@ -628,6 +636,7 @@ def detection_output(
:param name: Optional name for the output node.
:return: Node representing DetectionOutput operation.
Available attributes are:
* background_label_id The background label id.
Range of values: integer value
Default value: 0
@ -647,6 +656,7 @@ def detection_output(
* code_type The type of coding method for bounding boxes.
Range of values: {'caffe.PriorBoxParameter.CENTER_SIZE',
'caffe.PriorBoxParameter.CORNER'}
Default value: 'caffe.PriorBoxParameter.CORNER'
Required: no
* share_location The flag that denotes if bounding boxes are shared among different
@ -676,6 +686,7 @@ def detection_output(
* decrease_label_id The flag that denotes how to perform NMS.
Range of values: False - perform NMS like in Caffe*.
True - perform NMS like in MxNet*.
Default value: False
Required: no
* normalized The flag that denotes whether input tensors with boxes are normalized.
@ -694,6 +705,7 @@ def detection_output(
Range of values: non-negative float number
Default value: 0
Required: no
Example of attribute dictionary:
.. code-block:: python

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -206,7 +207,7 @@ def multiclass_nms(
keep_top_k: Optional[int] = -1,
background_class: Optional[int] = -1,
nms_eta: Optional[float] = 1.0,
normalized: Optional[bool] = True
normalized: Optional[bool] = True,
) -> Node:
"""Return a node which performs MulticlassNms.
@ -248,7 +249,7 @@ def multiclass_nms(
"keep_top_k": keep_top_k,
"background_class": background_class,
"nms_eta": nms_eta,
"normalized": normalized
"normalized": normalized,
}
return _get_node_factory_opset9().create("MulticlassNms", inputs, attributes)
@ -294,7 +295,7 @@ def generate_proposals(
"post_nms_count": post_nms_count,
"normalized": normalized,
"nms_eta": nms_eta,
"roi_num_type": roi_num_type
"roi_num_type": roi_num_type,
}
return _get_node_factory_opset9().create("GenerateProposals", inputs, attributes)
@ -304,7 +305,7 @@ def grid_sample(
data: NodeInput,
grid: NodeInput,
attributes: dict,
name: Optional[str] = None
name: Optional[str] = None,
) -> Node:
"""Return a node which performs GridSample operation.
@ -312,7 +313,9 @@ def grid_sample(
:param grid: Grid values (normalized input coordinates).
:param attributes: A dictionary containing GridSample's attributes.
:param name: Optional name of the node.
Available attributes:
* align_corners A flag which specifies whether to align the grid extrema values
with the borders or center points of the input tensor's border pixels.
Range of values: true, false
@ -326,6 +329,7 @@ def grid_sample(
Range of values: zeros, border, reflection
Default value: zeros
Required: no
:return: A new GridSample node.
"""
return _get_node_factory_opset9().create("GridSample", as_nodes(data, grid), attributes)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# type: ignore

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# type: ignore

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -5,13 +6,18 @@ import logging
from typing import List
from openvino.runtime import AxisSet, Node
from openvino.runtime.utils.types import NodeInput, TensorShape, get_dtype, make_constant_node
from openvino.runtime.utils.types import (
NodeInput,
TensorShape,
get_dtype,
make_constant_node,
)
log = logging.getLogger(__name__)
def get_broadcast_axes(
output_shape: TensorShape, input_shape: TensorShape, axis: int = None
output_shape: TensorShape, input_shape: TensorShape, axis: int = None,
) -> AxisSet:
"""Generate a list of broadcast axes for openvino broadcast.
@ -22,7 +28,8 @@ def get_broadcast_axes(
:param output_shape: The new shape for the output tensor.
:param input_shape: The shape of input tensor.
:param axis: The axis along which we want to replicate elements.
returns The indices of added axes.
returns: The indices of added axes.
"""
axes_indexes = list(range(0, len(output_shape)))
if axis is None:

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -35,19 +36,16 @@ def _check_value(op_name, attr_key, value, val_type, cond=None):
:param cond: The optional function running additional checks.
:raises UserInputError:
returns True if attribute satisfies all criterias. Otherwise False.
returns: True if attribute satisfies all criterias. Otherwise False.
"""
if not np.issubdtype(type(value), val_type):
raise UserInputError(
'{} operator attribute "{}" value must by of type {}.'.format(
op_name, attr_key, val_type
)
f'{op_name} operator attribute "{attr_key}" value must by of type {val_type}.',
)
if cond is not None and not cond(value):
raise UserInputError(
'{} operator attribute "{}" value does not satisfy provided condition.'.format(
op_name, attr_key
)
f'{op_name} operator attribute "{attr_key}" value does not satisfy provided condition.',
)
return True
@ -72,9 +70,7 @@ def check_valid_attribute(op_name, attr_dict, attr_key, val_type, cond=None, req
if required and attr_key not in attr_dict:
raise UserInputError(
'Provided dictionary is missing {} operator required attribute "{}"'.format(
op_name, attr_key
)
f'Provided dictionary is missing {op_name} operator required attribute "{attr_key}"',
)
if attr_key not in attr_dict:
@ -85,8 +81,8 @@ def check_valid_attribute(op_name, attr_dict, attr_key, val_type, cond=None, req
if np.isscalar(attr_value):
result = result and _check_value(op_name, attr_key, attr_value, val_type, cond)
else:
for v in attr_value:
result = result and _check_value(op_name, attr_key, v, val_type, cond)
for value in attr_value:
result = result and _check_value(op_name, attr_key, value, val_type, cond)
return result
@ -104,33 +100,34 @@ def check_valid_attributes(
:param requirements: The list of tuples describing attributes' requirements. The tuple should
contain following values:
(attr_name: str,
is_required: bool,
value_type: Type,
value_condition: Callable)
is_required: bool,
value_type: Type,
value_condition: Callable)
:raises UserInputError:
returns True if all attributes satisfies criterias. Otherwise False.
:returns True if all attributes satisfies criterias. Otherwise False.
"""
for attr, required, val_type, cond in requirements:
check_valid_attribute(op_name, attributes, attr, val_type, cond, required)
return True
def is_positive_value(x): # type: (Any) -> bool
def is_positive_value(value): # type: (Any) -> bool
"""Determine whether the specified x is positive value.
:param x: The value to check.
:param value: The value to check.
returns True if the specified x is positive value, False otherwise.
"""
return x > 0
return value > 0
def is_non_negative_value(x): # type: (Any) -> bool
def is_non_negative_value(value): # type: (Any) -> bool
"""Determine whether the specified x is non-negative value.
:param x: The value to check.
:param value: The value to check.
returns True if the specified x is non-negative value, False otherwise.
"""
return x >= 0
return value >= 0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -48,11 +49,7 @@ class NodeFactory(object):
return node
if arguments is None and attributes is not None:
raise UserInputError(
'Error: cannot create "{}" op without arguments.'.format(
op_type_name
)
)
raise UserInputError(f'Error: cannot create "{op_type_name}" op without arguments.')
if attributes is None:
attributes = {}
@ -66,14 +63,15 @@ class NodeFactory(object):
if node.get_type_name() == "TensorIterator":
return node
# Set getters and setters for each node's attribute.
# node.get_attribute_name()
# node.set_attribute_name()
# For compound (with more than one level of nesting) attributes of form ie.:
# node.class_member_name.some_metric.attr_name:
# node.get_some_metric_attr_name()
# node.set_some_metric_attr_name()
# Please see test_dyn_attributes.py for more usage examples.
"""Set getters and setters for each node's attribute.
node.get_attribute_name()
node.set_attribute_name()
For compound (with more than one level of nesting) attributes of form ie.:
node.class_member_name.some_metric.attr_name:
node.get_some_metric_attr_name()
node.set_some_metric_attr_name()
Please see test_dyn_attributes.py for more usage examples.
"""
all_attributes = node.get_attributes()
for attr_name in all_attributes.keys():
setattr(
@ -118,26 +116,6 @@ class NodeFactory(object):
attr_name = attr_name[attr_name.find(".") + 1:]
return prefix + attr_name.replace(".", "_")
@classmethod
def _normalize_attr_name_getter(cls, attr_name: str) -> str:
"""Normalize atr name to be suitable for getter function name.
:param attr_name: The attribute name to normalize
:return: The appropriate getter function name.
"""
return cls._normalize_attr_name(attr_name, "get_")
@classmethod
def _normalize_attr_name_setter(cls, attr_name: str) -> str:
"""Normalize attribute name to be suitable for setter function name.
:param attr_name: The attribute name to normalize
:return: The appropriate setter function name.
"""
return cls._normalize_attr_name(attr_name, "set_")
@staticmethod
def _get_node_attr_value(node: Node, attr_name: str) -> Any:
"""Get provided node attribute value.
@ -162,3 +140,23 @@ class NodeFactory(object):
"""
node.set_attribute(attr_name, value)
node._attr_cache[attr_name] = value
@classmethod
def _normalize_attr_name_getter(cls, attr_name: str) -> str:
"""Normalize atr name to be suitable for getter function name.
:param attr_name: The attribute name to normalize
:return: The appropriate getter function name.
"""
return cls._normalize_attr_name(attr_name, "get_")
@classmethod
def _normalize_attr_name_setter(cls, attr_name: str) -> str:
"""Normalize attribute name to be suitable for setter function name.
:param attr_name: The attribute name to normalize
:return: The appropriate setter function name.
"""
return cls._normalize_attr_name(attr_name, "set_")

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -13,7 +14,8 @@ def get_reduction_axes(node: Node, reduction_axes: Optional[Iterable[int]]) -> I
:param node: The node we fill reduction axes for.
:param reduction_axes: The collection of indices of axes to reduce. May be None.
returns Set filled with indices of axes we want to reduce.
returns: Set filled with indices of axes we want to reduce.
"""
if reduction_axes is None:
reduction_axes = set(range(len(node.shape)))

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -63,7 +64,7 @@ def get_element_type(data_type: NumericType) -> Type:
return Type.f32
ov_type = next(
(ov_type for (ov_type, np_type) in openvino_to_numpy_types_map if np_type == data_type), None
(ov_type for (ov_type, np_type) in openvino_to_numpy_types_map if np_type == data_type), None,
)
if ov_type:
return ov_type

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -37,7 +38,7 @@ class Runtime(object):
def __init__(self, backend_name: str) -> None:
self.backend_name = backend_name
log.debug("Creating Inference Engine for %s" % backend_name)
log.debug(f"Creating Inference Engine for {backend_name}")
self.backend = Core()
assert backend_name in self.backend.available_devices, (
'The requested device "' + backend_name + '" is not supported!'
@ -47,9 +48,6 @@ class Runtime(object):
"""Set the inference engine configuration."""
self.backend.set_property(device_name=self.backend_name, properties=config)
def __repr__(self) -> str:
return "<Runtime: Backend='{}'>".format(self.backend_name)
def computation(self, node_or_function: Union[Node, Model], *inputs: Node) -> "Computation":
"""Return a callable Computation object."""
if isinstance(node_or_function, Node):
@ -65,6 +63,9 @@ class Runtime(object):
node_or_function,
)
def __repr__(self) -> str:
return f"<Runtime: Backend='{self.backend_name}'>"
class Computation(object):
"""nGraph callable computation object."""
@ -76,40 +77,40 @@ class Computation(object):
self.results = ng_function.get_results()
self.network_cache = {}
def __repr__(self) -> str:
params_string = ", ".join([param.name for param in self.parameters])
return "<Computation: {}({})>".format(self.function.get_name(), params_string)
def convert_buffers(self, source_buffers, target_dtypes):
converted_buffers = []
for i in range(len(source_buffers)):
k = list(source_buffers)[i]
key = list(source_buffers)[i]
target_dtype = target_dtypes[i]
# custom conversion for bf16
if self.results[i].get_output_element_type(0) == Type.bf16:
converted_buffers.append((source_buffers[k].view(target_dtype)).astype(target_dtype))
converted_buffers.append((source_buffers[key].view(target_dtype)).astype(target_dtype))
else:
converted_buffers.append(source_buffers[k].astype(target_dtype))
converted_buffers.append(source_buffers[key].astype(target_dtype))
return converted_buffers
def convert_to_tensors(self, input_values):
input_tensors = []
for parameter, input in zip(self.parameters, input_values):
if not isinstance(input, (np.ndarray)):
input = np.ndarray([], type(input), np.array(input))
for parameter, input_val in zip(self.parameters, input_values):
if not isinstance(input_val, (np.ndarray)):
input_val = np.ndarray([], type(input_val), np.array(input_val))
if parameter.get_output_element_type(0) == Type.bf16:
input_tensors.append(Tensor(Type.bf16, input.shape))
input_tensors[-1].data[:] = input.view(np.float16)
input_tensors.append(Tensor(Type.bf16, input_val.shape))
input_tensors[-1].data[:] = input_val.view(np.float16)
else:
input_tensors.append(Tensor(input))
input_tensors.append(Tensor(input_val))
return input_tensors
def __repr__(self) -> str:
params_string = ", ".join([param.name for param in self.parameters])
return f"<Computation: {self.function.get_name()}({params_string})>"
def __call__(self, *input_values: NumericData) -> List[NumericData]:
"""Run computation on input values and return result."""
# Input validation
if len(input_values) < len(self.parameters):
raise UserInputError(
"Expected %s params, received not enough %s values.", len(self.parameters), len(input_values)
"Expected %s params, received not enough %s values.", len(self.parameters), len(input_values),
)
param_names = [param.friendly_name for param in self.parameters]
@ -132,14 +133,14 @@ class Computation(object):
request = executable_network.create_infer_request()
result_buffers = request.infer(dict(zip(param_names, input_values)))
# # Note: other methods to get result_buffers from request
# # First call infer with no return value:
# request.infer(dict(zip(param_names, input_values)))
# # Now use any of following options:
# result_buffers = [request.get_tensor(n).data for n in request.outputs]
# result_buffers = [request.get_output_tensor(i).data for i in range(len(request.outputs))]
# result_buffers = [t.data for t in request.output_tensors]
"""Note: other methods to get result_buffers from request
First call infer with no return value:
request.infer(dict(zip(param_names, input_values)))
Now use any of following options:
result_buffers = [request.get_tensor(n).data for n in request.outputs]
result_buffers = [request.get_output_tensor(i).data for i in range(len(request.outputs))]
result_buffers = [t.data for t in request.output_tensors]
"""
# # Since OV overwrite result data type we have to convert results to the original one.
original_dtypes = [get_dtype(result.get_output_element_type(0)) for result in self.results]
converted_buffers = self.convert_buffers(result_buffers, original_dtypes)

View File

@ -1,2 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -44,13 +45,13 @@ def create_onnx_model_2():
def create_onnx_model_with_subgraphs():
A = onnx.helper.make_tensor_value_info("A", onnx.TensorProto.FLOAT, [3])
B = onnx.helper.make_tensor_value_info("B", onnx.TensorProto.FLOAT, [3])
x1 = onnx.helper.make_tensor_value_info("x1", onnx.TensorProto.FLOAT, [3])
x2 = onnx.helper.make_tensor_value_info("x2", onnx.TensorProto.FLOAT, [3])
add_out = onnx.helper.make_tensor_value_info("add_out", onnx.TensorProto.FLOAT, [3])
sub_out = onnx.helper.make_tensor_value_info("sub_out", onnx.TensorProto.FLOAT, [3])
add = onnx.helper.make_node("Add", inputs=["A", "B"], outputs=["add_out"])
sub = onnx.helper.make_node("Sub", inputs=["A", "B"], outputs=["sub_out"])
add = onnx.helper.make_node("Add", inputs=["x1", "x2"], outputs=["add_out"])
sub = onnx.helper.make_node("Sub", inputs=["x1", "x2"], outputs=["sub_out"])
then_body = make_graph([add], "then_body", [], [add_out])
else_body = make_graph([sub], "else_body", [], [sub_out])
@ -60,12 +61,12 @@ def create_onnx_model_with_subgraphs():
inputs=["cond"],
outputs=["res"],
then_branch=then_body,
else_branch=else_body
else_branch=else_body,
)
cond = onnx.helper.make_tensor_value_info("cond", onnx.TensorProto.BOOL, [])
res = onnx.helper.make_tensor_value_info("res", onnx.TensorProto.FLOAT, [3])
graph = make_graph([if_node], "graph", [cond, A, B], [res])
graph = make_graph([if_node], "graph", [cond, x1, x2], [res])
return make_model(graph, producer_name="ONNX Frontend")
@ -196,13 +197,13 @@ def test_convert():
function = fe.convert(model)
assert function
a = np.array([[1, 2], [3, 4]], dtype=np.float32)
b = np.array([[2, 3], [4, 5]], dtype=np.float32)
input_1 = np.array([[1, 2], [3, 4]], dtype=np.float32)
input_2 = np.array([[2, 3], [4, 5]], dtype=np.float32)
expected = np.array([[1.5, 5], [10.5, 18]], dtype=np.float32)
run_function(function, a, b, expected=[expected])
run_function(function, input_1, input_2, expected=[expected])
@pytest.mark.parametrize("model_filename, inputs, expected", [
@pytest.mark.parametrize(("model_filename", "inputs", "expected"), [
[onnx_model_filename,
[np.array([[1, 2], [3, 4]], dtype=np.float32),
np.array([[2, 3], [4, 5]], dtype=np.float32)],
@ -293,9 +294,9 @@ def test_onnx_conversion_extension_check_attributes():
check_attribute(node, "attribute_list_bool", list, [1, 0, 1])
check_attribute(node, "attribute_list_type", list, [6, 1])
a = node.get_input(0)
b = node.get_input(1)
add = ops.add(a, b)
input_1 = node.get_input(0)
input_2 = node.get_input(1)
add = ops.add(input_1, input_2)
return [add.output(0)]
fe.add_extension(ConversionExtension("Add", custom_converter))
@ -351,9 +352,9 @@ def test_onnx_conversion_extension_attribute_with_default_value():
check_attribute(node, "attribute_list_type", np.array([onnx.TensorProto.INT32,
onnx.TensorProto.FLOAT]))
a = node.get_input(0)
b = node.get_input(1)
add = ops.add(a, b)
input_1 = node.get_input(0)
input_2 = node.get_input(1)
add = ops.add(input_1, input_2)
return [add.output(0)]
fe.add_extension(ConversionExtension("Add", custom_converter))
@ -408,9 +409,9 @@ def test_onnx_conversion_extension_cast_attributes():
check_attribute(node, "attribute_list_bool", [True, False, True], bool)
check_attribute(node, "attribute_list_type", [Type.i32, Type.f32], Type)
a = node.get_input(0)
b = node.get_input(1)
add = ops.add(a, b)
input_1 = node.get_input(0)
input_2 = node.get_input(1)
add = ops.add(input_1, input_2)
return [add.output(0)]
fe.add_extension(ConversionExtension("Add", custom_converter))
@ -438,9 +439,9 @@ def test_onnx_conversion_extension_common():
def custom_converter(node: NodeContext):
nonlocal invoked
invoked = True
a = node.get_input(0)
b = node.get_input(1)
add = ops.add(a, b)
input_1 = node.get_input(0)
input_2 = node.get_input(1)
add = ops.add(input_1, input_2)
return [add.output(0)]
fe.add_extension(ConversionExtension("Add", custom_converter))
@ -468,9 +469,9 @@ def test_onnx_conversion_extension():
def custom_converter(node: NodeContext):
nonlocal invoked
invoked = True
a = node.get_input(0)
b = node.get_input(1)
add = ops.add(a, b)
input_1 = node.get_input(0)
input_2 = node.get_input(1)
add = ops.add(input_1, input_2)
return [add.output(0)]
fe.add_extension(ConversionExtension("Add", custom_converter))
@ -518,8 +519,7 @@ def test_op_extension_specify_wrong_opset(opset_prefix):
fw_operation = "Floor"
ov_operation = opset_prefix + fw_operation
ie.add_extension(OpExtension(ov_operation, fw_operation))
with pytest.raises(Exception):
with pytest.raises(RuntimeError):
ie.read_model(onnx_model_for_op_extension_test)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -86,7 +87,7 @@ def create_test_onnx_models():
# Input model 2
split_2 = onnx.helper.make_node("Split", inputs=["add_out"],
outputs=["sp_out1", "sp_out2"], name="split2", axis=0)
abs = onnx.helper.make_node("Abs", inputs=["sp_out1"], outputs=["out1"], name="abs1")
absolute = onnx.helper.make_node("Abs", inputs=["sp_out1"], outputs=["out1"], name="abs1")
sin = onnx.helper.make_node("Sin", inputs=["sp_out2"], outputs=["out2"])
input_tensors = [
@ -97,7 +98,7 @@ def create_test_onnx_models():
make_tensor_value_info("out1", onnx.TensorProto.FLOAT, (1, 2)),
make_tensor_value_info("out2", onnx.TensorProto.FLOAT, (1, 2)),
]
graph = make_graph([add, split_2, abs, sin], "test_graph_2", input_tensors, output_tensors)
graph = make_graph([add, split_2, absolute, sin], "test_graph_2", input_tensors, output_tensors)
models["input_model_2.onnx"] = make_model(graph, producer_name="ONNX Importer",
opset_imports=[onnx.helper.make_opsetid("", 13)])
@ -336,7 +337,7 @@ def create_test_onnx_models():
make_tensor_value_info("sub_out", onnx.TensorProto.FLOAT, (2, 2)),
]
initializers = [
onnx.helper.make_tensor("one_const", 1, [1], [1])
onnx.helper.make_tensor("one_const", 1, [1], [1]),
]
graph = make_graph([add, sub, split, mul], "test_graph", input_tensors, output_tensors,
value_info=value_infos, initializer=initializers)
@ -397,17 +398,17 @@ def compare_functions(current, expected): # noqa: C901 the function is too comp
if current_ops[i].get_output_size() != expected_ops[i].get_output_size():
result = False
msg += f"Not equal output size of {current_ops[i].get_friendly_name()}. "
for j in range(current_ops[i].get_output_size()):
if current_ops[i].get_output_partial_shape(j) != expected_ops[i].get_output_partial_shape(j):
for idx in range(current_ops[i].get_output_size()):
if current_ops[i].get_output_partial_shape(idx) != expected_ops[i].get_output_partial_shape(idx):
result = False
msg += f"Not equal op partial shapes of {current_ops[i].get_friendly_name()}. "
msg += f"Current: {current_ops[i].get_partial_shape({j})}, "
msg += f"expected: {expected_ops[i].get_partial_shape({j})}. "
if current_ops[i].get_output_element_type(j) != expected_ops[i].get_output_element_type(j):
msg += f"Current: {current_ops[i].get_partial_shape({idx})}, "
msg += f"expected: {expected_ops[i].get_partial_shape({idx})}. "
if current_ops[i].get_output_element_type(idx) != expected_ops[i].get_output_element_type(idx):
result = False
msg += f"Not equal output element type of {current_ops[i].get_friendly_name()}. "
msg += f"Current: {current_ops[i].get_output_element_type(j)}, "
msg += f"expected: {expected_ops[i].get_output_element_type(j)}. "
msg += f"Current: {current_ops[i].get_output_element_type(idx)}, "
msg += f"expected: {expected_ops[i].get_output_element_type(idx)}. "
if not result:
print(msg)
@ -1065,8 +1066,7 @@ def test_get_consuming_ports_2():
split_op = model.get_place_by_operation_name(operation_name="split2")
split_op_consuming_ports = split_op.get_consuming_ports()
assert len(split_op_consuming_ports) == 2
abs_input_port = model.get_place_by_operation_name(operation_name="abs1") \
.get_input_port(input_port_index=0)
abs_input_port = model.get_place_by_operation_name(operation_name="abs1").get_input_port(input_port_index=0)
assert split_op_consuming_ports[0].is_equal(abs_input_port)
out2_tensor = model.get_place_by_tensor_name(tensor_name="out2")
sin_input_port = out2_tensor.get_producing_operation().get_input_port(input_port_index=0)
@ -1352,16 +1352,16 @@ def test_set_tensor_value():
model_func = fe.convert(model)
iter = None
iteration = None
current_ops = model_func.get_ordered_ops()
for i in range(len(current_ops)):
if (current_ops[i].get_friendly_name() == "in1"):
iter = i
iteration = i
assert current_ops[iter] is not None
assert current_ops[iteration] is not None
retrieved_data = current_ops[iter].get_data()
retrieved_data = current_ops[iteration].get_data()
assert np.allclose(new_values, retrieved_data)
@ -1388,18 +1388,18 @@ def test_set_name_for_tensor():
# ignore rename to own name (expect no exception)
model.set_name_for_tensor(tensor=tensor, new_name=old_name)
with pytest.raises(Exception) as e:
with pytest.raises(RuntimeError) as e:
model.set_name_for_tensor(tensor=tensor, new_name="")
assert "name must not be empty" in str(e.value)
# ONNX model stores tensor info separately for inputs, outputs and between nodes tensors
with pytest.raises(Exception) as e:
with pytest.raises(RuntimeError) as e:
model.set_name_for_tensor(tensor=tensor, new_name="in1")
assert "already used by another tensor" in str(e.value)
with pytest.raises(Exception) as e:
with pytest.raises(RuntimeError) as e:
model.set_name_for_tensor(tensor=tensor, new_name="out1")
assert "already used by another tensor" in str(e.value)
with pytest.raises(Exception) as e:
with pytest.raises(RuntimeError) as e:
model.set_name_for_tensor(tensor=tensor, new_name="sub_out")
assert "already used by another tensor" in str(e.value)
@ -1495,13 +1495,12 @@ def test_set_name_for_dimension():
sub_output = model.get_place_by_tensor_name(tensor_name="sub_out")
model.set_name_for_dimension(sub_output, 3, dim_name)
assert model.get_partial_shape(sub_output) == PartialShape([2, 2, -1, -1])
with pytest.raises(Exception) as e:
with pytest.raises(RuntimeError) as e:
model.set_name_for_dimension(input1, 0, "")
assert "name must not be empty" in str(e.value)
one_const = model.get_place_by_tensor_name(tensor_name="one_const")
with pytest.raises(Exception) as e:
with pytest.raises(RuntimeError) as e:
model.set_name_for_dimension(one_const, 0, dim_name)
assert "ONNX initializer shape dimension cannot be dynamic." in str(e.value)
@ -1550,8 +1549,8 @@ def test_set_partial_shape_with_range_and_cut_it_off():
model.extract_subgraph(inputs=[add_out], outputs=[])
ov_model = fe.convert(model)
for input in ov_model.inputs:
assert input.get_partial_shape() != ranged_shape
for model_input in ov_model.inputs:
assert model_input.get_partial_shape() != ranged_shape
def test_set_partial_shape_with_range_and_rename_it():

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -13,8 +14,14 @@ import pytest
mock_available = True
try:
from pybind_mock_frontend import get_fe_stat, clear_fe_stat,\
get_mdl_stat, clear_mdl_stat, get_place_stat, clear_place_stat
from pybind_mock_frontend import (
get_fe_stat,
clear_fe_stat,
get_mdl_stat,
clear_mdl_stat,
get_place_stat,
clear_place_stat,
)
except Exception:
print("No mock frontend available")
mock_available = False
@ -23,8 +30,7 @@ except Exception:
# This is because destroy of FrontEndManager will unload all plugins, no objects shall exist after this
fem = FrontEndManager()
mock_needed = pytest.mark.skipif(not mock_available,
reason="mock fe is not available")
mock_needed = pytest.mark.skipif(not mock_available, reason="mock fe is not available")
def clear_all_stat():
@ -39,8 +45,8 @@ def test_pickle():
def test_load_by_unknown_framework():
frontEnds = fem.get_available_front_ends()
assert not ("UnknownFramework" in frontEnds)
frontends = fem.get_available_front_ends()
assert not ("UnknownFramework" in frontends)
try:
fem.load_by_framework("UnknownFramework")
except InitializationFailure as exc:
@ -494,7 +500,7 @@ def test_place_get_consuming_operations():
assert stat.get_consuming_operations == 3
assert stat.lastArgInt == -1
assert stat.lastArgString == "2"
assert place.get_consuming_operations(output_name="3", output_port_index=33) is not None
assert (place.get_consuming_operations(output_name="3", output_port_index=33) is not None)
stat = get_place_stat()
assert stat.get_consuming_operations == 4
assert stat.lastArgInt == 33
@ -540,7 +546,7 @@ def test_place_get_producing_operation():
assert stat.get_producing_operation == 3
assert stat.lastArgInt == -1
assert stat.lastArgString == "2"
assert place.get_producing_operation(input_name="3", input_port_index=33) is not None
assert (place.get_producing_operation(input_name="3", input_port_index=33) is not None)
stat = get_place_stat()
assert stat.get_producing_operation == 4
assert stat.lastArgInt == 33

View File

@ -1,2 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -7,8 +8,8 @@ from openvino.runtime import Tensor, Type
def test_run():
t = Tensor(np.random.randn(1, 3, 224, 224).astype(np.float32))
assert t.element_type == Type.f32
tensor = Tensor(np.random.randn(1, 3, 224, 224).astype(np.float32))
assert tensor.element_type == Type.f32
if __name__ == "__main__":

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -79,10 +80,10 @@ def test_get_input_i(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.input(0)
input_node = input.get_node()
net_input = exec_net.input(0)
input_node = net_input.get_node()
name = input_node.friendly_name
assert isinstance(input, ConstOutput)
assert isinstance(net_input, ConstOutput)
assert name == "data"
@ -90,10 +91,10 @@ def test_get_input_tensor_name(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.input("data")
input_node = input.get_node()
net_input = exec_net.input("data")
input_node = net_input.get_node()
name = input_node.friendly_name
assert isinstance(input, ConstOutput)
assert isinstance(net_input, ConstOutput)
assert name == "data"
@ -101,10 +102,10 @@ def test_get_input(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.input()
input_node = input.get_node()
net_input = exec_net.input()
input_node = net_input.get_node()
name = input_node.friendly_name
assert isinstance(input, ConstOutput)
assert isinstance(net_input, ConstOutput)
assert name == "data"
@ -128,11 +129,11 @@ def test_input_set_friendly_name(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.input("data")
input_node = input.get_node()
net_input = exec_net.input("data")
input_node = net_input.get_node()
input_node.set_friendly_name("input_1")
name = input_node.friendly_name
assert isinstance(input, ConstOutput)
assert isinstance(net_input, ConstOutput)
assert name == "input_1"
@ -187,9 +188,9 @@ def test_input_get_index(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.input(0)
net_input = exec_net.input(0)
expected_idx = 0
assert input.get_index() == expected_idx
assert net_input.get_index() == expected_idx
def test_inputs(device):
@ -302,10 +303,10 @@ def test_infer_tensor_wrong_input_data(device):
def test_infer_numpy_model_from_buffer(device):
core = Core()
with open(test_net_bin, "rb") as f:
bin = f.read()
weights = f.read()
with open(test_net_xml, "rb") as f:
xml = f.read()
func = core.read_model(model=xml, weights=bin)
func = core.read_model(model=xml, weights=weights)
img = read_image()
exec_net = core.compile_model(func, device)
res = exec_net.infer_new_request({"data": img})
@ -315,10 +316,10 @@ def test_infer_numpy_model_from_buffer(device):
def test_infer_tensor_model_from_buffer(device):
core = Core()
with open(test_net_bin, "rb") as f:
bin = f.read()
weights = f.read()
with open(test_net_xml, "rb") as f:
xml = f.read()
func = core.read_model(model=xml, weights=bin)
func = core.read_model(model=xml, weights=weights)
img = read_image()
tensor = Tensor(img)
exec_net = core.compile_model(func, device)
@ -329,10 +330,10 @@ def test_infer_tensor_model_from_buffer(device):
def test_direct_infer(device):
core = Core()
with open(test_net_bin, "rb") as f:
bin = f.read()
weights = f.read()
with open(test_net_xml, "rb") as f:
xml = f.read()
model = core.read_model(model=xml, weights=bin)
model = core.read_model(model=xml, weights=weights)
img = read_image()
tensor = Tensor(img)
comp_model = core.compile_model(model, device)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -8,11 +9,24 @@ from sys import platform
from pathlib import Path
import openvino.runtime.opset8 as ov
from openvino.runtime import Model, Core, CompiledModel, Tensor, PartialShape, Extension,\
tensor_from_file, compile_model
from openvino.runtime import (
Model,
Core,
CompiledModel,
Tensor,
PartialShape,
Extension,
tensor_from_file,
compile_model,
)
from ..conftest import model_path, model_onnx_path, plugins_path, read_image, \
get_model_with_template_extension
from ..conftest import (
model_path,
model_onnx_path,
plugins_path,
read_image,
get_model_with_template_extension,
)
test_net_xml, test_net_bin = model_path()
@ -24,7 +38,7 @@ def test_compact_api_xml():
img = read_image()
model = compile_model(test_net_xml)
assert(isinstance(model, CompiledModel))
assert isinstance(model, CompiledModel)
results = model.infer_new_request({"data": img})
assert np.argmax(results[list(results)[0]]) == 2
@ -33,7 +47,7 @@ def test_compact_api_onnx():
img = read_image()
model = compile_model(test_net_onnx)
assert(isinstance(model, CompiledModel))
assert isinstance(model, CompiledModel)
results = model.infer_new_request({"data": img})
assert np.argmax(results[list(results)[0]]) == 2
@ -116,20 +130,20 @@ def test_read_model_from_onnx_as_path():
def test_read_net_from_buffer():
core = Core()
with open(test_net_bin, "rb") as f:
bin = f.read()
weights = f.read()
with open(model_path()[0], "rb") as f:
xml = f.read()
func = core.read_model(model=xml, weights=bin)
func = core.read_model(model=xml, weights=weights)
assert isinstance(func, Model)
def test_net_from_buffer_valid():
core = Core()
with open(test_net_bin, "rb") as f:
bin = f.read()
weights = f.read()
with open(model_path()[0], "rb") as f:
xml = f.read()
func = core.read_model(model=xml, weights=bin)
func = core.read_model(model=xml, weights=weights)
ref_func = core.read_model(model=test_net_xml, weights=test_net_bin)
assert func.get_parameters() == ref_func.get_parameters()
assert func.get_results() == ref_func.get_results()
@ -140,7 +154,7 @@ def test_get_version(device):
ie = Core()
version = ie.get_versions(device)
assert isinstance(version, dict), "Returned version must be a dictionary"
assert device in version, "{} plugin version wasn't found in versions"
assert device in version, f"{device} plugin version wasn't found in versions"
assert hasattr(version[device], "major"), "Returned version has no field 'major'"
assert hasattr(version[device], "minor"), "Returned version has no field 'minor'"
assert hasattr(version[device], "description"), "Returned version has no field 'description'"
@ -150,8 +164,10 @@ def test_get_version(device):
def test_available_devices(device):
ie = Core()
devices = ie.available_devices
assert device in devices, f"Current device '{device}' is not listed in " \
f"available devices '{', '.join(devices)}'"
assert device in devices, (
f"Current device '{device}' is not listed in "
f"available devices '{', '.join(devices)}'"
)
def test_get_property():
@ -160,46 +176,66 @@ def test_get_property():
assert conf == "YES"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test")
@pytest.mark.skipif(
os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test",
)
def test_get_property_list_of_str():
ie = Core()
param = ie.get_property("CPU", "OPTIMIZATION_CAPABILITIES")
assert isinstance(param, list), "Parameter value for 'OPTIMIZATION_CAPABILITIES' " \
f"metric must be a list but {type(param)} is returned"
assert all(isinstance(v, str) for v in param), \
"Not all of the parameter values for 'OPTIMIZATION_CAPABILITIES' metric are strings!"
assert isinstance(param, list), (
"Parameter value for 'OPTIMIZATION_CAPABILITIES' "
f"metric must be a list but {type(param)} is returned"
)
assert all(
isinstance(v, str) for v in param
), "Not all of the parameter values for 'OPTIMIZATION_CAPABILITIES' metric are strings!"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test")
@pytest.mark.skipif(
os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test",
)
def test_get_property_tuple_of_two_ints():
ie = Core()
param = ie.get_property("CPU", "RANGE_FOR_STREAMS")
assert isinstance(param, tuple), "Parameter value for 'RANGE_FOR_STREAMS' " \
f"metric must be tuple but {type(param)} is returned"
assert all(isinstance(v, int) for v in param), \
"Not all of the parameter values for 'RANGE_FOR_STREAMS' metric are integers!"
assert isinstance(param, tuple), (
"Parameter value for 'RANGE_FOR_STREAMS' "
f"metric must be tuple but {type(param)} is returned"
)
assert all(
isinstance(v, int) for v in param
), "Not all of the parameter values for 'RANGE_FOR_STREAMS' metric are integers!"
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test")
@pytest.mark.skipif(
os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test",
)
def test_get_property_tuple_of_three_ints():
ie = Core()
param = ie.get_property("CPU", "RANGE_FOR_ASYNC_INFER_REQUESTS")
assert isinstance(param, tuple), "Parameter value for 'RANGE_FOR_ASYNC_INFER_REQUESTS' " \
f"metric must be tuple but {type(param)} is returned"
assert all(isinstance(v, int) for v in param), "Not all of the parameter values for " \
"'RANGE_FOR_ASYNC_INFER_REQUESTS' metric are integers!"
assert isinstance(param, tuple), (
"Parameter value for 'RANGE_FOR_ASYNC_INFER_REQUESTS' "
f"metric must be tuple but {type(param)} is returned"
)
assert all(isinstance(v, int) for v in param), (
"Not all of the parameter values for "
"'RANGE_FOR_ASYNC_INFER_REQUESTS' metric are integers!"
)
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test")
@pytest.mark.skipif(
os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Cannot run test on device {os.environ.get('TEST_DEVICE')}, Plugin specific test",
)
def test_get_property_str():
ie = Core()
param = ie.get_property("CPU", "FULL_DEVICE_NAME")
assert isinstance(param, str), "Parameter value for 'FULL_DEVICE_NAME' " \
f"metric must be string but {type(param)} is returned"
assert isinstance(param, str), (
"Parameter value for 'FULL_DEVICE_NAME' "
f"metric must be string but {type(param)} is returned"
)
def test_query_model(device):
@ -208,23 +244,23 @@ def test_query_model(device):
query_res = ie.query_model(model=func, device_name=device)
ops_func = func.get_ordered_ops()
ops_func_names = [op.friendly_name for op in ops_func]
assert [key for key in query_res.keys() if key not in ops_func_names] == [], \
"Not all network layers present in query_model results"
assert [
key for key in query_res.keys() if key not in ops_func_names
] == [], "Not all network layers present in query_model results"
assert next(iter(set(query_res.values()))) == device, "Wrong device for some layers"
@pytest.mark.dynamic_library
@pytest.mark.dynamic_library()
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason="Device independent test")
def test_register_plugin():
ie = Core()
ie.register_plugin("openvino_intel_cpu_plugin", "BLA")
func = ie.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = ie.compile_model(func, "BLA")
assert isinstance(exec_net, CompiledModel), \
"Cannot load the network to the registered plugin with name 'BLA'"
assert isinstance(exec_net, CompiledModel), "Cannot load the network to the registered plugin with name 'BLA'"
@pytest.mark.dynamic_library
@pytest.mark.dynamic_library()
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU", reason="Device independent test")
def test_register_plugins():
ie = Core()
@ -237,10 +273,11 @@ def test_register_plugins():
func = ie.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = ie.compile_model(func, "CUSTOM")
assert isinstance(exec_net,
CompiledModel), "Cannot load the network to " \
"the registered plugin with name 'CUSTOM' " \
"registered in the XML file"
assert isinstance(exec_net, CompiledModel), (
"Cannot load the network to "
"the registered plugin with name 'CUSTOM' "
"registered in the XML file"
)
@pytest.mark.skip(reason="Need to figure out if it's expected behaviour (fails with C++ API as well")
@ -250,10 +287,13 @@ def test_unregister_plugin(device):
func = ie.read_model(model=test_net_xml, weights=test_net_bin)
with pytest.raises(RuntimeError) as e:
ie.load_network(func, device)
assert f"Device with '{device}' name is not registered in the InferenceEngine" in str(e.value)
assert (
f"Device with '{device}' name is not registered in the InferenceEngine"
in str(e.value)
)
@pytest.mark.template_extension
@pytest.mark.template_extension()
def test_add_extension_template_extension(device):
core, model = get_model_with_template_extension()
assert isinstance(model, Model)
@ -282,7 +322,8 @@ def test_add_extension():
def test_read_model_from_buffer_no_weights(device):
model = bytes(b"""<net name="add_model" version="10">
model = bytes(
b"""<net name="add_model" version="10">
<layers>
<layer id="0" name="x" type="Parameter" version="opset1">
<data element_type="f32" shape="3,4,5"/>

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -5,8 +6,19 @@ import numpy as np
import pytest
import openvino.runtime.opset8 as ops
from openvino.runtime import Core, Model, Tensor, Output, Dimension,\
Layout, Type, PartialShape, Shape, set_batch, get_batch
from openvino.runtime import (
Core,
Model,
Tensor,
Output,
Dimension,
Layout,
Type,
PartialShape,
Shape,
set_batch,
get_batch,
)
def create_test_model():
@ -276,7 +288,7 @@ def test_get_batch():
assert get_batch(model) == 2
def test_get_batch_CHWN():
def test_get_batch_chwn():
param1 = ops.parameter(Shape([3, 1, 3, 4]), dtype=np.float32, name="data1")
param2 = ops.parameter(Shape([3, 1, 3, 4]), dtype=np.float32, name="data2")
param3 = ops.parameter(Shape([3, 1, 3, 4]), dtype=np.float32, name="data3")
@ -292,7 +304,7 @@ def test_set_batch_dimension():
model = create_test_model()
model_param1 = model.get_parameters()[0]
model_param2 = model.get_parameters()[1]
# batch == 2
# check batch == 2
model_param1.set_layout(Layout("NC"))
assert get_batch(model) == 2
# set batch to 1
@ -308,7 +320,7 @@ def test_set_batch_int():
model = create_test_model()
model_param1 = model.get_parameters()[0]
model_param2 = model.get_parameters()[1]
# batch == 2
# check batch == 2
model_param1.set_layout(Layout("NC"))
assert get_batch(model) == 2
# set batch to 1
@ -331,26 +343,26 @@ def test_set_batch_default_batch_size():
def test_reshape_with_ports():
model = create_test_model()
new_shape = PartialShape([1, 4])
for input in model.inputs:
assert isinstance(input, Output)
model.reshape({input: new_shape})
assert input.partial_shape == new_shape
for model_input in model.inputs:
assert isinstance(model_input, Output)
model.reshape({model_input: new_shape})
assert model_input.partial_shape == new_shape
def test_reshape_with_indexes():
model = create_test_model()
new_shape = PartialShape([1, 4])
for index, input in enumerate(model.inputs):
for index, model_input in enumerate(model.inputs):
model.reshape({index: new_shape})
assert input.partial_shape == new_shape
assert model_input.partial_shape == new_shape
def test_reshape_with_names():
model = create_test_model()
new_shape = PartialShape([1, 4])
for input in model.inputs:
model.reshape({input.any_name: new_shape})
assert input.partial_shape == new_shape
for model_input in model.inputs:
model.reshape({model_input.any_name: new_shape})
assert model_input.partial_shape == new_shape
def test_reshape(device):
@ -369,8 +381,8 @@ def test_reshape_with_python_types(device):
model = create_test_model()
def check_shape(new_shape):
for input in model.inputs:
assert input.partial_shape == new_shape
for model_input in model.inputs:
assert model_input.partial_shape == new_shape
shape1 = [1, 4]
new_shapes = {input: shape1 for input in model.inputs}
@ -429,10 +441,15 @@ def test_reshape_with_python_types(device):
shape10 = [1, 1, 1, 1]
with pytest.raises(TypeError) as e:
model.reshape({model.input().node: shape10})
assert "Incorrect key type <class 'openvino.pyopenvino.op.Parameter'> to reshape a model, " \
"expected keys as openvino.runtime.Output, int or str." in str(e.value)
assert (
"Incorrect key type <class 'openvino.pyopenvino.op.Parameter'> to reshape a model, "
"expected keys as openvino.runtime.Output, int or str." in str(e.value)
)
with pytest.raises(TypeError) as e:
model.reshape({0: range(1, 9)})
assert "Incorrect value type <class 'range'> to reshape a model, " \
"expected values as openvino.runtime.PartialShape, str, list or tuple." in str(e.value)
assert (
"Incorrect value type <class 'range'> to reshape a model, "
"expected values as openvino.runtime.PartialShape, str, list or tuple."
in str(e.value)
)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -119,10 +120,10 @@ def test_tensor_setter(device):
assert np.allclose(tensor.data, t1.data, atol=1e-2, rtol=1e-2)
res = request1.infer({0: tensor})
k = list(res)[0]
res_1 = np.sort(res[k])
key = list(res)[0]
res_1 = np.sort(res[key])
t2 = request1.get_tensor("fc_out")
assert np.allclose(t2.data, res[k].data, atol=1e-2, rtol=1e-2)
assert np.allclose(t2.data, res[key].data, atol=1e-2, rtol=1e-2)
request = compiled_2.create_infer_request()
res = request.infer({"data": tensor})
@ -140,10 +141,10 @@ def test_tensor_setter(device):
assert np.allclose(tensor.data, t1.data, atol=1e-2, rtol=1e-2)
res = request.infer()
k = list(res)[0]
res_1 = np.sort(res[k])
key = list(res)[0]
res_1 = np.sort(res[key])
t2 = request1.get_tensor(model.outputs[0])
assert np.allclose(t2.data, res[k].data, atol=1e-2, rtol=1e-2)
assert np.allclose(t2.data, res[key].data, atol=1e-2, rtol=1e-2)
def test_set_tensors(device):
@ -199,8 +200,8 @@ def test_set_tensors(device):
assert np.allclose(tensor4.data, t9.data, atol=1e-2, rtol=1e-2)
@pytest.mark.dynamic_library
@pytest.mark.template_extension
@pytest.mark.dynamic_library()
@pytest.mark.template_extension()
def test_batched_tensors(device):
core = Core()
# TODO: remove when plugins will support set_input_tensors
@ -256,8 +257,8 @@ def test_batched_tensors(device):
# Reference values for each batch:
_tmp = np.array([test_num + 11] * one_shape_size, dtype=np.float32).reshape([2, 2, 2])
for j in range(0, batch):
assert np.array_equal(actual[j], _tmp)
for idx in range(0, batch):
assert np.array_equal(actual[idx], _tmp)
def test_inputs_outputs_property(device):
@ -340,7 +341,9 @@ def test_infer_list_as_inputs(device):
request.infer(inputs)
check_fill_inputs(request, inputs)
inputs = [np.random.normal(size=input_shape).astype(dtype) for _ in range(num_inputs)]
inputs = [
np.random.normal(size=input_shape).astype(dtype) for _ in range(num_inputs)
]
request.infer(inputs)
check_fill_inputs(request, inputs)
@ -362,7 +365,7 @@ def test_infer_mixed_keys(device):
assert np.argmax(res[model.output()]) == 2
@pytest.mark.parametrize("ov_type, numpy_dtype", [
@pytest.mark.parametrize(("ov_type", "numpy_dtype"), [
(Type.f32, np.float32),
(Type.f64, np.float64),
(Type.f16, np.float16),
@ -386,7 +389,7 @@ def test_infer_mixed_values(device, ov_type, numpy_dtype):
assert np.array_equal(request.outputs[0].data, np.concatenate((tensor1.data, array1)))
@pytest.mark.parametrize("ov_type, numpy_dtype", [
@pytest.mark.parametrize(("ov_type", "numpy_dtype"), [
(Type.f32, np.float32),
(Type.f64, np.float64),
(Type.f16, np.float16),
@ -411,7 +414,7 @@ def test_async_mixed_values(device, ov_type, numpy_dtype):
assert np.array_equal(request.outputs[0].data, np.concatenate((tensor1.data, array1)))
@pytest.mark.parametrize("ov_type, numpy_dtype", [
@pytest.mark.parametrize(("ov_type", "numpy_dtype"), [
(Type.f32, np.float32),
(Type.f64, np.float64),
(Type.f16, np.float16),
@ -432,7 +435,7 @@ def test_infer_single_input(device, ov_type, numpy_dtype):
assert np.array_equal(request.get_output_tensor().data, np.abs(tensor1.data))
@pytest.mark.parametrize("ov_type, numpy_dtype", [
@pytest.mark.parametrize(("ov_type", "numpy_dtype"), [
(Type.f32, np.float32),
(Type.f64, np.float64),
(Type.f16, np.float16),
@ -486,6 +489,7 @@ def test_infer_queue_is_ready(device):
def callback(request, _):
time.sleep(0.001)
infer_queue.set_callback(callback)
assert infer_queue.is_ready()
infer_queue.start_async()
@ -564,9 +568,11 @@ def test_infer_queue_get_idle_handle(device):
np.float16])
@pytest.mark.parametrize("mode", ["set_init_memory_state", "reset_memory_state", "normal"])
@pytest.mark.parametrize("input_shape", [[10], [10, 10], [10, 10, 10], [2, 10, 10, 10]])
@pytest.mark.skipif(os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Can't run test on device {os.environ.get('TEST_DEVICE', 'CPU')}, "
"Memory layers fully supported only on CPU")
@pytest.mark.skipif(
os.environ.get("TEST_DEVICE", "CPU") != "CPU",
reason=f"Can't run test on device {os.environ.get('TEST_DEVICE', 'CPU')}, "
"Memory layers fully supported only on CPU",
)
def test_query_state_write_buffer(device, input_shape, data_type, mode):
core = Core()
if device == "CPU":
@ -585,7 +591,7 @@ def test_query_state_write_buffer(device, input_shape, data_type, mode):
assert mem_state.name == "var_id_667"
# todo: Uncomment after fix 45611,
# CPU plugin returns outputs and memory state in FP32 in case of FP16 original precision
# assert mem_state.state.tensor_desc.precision == data_type
# Code: assert mem_state.state.tensor_desc.precision == data_type
for i in range(1, 10):
if mode == "set_init_memory_state":
@ -607,8 +613,7 @@ def test_query_state_write_buffer(device, input_shape, data_type, mode):
res = request.infer({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), \
"Expected values: {} \n Actual values: {} \n".format(expected_res, res)
assert np.allclose(res[list(res)[0]], expected_res, atol=1e-6), f"Expected values: {expected_res} \n Actual values: {res} \n"
def test_get_results(device):
@ -649,10 +654,13 @@ def test_results_async_infer(device):
np.allclose(list(outputs.values()), list(infer_queue[i].results.values()))
@pytest.mark.skipif(os.environ.get("TEST_DEVICE") not in ["GPU, FPGA", "MYRIAD"],
reason="Device independent test")
@pytest.mark.skipif(
os.environ.get("TEST_DEVICE") not in ["GPU, FPGA", "MYRIAD"],
reason="Device independent test",
)
def test_infer_float16(device):
model = bytes(b"""<net name="add_model" version="10">
model = bytes(
b"""<net name="add_model" version="10">
<layers>
<layer id="0" name="x" type="Parameter" version="opset1">
<data element_type="f16" shape="2,2,2"/>
@ -713,15 +721,15 @@ def test_infer_float16(device):
</net>""")
core = Core()
model = core.read_model(model=model)
p = PrePostProcessor(model)
p.input(0).tensor().set_element_type(Type.f16)
p.input(0).preprocess().convert_element_type(Type.f16)
p.input(1).tensor().set_element_type(Type.f16)
p.input(1).preprocess().convert_element_type(Type.f16)
p.output(0).tensor().set_element_type(Type.f16)
p.output(0).postprocess().convert_element_type(Type.f16)
ppp = PrePostProcessor(model)
ppp.input(0).tensor().set_element_type(Type.f16)
ppp.input(0).preprocess().convert_element_type(Type.f16)
ppp.input(1).tensor().set_element_type(Type.f16)
ppp.input(1).preprocess().convert_element_type(Type.f16)
ppp.output(0).tensor().set_element_type(Type.f16)
ppp.output(0).postprocess().convert_element_type(Type.f16)
model = p.build()
model = ppp.build()
compiled = core.compile_model(model, device)
input_data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]).astype(np.float16)
request = compiled.create_infer_request()

View File

@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
from ..conftest import model_path
from openvino.runtime import Input, Shape, PartialShape, Type, \
RTMap
from openvino.runtime import Input, Shape, PartialShape, Type, RTMap
from openvino.pyopenvino import DescriptorTensor
import openvino.runtime.opset8 as ops
@ -30,8 +30,8 @@ def test_input_type(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
assert isinstance(input_node, Input)
@ -39,8 +39,8 @@ def test_const_output_docs(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
exptected_string = "openvino.runtime.Input wraps ov::Input<Node>"
assert input_node.__doc__ == exptected_string
@ -49,8 +49,8 @@ def test_input_get_index(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
assert input_node.get_index() == 0
@ -58,8 +58,8 @@ def test_input_element_type(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
assert input_node.get_element_type() == Type.f32
@ -67,8 +67,8 @@ def test_input_get_shape(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
assert str(input_node.get_shape()) == str(Shape([1, 10]))
@ -76,8 +76,8 @@ def test_input_get_partial_shape(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
expected_partial_shape = PartialShape([1, 10])
assert input_node.get_partial_shape() == expected_partial_shape
@ -86,8 +86,8 @@ def test_input_get_source_output(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
name = input_node.get_source_output().get_node().get_friendly_name()
assert name == "fc_out"
@ -96,8 +96,8 @@ def test_input_get_tensor(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
tensor = input_node.get_tensor()
assert isinstance(tensor, DescriptorTensor)
@ -106,8 +106,8 @@ def test_input_get_rt_info(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
rt_info = input_node.get_rt_info()
assert isinstance(rt_info, RTMap)
@ -116,8 +116,8 @@ def test_input_rt_info(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
rt_info = input_node.rt_info
assert isinstance(rt_info, RTMap)
@ -140,10 +140,10 @@ def test_input_update_rt_info(device):
core = Core()
func = core.read_model(model=test_net_xml, weights=test_net_bin)
exec_net = core.compile_model(func, device)
input = exec_net.output(0)
input_node = input.get_node().inputs()[0]
net_input = exec_net.output(0)
input_node = net_input.get_node().inputs()[0]
rt = input_node.get_rt_info()
rt["test12345"] = "test"
for k, v in input_node.get_rt_info().items():
assert k == "test12345"
assert isinstance(v, OVAny)
for key, value in input_node.get_rt_info().items():
assert key == "test12345"
assert isinstance(value, OVAny)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -193,9 +194,9 @@ def test_query_state():
# Preprocessing
def test_pre_post_process_build():
p = PrePostProcessor(model)
p.input().model().set_layout(Layout("NC"))
check_gil_released_safe(p.build)
ppp = PrePostProcessor(model)
ppp.input().model().set_layout(Layout("NC"))
check_gil_released_safe(ppp.build)
def test_model_reshape():

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -5,10 +6,17 @@ import os
from ..conftest import model_path
import openvino.runtime.opset8 as ops
from openvino.runtime import ConstOutput, Shape, PartialShape, Type, \
Output, RTMap, OVAny
from openvino.runtime import (
ConstOutput,
Shape,
PartialShape,
Type,
Output,
RTMap,
OVAny,
Core,
)
from openvino.runtime import Core
is_myriad = os.environ.get("TEST_DEVICE") == "MYRIAD"
test_net_xml, test_net_bin = model_path(is_myriad)
@ -128,9 +136,9 @@ def test_update_rt_info(device):
output_node = Output._from_node(relu)
rt = output_node.get_rt_info()
rt["test12345"] = "test"
for k, v in output_node.get_rt_info().items():
assert k == "test12345"
assert isinstance(v, OVAny)
for key, value in output_node.get_rt_info().items():
assert key == "test12345"
assert isinstance(value, OVAny)
def test_operations():

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -8,18 +9,18 @@ from openvino.runtime import Core, Type, OVAny
from openvino.runtime import properties
def test_property_RW():
def test_property_rw():
assert properties.device.priorities() == "MULTI_DEVICE_PRIORITIES"
assert properties.device.priorities("CPU,GPU") == ("MULTI_DEVICE_PRIORITIES", OVAny("CPU,GPU,"))
assert properties.device.priorities("CPU", "GPU") == ("MULTI_DEVICE_PRIORITIES", OVAny("CPU,GPU,"))
with pytest.raises(TypeError) as e:
val = 6
properties.device.priorities("CPU", val)
assert f"Incorrect passed value: {val} , expected string values." in str(e.value)
value = 6
properties.device.priorities("CPU", value)
assert f"Incorrect passed value: {value} , expected string values." in str(e.value)
def test_property_RO():
def test_property_ro():
assert properties.available_devices() == "AVAILABLE_DEVICES"
with pytest.raises(TypeError) as e:
@ -72,7 +73,7 @@ def test_single_property_setting():
properties.hint.performance_mode(): properties.hint.PerformanceMode.LATENCY,
properties.hint.num_requests(): 12,
"NUM_STREAMS": properties.streams.Num(5),
}
},
])
def test_properties_core(properties_to_set):
core = Core()

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -16,7 +17,7 @@ import pytest
from ..conftest import read_image
@pytest.mark.parametrize("ov_type, numpy_dtype", [
@pytest.mark.parametrize(("ov_type", "numpy_dtype"), [
(ov.Type.f32, np.float32),
(ov.Type.f64, np.float64),
(ov.Type.f16, np.float16),
@ -51,7 +52,7 @@ def test_subprocess():
assert not status.returncode
@pytest.mark.parametrize("ov_type, numpy_dtype", [
@pytest.mark.parametrize(("ov_type", "numpy_dtype"), [
(ov.Type.f32, np.float32),
(ov.Type.f64, np.float64),
(ov.Type.f16, np.float16),
@ -63,7 +64,7 @@ def test_subprocess():
(ov.Type.u16, np.uint16),
(ov.Type.i64, np.int64),
(ov.Type.u64, np.uint64),
(ov.Type.boolean, np.bool)
(ov.Type.boolean, np.bool),
])
def test_init_with_numpy_dtype(ov_type, numpy_dtype):
shape = (1, 3, 127, 127)
@ -81,7 +82,7 @@ def test_init_with_numpy_dtype(ov_type, numpy_dtype):
assert np.all(ov_tensor.data.shape == shape for ov_tensor in ov_tensors)
@pytest.mark.parametrize("ov_type, numpy_dtype", [
@pytest.mark.parametrize(("ov_type", "numpy_dtype"), [
(ov.Type.f32, np.float32),
(ov.Type.f64, np.float64),
(ov.Type.f16, np.float16),
@ -93,7 +94,7 @@ def test_init_with_numpy_dtype(ov_type, numpy_dtype):
(ov.Type.u16, np.uint16),
(ov.Type.i64, np.int64),
(ov.Type.u64, np.uint64),
(ov.Type.boolean, np.bool)
(ov.Type.boolean, np.bool),
])
def test_init_with_numpy_shared_memory(ov_type, numpy_dtype):
arr = read_image().astype(numpy_dtype)
@ -118,7 +119,7 @@ def test_init_with_numpy_shared_memory(ov_type, numpy_dtype):
assert tuple(ov_tensor.get_strides()) == arr.strides
@pytest.mark.parametrize("ov_type, numpy_dtype", [
@pytest.mark.parametrize(("ov_type", "numpy_dtype"), [
(ov.Type.f32, np.float32),
(ov.Type.f64, np.float64),
(ov.Type.f16, np.float16),
@ -130,7 +131,7 @@ def test_init_with_numpy_shared_memory(ov_type, numpy_dtype):
(ov.Type.u16, np.uint16),
(ov.Type.i64, np.int64),
(ov.Type.u64, np.uint64),
(ov.Type.boolean, np.bool)
(ov.Type.boolean, np.bool),
])
def test_init_with_numpy_copy_memory(ov_type, numpy_dtype):
arr = read_image().astype(numpy_dtype)
@ -164,7 +165,7 @@ def test_init_with_roi_tensor():
assert np.array_equal(ov_tensor1.data[0:1, :, 24:, 24:], ov_tensor2.data)
@pytest.mark.parametrize("ov_type, numpy_dtype", [
@pytest.mark.parametrize(("ov_type", "numpy_dtype"), [
(ov.Type.f32, np.float32),
(ov.Type.f64, np.float64),
(ov.Type.f16, np.float16),
@ -186,7 +187,7 @@ def test_write_to_buffer(ov_type, numpy_dtype):
assert np.array_equal(ov_tensor.data, ones_arr)
@pytest.mark.parametrize("ov_type, numpy_dtype", [
@pytest.mark.parametrize(("ov_type", "numpy_dtype"), [
(ov.Type.f32, np.float32),
(ov.Type.f64, np.float64),
(ov.Type.f16, np.float16),
@ -322,7 +323,7 @@ def test_init_with_packed_buffer(dtype, ov_type):
([1, 3, 28, 28]),
([1, 3, 27, 27]),
])
@pytest.mark.parametrize("low, high, ov_type, dtype", [
@pytest.mark.parametrize(("low", "high", "ov_type", "dtype"), [
(0, 2, ov.Type.u1, np.uint8),
(0, 16, ov.Type.u4, np.uint8),
(-8, 7, ov.Type.i4, np.int8),
@ -358,19 +359,16 @@ def test_packing(shape, low, high, ov_type, dtype):
(ov.Type.u32),
(ov.Type.i64),
(ov.Type.u64),
# (ov.Type.f16),
# (ov.Type.f32),
# (ov.Type.f64),
])
def test_viewed_tensor(dtype, element_type):
buffer = np.random.normal(size=(2, 16)).astype(dtype)
fit = (dtype().nbytes * 8) / element_type.bitwidth
t = Tensor(buffer, (buffer.shape[0], int(buffer.shape[1] * fit)), element_type)
assert np.array_equal(t.data, buffer.view(ov.utils.types.get_dtype(element_type)))
tensor = Tensor(buffer, (buffer.shape[0], int(buffer.shape[1] * fit)), element_type)
assert np.array_equal(tensor.data, buffer.view(ov.utils.types.get_dtype(element_type)))
def test_viewed_tensor_default_type():
buffer = np.random.normal(size=(2, 16))
new_shape = (4, 8)
t = Tensor(buffer, new_shape)
assert np.array_equal(t.data, buffer.reshape(new_shape))
tensor = Tensor(buffer, new_shape)
assert np.array_equal(tensor.data, buffer.reshape(new_shape))

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -8,14 +9,15 @@ from tests.runtime import get_runtime
def test_adaptive_avg_pool():
runtime = get_runtime()
input = np.reshape([0.0, 4, 1, 3, -2, -5, -2,
-2, 1, -3, 1, -3, -4, 0,
-2, 1, -1, -2, 3, -1, -3,
-1, -2, 3, 4, -3, -4, 1,
2, 0, -4, -5, -2, -2, -3,
2, 3, 1, -5, 2, -4, -2], (2, 3, 7))
input_tensor = ov.constant(input)
input_vals = np.reshape([
0.0, 4, 1, 3, -2, -5, -2,
-2, 1, -3, 1, -3, -4, 0,
-2, 1, -1, -2, 3, -1, -3,
-1, -2, 3, 4, -3, -4, 1,
2, 0, -4, -5, -2, -2, -3,
2, 3, 1, -5, 2, -4, -2],
(2, 3, 7))
input_tensor = ov.constant(input_vals)
output_shape = ov.constant(np.array([3], dtype=np.int32))
adaptive_pool_node = ov.adaptive_avg_pool(input_tensor, output_shape)
@ -34,14 +36,15 @@ def test_adaptive_avg_pool():
def test_adaptive_max_pool():
runtime = get_runtime()
input = np.reshape([0, 4, 1, 3, -2, -5, -2,
-2, 1, -3, 1, -3, -4, 0,
-2, 1, -1, -2, 3, -1, -3,
-1, -2, 3, 4, -3, -4, 1,
2, 0, -4, -5, -2, -2, -3,
2, 3, 1, -5, 2, -4, -2], (2, 3, 7))
input_tensor = ov.constant(input)
input_vals = np.reshape([
0, 4, 1, 3, -2, -5, -2,
-2, 1, -3, 1, -3, -4, 0,
-2, 1, -1, -2, 3, -1, -3,
-1, -2, 3, 4, -3, -4, 1,
2, 0, -4, -5, -2, -2, -3,
2, 3, 1, -5, 2, -4, -2],
(2, 3, 7))
input_tensor = ov.constant(input_vals)
output_shape = ov.constant(np.array([3], dtype=np.int32))
adaptive_pool_node = ov.adaptive_max_pool(input_tensor, output_shape)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -5,73 +6,73 @@ from openvino.runtime import OVAny
def test_any_str():
var = OVAny("test_string")
assert isinstance(var.value, str)
assert var == "test_string"
string = OVAny("test_string")
assert isinstance(string.value, str)
assert string == "test_string"
def test_any_int():
var = OVAny(2137)
assert isinstance(var.value, int)
assert var == 2137
value = OVAny(2137)
assert isinstance(value.value, int)
assert value == 2137
def test_any_float():
var = OVAny(21.37)
assert isinstance(var.value, float)
value = OVAny(21.37)
assert isinstance(value.value, float)
def test_any_string_list():
var = OVAny(["test", "string"])
assert isinstance(var.value, list)
assert isinstance(var[0], str)
assert var[0] == "test"
str_list = OVAny(["test", "string"])
assert isinstance(str_list.value, list)
assert isinstance(str_list[0], str)
assert str_list[0] == "test"
def test_any_int_list():
v = OVAny([21, 37])
assert isinstance(v.value, list)
assert len(v) == 2
assert isinstance(v[0], int)
value = OVAny([21, 37])
assert isinstance(value.value, list)
assert len(value) == 2
assert isinstance(value[0], int)
def test_any_float_list():
v = OVAny([21.0, 37.0])
assert isinstance(v.value, list)
assert len(v) == 2
assert isinstance(v[0], float)
value = OVAny([21.0, 37.0])
assert isinstance(value.value, list)
assert len(value) == 2
assert isinstance(value[0], float)
def test_any_bool():
v = OVAny(False)
assert isinstance(v.value, bool)
assert v is not True
value = OVAny(False)
assert isinstance(value.value, bool)
assert value is not True
def test_any_dict_str():
v = OVAny({"key": "value"})
assert isinstance(v.value, dict)
assert v["key"] == "value"
value = OVAny({"key": "value"})
assert isinstance(value.value, dict)
assert value["key"] == "value"
def test_any_dict_str_int():
v = OVAny({"key": 2})
assert isinstance(v.value, dict)
assert v["key"] == 2
value = OVAny({"key": 2})
assert isinstance(value.value, dict)
assert value["key"] == 2
def test_any_int_dict():
v = OVAny({1: 2})
assert isinstance(v.value, dict)
assert v[1] == 2
value = OVAny({1: 2})
assert isinstance(value.value, dict)
assert value[1] == 2
def test_any_set_new_value():
v = OVAny(int(1))
assert isinstance(v.value, int)
v = OVAny("test")
assert isinstance(v.value, str)
assert v == "test"
value = OVAny(int(1))
assert isinstance(value.value, int)
value = OVAny("test")
assert isinstance(value.value, str)
assert value == "test"
def test_any_class():
@ -79,6 +80,6 @@ def test_any_class():
def __init__(self):
self.text = "test"
v = OVAny(TestClass())
assert isinstance(v.value, TestClass)
assert v.value.text == "test"
value = OVAny(TestClass())
assert isinstance(value.value, TestClass)
assert value.value.text == "test"

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -160,7 +161,7 @@ def test_broadcast_3():
@pytest.mark.parametrize(
"destination_type, input_data",
("destination_type", "input_data"),
[(bool, np.zeros((2, 2), dtype=np.int32)), ("boolean", np.zeros((2, 2), dtype=np.int32))],
)
def test_convert_to_bool(destination_type, input_data):
@ -171,7 +172,7 @@ def test_convert_to_bool(destination_type, input_data):
@pytest.mark.parametrize(
"destination_type, rand_range, in_dtype, expected_type",
("destination_type", "rand_range", "in_dtype", "expected_type"),
[
pytest.param(np.float32, (-8, 8), np.int32, np.float32),
pytest.param(np.float64, (-16383, 16383), np.int64, np.float64),
@ -189,7 +190,7 @@ def test_convert_to_float(destination_type, rand_range, in_dtype, expected_type)
@pytest.mark.parametrize(
"destination_type, expected_type",
("destination_type", "expected_type"),
[
(np.int8, np.int8),
(np.int16, np.int16),
@ -203,7 +204,8 @@ def test_convert_to_float(destination_type, rand_range, in_dtype, expected_type)
)
def test_convert_to_int(destination_type, expected_type):
np.random.seed(133391)
input_data = (np.ceil(-8 + np.random.rand(2, 3, 4) * 16)).astype(expected_type)
random_data = np.random.rand(2, 3, 4) * 16
input_data = (np.ceil(-8 + random_data)).astype(expected_type)
expected = np.array(input_data, dtype=expected_type)
result = run_op_node([input_data], ops.convert, destination_type)
assert np.allclose(result, expected)
@ -211,7 +213,7 @@ def test_convert_to_int(destination_type, expected_type):
@pytest.mark.parametrize(
"destination_type, expected_type",
("destination_type", "expected_type"),
[
(np.uint8, np.uint8),
(np.uint16, np.uint16),
@ -233,11 +235,11 @@ def test_convert_to_uint(destination_type, expected_type):
def test_bad_data_shape():
A = ops.parameter(shape=[2, 2], name="A", dtype=np.float32)
B = ops.parameter(shape=[2, 2], name="B")
model = A + B
param_a = ops.parameter(shape=[2, 2], name="A", dtype=np.float32)
param_b = ops.parameter(shape=[2, 2], name="B")
model = param_a + param_b
runtime = get_runtime()
computation = runtime.computation(model, A, B)
computation = runtime.computation(model, param_a, param_b)
value_a = np.array([[1, 2]], dtype=np.float32)
value_b = np.array([[5, 6], [7, 8]], dtype=np.float32)
@ -268,7 +270,7 @@ def test_constant_get_data_floating_point(data_type):
def test_constant_get_data_signed_integer(data_type):
np.random.seed(133391)
input_data = np.random.randint(
np.iinfo(data_type).min, np.iinfo(data_type).max, size=[2, 3, 4], dtype=data_type
np.iinfo(data_type).min, np.iinfo(data_type).max, size=[2, 3, 4], dtype=data_type,
)
node = ops.constant(input_data, dtype=data_type)
retrieved_data = node.get_data()
@ -418,22 +420,22 @@ def test_node_input_values():
assert np.equal(
[input_node.get_shape() for input_node in node.input_values()],
shapes
shapes,
).all()
assert np.equal(
[node.input_value(i).get_shape() for i in range(node.get_input_size())],
shapes
shapes,
).all()
assert np.allclose(
[input_node.get_node().get_vector() for input_node in node.input_values()],
[data1, data2]
[data1, data2],
)
assert np.allclose(
[node.input_value(i).get_node().get_vector() for i in range(node.get_input_size())],
[data1, data2]
[data1, data2],
)
@ -443,13 +445,13 @@ def test_node_input_tensor():
node = ops.add(data1, data2)
inputTensor1 = node.get_input_tensor(0)
inputTensor2 = node.get_input_tensor(1)
input_tensor1 = node.get_input_tensor(0)
input_tensor2 = node.get_input_tensor(1)
assert(isinstance(inputTensor1, DescriptorTensor))
assert(isinstance(inputTensor2, DescriptorTensor))
assert np.equal(inputTensor1.get_shape(), data1.shape).all()
assert np.equal(inputTensor2.get_shape(), data2.shape).all()
assert(isinstance(input_tensor1, DescriptorTensor))
assert(isinstance(input_tensor2, DescriptorTensor))
assert np.equal(input_tensor1.get_shape(), data1.shape).all()
assert np.equal(input_tensor2.get_shape(), data2.shape).all()
def test_node_evaluate():
@ -465,13 +467,13 @@ def test_node_evaluate():
node = ops.add(data1, data2)
inputTensor1 = Tensor(array=data1, shared_memory=True)
inputTensor2 = Tensor(array=data2, shared_memory=True)
inputsTensorVector = [inputTensor1, inputTensor2]
input_tensor1 = Tensor(array=data1, shared_memory=True)
input_tensor2 = Tensor(array=data2, shared_memory=True)
inputs_tensor_vector = [input_tensor1, input_tensor2]
outputTensorVector = [Tensor(array=output, shared_memory=True)]
assert node.evaluate(outputTensorVector, inputsTensorVector) is True
assert np.equal(outputTensorVector[0].data, expected_result).all()
output_tensor_vector = [Tensor(array=output, shared_memory=True)]
assert node.evaluate(output_tensor_vector, inputs_tensor_vector) is True
assert np.equal(output_tensor_vector[0].data, expected_result).all()
def test_node_input():
@ -490,7 +492,7 @@ def test_node_input():
model.get_element_type(),
).all()
assert np.equal(
[input_node.get_shape() for input_node in model_inputs], Shape(shape)
[input_node.get_shape() for input_node in model_inputs], Shape(shape),
).all()
assert np.equal(
[input_node.get_partial_shape() for input_node in model_inputs],
@ -618,17 +620,17 @@ def test_strides_iteration_methods():
def test_axis_vector_iteration_methods():
data = np.array([1, 2, 3])
axisVector = AxisVector(data)
axis_vector = AxisVector(data)
assert len(axisVector) == data.size
assert np.equal(axisVector, data).all()
assert np.equal([axisVector[i] for i in range(data.size)], data).all()
assert len(axis_vector) == data.size
assert np.equal(axis_vector, data).all()
assert np.equal([axis_vector[i] for i in range(data.size)], data).all()
data2 = np.array([5, 6, 7])
for i in range(data2.size):
axisVector[i] = data2[i]
axis_vector[i] = data2[i]
assert np.equal(axisVector, data2).all()
assert np.equal(axis_vector, data2).all()
def test_coordinate_iteration_methods():
@ -648,17 +650,17 @@ def test_coordinate_iteration_methods():
def test_coordinate_diff_iteration_methods():
data = np.array([1, 2, 3])
coordinateDiff = CoordinateDiff(data)
coordinate_diff = CoordinateDiff(data)
assert len(coordinateDiff) == data.size
assert np.equal(coordinateDiff, data).all()
assert np.equal([coordinateDiff[i] for i in range(data.size)], data).all()
assert len(coordinate_diff) == data.size
assert np.equal(coordinate_diff, data).all()
assert np.equal([coordinate_diff[i] for i in range(data.size)], data).all()
data2 = np.array([5, 6, 7])
for i in range(data2.size):
coordinateDiff[i] = data2[i]
coordinate_diff[i] = data2[i]
assert np.equal(coordinateDiff, data2).all()
assert np.equal(coordinate_diff, data2).all()
def test_get_and_set_layout():

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -29,7 +30,7 @@ def test_convolution_2d():
# filter weights should have shape M x C x kH x kW
input_filter = np.array([[1.0, 0.0, -1.0], [2.0, 0.0, -2.0], [1.0, 0.0, -1.0]], dtype=np.float32).reshape(
1, 1, 3, 3
1, 1, 3, 3,
)
strides = np.array([1, 1])
@ -55,8 +56,8 @@ def test_convolution_2d():
[0.0, -20.0, -20.0, 20.0, 20.0, 0.0, 0.0, 0.0, 0.0],
[0.0, -20.0, -20.0, 20.0, 20.0, 0.0, 0.0, 0.0, 0.0],
[0.0, -15.0, -15.0, 15.0, 15.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
],
],
dtype=np.float32,
),
@ -81,8 +82,8 @@ def test_convolution_2d():
[-20, -20, 20, 20, 0, 0, 0],
[-20, -20, 20, 20, 0, 0, 0],
[-20, -20, 20, 20, 0, 0, 0],
]
]
],
],
],
dtype=np.float32,
),
@ -106,8 +107,8 @@ def test_convolution_2d():
[-20.0, 20.0, 0.0, 0.0],
[-20.0, 20.0, 0.0, 0.0],
[-20.0, 20.0, 0.0, 0.0],
]
]
],
],
],
dtype=np.float32,
),
@ -131,8 +132,8 @@ def test_convolution_2d():
[0, 0, 20, 20, 0],
[0, 0, 20, 20, 0],
[0, 0, 20, 20, 0],
]
]
],
],
],
dtype=np.float32,
),
@ -164,14 +165,14 @@ def test_convolution_backprop_data():
[-20, -20, 20, 20, 0, 0, 0],
[-20, -20, 20, 20, 0, 0, 0],
[-20, -20, 20, 20, 0, 0, 0],
]
]
],
],
],
dtype=np.float32,
)
filter_data = np.array([[1.0, 0.0, -1.0], [2.0, 0.0, -2.0], [1.0, 0.0, -1.0]], dtype=np.float32).reshape(
1, 1, 3, 3
1, 1, 3, 3,
)
model = runtime.computation(deconvolution, data_node, filter_node)
@ -191,8 +192,8 @@ def test_convolution_backprop_data():
[-80.0, -80.0, 160.0, 160.0, -80.0, -80.0, 0.0, 0.0, 0.0],
[-60.0, -60.0, 120.0, 120.0, -60.0, -60.0, 0.0, 0.0, 0.0],
[-20.0, -20.0, 40.0, 40.0, -20.0, -20.0, 0.0, 0.0, 0.0],
]
]
],
],
],
dtype=np.float32,
),

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -77,31 +78,31 @@ def test_dimension_comparisons():
assert not d2.compatible(d1)
assert not d2.same_scheme(d1)
d = Dimension("?")
assert d == Dimension()
dim = Dimension("?")
assert dim == Dimension()
d = Dimension("1")
assert d == Dimension(1)
dim = Dimension("1")
assert dim == Dimension(1)
d = Dimension("..10")
assert d == Dimension(-1, 10)
dim = Dimension("..10")
assert dim == Dimension(-1, 10)
d = Dimension("10..")
assert d == Dimension(10, -1)
dim = Dimension("10..")
assert dim == Dimension(10, -1)
d = Dimension("5..10")
assert d == Dimension(5, 10)
dim = Dimension("5..10")
assert dim == Dimension(5, 10)
with pytest.raises(RuntimeError) as e:
d = Dimension("C")
dim = Dimension("C")
assert 'Cannot parse dimension: "C"' in str(e.value)
with pytest.raises(RuntimeError) as e:
d = Dimension("?..5")
dim = Dimension("?..5")
assert 'Cannot parse min bound: "?"' in str(e.value)
with pytest.raises(RuntimeError) as e:
d = Dimension("5..?")
dim = Dimension("5..?")
assert 'Cannot parse max bound: "?"' in str(e.value)
@ -169,25 +170,39 @@ def test_partial_shape():
assert repr(ps) == "<PartialShape: {?,?}>"
shape_list = [(1, 10), [2, 5], 4, Dimension(2), "..10"]
ref_ps = PartialShape([Dimension(1, 10), Dimension(2, 5), Dimension(4), Dimension(2), Dimension(-1, 10)])
ref_ps = PartialShape(
[
Dimension(1, 10),
Dimension(2, 5),
Dimension(4),
Dimension(2),
Dimension(-1, 10),
],
)
assert PartialShape(shape_list) == ref_ps
assert PartialShape(tuple(shape_list)) == ref_ps
with pytest.raises(TypeError) as e:
PartialShape([(1, 2, 3)])
assert "Two elements are expected in tuple(lower, upper) " \
"for dynamic dimension, but 3 elements were given." in str(e.value)
assert (
"Two elements are expected in tuple(lower, upper) "
"for dynamic dimension, but 3 elements were given." in str(e.value)
)
with pytest.raises(TypeError) as e:
PartialShape([("?", "?")])
assert "Incorrect pair of types (<class 'str'>, <class 'str'>) " \
"for dynamic dimension, ints are expected." in str(e.value)
assert (
"Incorrect pair of types (<class 'str'>, <class 'str'>) "
"for dynamic dimension, ints are expected." in str(e.value)
)
with pytest.raises(TypeError) as e:
PartialShape([range(10)])
assert "Incorrect type <class 'range'> for dimension. Expected types are: " \
"int, str, openvino.runtime.Dimension, list/tuple with lower " \
"and upper values for dynamic dimension." in str(e.value)
assert (
"Incorrect type <class 'range'> for dimension. Expected types are: "
"int, str, openvino.runtime.Dimension, list/tuple with lower "
"and upper values for dynamic dimension." in str(e.value)
)
ps = PartialShape("...")
assert ps == PartialShape.dynamic()
@ -301,10 +316,13 @@ def test_repr_dynamic_shape():
model = parameter_a + parameter_b
function = Model(model, [parameter_a, parameter_b], "simple_dyn_shapes_graph")
assert repr(function) == "<Model: 'simple_dyn_shapes_graph'\ninputs[" + \
"\n<ConstOutput: names[A] shape{?,2} type: f32>," +\
"\n<ConstOutput: names[B] shape{?,2} type: f32>\n]" + \
"\noutputs[\n<ConstOutput: names[] shape{?,2} type: f32>\n]>"
assert (
repr(function)
== "<Model: 'simple_dyn_shapes_graph'\ninputs["
+ "\n<ConstOutput: names[A] shape{?,2} type: f32>,"
+ "\n<ConstOutput: names[B] shape{?,2} type: f32>\n]"
+ "\noutputs[\n<ConstOutput: names[] shape{?,2} type: f32>\n]>"
)
ops = function.get_ordered_ops()
for op in ops:
@ -314,10 +332,10 @@ def test_repr_dynamic_shape():
def test_discrete_type_info():
data_shape = [6, 12, 10, 24]
data_parameter = ov.parameter(data_shape, name="Data", dtype=np.float32)
k = np.int32(3)
k_val = np.int32(3)
axis = np.int32(1)
n1 = ov.topk(data_parameter, k, axis, "max", "value")
n2 = ov.topk(data_parameter, k, axis, "max", "value")
n1 = ov.topk(data_parameter, k_val, axis, "max", "value")
n2 = ov.topk(data_parameter, k_val, axis, "max", "value")
n3 = ov.sin(0.2)
assert n1.type_info.name == "TopK"

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -149,7 +150,7 @@ def test_pad_edge():
[9, 9, 10, 11, 12, 12, 12, 12],
[9, 9, 10, 11, 12, 12, 12, 12],
[9, 9, 10, 11, 12, 12, 12, 12],
]
],
)
assert np.allclose(result, expected)
@ -173,7 +174,7 @@ def test_pad_constant():
[100, 9, 10, 11, 12, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100, 100],
]
],
)
assert np.allclose(result, expected)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -19,7 +20,7 @@ integral_np_types = [
@pytest.mark.parametrize(
"int_dtype, fp_dtype",
("int_dtype", "fp_dtype"),
[
(np.int8, np.float32),
(np.int16, np.float32),
@ -53,7 +54,7 @@ def test_detection_output(int_dtype, fp_dtype):
@pytest.mark.parametrize(
"int_dtype, fp_dtype",
("int_dtype", "fp_dtype"),
[
(np.int8, np.float32),
(np.int16, np.float32),

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -7,7 +8,7 @@ import pytest
@pytest.fixture()
def _proposal_node():
def proposal_node():
attributes = {
"base_size": np.uint16(1),
"pre_nms_topn": np.uint16(20),
@ -37,7 +38,7 @@ def test_dynamic_attributes_softmax():
@pytest.mark.parametrize(
"int_dtype, fp_dtype",
("int_dtype", "fp_dtype"),
[
(np.uint8, np.float32),
(np.uint16, np.float32),
@ -96,8 +97,8 @@ def test_dynamic_set_attribute_value(int_dtype, fp_dtype):
assert node.get_framework() == "OpenVINO"
def test_dynamic_attr_cache(_proposal_node):
node = _proposal_node
def test_dynamic_attr_cache(proposal_node):
node = proposal_node
assert not node._attr_cache_valid
node.set_nms_thresh(1.3453678102)
@ -106,8 +107,8 @@ def test_dynamic_attr_cache(_proposal_node):
assert node._attr_cache_valid
def test_dynamic_attr_transitivity(_proposal_node):
node = _proposal_node
def test_dynamic_attr_transitivity(proposal_node):
node = proposal_node
node2 = node
node.set_ratio(np.array([1.1, 2.5, 3.0, 4.5], dtype=np.float64))
@ -124,17 +125,17 @@ def test_dynamic_attributes_simple():
input_size = 16
hidden_size = 128
X_shape = [batch_size, input_size]
H_t_shape = [batch_size, hidden_size]
W_shape = [3 * hidden_size, input_size]
R_shape = [3 * hidden_size, hidden_size]
B_shape = [4 * hidden_size]
x_shape = [batch_size, input_size]
h_t_shape = [batch_size, hidden_size]
w_shape = [3 * hidden_size, input_size]
r_shape = [3 * hidden_size, hidden_size]
b_shape = [4 * hidden_size]
parameter_X = ov.parameter(X_shape, name="X", dtype=np.float32)
parameter_H_t = ov.parameter(H_t_shape, name="H_t", dtype=np.float32)
parameter_W = ov.parameter(W_shape, name="W", dtype=np.float32)
parameter_R = ov.parameter(R_shape, name="R", dtype=np.float32)
parameter_B = ov.parameter(B_shape, name="B", dtype=np.float32)
parameter_x = ov.parameter(x_shape, name="X", dtype=np.float32)
parameter_h_t = ov.parameter(h_t_shape, name="H_t", dtype=np.float32)
parameter_w = ov.parameter(w_shape, name="W", dtype=np.float32)
parameter_r = ov.parameter(r_shape, name="R", dtype=np.float32)
parameter_b = ov.parameter(b_shape, name="B", dtype=np.float32)
activations = ["tanh", "relu"]
activations_alpha = [1.0, 2.0]
@ -143,11 +144,11 @@ def test_dynamic_attributes_simple():
linear_before_reset = True
node = ov.gru_cell(
parameter_X,
parameter_H_t,
parameter_W,
parameter_R,
parameter_B,
parameter_x,
parameter_h_t,
parameter_w,
parameter_r,
parameter_b,
hidden_size,
activations,
activations_alpha,

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -20,7 +21,8 @@ def einsum_op_exec(input_shapes: list, equation: str, data_type: np.dtype,
:param equation: Einsum equation
:param data_type: a type of input data
:param with_value: if True - tests output data shape and type along with its value,
otherwise, tests only the output shape and type
otherwise, tests only the output shape and type
:param seed: a seed for random generation of input data
"""
np.random.seed(seed)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -11,7 +12,7 @@ from openvino.runtime.utils.types import get_element_type
@pytest.mark.parametrize(
"num_rows, num_columns, diagonal_index, out_type",
("num_rows", "num_columns", "diagonal_index", "out_type"),
[
pytest.param(2, 5, 0, np.float32),
pytest.param(5, 3, 2, np.int64),
@ -47,14 +48,15 @@ def test_eye_rectangle(num_rows, num_columns, diagonal_index, out_type):
assert tuple(eye_node.get_output_shape(0)) == expected_results.shape
# TODO: Enable with Eye reference implementation
# runtime = get_runtime()
# computation = runtime.computation(eye_node)
# eye_results = computation()
# assert np.allclose(eye_results, expected_results)
"""runtime = get_runtime()
computation = runtime.computation(eye_node)
eye_results = computation()
assert np.allclose(eye_results, expected_results)
"""
@pytest.mark.parametrize(
"num_rows, num_columns, diagonal_index, batch_shape, out_type",
("num_rows", "num_columns", "diagonal_index", "batch_shape", "out_type"),
[
pytest.param(2, 5, 0, [1], np.float32),
pytest.param(5, 3, 2, [2, 2], np.int64),
@ -96,7 +98,8 @@ def test_eye_batch_shape(num_rows, num_columns, diagonal_index, batch_shape, out
assert tuple(eye_node.get_output_shape(0)) == expected_results.shape
# TODO: Enable with Eye reference implementation
# runtime = get_runtime()
# computation = runtime.computation(eye_node)
# eye_results = computation()
# assert np.allclose(eye_results, expected_results)
"""runtime = get_runtime()
computation = runtime.computation(eye_node)
eye_results = computation()
assert np.allclose(eye_results, expected_results)
"""

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -9,13 +10,13 @@ from tests.test_ngraph.util import run_op_node
def test_gather():
input_data = np.array(
[1.0, 1.1, 1.2, 2.0, 2.1, 2.2, 3.0, 3.1, 3.2], np.float32
[1.0, 1.1, 1.2, 2.0, 2.1, 2.2, 3.0, 3.1, 3.2], np.float32,
).reshape((3, 3))
input_indices = np.array([0, 2], np.int32).reshape(1, 2)
input_axis = np.array([1], np.int32)
expected = np.array([1.0, 1.2, 2.0, 2.2, 3.0, 3.2], dtype=np.float32).reshape(
(3, 1, 2)
(3, 1, 2),
)
result = run_op_node([input_data], ov.gather, input_indices, input_axis)
@ -24,13 +25,13 @@ def test_gather():
def test_gather_with_scalar_axis():
input_data = np.array(
[1.0, 1.1, 1.2, 2.0, 2.1, 2.2, 3.0, 3.1, 3.2], np.float32
[1.0, 1.1, 1.2, 2.0, 2.1, 2.2, 3.0, 3.1, 3.2], np.float32,
).reshape((3, 3))
input_indices = np.array([0, 2], np.int32).reshape(1, 2)
input_axis = np.array(1, np.int32)
expected = np.array([1.0, 1.2, 2.0, 2.2, 3.0, 3.2], dtype=np.float32).reshape(
(3, 1, 2)
(3, 1, 2),
)
result = run_op_node([input_data], ov.gather, input_indices, input_axis)
@ -56,13 +57,13 @@ def test_gather_batch_dims_1():
def test_gather_negative_indices():
input_data = np.array(
[1.0, 1.1, 1.2, 2.0, 2.1, 2.2, 3.0, 3.1, 3.2], np.float32
[1.0, 1.1, 1.2, 2.0, 2.1, 2.2, 3.0, 3.1, 3.2], np.float32,
).reshape((3, 3))
input_indices = np.array([0, -1], np.int32).reshape(1, 2)
input_axis = np.array([1], np.int32)
expected = np.array([1.0, 1.2, 2.0, 2.2, 3.0, 3.2], dtype=np.float32).reshape(
(3, 1, 2)
(3, 1, 2),
)
result = run_op_node([input_data], ov.gather, input_indices, input_axis)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -14,39 +15,39 @@ def create_simple_if_with_two_outputs(condition_val):
condition = ov.constant(condition_val, dtype=np.bool)
# then_body
X_t = ov.parameter([], np.float32, "X")
Y_t = ov.parameter([], np.float32, "Y")
Z_t = ov.parameter([], np.float32, "Z")
x_t = ov.parameter([], np.float32, "X")
y_t = ov.parameter([], np.float32, "Y")
z_t = ov.parameter([], np.float32, "Z")
add_t = ov.add(X_t, Y_t)
mul_t = ov.multiply(Y_t, Z_t)
add_t = ov.add(x_t, y_t)
mul_t = ov.multiply(y_t, z_t)
then_body_res_1 = ov.result(add_t)
then_body_res_2 = ov.result(mul_t)
then_body = Model([then_body_res_1, then_body_res_2], [X_t, Y_t, Z_t], "then_body_function")
then_body = Model([then_body_res_1, then_body_res_2], [x_t, y_t, z_t], "then_body_function")
# else_body
X_e = ov.parameter([], np.float32, "X")
Z_e = ov.parameter([], np.float32, "Z")
W_e = ov.parameter([], np.float32, "W")
x_e = ov.parameter([], np.float32, "X")
z_e = ov.parameter([], np.float32, "Z")
w_e = ov.parameter([], np.float32, "W")
add_e = ov.add(X_e, W_e)
pow_e = ov.power(W_e, Z_e)
add_e = ov.add(x_e, w_e)
pow_e = ov.power(w_e, z_e)
else_body_res_1 = ov.result(add_e)
else_body_res_2 = ov.result(pow_e)
else_body = Model([else_body_res_1, else_body_res_2], [X_e, Z_e, W_e], "else_body_function")
else_body = Model([else_body_res_1, else_body_res_2], [x_e, z_e, w_e], "else_body_function")
X = ov.constant(15.0, dtype=np.float32)
Y = ov.constant(-5.0, dtype=np.float32)
Z = ov.constant(4.0, dtype=np.float32)
W = ov.constant(2.0, dtype=np.float32)
const_x = ov.constant(15.0, dtype=np.float32)
const_y = ov.constant(-5.0, dtype=np.float32)
const_z = ov.constant(4.0, dtype=np.float32)
const_w = ov.constant(2.0, dtype=np.float32)
if_node = ov.if_op(condition)
if_node.set_then_body(then_body)
if_node.set_else_body(else_body)
if_node.set_input(X.output(0), X_t, X_e)
if_node.set_input(Y.output(0), Y_t, None)
if_node.set_input(Z.output(0), Z_t, Z_e)
if_node.set_input(W.output(0), None, W_e)
if_node.set_input(const_x.output(0), x_t, x_e)
if_node.set_input(const_y.output(0), y_t, None)
if_node.set_input(const_z.output(0), z_t, z_e)
if_node.set_input(const_w.output(0), None, w_e)
if_node.set_output(then_body_res_1, else_body_res_1)
if_node.set_output(then_body_res_2, else_body_res_2)
return if_node
@ -56,32 +57,32 @@ def create_diff_if_with_two_outputs(condition_val):
condition = ov.constant(condition_val, dtype=np.bool)
# then_body
X_t = ov.parameter([2], np.float32, "X")
Y_t = ov.parameter([2], np.float32, "Y")
mmul_t = ov.matmul(X_t, Y_t, False, False)
mul_t = ov.multiply(Y_t, X_t)
x_t = ov.parameter([2], np.float32, "X")
y_t = ov.parameter([2], np.float32, "Y")
mmul_t = ov.matmul(x_t, y_t, False, False)
mul_t = ov.multiply(y_t, x_t)
then_body_res_1 = ov.result(mmul_t)
then_body_res_2 = ov.result(mul_t)
then_body = Model([then_body_res_1, then_body_res_2], [X_t, Y_t], "then_body_function")
then_body = Model([then_body_res_1, then_body_res_2], [x_t, y_t], "then_body_function")
# else_body
X_e = ov.parameter([2], np.float32, "X")
Z_e = ov.parameter([], np.float32, "Z")
mul_e = ov.multiply(X_e, Z_e)
else_body_res_1 = ov.result(Z_e)
x_e = ov.parameter([2], np.float32, "X")
z_e = ov.parameter([], np.float32, "Z")
mul_e = ov.multiply(x_e, z_e)
else_body_res_1 = ov.result(z_e)
else_body_res_2 = ov.result(mul_e)
else_body = Model([else_body_res_1, else_body_res_2], [X_e, Z_e], "else_body_function")
else_body = Model([else_body_res_1, else_body_res_2], [x_e, z_e], "else_body_function")
X = ov.constant([3, 4], dtype=np.float32)
Y = ov.constant([2, 1], dtype=np.float32)
Z = ov.constant(4.0, dtype=np.float32)
const_x = ov.constant([3, 4], dtype=np.float32)
const_y = ov.constant([2, 1], dtype=np.float32)
const_z = ov.constant(4.0, dtype=np.float32)
if_node = ov.if_op(condition)
if_node.set_then_body(then_body)
if_node.set_else_body(else_body)
if_node.set_input(X.output(0), X_t, X_e)
if_node.set_input(Y.output(0), Y_t, None)
if_node.set_input(Z.output(0), None, Z_e)
if_node.set_input(const_x.output(0), x_t, x_e)
if_node.set_input(const_y.output(0), y_t, None)
if_node.set_input(const_z.output(0), None, z_e)
if_node.set_output(then_body_res_1, else_body_res_1)
if_node.set_output(then_body_res_2, else_body_res_2)
@ -91,28 +92,28 @@ def create_diff_if_with_two_outputs(condition_val):
def simple_if(condition_val):
condition = ov.constant(condition_val, dtype=np.bool)
# then_body
X_t = ov.parameter([2], np.float32, "X")
Y_t = ov.parameter([2], np.float32, "Y")
x_t = ov.parameter([2], np.float32, "X")
y_t = ov.parameter([2], np.float32, "Y")
then_mul = ov.multiply(X_t, Y_t)
then_mul = ov.multiply(x_t, y_t)
then_body_res_1 = ov.result(then_mul)
then_body = Model([then_body_res_1], [X_t, Y_t], "then_body_function")
then_body = Model([then_body_res_1], [x_t, y_t], "then_body_function")
# else_body
X_e = ov.parameter([2], np.float32, "X")
Y_e = ov.parameter([2], np.float32, "Y")
add_e = ov.add(X_e, Y_e)
x_e = ov.parameter([2], np.float32, "X")
y_e = ov.parameter([2], np.float32, "Y")
add_e = ov.add(x_e, y_e)
else_body_res_1 = ov.result(add_e)
else_body = Model([else_body_res_1], [X_e, Y_e], "else_body_function")
else_body = Model([else_body_res_1], [x_e, y_e], "else_body_function")
X = ov.constant([3, 4], dtype=np.float32)
Y = ov.constant([2, 1], dtype=np.float32)
const_x = ov.constant([3, 4], dtype=np.float32)
const_y = ov.constant([2, 1], dtype=np.float32)
if_node = ov.if_op(condition)
if_node.set_then_body(then_body)
if_node.set_else_body(else_body)
if_node.set_input(X.output(0), X_t, X_e)
if_node.set_input(Y.output(0), Y_t, Y_e)
if_node.set_input(const_x.output(0), x_t, x_e)
if_node.set_input(const_y.output(0), y_t, y_e)
if_res = if_node.set_output(then_body_res_1, else_body_res_1)
relu = ov.relu(if_res)
@ -181,12 +182,12 @@ def test_simple_if_without_body_parameters():
def test_simple_if_basic():
condition = ov.constant(True, dtype=np.bool)
# then_body
X_t = ov.parameter([2], np.float32, "X")
Y_t = ov.parameter([2], np.float32, "Y")
x_t = ov.parameter([2], np.float32, "X")
y_t = ov.parameter([2], np.float32, "Y")
then_mul = ov.multiply(X_t, Y_t)
then_mul = ov.multiply(x_t, y_t)
then_body_res_1 = ov.result(then_mul)
then_body = Model([then_body_res_1], [X_t, Y_t], "then_body_function")
then_body = Model([then_body_res_1], [x_t, y_t], "then_body_function")
then_body_inputs = [InvariantInputDescription(1, 0), InvariantInputDescription(2, 1)]
else_body_outputs = [BodyOutputDescription(0, 0)]

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -40,7 +41,7 @@ def test_is_non_negative_value_unsigned_type(dtype):
@pytest.mark.parametrize(
"value, val_type",
("value", "val_type"),
[
(np.int8(64), np.integer),
(np.int16(64), np.integer),
@ -55,14 +56,14 @@ def test_is_non_negative_value_unsigned_type(dtype):
],
)
def test_check_value(value, val_type):
def is_even(x):
return x % 2 == 0
def is_even(value):
return value % 2 == 0
assert _check_value("TestOp", "test_attr", value, val_type, is_even)
@pytest.mark.parametrize(
"value, val_type",
("value", "val_type"),
[
(np.int8(64), np.floating),
(np.int16(64), np.floating),
@ -86,7 +87,7 @@ def test_check_value_fail_type(value, val_type):
@pytest.mark.parametrize(
"value, val_type",
("value", "val_type"),
[
(np.int8(61), np.integer),
(np.int16(61), np.integer),
@ -101,8 +102,8 @@ def test_check_value_fail_type(value, val_type):
],
)
def test_check_value_fail_cond(value, val_type):
def is_even(x):
return x % 2 == 0
def is_even(value):
return value % 2 == 0
try:
_check_value("TestOp", "test_attr", value, val_type, is_even)
@ -136,8 +137,8 @@ def test_check_valid_attributes():
"coefficients": [1, 2, 3, 4, 5],
}
def _is_supported_mode(x):
return x in ["linear", "area", "cubic", "bilinear"]
def _is_supported_mode(mode):
return mode in ["linear", "area", "cubic", "bilinear"]
requirements = [
("width", False, np.unsignedinteger, None),

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -5,42 +6,47 @@ import numpy as np
import openvino.runtime.opset8 as ov
from openvino.runtime import Model, Shape
from openvino.runtime.op.util import InvariantInputDescription, BodyOutputDescription,\
SliceInputDescription, MergedInputDescription, ConcatOutputDescription
from openvino.runtime.op.util import (
InvariantInputDescription,
BodyOutputDescription,
SliceInputDescription,
MergedInputDescription,
ConcatOutputDescription,
)
def test_simple_loop():
X = ov.parameter(Shape([32, 1, 10]), np.float32, "X")
Y = ov.parameter(Shape([32, 1, 10]), np.float32, "Y")
M = ov.parameter(Shape([32, 1, 10]), np.float32, "M")
param_x = ov.parameter(Shape([32, 1, 10]), np.float32, "X")
param_y = ov.parameter(Shape([32, 1, 10]), np.float32, "Y")
param_m = ov.parameter(Shape([32, 1, 10]), np.float32, "M")
input_shape = Shape([])
current_iteration = ov.parameter(Shape([1]), np.int64)
X_i = ov.parameter(input_shape, np.float32)
Y_i = ov.parameter(input_shape, np.float32)
M_body = ov.parameter(input_shape, np.float32)
x_i = ov.parameter(input_shape, np.float32)
y_i = ov.parameter(input_shape, np.float32)
m_body = ov.parameter(input_shape, np.float32)
bool_val = np.array([1], dtype=np.bool)
bool_val[0] = True
body_condition = ov.constant(bool_val)
trip_count = ov.constant(10, dtype=np.int64)
exec_condition = ov.constant(True, dtype=np.bool)
sum = ov.add(X_i, Y_i)
Zo = ov.multiply(sum, M_body)
add = ov.add(x_i, y_i)
zo = ov.multiply(add, m_body)
body = Model([body_condition, Zo], [current_iteration, X_i, Y_i, M_body], "body_function")
body = Model([body_condition, zo], [current_iteration, x_i, y_i, m_body], "body_function")
loop = ov.loop(trip_count, exec_condition)
loop.set_function(body)
loop.set_invariant_input(X_i, X.output(0))
loop.set_invariant_input(Y_i, Y.output(0))
loop.set_merged_input(M_body, M.output(0), Zo.output(0))
loop.set_invariant_input(x_i, param_x.output(0))
loop.set_invariant_input(y_i, param_y.output(0))
loop.set_merged_input(m_body, param_m.output(0), zo.output(0))
loop.set_special_body_ports([-1, 0])
out0 = loop.get_iter_value(body_condition.output(0), -1)
out1 = loop.get_iter_value(Zo.output(0), -1)
out2 = loop.get_concatenated_slices(Zo.output(0), 0, 1, 1, -1, 1)
out1 = loop.get_iter_value(zo.output(0), -1)
out2 = loop.get_concatenated_slices(zo.output(0), 0, 1, 1, -1, 1)
result0 = ov.result(out0)
result1 = ov.result(out1)
@ -87,8 +93,11 @@ def test_loop_basic():
iter_cnt = ov.range(zero, np.int32(16), np.int32(1))
body_const_condition = ov.constant(bool_val)
graph_body = Model([curr_cma, cma_hist, body_const_condition], [body_timestep,
body_data_in, body_prev_cma, body_const_one], "body_function")
graph_body = Model(
[curr_cma, cma_hist, body_const_condition],
[body_timestep, body_data_in, body_prev_cma, body_const_one],
"body_function",
)
ti_slice_input_desc = [
# timestep
@ -137,14 +146,18 @@ def test_loop_basic():
input_desc = loop.get_input_descriptions()
output_desc = loop.get_output_descriptions()
assert len(input_desc) == len(ti_slice_input_desc) + \
len(ti_merged_input_desc) + len(ti_invariant_input_desc)
assert len(input_desc) == len(ti_slice_input_desc) + len(
ti_merged_input_desc,
) + len(ti_invariant_input_desc)
assert len(output_desc) == len(ti_body_output_desc) + len(ti_concat_output_desc)
for i in range(len(ti_slice_input_desc)):
assert input_desc[i].get_type_info() == ti_slice_input_desc[i].get_type_info()
assert input_desc[i].input_index == ti_slice_input_desc[i].input_index
assert input_desc[i].body_parameter_index == ti_slice_input_desc[i].body_parameter_index
assert (
input_desc[i].body_parameter_index
== ti_slice_input_desc[i].body_parameter_index
)
assert input_desc[i].start == ti_slice_input_desc[i].start
assert input_desc[i].stride == ti_slice_input_desc[i].stride
assert input_desc[i].part_size == ti_slice_input_desc[i].part_size
@ -152,22 +165,53 @@ def test_loop_basic():
assert input_desc[i].axis == ti_slice_input_desc[i].axis
for i in range(len(ti_merged_input_desc)):
assert input_desc[len(ti_slice_input_desc)
+ i].get_type_info() == ti_merged_input_desc[i].get_type_info()
assert input_desc[len(ti_slice_input_desc) + i].input_index == ti_merged_input_desc[i].input_index
assert input_desc[len(ti_slice_input_desc)
+ i].body_parameter_index == ti_merged_input_desc[i].body_parameter_index
assert input_desc[len(ti_slice_input_desc)
+ i].body_value_index == ti_merged_input_desc[i].body_value_index
assert (
input_desc[len(ti_slice_input_desc) + i].get_type_info()
== ti_merged_input_desc[i].get_type_info()
)
assert (
input_desc[len(ti_slice_input_desc) + i].input_index
== ti_merged_input_desc[i].input_index
)
assert (
input_desc[len(ti_slice_input_desc) + i].body_parameter_index
== ti_merged_input_desc[i].body_parameter_index
)
assert (
input_desc[len(ti_slice_input_desc) + i].body_value_index
== ti_merged_input_desc[i].body_value_index
)
for i in range(len(ti_concat_output_desc)):
assert output_desc[len(ti_body_output_desc)
+ i].get_type_info() == ti_concat_output_desc[i].get_type_info()
assert output_desc[len(ti_body_output_desc) + i].output_index == ti_concat_output_desc[i].output_index
assert output_desc[len(ti_body_output_desc)
+ i].body_value_index == ti_concat_output_desc[i].body_value_index
assert output_desc[len(ti_body_output_desc) + i].start == ti_concat_output_desc[i].start
assert output_desc[len(ti_body_output_desc) + i].stride == ti_concat_output_desc[i].stride
assert output_desc[len(ti_body_output_desc) + i].part_size == ti_concat_output_desc[i].part_size
assert output_desc[len(ti_body_output_desc) + i].end == ti_concat_output_desc[i].end
assert output_desc[len(ti_body_output_desc) + i].axis == ti_concat_output_desc[i].axis
assert (
output_desc[len(ti_body_output_desc) + i].get_type_info()
== ti_concat_output_desc[i].get_type_info()
)
assert (
output_desc[len(ti_body_output_desc) + i].output_index
== ti_concat_output_desc[i].output_index
)
assert (
output_desc[len(ti_body_output_desc) + i].body_value_index
== ti_concat_output_desc[i].body_value_index
)
assert (
output_desc[len(ti_body_output_desc) + i].start
== ti_concat_output_desc[i].start
)
assert (
output_desc[len(ti_body_output_desc) + i].stride
== ti_concat_output_desc[i].stride
)
assert (
output_desc[len(ti_body_output_desc) + i].part_size
== ti_concat_output_desc[i].part_size
)
assert (
output_desc[len(ti_body_output_desc) + i].end
== ti_concat_output_desc[i].end
)
assert (
output_desc[len(ti_body_output_desc) + i].axis
== ti_concat_output_desc[i].axis
)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -39,11 +40,11 @@ def test_node_factory_wrapper_add():
def test_node_factory_topk():
dtype = np.int32
data = ov.parameter([2, 10], dtype=dtype, name="A")
k = ov.constant(3, dtype=dtype, name="B")
const = ov.constant(3, dtype=dtype, name="B")
factory = NodeFactory("opset1")
arguments = NodeFactory._arguments_as_outputs([data, k])
arguments = NodeFactory._arguments_as_outputs([data, const])
node = factory.create(
"TopK", arguments, {"axis": 1, "mode": "max", "sort": "value"}
"TopK", arguments, {"axis": 1, "mode": "max", "sort": "value"},
)
attributes = node.get_attributes()
@ -65,9 +66,9 @@ def test_node_factory_empty_topk():
def test_node_factory_empty_topk_with_args_and_attrs():
dtype = np.int32
data = ov.parameter([2, 10], dtype=dtype, name="A")
k = ov.constant(3, dtype=dtype, name="B")
const = ov.constant(3, dtype=dtype, name="B")
factory = NodeFactory("opset1")
arguments = NodeFactory._arguments_as_outputs([data, k])
arguments = NodeFactory._arguments_as_outputs([data, const])
node = factory.create("TopK", None, None)
node.set_arguments(arguments)
node.set_attribute("axis", 1)
@ -85,7 +86,7 @@ def test_node_factory_validate_missing_arguments():
try:
factory.create(
"TopK", None, {"axis": 1, "mode": "max", "sort": "value"}
"TopK", None, {"axis": 1, "mode": "max", "sort": "value"},
)
except UserInputError:
pass

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -49,7 +50,7 @@ def test_lrn_factory():
bias = 2.0
nsize = 3
axis = np.array([1], dtype=np.int32)
x = np.array(
inputs = np.array(
[
[
[
@ -62,7 +63,7 @@ def test_lrn_factory():
[-0.10769883, 0.75242394, -0.2507971, 1.0447186],
[-1.4777364, 0.19993274, 0.925649, -2.282516],
],
]
],
],
dtype=np.float32,
)
@ -79,11 +80,11 @@ def test_lrn_factory():
[-0.07615435, 0.53203356, -0.17733987, 0.7387126],
[-1.0448756, 0.14137045, 0.6544598, -1.6138376],
],
]
],
],
dtype=np.float32,
)
result = run_op_node([x], ov.lrn, axis, alpha, beta, bias, nsize)
result = run_op_node([inputs], ov.lrn, axis, alpha, beta, bias, nsize)
assert np.allclose(result, excepted)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -12,7 +13,7 @@ from tests.test_ngraph.util import run_op_node
@pytest.mark.parametrize(
"ng_api_helper,numpy_function",
("ng_api_helper", "numpy_function"),
[
(ov.add, np.add),
(ov.divide, np.divide),
@ -48,7 +49,7 @@ def test_binary_op(ng_api_helper, numpy_function):
@pytest.mark.parametrize(
"ng_api_helper,numpy_function",
("ng_api_helper", "numpy_function"),
[
(ov.add, np.add),
(ov.divide, np.divide),
@ -83,7 +84,7 @@ def test_binary_op_with_scalar(ng_api_helper, numpy_function):
@pytest.mark.parametrize(
"ng_api_helper,numpy_function",
("ng_api_helper", "numpy_function"),
[(ov.logical_and, np.logical_and), (ov.logical_or, np.logical_or), (ov.logical_xor, np.logical_xor)],
)
def test_binary_logical_op(ng_api_helper, numpy_function):
@ -105,7 +106,7 @@ def test_binary_logical_op(ng_api_helper, numpy_function):
@pytest.mark.parametrize(
"ng_api_helper,numpy_function",
("ng_api_helper", "numpy_function"),
[(ov.logical_and, np.logical_and), (ov.logical_or, np.logical_or), (ov.logical_xor, np.logical_xor)],
)
def test_binary_logical_op_with_scalar(ng_api_helper, numpy_function):
@ -126,7 +127,7 @@ def test_binary_logical_op_with_scalar(ng_api_helper, numpy_function):
@pytest.mark.parametrize(
"operator,numpy_function",
("operator", "numpy_function"),
[
(operator.add, np.add),
(operator.sub, np.subtract),
@ -158,7 +159,7 @@ def test_binary_operators(operator, numpy_function):
@pytest.mark.parametrize(
"operator,numpy_function",
("operator", "numpy_function"),
[
(operator.add, np.add),
(operator.sub, np.subtract),
@ -190,20 +191,20 @@ def test_binary_operators_with_scalar(operator, numpy_function):
def test_multiply():
A = np.arange(48, dtype=np.int32).reshape((8, 1, 6, 1))
B = np.arange(35, dtype=np.int32).reshape((7, 1, 5))
param_a = np.arange(48, dtype=np.int32).reshape((8, 1, 6, 1))
param_b = np.arange(35, dtype=np.int32).reshape((7, 1, 5))
expected = np.multiply(A, B)
result = run_op_node([A, B], ov.multiply)
expected = np.multiply(param_a, param_b)
result = run_op_node([param_a, param_b], ov.multiply)
assert np.allclose(result, expected)
def test_power_v1():
A = np.arange(48, dtype=np.float32).reshape((8, 1, 6, 1))
B = np.arange(20, dtype=np.float32).reshape((4, 1, 5))
param_a = np.arange(48, dtype=np.float32).reshape((8, 1, 6, 1))
param_b = np.arange(20, dtype=np.float32).reshape((4, 1, 5))
expected = np.power(A, B)
result = run_op_node([A, B], ov.power)
expected = np.power(param_a, param_b)
result = run_op_node([param_a, param_b], ov.power)
assert np.allclose(result, expected)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -91,8 +92,8 @@ def test_fake_quantize():
[11.33333301, 11.33333301, 11.33333301, 11.33333301],
[16.0, 16.0, 16.0, 16.0],
],
]
]
],
],
],
dtype=np.float32,
)
@ -109,7 +110,7 @@ def test_depth_to_space():
[[6, 7, 8], [9, 10, 11]],
[[12, 13, 14], [15, 16, 17]],
[[18, 19, 20], [21, 22, 23]],
]
],
],
dtype=np.float32,
)
@ -305,7 +306,7 @@ def test_shuffle_channels_operator():
[[32.0, 33.0], [34.0, 35.0]],
[[44.0, 45.0], [46.0, 47.0]],
[[56.0, 57.0], [58.0, 59.0]],
]
],
],
dtype=np.float32,
)
@ -354,7 +355,7 @@ def test_grn_operator():
[0.9593655, 0.9486833, 0.9383431, 0.9284767],
[0.91914505, 0.9103665, 0.9021342, 0.8944272],
],
]
],
],
dtype=np.float32,
)
@ -386,7 +387,7 @@ def test_selu_operator():
data_shape = [4, 2, 3, 1]
data = np.arange(start=1.0, stop=25.0, dtype=np.float32).reshape(data_shape)
data = np.arange(start=-1.0, stop=23.0, dtype=np.float32).reshape(data_shape)
alpha = np.array(1.6733, dtype=np.float32)
lambda_value = np.array(1.0507, dtype=np.float32)
@ -395,7 +396,8 @@ def test_selu_operator():
computation = runtime.computation(model, parameter_data)
result = computation(data)
expected = lambda_value * ((data > 0) * data + (data <= 0) * (alpha * np.exp(data) - alpha))
mask = (data > 0) * data + (data <= 0) * (alpha * np.exp(data) - alpha)
expected = mask * lambda_value
assert np.allclose(result, expected)
@ -539,25 +541,25 @@ def test_space_to_depth_operator():
input_size = 3
hidden_size = 3
X_shape = [batch_size, input_size]
H_t_shape = [batch_size, hidden_size]
W_shape = [hidden_size, input_size]
R_shape = [hidden_size, hidden_size]
B_shape = [hidden_size]
x_shape = [batch_size, input_size]
h_t_shape = [batch_size, hidden_size]
w_shape = [hidden_size, input_size]
r_shape = [hidden_size, hidden_size]
b_shape = [hidden_size]
parameter_X = ov.parameter(X_shape, name="X", dtype=np.float32)
parameter_H_t = ov.parameter(H_t_shape, name="H_t", dtype=np.float32)
parameter_W = ov.parameter(W_shape, name="W", dtype=np.float32)
parameter_R = ov.parameter(R_shape, name="R", dtype=np.float32)
parameter_B = ov.parameter(B_shape, name="B", dtype=np.float32)
parameter_x = ov.parameter(x_shape, name="X", dtype=np.float32)
parameter_h_t = ov.parameter(h_t_shape, name="H_t", dtype=np.float32)
parameter_w = ov.parameter(w_shape, name="W", dtype=np.float32)
parameter_r = ov.parameter(r_shape, name="R", dtype=np.float32)
parameter_b = ov.parameter(b_shape, name="B", dtype=np.float32)
X_value = np.array(
[0.3432185, 0.612268, 0.20272376, 0.9513413, 0.30585995, 0.7265472], dtype=np.float32
).reshape(X_shape)
H_t_value = np.array(
[0.12444675, 0.52055854, 0.46489045, 0.4983964, 0.7730452, 0.28439692], dtype=np.float32
).reshape(H_t_shape)
W_value = np.array(
x_value = np.array(
[0.3432185, 0.612268, 0.20272376, 0.9513413, 0.30585995, 0.7265472], dtype=np.float32,
).reshape(x_shape)
h_t_value = np.array(
[0.12444675, 0.52055854, 0.46489045, 0.4983964, 0.7730452, 0.28439692], dtype=np.float32,
).reshape(h_t_shape)
w_value = np.array(
[
0.41930267,
0.7872176,
@ -570,8 +572,8 @@ def test_space_to_depth_operator():
0.4559603,
],
dtype=np.float32,
).reshape(W_shape)
R_value = np.array(
).reshape(w_shape)
r_value = np.array(
[
0.8374871,
0.86660194,
@ -584,19 +586,19 @@ def test_space_to_depth_operator():
0.85531586,
],
dtype=np.float32,
).reshape(R_shape)
B_value = np.array([1.0289404, 1.6362579, 0.4370661], dtype=np.float32).reshape(B_shape)
).reshape(r_shape)
b_value = np.array([1.0289404, 1.6362579, 0.4370661], dtype=np.float32).reshape(b_shape)
activations = ["sigmoid"]
activation_alpha = []
activation_beta = []
clip = 2.88
model = ov.rnn_cell(
parameter_X,
parameter_H_t,
parameter_W,
parameter_R,
parameter_B,
parameter_x,
parameter_h_t,
parameter_w,
parameter_r,
parameter_b,
hidden_size,
activations,
activation_alpha,
@ -604,12 +606,12 @@ def test_space_to_depth_operator():
clip,
)
computation = runtime.computation(
model, parameter_X, parameter_H_t, parameter_W, parameter_R, parameter_B
model, parameter_x, parameter_h_t, parameter_w, parameter_r, parameter_b,
)
result = computation(X_value, H_t_value, W_value, R_value, B_value)
result = computation(x_value, h_t_value, w_value, r_value, b_value)
expected = np.array(
[0.94126844, 0.9036043, 0.841243, 0.9468489, 0.934215, 0.873708], dtype=np.float32
[0.94126844, 0.9036043, 0.841243, 0.9468489, 0.934215, 0.873708], dtype=np.float32,
).reshape(batch_size, hidden_size)
assert np.allclose(result, expected)
@ -654,7 +656,7 @@ def test_group_convolution_backprop_data():
data_node = ov.parameter(data_shape, name="Data", dtype=np.float32)
filters_node = ov.parameter(filters_shape, name="Filters", dtype=np.float32)
model = ov.group_convolution_backprop_data(
data_node, filters_node, strides, None, pads_begin, pads_end, output_padding=output_padding
data_node, filters_node, strides, None, pads_begin, pads_end, output_padding=output_padding,
)
data_value = np.array(
@ -747,11 +749,11 @@ def test_group_convolution_backprop_data_output_shape():
output_shape_node = ov.constant(np.array([1, 14], dtype=np.int64))
model = ov.group_convolution_backprop_data(
data_node, filters_node, strides, output_shape_node, auto_pad="same_upper"
data_node, filters_node, strides, output_shape_node, auto_pad="same_upper",
)
data_value = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], dtype=np.float32).reshape(
data_shape
data_shape,
)
filters_value = np.array([1.0, 2.0, 3.0, 2.0, 1.0], dtype=np.float32).reshape(filters_shape)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -9,7 +10,7 @@ from tests.test_ngraph.util import run_op_node
@pytest.mark.parametrize(
"shape_a, shape_b, transpose_a, transpose_b",
("shape_a", "shape_b", "transpose_a", "transpose_b"),
[
# matrix, vector
([2, 4], [4], False, False),

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-/home/bszmelcz/openvino/src/bindings/python/tests/test_ngraph/test_ops_util_variable.py
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -10,22 +11,22 @@ from tests.test_ngraph.util import run_op_node, run_op_numeric_data
def test_concat():
a = np.array([[1, 2], [3, 4]]).astype(np.float32)
b = np.array([[5, 6]]).astype(np.float32)
input_a = np.array([[1, 2], [3, 4]]).astype(np.float32)
input_b = np.array([[5, 6]]).astype(np.float32)
axis = 0
expected = np.concatenate((a, b), axis=0)
expected = np.concatenate((input_a, input_b), axis=0)
runtime = get_runtime()
parameter_a = ov.parameter(list(a.shape), name="A", dtype=np.float32)
parameter_b = ov.parameter(list(b.shape), name="B", dtype=np.float32)
parameter_a = ov.parameter(list(input_a.shape), name="A", dtype=np.float32)
parameter_b = ov.parameter(list(input_b.shape), name="B", dtype=np.float32)
node = ov.concat([parameter_a, parameter_b], axis)
computation = runtime.computation(node, parameter_a, parameter_b)
result = computation(a, b)
result = computation(input_a, input_b)
assert np.allclose(result, expected)
@pytest.mark.parametrize(
"val_type, value", [(bool, False), (bool, np.empty((2, 2), dtype=bool))]
("val_type", "value"), [(bool, False), (bool, np.empty((2, 2), dtype=bool))],
)
def test_constant_from_bool(val_type, value):
expected = np.array(value, dtype=val_type)
@ -34,7 +35,7 @@ def test_constant_from_bool(val_type, value):
@pytest.mark.parametrize(
"val_type, value",
("val_type", "value"),
[
pytest.param(np.int16, np.int16(-12345)),
pytest.param(np.int64, np.int64(-1234567)),
@ -69,7 +70,7 @@ def test_constant_from_float_array(val_type):
@pytest.mark.parametrize(
"val_type, range_start, range_end",
("val_type", "range_start", "range_end"),
[
pytest.param(np.int16, -64, 64),
pytest.param(np.int64, -16383, 16383),
@ -84,7 +85,7 @@ def test_constant_from_float_array(val_type):
def test_constant_from_integer_array(val_type, range_start, range_end):
np.random.seed(133391)
input_data = np.array(
np.random.randint(range_start, range_end, size=(2, 2)), dtype=val_type
np.random.randint(range_start, range_end, size=(2, 2)), dtype=val_type,
)
result = run_op_numeric_data(input_data, ov.constant, val_type)
assert np.allclose(result, input_data)
@ -96,7 +97,7 @@ def test_broadcast_numpy():
data_parameter = ov.parameter(data_shape, name="Data", dtype=np.float32)
target_shape_parameter = ov.parameter(
target_shape_shape, name="Target_shape", dtype=np.int64
target_shape_shape, name="Target_shape", dtype=np.int64,
)
node = ov.broadcast(data_parameter, target_shape_parameter)
@ -111,7 +112,7 @@ def test_broadcast_bidirectional():
data_parameter = ov.parameter(data_shape, name="Data", dtype=np.float32)
target_shape_parameter = ov.parameter(
target_shape_shape, name="Target_shape", dtype=np.int64
target_shape_shape, name="Target_shape", dtype=np.int64,
)
node = ov.broadcast(data_parameter, target_shape_parameter, "BIDIRECTIONAL")
@ -122,7 +123,7 @@ def test_broadcast_bidirectional():
def test_transpose():
input_tensor = np.arange(3 * 3 * 224 * 224, dtype=np.int32).reshape(
(3, 3, 224, 224)
(3, 3, 224, 224),
)
input_order = np.array([0, 2, 3, 1], dtype=np.int32)
@ -145,7 +146,7 @@ def test_tile():
@pytest.mark.xfail(
reason="RuntimeError: Check 'shape_size(get_input_shape(0)) == shape_size(output_shape)'"
reason="RuntimeError: Check 'shape_size(get_input_shape(0)) == shape_size(output_shape)'",
)
def test_strided_slice():
input_tensor = np.arange(2 * 3 * 4, dtype=np.float32).reshape((2, 3, 4))
@ -172,20 +173,20 @@ def test_strided_slice():
)
expected = np.array(
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], dtype=np.float32
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], dtype=np.float32,
).reshape((1, 3, 4))
assert np.allclose(result, expected)
def test_reshape_v1():
A = np.arange(1200, dtype=np.float32).reshape((2, 5, 5, 24))
param_a = np.arange(1200, dtype=np.float32).reshape((2, 5, 5, 24))
shape = np.array([0, -1, 4], dtype=np.int32)
special_zero = True
expected_shape = np.array([2, 150, 4])
expected = np.reshape(A, expected_shape)
result = run_op_node([A], ov.reshape, shape, special_zero)
expected = np.reshape(param_a, expected_shape)
result = run_op_node([param_a], ov.reshape, shape, special_zero)
assert np.allclose(result, expected)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -11,7 +12,7 @@ from tests.test_ngraph.util import run_op_node
@pytest.mark.parametrize(
"ng_api_fn, numpy_fn, range_start, range_end",
("ng_api_fn", "numpy_fn", "range_start", "range_end"),
[
(ov.absolute, np.abs, -1, 1),
(ov.abs, np.abs, -1, 1),
@ -47,7 +48,7 @@ def test_unary_op_array(ng_api_fn, numpy_fn, range_start, range_end):
@pytest.mark.parametrize(
"ng_api_fn, numpy_fn, input_data",
("ng_api_fn", "numpy_fn", "input_data"),
[
pytest.param(ov.absolute, np.abs, np.float32(-3)),
pytest.param(ov.abs, np.abs, np.float32(-3)),
@ -78,7 +79,7 @@ def test_unary_op_scalar(ng_api_fn, numpy_fn, input_data):
@pytest.mark.parametrize(
"input_data", [(np.array([True, False, True, False])), (np.array([True])), (np.array([False]))]
"input_data", [(np.array([True, False, True, False])), (np.array([True])), (np.array([False]))],
)
def test_logical_not(input_data):
expected = np.logical_not(input_data)
@ -91,8 +92,8 @@ def test_sigmoid():
input_data = np.array([-3.14, -1.0, 0.0, 2.71001, 1000.0], dtype=np.float32)
result = run_op_node([input_data], ov.sigmoid)
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
def sigmoid(value):
return 1.0 / (1.0 + np.exp(-value))
expected = np.array(list(map(sigmoid, input_data)))

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -10,10 +11,10 @@ def test_info_as_property():
info.data_shape = PartialShape([1])
info.data_type = Type.f32
info.variable_id = "test_id"
variable = Variable(info)
assert variable.info.data_shape == info.data_shape
assert variable.info.data_type == info.data_type
assert variable.info.variable_id == info.variable_id
var_from_info = Variable(info)
assert var_from_info.info.data_shape == info.data_shape
assert var_from_info.info.data_type == info.data_type
assert var_from_info.info.variable_id == info.variable_id
def test_get_info():
@ -21,10 +22,10 @@ def test_get_info():
info.data_shape = PartialShape([1])
info.data_type = Type.f32
info.variable_id = "test_id"
variable = Variable(info)
assert variable.get_info().data_shape == info.data_shape
assert variable.get_info().data_type == info.data_type
assert variable.get_info().variable_id == info.variable_id
var_from_info = Variable(info)
assert var_from_info.get_info().data_shape == info.data_shape
assert var_from_info.get_info().data_type == info.data_type
assert var_from_info.get_info().variable_id == info.variable_id
def test_info_update():
@ -33,14 +34,14 @@ def test_info_update():
info1.data_type = Type.f32
info1.variable_id = "test_id"
variable = Variable(info1)
var_from_info = Variable(info1)
info2 = VariableInfo()
info2.data_shape = PartialShape([2, 1])
info2.data_type = Type.i64
info2.variable_id = "test_id2"
variable.update(info2)
assert variable.info.data_shape == info2.data_shape
assert variable.info.data_type == info2.data_type
assert variable.info.variable_id == info2.variable_id
var_from_info.update(info2)
assert var_from_info.info.data_shape == info2.data_shape
assert var_from_info.info.data_type == info2.data_type
assert var_from_info.info.variable_id == info2.variable_id

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -8,14 +9,14 @@ import openvino.runtime.opset8 as ov
from tests.runtime import get_runtime
@pytest.fixture
def _ndarray_1x1x4x4():
@pytest.fixture()
def ndarray_1x1x4x4():
return np.arange(11, 27, dtype=np.float32).reshape(1, 1, 4, 4)
def test_avg_pool_2d(_ndarray_1x1x4x4):
def test_avg_pool_2d(ndarray_1x1x4x4):
runtime = get_runtime()
input_data = _ndarray_1x1x4x4
input_data = ndarray_1x1x4x4
param = ov.parameter(input_data.shape, name="A", dtype=np.float32)
kernel_shape = [2, 2]
@ -57,9 +58,9 @@ def test_avg_pool_2d(_ndarray_1x1x4x4):
assert np.allclose(result, expected)
def test_avg_pooling_3d(_ndarray_1x1x4x4):
def test_avg_pooling_3d(ndarray_1x1x4x4):
rt = get_runtime()
data = _ndarray_1x1x4x4
data = ndarray_1x1x4x4
data = np.broadcast_to(data, (1, 1, 4, 4, 4))
param = ov.parameter(list(data.shape))
kernel_shape = [2, 2, 2]
@ -79,10 +80,11 @@ def test_avg_pooling_3d(_ndarray_1x1x4x4):
def test_max_pool_basic():
rt = get_runtime()
# array([[[[ 0.5, 1.5, 2.5, 3.5],
# [ 4.5, 5.5, 6.5, 7.5],
# [ 8.5, 9.5, 10.5, 11.5],
# [12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""array([[[[ 0.5, 1.5, 2.5, 3.5],
[ 4.5, 5.5, 6.5, 7.5],
[ 8.5, 9.5, 10.5, 11.5],
[12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""
data = np.arange(0.5, 16, dtype=np.float32).reshape((1, 1, 4, 4))
strides = [1, 1]
dilations = [1, 1]
@ -108,9 +110,7 @@ def test_max_pool_basic():
comp = rt.computation(maxpool_node, data_node)
result = comp(data)
expected = np.array(
[[[[5.5, 6.5, 7.5], [9.5, 10.5, 11.5], [13.5, 14.5, 15.5]]]], dtype=np.float32
)
expected = np.array([[[[5.5, 6.5, 7.5], [9.5, 10.5, 11.5], [13.5, 14.5, 15.5]]]], dtype=np.float32)
expected_idx = np.array([[[[5, 6, 7], [9, 10, 11], [13, 14, 15]]]], dtype=np.int32)
assert np.allclose(result[0], expected)
assert np.allclose(result[1], expected_idx)
@ -119,10 +119,11 @@ def test_max_pool_basic():
def test_max_pool_strides():
rt = get_runtime()
# array([[[[ 0.5, 1.5, 2.5, 3.5],
# [ 4.5, 5.5, 6.5, 7.5],
# [ 8.5, 9.5, 10.5, 11.5],
# [12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""array([[[[ 0.5, 1.5, 2.5, 3.5],
[ 4.5, 5.5, 6.5, 7.5],
[ 8.5, 9.5, 10.5, 11.5],
[12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""
data = np.arange(0.5, 16, dtype=np.float32).reshape((1, 1, 4, 4))
strides = [2, 1]
dilations = [1, 1]
@ -157,10 +158,11 @@ def test_max_pool_strides():
def test_max_pool_kernel_shape1x1():
rt = get_runtime()
# array([[[[ 0.5, 1.5, 2.5, 3.5],
# [ 4.5, 5.5, 6.5, 7.5],
# [ 8.5, 9.5, 10.5, 11.5],
# [12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""array([[[[ 0.5, 1.5, 2.5, 3.5],
[ 4.5, 5.5, 6.5, 7.5],
[ 8.5, 9.5, 10.5, 11.5],
[12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""
data = np.arange(0.5, 16, dtype=np.float32).reshape((1, 1, 4, 4))
strides = [1, 1]
dilations = [1, 1]
@ -193,10 +195,11 @@ def test_max_pool_kernel_shape1x1():
def test_max_pool_kernel_shape3x3():
rt = get_runtime()
# array([[[[ 0.5, 1.5, 2.5, 3.5],
# [ 4.5, 5.5, 6.5, 7.5],
# [ 8.5, 9.5, 10.5, 11.5],
# [12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""array([[[[ 0.5, 1.5, 2.5, 3.5],
[ 4.5, 5.5, 6.5, 7.5],
[ 8.5, 9.5, 10.5, 11.5],
[12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""
data = np.arange(0.5, 16, dtype=np.float32).reshape((1, 1, 4, 4))
strides = [1, 1]
dilations = [1, 1]
@ -229,21 +232,23 @@ def test_max_pool_kernel_shape3x3():
def test_max_pool_non_zero_pads():
rt = get_runtime()
# array([[[[ 0.5, 1.5, 2.5, 3.5],
# [ 4.5, 5.5, 6.5, 7.5],
# [ 8.5, 9.5, 10.5, 11.5],
# [12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""array([[[[ 0.5, 1.5, 2.5, 3.5],
[ 4.5, 5.5, 6.5, 7.5],
[ 8.5, 9.5, 10.5, 11.5],
[12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""
data = np.arange(0.5, 16, dtype=np.float32).reshape((1, 1, 4, 4))
strides = [1, 1]
dilations = [1, 1]
pads_begin = [1, 1]
pads_end = [1, 1]
# 0 0 , 0 , 0 , 0, 0
# 0 [ 0.5, 1.5, 2.5, 3.5], 0,
# 0 [ 4.5, 5.5, 6.5, 7.5], 0,
# 0 [ 8.5, 9.5, 10.5, 11.5], 0,
# 0 [12.5, 13.5, 14.5, 15.5], 0
# 0 0 , 0 , 0 , 0, 0
"""0 0 , 0 , 0 , 0, 0
0 [ 0.5, 1.5, 2.5, 3.5], 0,
0 [ 4.5, 5.5, 6.5, 7.5], 0,
0 [ 8.5, 9.5, 10.5, 11.5], 0,
0 [12.5, 13.5, 14.5, 15.5], 0
0 0 , 0 , 0 , 0, 0
"""
kernel_shape = [2, 2]
rounding_type = "floor"
auto_pad = None
@ -273,8 +278,8 @@ def test_max_pool_non_zero_pads():
[8.5, 9.5, 10.5, 11.5, 11.5],
[12.5, 13.5, 14.5, 15.5, 15.5],
[12.5, 13.5, 14.5, 15.5, 15.5],
]
]
],
],
],
dtype=np.float32,
)
@ -287,8 +292,8 @@ def test_max_pool_non_zero_pads():
[8, 9, 10, 11, 11],
[12, 13, 14, 15, 15],
[12, 13, 14, 15, 15],
]
]
],
],
],
dtype=np.int32,
)
@ -299,20 +304,22 @@ def test_max_pool_non_zero_pads():
def test_max_pool_same_upper_auto_pads():
rt = get_runtime()
# array([[[[ 0.5, 1.5, 2.5, 3.5],
# [ 4.5, 5.5, 6.5, 7.5],
# [ 8.5, 9.5, 10.5, 11.5],
# [12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""array([[[[ 0.5, 1.5, 2.5, 3.5],
[ 4.5, 5.5, 6.5, 7.5],
[ 8.5, 9.5, 10.5, 11.5],
[12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""
data = np.arange(0.5, 16, dtype=np.float32).reshape((1, 1, 4, 4))
strides = [1, 1]
dilations = [1, 1]
pads_begin = [0, 0]
pads_end = [0, 0]
# [ 0.5, 1.5, 2.5, 3.5], 0,
# [ 4.5, 5.5, 6.5, 7.5], 0,
# [ 8.5, 9.5, 10.5, 11.5], 0,
# [12.5, 13.5, 14.5, 15.5], 0
# 0 , 0 , 0 , 0, 0
"""[ 0.5, 1.5, 2.5, 3.5], 0,
[ 4.5, 5.5, 6.5, 7.5], 0,
[ 8.5, 9.5, 10.5, 11.5], 0,
[12.5, 13.5, 14.5, 15.5], 0
0 , 0 , 0 , 0, 0
"""
kernel_shape = [2, 2]
auto_pad = "same_upper"
rounding_type = "floor"
@ -341,8 +348,8 @@ def test_max_pool_same_upper_auto_pads():
[9.5, 10.5, 11.5, 11.5],
[13.5, 14.5, 15.5, 15.5],
[13.5, 14.5, 15.5, 15.5],
]
]
],
],
],
dtype=np.float32,
)
@ -354,8 +361,8 @@ def test_max_pool_same_upper_auto_pads():
[9, 10, 11, 11],
[13, 14, 15, 15],
[13, 14, 15, 15],
]
]
],
],
],
dtype=np.int32,
)
@ -366,20 +373,22 @@ def test_max_pool_same_upper_auto_pads():
def test_max_pool_same_lower_auto_pads():
rt = get_runtime()
# array([[[[ 0.5, 1.5, 2.5, 3.5],
# [ 4.5, 5.5, 6.5, 7.5],
# [ 8.5, 9.5, 10.5, 11.5],
# [12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""array([[[[ 0.5, 1.5, 2.5, 3.5],
[ 4.5, 5.5, 6.5, 7.5],
[ 8.5, 9.5, 10.5, 11.5],
[12.5, 13.5, 14.5, 15.5]]]], dtype=float32)
"""
data = np.arange(0.5, 16, dtype=np.float32).reshape((1, 1, 4, 4))
strides = [1, 1]
dilations = [1, 1]
pads_begin = [0, 0]
pads_end = [0, 0]
# 0 0 , 0 , 0 , 0,
# 0 [ 0.5, 1.5, 2.5, 3.5],
# 0 [ 4.5, 5.5, 6.5, 7.5],
# 0 [ 8.5, 9.5, 10.5, 11.5],
# 0 [12.5, 13.5, 14.5, 15.5],
"""0 0 , 0 , 0 , 0,
0 [ 0.5, 1.5, 2.5, 3.5],
0 [ 4.5, 5.5, 6.5, 7.5],
0 [ 8.5, 9.5, 10.5, 11.5],
0 [12.5, 13.5, 14.5, 15.5],
"""
kernel_shape = [2, 2]
auto_pad = "same_lower"
rounding_type = "floor"
@ -408,8 +417,8 @@ def test_max_pool_same_lower_auto_pads():
[4.5, 5.5, 6.5, 7.5],
[8.5, 9.5, 10.5, 11.5],
[12.5, 13.5, 14.5, 15.5],
]
]
],
],
],
dtype=np.float32,
)
@ -421,8 +430,8 @@ def test_max_pool_same_lower_auto_pads():
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15],
]
]
],
],
],
dtype=np.int32,
)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -19,11 +20,11 @@ def test_ngraph_preprocess_mean():
model = parameter_a
function = Model(model, [parameter_a], "TestFunction")
p = PrePostProcessor(function)
inp = p.input()
ppp = PrePostProcessor(function)
inp = ppp.input()
prep = inp.preprocess()
prep.mean(1.0)
function = p.build()
function = ppp.build()
input_data = np.array([[1, 2], [3, 4]]).astype(np.float32)
expected_output = np.array([[0, 1], [2, 3]]).astype(np.float32)
@ -41,10 +42,10 @@ def test_ngraph_preprocess_mean_vector():
function = Model(model, [parameter_a], "TestFunction")
layout = ov.Layout("NC")
p = PrePostProcessor(function)
p.input().tensor().set_layout(layout)
p.input().preprocess().mean([1., 2.])
function = p.build()
ppp = PrePostProcessor(function)
ppp.input().tensor().set_layout(layout)
ppp.input().preprocess().mean([1., 2.])
function = ppp.build()
input_data = np.array([[1, 2], [3, 4]]).astype(np.float32)
expected_output = np.array([[0, 0], [2, 2]]).astype(np.float32)
@ -62,11 +63,11 @@ def test_ngraph_preprocess_scale_vector():
function = Model(model, [parameter_a], "TestFunction")
layout = ov.Layout("NC")
p = PrePostProcessor(function)
inp = p.input()
ppp = PrePostProcessor(function)
inp = ppp.input()
inp.tensor().set_layout(layout)
inp.preprocess().scale([0.5, 2.0])
function = p.build()
function = ppp.build()
input_data = np.array([[1, 2], [3, 4]]).astype(np.float32)
expected_output = np.array([[2, 1], [6, 2]]).astype(np.float32)
@ -87,13 +88,14 @@ def test_ngraph_preprocess_mean_scale_convert():
def custom_preprocess(output: Output):
return ops.abs(output)
p = PrePostProcessor(function)
inp2 = p.input(1)
ppp = PrePostProcessor(function)
inp2 = ppp.input(1)
inp2.tensor().set_element_type(Type.i32)
inp2.preprocess().convert_element_type(Type.f32).mean(1.).scale(2.).convert_element_type()
inp1 = p.input(0)
inp2.preprocess().convert_element_type(Type.f32).mean(1.).scale(2.)
inp2.preprocess().convert_element_type()
inp1 = ppp.input(0)
inp1.preprocess().convert_element_type(Type.f32).mean(1.).custom(custom_preprocess)
function = p.build()
function = ppp.build()
input_data1 = np.array([[0, 1], [2, -2]]).astype(np.int32)
input_data2 = np.array([[1, 3], [5, 7]]).astype(np.int32)
@ -117,17 +119,17 @@ def test_ngraph_preprocess_input_output_by_name():
def custom_preprocess(output: Output):
return ops.abs(output)
p = PrePostProcessor(function)
inp2 = p.input("B")
ppp = PrePostProcessor(function)
inp2 = ppp.input("B")
inp2.tensor().set_element_type(Type.i32)
inp2.preprocess().convert_element_type(Type.f32).mean(1.).scale(2.)
inp1 = p.input("A")
inp1 = ppp.input("A")
inp1.preprocess().convert_element_type(Type.f32).mean(1.)
out1 = p.output("A")
out1 = ppp.output("A")
out1.postprocess().custom(custom_preprocess)
out2 = p.output("B")
out2 = ppp.output("B")
out2.postprocess().custom(custom_preprocess)
function = p.build()
function = ppp.build()
input_data1 = np.array([[0, 1], [2, -2]]).astype(np.int32)
input_data2 = np.array([[-1, 3], [5, 7]]).astype(np.int32)
@ -154,20 +156,17 @@ def test_ngraph_preprocess_output_postprocess():
def custom_postprocess(output: Output):
return ops.abs(output)
p = PrePostProcessor(function)
inp = p.input()
ppp = PrePostProcessor(function)
inp = ppp.input()
inp.tensor().set_layout(layout1)
inp.preprocess().convert_element_type(Type.f32).mean([1., 2., 3.])
out = p.output()
inp.preprocess().convert_element_type(Type.f32).mean([1.0, 2.0, 3.0])
out = ppp.output()
out.tensor().set_element_type(Type.f32)
out.model().set_layout(layout1)
out.postprocess().convert_element_type(Type.f32) \
.convert_layout(layout2) \
.convert_layout(layout3) \
.custom(custom_postprocess) \
.convert_element_type(Type.f16) \
.convert_element_type()
function = p.build()
out.postprocess().convert_element_type(Type.f32)
out.postprocess().convert_layout(layout2).convert_layout(layout3)
out.postprocess().custom(custom_postprocess).convert_element_type(Type.f16).convert_element_type()
function = ppp.build()
input_data = np.array([[-1, -2, -3], [-4, -5, -6]]).astype(np.int32)
expected_output = np.array([[2, 4, 6], [5, 7, 9]]).astype(np.float32)
@ -187,15 +186,15 @@ def test_ngraph_preprocess_spatial_static_shape():
color_format = ColorFormat.RGB
p = PrePostProcessor(function)
inp = p.input()
ppp = PrePostProcessor(function)
inp = ppp.input()
inp.tensor().set_layout(layout).set_spatial_static_shape(2, 2).set_color_format(color_format)
inp.preprocess().convert_element_type(Type.f32).mean([1., 2.])
inp.model().set_layout(layout)
out = p.output()
out = ppp.output()
out.tensor().set_layout(layout).set_element_type(Type.f32)
out.model().set_layout(layout)
function = p.build()
function = ppp.build()
input_data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]).astype(np.int32)
expected_output = np.array([[[0, 1], [2, 3]], [[3, 4], [5, 6]]]).astype(np.float32)
@ -220,11 +219,11 @@ def test_ngraph_preprocess_set_shape():
axis = ops.constant(np.array([0, 1, 2]), dtype=np.int32)
return ops.slice(out_node, start, stop, step, axis)
p = PrePostProcessor(function)
inp = p.input()
ppp = PrePostProcessor(function)
inp = ppp.input()
inp.tensor().set_shape([3, 3, 3])
inp.preprocess().custom(custom_crop)
function = p.build()
function = ppp.build()
input_data = np.array([[[0, 1, 2], [3, 4, 5], [6, 7, 8]],
[[9, 10, 11], [12, 13, 14], [15, 16, 17]],
@ -246,11 +245,11 @@ def test_ngraph_preprocess_set_from_tensor():
function = Model(model, [parameter_a], "TestFunction")
input_data = ov.Tensor(Type.i32, inp_shape)
p = PrePostProcessor(function)
inp = p.input()
ppp = PrePostProcessor(function)
inp = ppp.input()
inp.tensor().set_from(input_data)
inp.preprocess().resize(ResizeAlgorithm.RESIZE_LINEAR)
function = p.build()
function = ppp.build()
assert function.input().shape == ov.Shape(inp_shape)
assert function.input().element_type == Type.i32
assert function.output().shape == ov.Shape(shape)
@ -275,11 +274,11 @@ def test_ngraph_preprocess_set_from_np_infer():
[[9, 10, 11], [12, 13, 14], [15, 16, 17]],
[[18, 19, 20], [21, 22, 23], [24, 25, 26]]]).astype(np.int32)
p = PrePostProcessor(function)
inp = p.input()
ppp = PrePostProcessor(function)
inp = ppp.input()
inp.tensor().set_from(input_data)
inp.preprocess().convert_element_type().custom(custom_crop)
function = p.build()
function = ppp.build()
assert function.input().shape == ov.Shape([3, 3, 3])
assert function.input().element_type == Type.i32
@ -298,15 +297,15 @@ def test_ngraph_preprocess_set_memory_type():
model = op
function = Model(model, [parameter_a], "TestFunction")
p = PrePostProcessor(function)
p.input().tensor().set_memory_type("some_memory_type")
function = p.build()
ppp = PrePostProcessor(function)
ppp.input().tensor().set_memory_type("some_memory_type")
function = ppp.build()
assert any(key for key in function.input().rt_info if "memory_type" in key)
@pytest.mark.parametrize(
"algorithm, color_format1, color_format2, is_failing",
("algorithm", "color_format1", "color_format2", "is_failing"),
[(ResizeAlgorithm.RESIZE_LINEAR, ColorFormat.UNDEFINED, ColorFormat.BGR, True),
(ResizeAlgorithm.RESIZE_NEAREST, ColorFormat.RGB, ColorFormat.I420_SINGLE_PLANE, True),
(ResizeAlgorithm.RESIZE_NEAREST, ColorFormat.RGB, ColorFormat.I420_THREE_PLANES, True),
@ -336,7 +335,8 @@ def test_ngraph_preprocess_steps(algorithm, color_format1, color_format2, is_fai
custom_processor = PrePostProcessor(function)
inp = custom_processor.input()
inp.tensor().set_layout(layout1).set_color_format(color_format1, [])
inp.preprocess().mean(1.).resize(algorithm, 3, 3).convert_layout(layout2).convert_color(color_format2)
inp.preprocess().mean(1.).resize(algorithm, 3, 3)
inp.preprocess().convert_layout(layout2).convert_color(color_format2)
if is_failing:
with pytest.raises(RuntimeError) as e:
@ -361,13 +361,13 @@ def test_ngraph_preprocess_postprocess_layout():
layout1 = ov.Layout("NCWH")
layout2 = ov.Layout("NCHW")
p = PrePostProcessor(function)
inp = p.input()
ppp = PrePostProcessor(function)
inp = ppp.input()
inp.tensor().set_layout(layout1)
inp.preprocess().mean(1.).convert_layout(layout2).reverse_channels()
out = p.output()
out = ppp.output()
out.postprocess().convert_layout([0, 1, 2, 3])
function = p.build()
function = ppp.build()
input_data = np.array([[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]]).astype(np.float32)
expected_output = np.array([[[[0, 3, 6], [1, 4, 7], [2, 5, 8]]]]).astype(np.float32)
@ -385,11 +385,11 @@ def test_ngraph_preprocess_reverse_channels():
function = Model(model, [parameter_a], "TestFunction")
layout1 = ov.Layout("NCWH")
p = PrePostProcessor(function)
inp = p.input()
ppp = PrePostProcessor(function)
inp = ppp.input()
inp.tensor().set_layout(layout1)
inp.preprocess().mean(1.).reverse_channels()
function = p.build()
function = ppp.build()
input_data = np.array([[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]]).astype(np.float32)
expected_output = np.array([[[[4, 5], [6, 7]], [[0, 1], [2, 3]]]]).astype(np.float32)
@ -407,10 +407,10 @@ def test_ngraph_preprocess_crop():
model = ops.relu(parameter_a)
function = Model(model, [parameter_a], "TestFunction")
p = PrePostProcessor(function)
p.input().tensor().set_shape(tensor_shape)
p.input().preprocess().crop([0, 0, 1, 1], [1, 2, -1, -1])
function = p.build()
ppp = PrePostProcessor(function)
ppp.input().tensor().set_shape(tensor_shape)
ppp.input().preprocess().crop([0, 0, 1, 1], [1, 2, -1, -1])
function = ppp.build()
input_data = np.arange(18).astype(np.float32).reshape(tensor_shape)
expected_output = np.array([4, 13]).astype(np.float32).reshape(orig_shape)
@ -429,11 +429,11 @@ def test_ngraph_preprocess_resize_algorithm():
resize_alg = ResizeAlgorithm.RESIZE_CUBIC
layout1 = ov.Layout("NCWH")
p = PrePostProcessor(function)
inp = p.input()
ppp = PrePostProcessor(function)
inp = ppp.input()
inp.tensor().set_layout(layout1)
inp.preprocess().mean(1.).resize(resize_alg, 3, 3)
function = p.build()
function = ppp.build()
input_data = np.array([[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]]).astype(np.float32)
expected_output = np.array([[[[0, 1, 2], [3, 4, 5], [6, 7, 8]]]]).astype(np.float32)
@ -511,11 +511,11 @@ def test_ngraph_preprocess_model():
def custom_preprocess(output: Output):
return ops.abs(output)
p = PrePostProcessor(function)
p.input(1).preprocess().convert_element_type(Type.f32).scale(0.5)
p.input(0).preprocess().convert_element_type(Type.f32).mean(5.)
p.output(0).postprocess().custom(custom_preprocess)
function = p.build()
ppp = PrePostProcessor(function)
ppp.input(1).preprocess().convert_element_type(Type.f32).scale(0.5)
ppp.input(0).preprocess().convert_element_type(Type.f32).mean(5.)
ppp.output(0).postprocess().custom(custom_preprocess)
function = ppp.build()
input_data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]).astype(np.float32)
expected_output = np.array([[[2, 1], [4, 7]], [[10, 13], [16, 19]]]).astype(np.float32)
@ -533,20 +533,15 @@ def test_ngraph_preprocess_dump():
model = parameter_a
function = Model(model, [parameter_a], "TestFunction")
p = PrePostProcessor(function)
p.input().tensor()\
.set_layout(ov.Layout("NHWC"))\
.set_element_type(Type.u8)\
.set_spatial_dynamic_shape()
p.input().preprocess()\
.convert_element_type(Type.f32)\
.reverse_channels()\
.mean([1, 2, 3])\
.scale([4, 5, 6])\
.resize(ResizeAlgorithm.RESIZE_LINEAR)
p.input().model().set_layout(ov.Layout("NCHW"))
p_str = str(p)
print(p)
ppp = PrePostProcessor(function)
ppp.input().tensor().set_layout(ov.Layout("NHWC")).set_element_type(Type.u8)
ppp.input().tensor().set_spatial_dynamic_shape()
ppp.input().preprocess().convert_element_type(Type.f32).reverse_channels()
ppp.input().preprocess().mean([1, 2, 3]).scale([4, 5, 6])
ppp.input().preprocess().resize(ResizeAlgorithm.RESIZE_LINEAR)
ppp.input().model().set_layout(ov.Layout("NCHW"))
p_str = str(ppp)
print(ppp)
assert "Pre-processing steps (5):" in p_str
assert "convert type (f32):" in p_str
assert "reverse channels:" in p_str

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -12,7 +13,7 @@ from tests.test_ngraph.util import run_op_node
@pytest.mark.parametrize(
"ng_api_helper, numpy_function, reduction_axes",
("ng_api_helper", "numpy_function", "reduction_axes"),
[
(ov.reduce_max, np.max, np.array([0, 1, 2, 3])),
(ov.reduce_min, np.min, np.array([0, 1, 2, 3])),
@ -39,7 +40,7 @@ def test_reduction_ops(ng_api_helper, numpy_function, reduction_axes):
@pytest.mark.parametrize(
"ng_api_helper, numpy_function, reduction_axes",
("ng_api_helper", "numpy_function", "reduction_axes"),
[
(ov.reduce_logical_and, np.logical_and.reduce, np.array([0])),
(ov.reduce_logical_or, np.logical_or.reduce, np.array([0])),
@ -62,9 +63,9 @@ def test_reduction_logical_ops(ng_api_helper, numpy_function, reduction_axes):
def test_topk():
data_shape = [6, 12, 10, 24]
data_parameter = ov.parameter(data_shape, name="Data", dtype=np.float32)
K = np.int32(3)
k_val = np.int32(3)
axis = np.int32(1)
node = ov.topk(data_parameter, K, axis, "max", "value")
node = ov.topk(data_parameter, k_val, axis, "max", "value")
assert node.get_type_name() == "TopK"
assert node.get_output_size() == 2
assert list(node.get_output_shape(0)) == [6, 3, 10, 24]
@ -72,7 +73,7 @@ def test_topk():
@pytest.mark.parametrize(
"ng_api_helper, numpy_function, reduction_axes",
("ng_api_helper", "numpy_function", "reduction_axes"),
[
(ov.reduce_mean, np.mean, np.array([0, 1, 2, 3])),
(ov.reduce_mean, np.mean, np.array([0])),
@ -134,7 +135,7 @@ def test_roi_align():
@pytest.mark.parametrize(
"input_shape, cumsum_axis, reverse",
("input_shape", "cumsum_axis", "reverse"),
[([5, 2], 0, False), ([5, 2], 1, False), ([5, 2, 6], 2, False), ([5, 2], 0, True)],
)
def test_cum_sum(input_shape, cumsum_axis, reverse):
@ -191,7 +192,7 @@ def test_normalize_l2():
0.31428573,
0.32857144,
0.34285715,
]
],
).reshape(input_shape)
assert np.allclose(result, expected)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -8,14 +9,14 @@ from tests.runtime import get_runtime
def test_roll():
runtime = get_runtime()
input = np.reshape(np.arange(10), (2, 5))
input_tensor = ov.constant(input)
input_vals = np.reshape(np.arange(10), (2, 5))
input_tensor = ov.constant(input_vals)
input_shift = ov.constant(np.array([-10, 7], dtype=np.int32))
input_axes = ov.constant(np.array([-1, 0], dtype=np.int32))
roll_node = ov.roll(input_tensor, input_shift, input_axes)
computation = runtime.computation(roll_node)
roll_results = computation()
expected_results = np.roll(input, shift=(-10, 7), axis=(-1, 0))
expected_results = np.roll(input_vals, shift=(-10, 7), axis=(-1, 0))
assert np.allclose(roll_results, expected_results)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -5,32 +6,37 @@ import numpy as np
import openvino.runtime.opset8 as ov
from openvino.runtime import Model, Shape
from openvino.runtime.op.util import InvariantInputDescription, BodyOutputDescription,\
SliceInputDescription, MergedInputDescription, ConcatOutputDescription
from openvino.runtime.op.util import (
InvariantInputDescription,
BodyOutputDescription,
SliceInputDescription,
MergedInputDescription,
ConcatOutputDescription,
)
def test_simple_tensor_iterator():
X = ov.parameter(Shape([32, 40, 10]), np.float32, "X")
Y = ov.parameter(Shape([32, 40, 10]), np.float32, "Y")
M = ov.parameter(Shape([32, 2, 10]), np.float32, "M")
param_x = ov.parameter(Shape([32, 40, 10]), np.float32, "X")
param_y = ov.parameter(Shape([32, 40, 10]), np.float32, "Y")
param_m = ov.parameter(Shape([32, 2, 10]), np.float32, "M")
X_i = ov.parameter(Shape([32, 2, 10]), np.float32, "X_i")
Y_i = ov.parameter(Shape([32, 2, 10]), np.float32, "Y_i")
M_body = ov.parameter(Shape([32, 2, 10]), np.float32, "M_body")
x_i = ov.parameter(Shape([32, 2, 10]), np.float32, "X_i")
y_i = ov.parameter(Shape([32, 2, 10]), np.float32, "Y_i")
m_body = ov.parameter(Shape([32, 2, 10]), np.float32, "M_body")
sum = ov.add(X_i, Y_i)
Zo = ov.multiply(sum, M_body)
add = ov.add(x_i, y_i)
zo = ov.multiply(add, m_body)
body = Model([Zo], [X_i, Y_i, M_body], "body_function")
body = Model([zo], [x_i, y_i, m_body], "body_function")
ti = ov.tensor_iterator()
ti.set_body(body)
ti.set_sliced_input(X_i, X.output(0), 0, 2, 2, 39, 1)
ti.set_sliced_input(Y_i, Y.output(0), 0, 2, 2, -1, 1)
ti.set_invariant_input(M_body, M.output(0))
ti.set_sliced_input(x_i, param_x.output(0), 0, 2, 2, 39, 1)
ti.set_sliced_input(y_i, param_y.output(0), 0, 2, 2, -1, 1)
ti.set_invariant_input(m_body, param_m.output(0))
out0 = ti.get_iter_value(Zo.output(0), -1)
out1 = ti.get_concatenated_slices(Zo.output(0), 0, 2, 2, 39, 1)
out0 = ti.get_iter_value(zo.output(0), -1)
out1 = ti.get_concatenated_slices(zo.output(0), 0, 2, 2, 39, 1)
result0 = ov.result(out0)
result1 = ov.result(out1)
@ -67,8 +73,11 @@ def test_tensor_iterator_basic():
initial_cma = ov.constant(np.zeros([2, 2], dtype=np.float32), dtype=np.float32)
iter_cnt = ov.range(zero, np.int32(16), np.int32(1))
graph_body = Model([curr_cma, cma_hist], [body_timestep,
body_data_in, body_prev_cma, body_const_one], "body_function")
graph_body = Model(
[curr_cma, cma_hist],
[body_timestep, body_data_in, body_prev_cma, body_const_one],
"body_function",
)
ti_slice_input_desc = [
# timestep
@ -115,14 +124,16 @@ def test_tensor_iterator_basic():
input_desc = ti.get_input_descriptions()
output_desc = ti.get_output_descriptions()
assert len(input_desc) == len(ti_slice_input_desc) + \
len(ti_merged_input_desc) + len(ti_invariant_input_desc)
assert len(input_desc) == len(ti_slice_input_desc) + len(ti_merged_input_desc) + len(ti_invariant_input_desc)
assert len(output_desc) == len(ti_body_output_desc) + len(ti_concat_output_desc)
for i in range(len(ti_slice_input_desc)):
assert input_desc[i].get_type_info() == ti_slice_input_desc[i].get_type_info()
assert input_desc[i].input_index == ti_slice_input_desc[i].input_index
assert input_desc[i].body_parameter_index == ti_slice_input_desc[i].body_parameter_index
assert (
input_desc[i].body_parameter_index
== ti_slice_input_desc[i].body_parameter_index
)
assert input_desc[i].start == ti_slice_input_desc[i].start
assert input_desc[i].stride == ti_slice_input_desc[i].stride
assert input_desc[i].part_size == ti_slice_input_desc[i].part_size
@ -130,16 +141,27 @@ def test_tensor_iterator_basic():
assert input_desc[i].axis == ti_slice_input_desc[i].axis
for i in range(len(ti_merged_input_desc)):
assert input_desc[len(ti_slice_input_desc)
+ i].get_type_info() == ti_merged_input_desc[i].get_type_info()
assert input_desc[len(ti_slice_input_desc) + i].input_index == ti_merged_input_desc[i].input_index
assert input_desc[len(ti_slice_input_desc)
+ i].body_parameter_index == ti_merged_input_desc[i].body_parameter_index
assert input_desc[len(ti_slice_input_desc)
+ i].body_value_index == ti_merged_input_desc[i].body_value_index
assert (
input_desc[len(ti_slice_input_desc) + i].get_type_info()
== ti_merged_input_desc[i].get_type_info()
)
assert (
input_desc[len(ti_slice_input_desc) + i].input_index
== ti_merged_input_desc[i].input_index
)
assert (
input_desc[len(ti_slice_input_desc) + i].body_parameter_index
== ti_merged_input_desc[i].body_parameter_index
)
assert (
input_desc[len(ti_slice_input_desc) + i].body_value_index
== ti_merged_input_desc[i].body_value_index
)
for i in range(len(ti_body_output_desc)):
assert output_desc[i].get_type_info() == ti_body_output_desc[i].get_type_info()
assert output_desc[i].output_index == ti_body_output_desc[i].output_index
assert output_desc[i].body_value_index == ti_body_output_desc[i].body_value_index
assert (
output_desc[i].body_value_index == ti_body_output_desc[i].body_value_index
)
assert output_desc[i].iteration == ti_body_output_desc[i].iteration

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,2 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -61,15 +62,16 @@ def expect_fail(test_case_path, xfail): # type: (str) -> None
xfail(getattr(module, test_name))
else:
logging.getLogger().warning(
"Could not mark test as XFAIL, not found: %s", test_case_path
"Could not mark test as XFAIL, not found: %s", test_case_path,
)
OpenVinoTestBackend.backend_name = BACKEND_NAME
# This is a pytest magic variable to load extra plugins
# Uncomment the line below to enable the ONNX compatibility report
# pytest_plugins = "onnx.backend.test.report",
"""This is a pytest magic variable to load extra plugins
Uncomment the line below to enable the ONNX compatibility report
pytest_plugins = "onnx.backend.test.report",
"""
# import all test cases at global scope to make them visible to python.unittest
backend_test = onnx.backend.test.BackendTest(OpenVinoTestBackend, __name__)
@ -412,4 +414,4 @@ tests_expected_to_fail = [
for test_group in tests_expected_to_fail:
for test_case in test_group[1:]:
expect_fail("{}".format(test_case), test_group[0])
expect_fail(f"{test_case}", test_group[0])

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
@ -9,7 +10,7 @@ from tests.test_onnx.utils import run_node
def make_batch_norm_node(**node_attributes):
return onnx.helper.make_node(
"BatchNormalization", inputs=["X", "scale", "B", "mean", "var"], outputs=["Y"], **node_attributes
"BatchNormalization", inputs=["X", "scale", "B", "mean", "var"], outputs=["Y"], **node_attributes,
)
@ -18,7 +19,7 @@ def test_batch_norm_test_node():
scale = np.ones((3,)).astype(np.float32) # Gamma
bias = np.zeros((3,)).astype(np.float32) # Beta
mean = np.mean(data, axis=(0, 2, 3))
var = np.var(data, axis=(0, 2, 3))
variance = np.var(data, axis=(0, 2, 3))
expected_output = np.array(
[
@ -41,13 +42,13 @@ def test_batch_norm_test_node():
[0.10846233, 0.32538795, 0.54231358, 0.7592392],
[0.97616386, 1.19308949, 1.41001511, 1.62694073],
],
]
],
],
dtype=np.float32,
)
node = make_batch_norm_node()
result = run_node(node, [data, scale, bias, mean, var])[0]
result = run_node(node, [data, scale, bias, mean, variance])[0]
assert np.allclose(result, expected_output, rtol=1e-04, atol=1e-08)
scale = np.broadcast_to(0.1, (3,)).astype(np.float32) # Gamma
@ -74,11 +75,11 @@ def test_batch_norm_test_node():
[1.01084626, 1.03253877, 1.05423141, 1.07592392],
[1.09761643, 1.11930895, 1.14100146, 1.16269398],
],
]
],
],
dtype=np.float32,
)
node = make_batch_norm_node()
result = run_node(node, [data, scale, bias, mean, var])[0]
result = run_node(node, [data, scale, bias, mean, variance])[0]
assert np.allclose(result, expected_output, rtol=1e-04, atol=1e-08)

Some files were not shown because too many files have changed in this diff Show More