[PyOV] Fix mypy after bump, general refactor (#13913)

* Fix mypy errors after bump PEP482, reformat code in general

* Enable checks

* Fix smaller issues

* Revert typo with comments

* Fix indents
This commit is contained in:
Jan Iwaszkiewicz authored and GitHub committed 2022-11-08 19:26:39 +04:00
1 parent 116f294a9a
commit 5ae221e107
47 files changed
+895 -985

No files matched your search

+21 -21
View File
@@ -47,9 +47,9 @@ jobs:
name: samples_diff
path: samples_diff.diff
# IE Python API Flake code-style
#- name: Run flake8 on IE Python API
# run: python -m flake8 ./ --config=setup.cfg
# working-directory: src/bindings/python/src/compatibility/openvino
- name: Run flake8 on IE Python API
run: python -m flake8 ./ --config=setup.cfg
working-directory: src/bindings/python/src/compatibility/openvino
- name: Create code style diff for IE Python API
if: failure()
run: |
@@ -62,9 +62,9 @@ jobs:
name: ie_python_diff
path: ie_python_diff.diff
# nGraph Python API Flake code-style
#- name: Run flake8 on nGraph Python API
# run: python -m flake8 ./src/compatibility/ngraph --config=setup.cfg
# working-directory: src/bindings/python
- name: Run flake8 on nGraph Python API
run: python -m flake8 ./src/compatibility/ngraph --config=setup.cfg
working-directory: src/bindings/python
- name: Create code style diff for nGraph Python API
if: failure()
run: |
@@ -77,9 +77,9 @@ jobs:
name: pyngraph_diff
path: pyngraph_diff.diff
# Python API 2.0 Flake code-style
#- name: Run flake8 on Python API 2.0
# run: python -m flake8 ./src/openvino --config=setup.cfg
# working-directory: src/bindings/python
- name: Run flake8 on Python API 2.0
run: python -m flake8 ./src/openvino --config=setup.cfg
working-directory: src/bindings/python
- name: Create code style diff for Python API 2.0
if: failure()
run: |
@@ -107,22 +107,22 @@ jobs:
name: wheel_diff
path: wheel_diff.diff
# Python API 2.0 tests Flake code-style
#- name: Run flake8 on python tests
- name: Run flake8 on python tests
# ignore lack of docs in tests
# run: python -m flake8 tests/ --config=setup.cfg
# working-directory: src/bindings/python
run: python -m flake8 tests/ --config=setup.cfg
working-directory: src/bindings/python
# IE Python API mypy check
#- name: Run mypy on IE Python API
# run: python -m mypy ./ --config-file ./setup.cfg
# working-directory: src/bindings/python/src/compatibility/openvino
- name: Run mypy on IE Python API
run: python -m mypy ./ --config-file ./setup.cfg
working-directory: src/bindings/python/src/compatibility/openvino
# nGraph Python API mypy check
#- name: Run mypy on nGraph Python API
# run: python -m mypy ./src/compatibility/ngraph --config-file ./setup.cfg
# working-directory: src/bindings/python
- name: Run mypy on nGraph Python API
run: python -m mypy ./src/compatibility/ngraph --config-file ./setup.cfg
working-directory: src/bindings/python
# Python API 2.0 mypy check
#- name: Run mypy on Python API 2.0
# run: python -m mypy ./src/openvino --config-file ./setup.cfg
# working-directory: src/bindings/python
- name: Run mypy on Python API 2.0
run: python -m mypy ./src/openvino --config-file ./setup.cfg
working-directory: src/bindings/python
- name: Run Bandit
run: python -m bandit -r ./ -f screen
-1
View File
@@ -82,4 +82,3 @@ follow_imports = normal
disallow_untyped_defs = True
disallow_untyped_calls = True
check_untyped_defs = True
show_none_errors = True
@@ -6,6 +6,7 @@
try:
from ngraph.impl import util
__version__ = util.get_ngraph_version_string()
except ImportError:
__version__ = "0.0.0.dev0"
@@ -19,8 +19,7 @@ if sys.platform == "win32":
# add the location of openvino dlls to your system PATH.
#
# looking for the libs in the pip installation path by default.
openvino_libs = [os.path.join(os.path.dirname(__file__), '..', '..', '..'),
os.path.join(os.path.dirname(__file__), '..', '..', 'openvino', 'libs')]
openvino_libs = [os.path.join(os.path.dirname(__file__), '..', '..', '..'), os.path.join(os.path.dirname(__file__), '..', '..', 'openvino', 'libs')]
# setupvars.bat script set all libs paths to OPENVINO_LIB_PATHS environment variable.
openvino_libs_installer = os.getenv('OPENVINO_LIB_PATHS')
if openvino_libs_installer:
@@ -1,6 +1,5 @@
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Factory functions for all ngraph ops."""
from typing import Callable, Iterable, List, Optional, Set, Union
@@ -76,9 +75,7 @@ def add(
name: Optional[str] = None,
) -> 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()}
)
return _get_node_factory_opset1().create("Add", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@unary_op
@@ -238,9 +235,7 @@ def broadcast(
inputs = as_nodes(data, target_shape)
if mode.upper() == "EXPLICIT":
inputs.append(as_node(axes_mapping))
return _get_node_factory_opset1().create(
"Broadcast", inputs, {"mode": mode.upper()}
)
return _get_node_factory_opset1().create("Broadcast", inputs, {"mode": mode.upper()})
@nameable_op
@@ -259,9 +254,7 @@ def ctc_greedy_decoder(
:return: The new node performing an CTCGreedyDecoder operation on input tensor.
"""
node_inputs = as_nodes(data, sequence_mask)
return _get_node_factory_opset1().create(
"CTCGreedyDecoder", node_inputs, {"ctc_merge_repeated": merge_repeated}
)
return _get_node_factory_opset1().create("CTCGreedyDecoder", node_inputs, {"ctc_merge_repeated": merge_repeated})
@unary_op
@@ -276,9 +269,7 @@ 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
) -> Node:
def clamp(data: NodeInput, min_value: ScalarData, max_value: ScalarData, name: Optional[str] = None) -> Node:
"""Perform clamp element-wise on data from input node.
:param data: Input tensor. One of: input node, array or scalar.
@@ -303,9 +294,7 @@ def clamp(
elif data > max_value:
data=max_value
"""
return _get_node_factory_opset1().create(
"Clamp", [as_node(data)], {"min": min_value, "max": max_value}
)
return _get_node_factory_opset1().create("Clamp", [as_node(data)], {"min": min_value, "max": max_value})
@nameable_op
@@ -321,7 +310,7 @@ def concat(nodes: List[NodeInput], axis: int, name: Optional[str] = None) -> Nod
@nameable_op
def constant(value: NumericData, dtype: NumericType = None, name: Optional[str] = None) -> Constant:
def constant(value: NumericData, dtype: Optional[NumericType] = None, name: Optional[str] = None) -> Constant:
"""Create a Constant node from provided value.
:param value: One of: array of values or scalar to initialize node with.
@@ -333,9 +322,7 @@ def constant(value: NumericData, dtype: NumericType = None, name: Optional[str]
@nameable_op
def convert(
data: NodeInput, destination_type: Union[str, NumericType], name: Optional[str] = None
) -> Node:
def convert(data: NodeInput, destination_type: Union[str, NumericType], name: Optional[str] = None) -> Node:
"""Return node which casts input node values to specified type.
:param data: Node which produces the input tensor.
@@ -345,9 +332,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()}
)
return _get_node_factory_opset1().create("Convert", [as_node(data)], {"destination_type": destination_type.lower()})
@binary_op
@@ -576,7 +561,7 @@ def deformable_psroi_pooling(
@nameable_op
def depth_to_space(node: Node, mode: str, block_size: int = 1, name: str = None) -> Node:
def depth_to_space(node: Node, mode: str, block_size: int = 1, name: Optional[str] = None) -> Node:
"""Rearranges input tensor from depth into blocks of spatial data.
Values from the height and width dimensions are moved to the depth dimension.
@@ -600,7 +585,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},
)
@@ -782,9 +769,7 @@ def divide(
:param name: Optional name for output node.
:return: The node performing element-wise division.
"""
return _get_node_factory_opset1().create(
"Divide", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
)
return _get_node_factory_opset1().create("Divide", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@nameable_op
@@ -820,9 +805,7 @@ def equal(
:param name: The optional name for output new node.
:return: The node performing element-wise equality check.
"""
return _get_node_factory_opset1().create(
"Equal", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
)
return _get_node_factory_opset1().create("Equal", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@unary_op
@@ -922,15 +905,11 @@ def floor_mod(
:param name: Optional name for output node.
:return: The node performing element-wise FloorMod operation.
"""
return _get_node_factory_opset1().create(
"FloorMod", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
)
return _get_node_factory_opset1().create("FloorMod", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@nameable_op
def gather(
data: NodeInput, indices: NodeInput, axis: NodeInput, name: Optional[str] = None
) -> Node:
def gather(data: NodeInput, indices: NodeInput, axis: NodeInput, name: Optional[str] = None) -> Node:
"""Return Gather node which takes slices from axis of data according to indices.
:param data: The tensor from which slices are gathered.
@@ -998,9 +977,7 @@ def greater(
:param name: The optional new name for output node.
: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()}
)
return _get_node_factory_opset1().create("Greater", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@binary_op
@@ -1020,9 +997,7 @@ def greater_equal(
: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()}
)
return _get_node_factory_opset1().create("GreaterEqual", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
def grn(data: Node, bias: float, name: Optional[str] = None) -> Node:
@@ -1171,9 +1146,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
) -> Node:
def interpolate(image: Node, output_shape: NodeInput, attrs: dict, name: Optional[str] = None) -> Node:
"""Perform interpolation of independent slices in input tensor.
:param image: The node providing input tensor with data for interpolation.
@@ -1263,9 +1236,7 @@ def less(
:param name: The optional new name for output node.
: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()}
)
return _get_node_factory_opset1().create("Less", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@binary_op
@@ -1285,9 +1256,7 @@ def less_equal(
:return: The node performing element-wise check whether left_node is less than or equal the
right_node.
"""
return _get_node_factory_opset1().create(
"LessEqual", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
)
return _get_node_factory_opset1().create("LessEqual", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@unary_op
@@ -1317,9 +1286,7 @@ def logical_and(
:param name: The optional new name for output node.
: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()}
)
return _get_node_factory_opset1().create("LogicalAnd", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@unary_op
@@ -1349,9 +1316,7 @@ def logical_or(
:param name: The optional new name for output node.
: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()}
)
return _get_node_factory_opset1().create("LogicalOr", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@binary_op
@@ -1370,9 +1335,7 @@ def logical_xor(
:param name: The optional new name for output node.
: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()}
)
return _get_node_factory_opset1().create("LogicalXor", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@nameable_op
@@ -1408,9 +1371,9 @@ def lstm_cell(
R: NodeInput,
B: NodeInput,
hidden_size: int,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
@@ -1474,9 +1437,9 @@ def lstm_sequence(
B: NodeInput,
hidden_size: int,
direction: str,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
@@ -1558,9 +1521,7 @@ def matmul(
:param transpose_b: should the second matrix be transposed
: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}
)
return _get_node_factory_opset1().create("MatMul", as_nodes(data_a, data_b), {"transpose_a": transpose_a, "transpose_b": transpose_b})
@nameable_op
@@ -1614,9 +1575,7 @@ def maximum(
name: Optional[str] = None,
) -> 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()}
)
return _get_node_factory_opset1().create("Maximum", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@binary_op
@@ -1627,9 +1586,7 @@ def minimum(
name: Optional[str] = None,
) -> 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()}
)
return _get_node_factory_opset1().create("Minimum", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@binary_op
@@ -1647,9 +1604,7 @@ def mod(
:param name: Optional name for output node.
:return: The node performing element-wise Mod operation.
"""
return _get_node_factory_opset1().create(
"Mod", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
)
return _get_node_factory_opset1().create("Mod", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@binary_op
@@ -1660,9 +1615,7 @@ def multiply(
name: Optional[str] = None,
) -> 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()}
)
return _get_node_factory_opset1().create("Multiply", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@unary_op
@@ -1712,9 +1665,7 @@ def non_max_suppression(
@nameable_op
def normalize_l2(
data: NodeInput, axes: NodeInput, eps: float, eps_mode: str, name: Optional[str] = None
) -> Node:
def normalize_l2(data: NodeInput, axes: NodeInput, eps: float, eps_mode: str, name: Optional[str] = None) -> Node:
"""Construct an NormalizeL2 operation.
:param data: Node producing the input tensor
@@ -1723,9 +1674,7 @@ def normalize_l2(
:param eps_mode: how eps is combined with L2 value (`add` or `max`)
:return: New node which performs the L2 normalization.
"""
return _get_node_factory_opset1().create(
"NormalizeL2", as_nodes(data, axes), {"eps": eps, "mode": eps_mode}
)
return _get_node_factory_opset1().create("NormalizeL2", as_nodes(data, axes), {"eps": eps, "mode": eps_mode})
@binary_op
@@ -1744,9 +1693,7 @@ def not_equal(
:param name: The optional name for output new node.
:return: The node performing element-wise inequality check.
"""
return _get_node_factory_opset1().create(
"NotEqual", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
)
return _get_node_factory_opset1().create("NotEqual", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@nameable_op
@@ -1771,9 +1718,7 @@ def one_hot(
:param name: The optional name for new output node.
:return: New node performing one-hot operation.
"""
return _get_node_factory_opset1().create(
"OneHot", as_nodes(indices, depth, on_value, off_value), {"axis": axis}
)
return _get_node_factory_opset1().create("OneHot", as_nodes(indices, depth, on_value, off_value), {"axis": axis})
@nameable_op
@@ -1804,9 +1749,7 @@ def pad(
@nameable_op
def parameter(
shape: TensorShape, dtype: NumericType = np.float32, name: Optional[str] = None
) -> Parameter:
def parameter(shape: TensorShape, dtype: NumericType = np.float32, name: Optional[str] = None) -> Parameter:
"""Return an ngraph Parameter object."""
element_type = get_element_type(dtype)
return Parameter(element_type, PartialShape(shape))
@@ -1828,9 +1771,7 @@ def power(
auto-broadcasting of input tensors.
: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()}
)
return _get_node_factory_opset1().create("Power", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@nameable_op
@@ -1856,9 +1797,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
) -> Node:
def prior_box_clustered(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.
:param output_size: 1D tensor with two integer elements [height, width]. Specifies the
@@ -1936,15 +1875,11 @@ def prior_box_clustered(
check_valid_attributes("PriorBoxClustered", attrs, requirements)
return _get_node_factory_opset1().create(
"PriorBoxClustered", [output_size, as_node(image_size)], attrs
)
return _get_node_factory_opset1().create("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
) -> Node:
def prior_box(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.
:param layer_shape: Shape of layer for which prior boxes are computed.
@@ -2186,9 +2121,7 @@ def proposal(
check_valid_attributes("Proposal", attrs, requirements)
return _get_node_factory_opset1().create(
"Proposal", [class_probs, bbox_deltas, as_node(image_shape)], attrs
)
return _get_node_factory_opset1().create("Proposal", [class_probs, bbox_deltas, as_node(image_shape)], attrs)
@nameable_op
@@ -2255,9 +2188,7 @@ 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:
def reduce_logical_and(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.
:param node: The tensor we want to reduce.
@@ -2266,15 +2197,11 @@ def reduce_logical_and(
:param name: Optional name for output node.
:return: The new node performing reduction operation.
"""
return _get_node_factory_opset1().create(
"ReduceLogicalAnd", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
)
return _get_node_factory_opset1().create("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:
def reduce_logical_or(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.
:param node: The tensor we want to reduce.
@@ -2283,15 +2210,11 @@ def reduce_logical_or(
:param name: Optional name for output node.
:return: The new node performing reduction operation.
"""
return _get_node_factory_opset1().create(
"ReduceLogicalOr", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
)
return _get_node_factory_opset1().create("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:
def reduce_max(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.
:param node: The tensor we want to max-reduce.
@@ -2299,15 +2222,11 @@ def reduce_max(
:param keep_dims: If set to True it holds axes that are used for reduction
:param name: Optional name for output node.
"""
return _get_node_factory_opset1().create(
"ReduceMax", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
)
return _get_node_factory_opset1().create("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:
def reduce_mean(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.
:param node: The tensor we want to mean-reduce.
@@ -2316,15 +2235,11 @@ def reduce_mean(
:param name: Optional name for output node.
:return: The new node performing mean-reduction operation.
"""
return _get_node_factory_opset1().create(
"ReduceMean", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
)
return _get_node_factory_opset1().create("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:
def reduce_min(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.
:param node: The tensor we want to min-reduce.
@@ -2332,15 +2247,11 @@ def reduce_min(
:param keep_dims: If set to True it holds axes that are used for reduction
:param name: Optional name for output node.
"""
return _get_node_factory_opset1().create(
"ReduceMin", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
)
return _get_node_factory_opset1().create("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:
def reduce_prod(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.
:param node: The tensor we want to product-reduce.
@@ -2349,15 +2260,11 @@ def reduce_prod(
:param name: Optional name for output node.
:return: The new node performing product-reduction operation.
"""
return _get_node_factory_opset1().create(
"ReduceProd", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
)
return _get_node_factory_opset1().create("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:
def reduce_sum(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.
:param node: The node providing data for operation.
@@ -2366,9 +2273,7 @@ def reduce_sum(
:param name: The optional new name for output node.
: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}
)
return _get_node_factory_opset1().create("ReduceSum", as_nodes(node, reduction_axes), {"keep_dims": keep_dims})
@nameable_op
@@ -2381,7 +2286,7 @@ def region_yolo(
mask: List[int],
axis: int,
end_axis: int,
anchors: List[float] = None,
anchors: Optional[List[float]] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which produces the RegionYolo operation.
@@ -2418,9 +2323,7 @@ def region_yolo(
@nameable_op
def reshape(
node: NodeInput, output_shape: NodeInput, special_zero: bool, name: Optional[str] = None
) -> Node:
def reshape(node: NodeInput, output_shape: NodeInput, special_zero: bool, name: Optional[str] = None) -> Node:
"""Return reshaped node according to provided parameters.
:param node: The tensor we want to reshape.
@@ -2433,9 +2336,7 @@ def reshape(
of corresponding dimensions from data.shape into the output shape.
Range of values: False or True
"""
return _get_node_factory_opset1().create(
"Reshape", as_nodes(node, output_shape), {"special_zero": special_zero}
)
return _get_node_factory_opset1().create("Reshape", as_nodes(node, output_shape), {"special_zero": special_zero})
@unary_op
@@ -2491,17 +2392,11 @@ def select(
:return: The new node with values selected according to provided arguments.
"""
inputs = as_nodes(cond, then_node, else_node)
return _get_node_factory_opset1().create(
"Select",
inputs,
{"auto_broadcast": auto_broadcast.upper()}
)
return _get_node_factory_opset1().create("Select", inputs, {"auto_broadcast": auto_broadcast.upper()})
@nameable_op
def selu(
data: NodeInput, alpha: NodeInput, lambda_value: NodeInput, name: Optional[str] = None
) -> Node:
def selu(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.
:param data: input node, array or scalar.
@@ -2579,7 +2474,7 @@ def softmax(data: NodeInput, axis: int, name: Optional[str] = None) -> Node:
@nameable_op
def space_to_depth(data: Node, mode: str, block_size: int = 1, name: str = None) -> Node:
def space_to_depth(data: Node, mode: str, block_size: int = 1, name: Optional[str] = None) -> Node:
"""Perform SpaceToDepth operation on the input tensor.
SpaceToDepth rearranges blocks of spatial data into depth.
@@ -2597,7 +2492,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},
)
@@ -2610,11 +2507,7 @@ def split(data: NodeInput, axis: NodeInput, num_splits: int, name: Optional[str]
:param num_splits: Number of the output tensors that should be produced
:return: Split node
"""
return _get_node_factory_opset1().create(
"Split",
as_nodes(data, axis),
{"num_splits": num_splits}
)
return _get_node_factory_opset1().create("Split", as_nodes(data, axis), {"num_splits": num_splits})
@unary_op
@@ -2629,9 +2522,7 @@ 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
) -> Node:
def squared_difference(x1: NodeInput, x2: NodeInput, auto_broadcast: str = "NUMPY", name: Optional[str] = None) -> Node:
r"""Perform an element-wise squared difference between two tensors.
..math:: y[i] = (x_1[i] - x_2[i])^2
@@ -2643,9 +2534,7 @@ def squared_difference(
:param name: Optional new name for output node.
: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()}
)
return _get_node_factory_opset1().create("SquaredDifference", [x1, x2], {"auto_broadcast": auto_broadcast.upper()})
@nameable_op
@@ -2715,9 +2604,7 @@ def strided_slice(
"ellipsis_mask": ellipsis_mask,
}
return _get_node_factory_opset1().create(
"StridedSlice", as_nodes(data, begin, end, strides), attributes
)
return _get_node_factory_opset1().create("StridedSlice", as_nodes(data, begin, end, strides), attributes)
@binary_op
@@ -2736,9 +2623,7 @@ def subtract(
:param name: The optional name for output node.
: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()}
)
return _get_node_factory_opset1().create("Subtract", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()})
@unary_op
@@ -2796,11 +2681,15 @@ def tensor_iterator(
"""
attributes = {
"body": graph_body.serialize(),
"input_descriptions": {"slice_input_desc": [desc.serialize() for desc in slice_input_desc],
"merged_input_desc": [desc.serialize() for desc in merged_input_desc],
"invariant_input_desc": [desc.serialize() for desc in invariant_input_desc]},
"output_descriptions": {"body_output_desc": [desc.serialize() for desc in body_output_desc],
"concat_output_desc": [desc.serialize() for desc in concat_output_desc]}
"input_descriptions": {
"slice_input_desc": [desc.serialize() for desc in slice_input_desc],
"merged_input_desc": [desc.serialize() for desc in merged_input_desc],
"invariant_input_desc": [desc.serialize() for desc in invariant_input_desc],
},
"output_descriptions": {
"body_output_desc": [desc.serialize() for desc in body_output_desc],
"concat_output_desc": [desc.serialize() for desc in concat_output_desc],
},
}
return _get_node_factory_opset1().create("TensorIterator", as_nodes(*inputs), attributes)
@@ -2872,9 +2761,7 @@ 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
) -> Node:
def variadic_split(data: NodeInput, axis: NodeInput, split_lengths: NodeInput, name: Optional[str] = None) -> Node:
"""Return a node which splits the input tensor into variadic length slices.
:param data: The input tensor to be split
@@ -76,9 +76,7 @@ def interpolate(
attrs["pads_begin"] = [] if pads_begin is None else pads_begin
attrs["pads_end"] = [] if pads_end is None else pads_end
inputs = as_nodes(image, output_shape, scales) if axes is None else as_nodes(image,
output_shape,
scales, axes)
inputs = as_nodes(image, output_shape, scales) if axes is None else as_nodes(image, output_shape, scales, axes)
# This is an update of the operator version, so even though this is opset 10,
# the operator is taken from opset 4.
@@ -1,6 +1,5 @@
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Factory functions for all ngraph ops."""
from typing import Callable, Iterable, List, Optional, Set, Union
@@ -65,9 +64,7 @@ def batch_to_space(
:param name: Optional output node name.
:return: The new node performing a BatchToSpace operation.
"""
return _get_node_factory_opset2().create(
"BatchToSpace", as_nodes(data, block_shape, crops_begin, crops_end)
)
return _get_node_factory_opset2().create("BatchToSpace", as_nodes(data, block_shape, crops_begin, crops_end))
@unary_op
@@ -93,7 +90,7 @@ def mvn(
across_channels: bool = False,
normalize_variance: bool = False,
eps: float = 1e-9,
name: str = None,
name: Optional[str] = None,
) -> Node:
r"""Perform Mean Variance Normalization operation on data from input node.
@@ -175,6 +172,4 @@ def space_to_batch(
:param name: Optional output node name.
:return: The new node performing a SpaceToBatch operation.
"""
return _get_node_factory_opset2().create(
"SpaceToBatch", as_nodes(data, block_shape, pads_begin, pads_end)
)
return _get_node_factory_opset2().create("SpaceToBatch", as_nodes(data, block_shape, pads_begin, pads_end))
@@ -1,6 +1,5 @@
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Factory functions for all ngraph ops."""
from typing import Callable, Iterable, List, Optional, Set, Union
@@ -55,11 +54,7 @@ def assign(new_value: NodeInput, variable_id: str, name: Optional[str] = None) -
:param name: Optional name for output node.
:return: Assign node
"""
return _get_node_factory_opset3().create(
"Assign",
[as_node(new_value)],
{"variable_id": variable_id}
)
return _get_node_factory_opset3().create("Assign", [as_node(new_value)], {"variable_id": variable_id})
@nameable_op
@@ -84,9 +79,7 @@ def broadcast(
inputs = as_nodes(data, target_shape)
if broadcast_spec.upper() == "EXPLICIT":
inputs.append(as_node(axes_mapping))
return _get_node_factory_opset3().create(
"Broadcast", inputs, {"mode": broadcast_spec.upper()}
)
return _get_node_factory_opset3().create("Broadcast", inputs, {"mode": broadcast_spec.upper()})
@nameable_op
@@ -130,9 +123,7 @@ def cum_sum(
:param reverse: if set to true, will perform the sums in reverse direction
:return: New node performing the operation
"""
return _get_node_factory_opset3().create(
"CumSum", as_nodes(arg, axis), {"exclusive": exclusive, "reverse": reverse}
)
return _get_node_factory_opset3().create("CumSum", as_nodes(arg, axis), {"exclusive": exclusive, "reverse": reverse})
@nameable_op
@@ -261,9 +252,9 @@ def gru_cell(
R: NodeInput,
B: NodeInput,
hidden_size: int,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
linear_before_reset: bool = False,
name: Optional[str] = None,
@@ -362,7 +353,11 @@ 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.
@@ -370,11 +365,7 @@ def non_zero(data: NodeInput, output_type: str = "i64", name: Optional[str] = No
:return: The new node which performs NonZero
"""
return _get_node_factory_opset3().create(
"NonZero",
[as_node(data)],
{"output_type": output_type}
)
return _get_node_factory_opset3().create("NonZero", [as_node(data)], {"output_type": output_type})
@nameable_op
@@ -386,11 +377,7 @@ def read_value(init_value: NodeInput, variable_id: str, name: Optional[str] = No
:param name: Optional name for output node.
:return: ReadValue node
"""
return _get_node_factory_opset3().create(
"ReadValue",
[as_node(init_value)],
{"variable_id": variable_id}
)
return _get_node_factory_opset3().create("ReadValue", [as_node(init_value)], {"variable_id": variable_id})
@nameable_op
@@ -515,15 +502,11 @@ def scatter_elements_update(
to `axis` is obtained from the index of the entry itself.
"""
return _get_node_factory_opset3().create(
"ScatterElementsUpdate", as_nodes(data, indices, updates, axis)
)
return _get_node_factory_opset3().create("ScatterElementsUpdate", as_nodes(data, indices, updates, axis))
@nameable_op
def scatter_update(
data: Node, indices: NodeInput, updates: NodeInput, axis: NodeInput, name: Optional[str] = None
) -> Node:
def scatter_update(data: Node, indices: NodeInput, updates: NodeInput, axis: NodeInput, name: Optional[str] = None) -> Node:
"""Return a node which produces a ScatterUpdate operation.
ScatterUpdate sets new values to slices from data addressed by indices.
@@ -534,10 +517,7 @@ def scatter_update(
:param axis: The axis at which elements will be updated.
:return: ScatterUpdate node
"""
return _get_node_factory_opset3().create(
"ScatterUpdate",
as_nodes(data, indices, updates, axis)
)
return _get_node_factory_opset3().create("ScatterUpdate", as_nodes(data, indices, updates, axis))
@nameable_op
@@ -548,11 +528,7 @@ def shape_of(data: NodeInput, output_type: str = "i64", name: Optional[str] = No
:param output_type: Output element type.
:return: ShapeOf node
"""
return _get_node_factory_opset3().create(
"ShapeOf",
[as_node(data)],
{"output_type": output_type}
)
return _get_node_factory_opset3().create("ShapeOf", [as_node(data)], {"output_type": output_type})
@nameable_op
@@ -603,9 +579,7 @@ def shuffle_channels(data: Node, axis: int, group: int, name: Optional[str] = No
[[12., 13.], [14., 15.]],
[[20., 21.], [22., 23.]]]]
"""
return _get_node_factory_opset3().create(
"ShuffleChannels", [as_node(data)], {"axis": axis, "group": group}
)
return _get_node_factory_opset3().create("ShuffleChannels", [as_node(data)], {"axis": axis, "group": group})
@nameable_op
@@ -1,6 +1,5 @@
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Factory functions for all ngraph ops."""
from typing import Callable, Iterable, List, Optional, Set, Union
@@ -138,7 +137,10 @@ 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.
@@ -148,7 +150,10 @@ 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.
@@ -208,11 +213,11 @@ def atanh(node: NodeInput, name: Optional[str] = None) -> Node:
@nameable_op
def proposal(
class_probs: Node,
bbox_deltas: Node,
image_shape: NodeInput,
attrs: dict,
name: Optional[str] = None,
class_probs: Node,
bbox_deltas: Node,
image_shape: NodeInput,
attrs: dict,
name: Optional[str] = None,
) -> Node:
"""Filter bounding boxes and outputs only those with the highest prediction confidence.
@@ -322,15 +327,11 @@ def proposal(
check_valid_attributes("Proposal", attrs, requirements)
return _get_node_factory_opset4().create(
"Proposal", [class_probs, bbox_deltas, as_node(image_shape)], attrs
)
return _get_node_factory_opset4().create("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:
def reduce_l1(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.
:param node: The tensor we want to mean-reduce.
@@ -339,15 +340,11 @@ def reduce_l1(
:param name: Optional name for output node.
:return: The new node performing mean-reduction operation.
"""
return _get_node_factory_opset4().create(
"ReduceL1", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
)
return _get_node_factory_opset4().create("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:
def reduce_l2(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.
:param node: The tensor we want to mean-reduce.
@@ -356,9 +353,7 @@ def reduce_l2(
:param name: Optional name for output node.
:return: The new node performing mean-reduction operation.
"""
return _get_node_factory_opset4().create(
"ReduceL2", as_nodes(node, reduction_axes), {"keep_dims": keep_dims}
)
return _get_node_factory_opset4().create("ReduceL2", as_nodes(node, reduction_axes), {"keep_dims": keep_dims})
@nameable_op
@@ -370,9 +365,9 @@ def lstm_cell(
R: NodeInput,
B: NodeInput,
hidden_size: int,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
@@ -1,6 +1,5 @@
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Factory functions for all ngraph ops."""
from typing import Callable, Iterable, List, Optional, Set, Union
@@ -88,9 +87,7 @@ def gather_nd(
"""
inputs = as_nodes(data, indices)
attributes = {
"batch_dims": batch_dims
}
attributes = {"batch_dims": batch_dims}
return _get_node_factory_opset5().create("GatherND", inputs, attributes)
@@ -141,13 +138,9 @@ def non_max_suppression(
if score_threshold is None:
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
)
inputs = as_nodes(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
)
inputs = as_nodes(boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold, soft_nms_sigma)
attributes = {
"box_encoding": box_encoding,
@@ -174,20 +167,20 @@ def round(data: NodeInput, mode: str = "half_to_even", name: Optional[str] = Non
@nameable_op
def lstm_sequence(
X: NodeInput,
initial_hidden_state: NodeInput,
initial_cell_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
clip: float = 0.0,
name: Optional[str] = None,
X: NodeInput,
initial_hidden_state: NodeInput,
initial_cell_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs LSTMSequence operation.
@@ -236,7 +229,10 @@ 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.
@@ -247,20 +243,20 @@ def hsigmoid(data: NodeInput, name: Optional[str] = None,) -> Node:
@nameable_op
def gru_sequence(
X: NodeInput,
initial_hidden_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
clip: float = 0.0,
linear_before_reset: bool = False,
name: Optional[str] = None,
X: NodeInput,
initial_hidden_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
linear_before_reset: bool = False,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs GRUSequence operation.
@@ -311,19 +307,19 @@ def gru_sequence(
@nameable_op
def rnn_sequence(
X: NodeInput,
initial_hidden_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
clip: float = 0.0,
name: Optional[str] = None,
X: NodeInput,
initial_hidden_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs RNNSequence operation.
@@ -416,13 +412,15 @@ def loop(
"""
attributes = {
"body": graph_body.serialize(),
"input_descriptions": {"slice_input_desc": [desc.serialize() for desc in slice_input_desc],
"merged_input_desc": [desc.serialize() for desc in merged_input_desc],
"invariant_input_desc": [desc.serialize() for desc in invariant_input_desc]},
"output_descriptions": {"body_output_desc": [desc.serialize() for desc in body_output_desc],
"concat_output_desc": [desc.serialize() for desc in concat_output_desc]},
"special_body_ports": {"body_condition_output_idx": body_condition_output_idx,
"current_iteration_input_idx": current_iteration_input_idx}
"input_descriptions": {
"slice_input_desc": [desc.serialize() for desc in slice_input_desc],
"merged_input_desc": [desc.serialize() for desc in merged_input_desc],
"invariant_input_desc": [desc.serialize() for desc in invariant_input_desc],
},
"output_descriptions": {
"body_output_desc": [desc.serialize() for desc in body_output_desc],
"concat_output_desc": [desc.serialize() for desc in concat_output_desc],
},
"special_body_ports": {"body_condition_output_idx": body_condition_output_idx, "current_iteration_input_idx": current_iteration_input_idx},
}
return _get_node_factory_opset5().create("Loop", as_nodes(trip_count, execution_condition, *inputs),
attributes)
return _get_node_factory_opset5().create("Loop", as_nodes(trip_count, execution_condition, *inputs), attributes)
@@ -47,13 +47,13 @@ _get_node_factory_opset6 = partial(_get_node_factory, "opset6")
@nameable_op
def ctc_greedy_decoder_seq_len(
data: NodeInput,
sequence_length: NodeInput,
blank_index: Optional[NodeInput] = None,
merge_repeated: bool = True,
classes_index_type: str = "i32",
sequence_length_type: str = "i32",
name: Optional[str] = None,
data: NodeInput,
sequence_length: NodeInput,
blank_index: Optional[NodeInput] = None,
merge_repeated: bool = True,
classes_index_type: str = "i32",
sequence_length_type: str = "i32",
name: Optional[str] = None,
) -> Node:
"""Return a node which performs CTCGreedyDecoderSeqLen.
@@ -68,11 +68,7 @@ def ctc_greedy_decoder_seq_len(
else:
inputs = as_nodes(data, sequence_length)
attributes = {
"merge_repeated": merge_repeated,
"classes_index_type": classes_index_type,
"sequence_length_type": sequence_length_type
}
attributes = {"merge_repeated": merge_repeated, "classes_index_type": classes_index_type, "sequence_length_type": sequence_length_type}
return _get_node_factory_opset6().create("CTCGreedyDecoderSeqLen", inputs, attributes)
@@ -93,9 +89,7 @@ def gather_elements(
"""
inputs = as_nodes(data, indices)
attributes = {
"axis": axis
}
attributes = {"axis": axis}
return _get_node_factory_opset6().create("GatherElements", inputs, attributes)
@@ -122,11 +116,7 @@ def mvn(
"""
inputs = as_nodes(data, axes)
attributes = {
"normalize_variance": normalize_variance,
"eps": eps,
"eps_mode": eps_mode
}
attributes = {"normalize_variance": normalize_variance, "eps": eps, "eps_mode": eps_mode}
return _get_node_factory_opset6().create("MVN", inputs, attributes)
@@ -140,11 +130,7 @@ def assign(new_value: NodeInput, variable_id: str, name: Optional[str] = None) -
:param name: Optional name for output node.
:return: Assign node
"""
return _get_node_factory_opset6().create(
"Assign",
[as_node(new_value)],
{"variable_id": variable_id}
)
return _get_node_factory_opset6().create("Assign", [as_node(new_value)], {"variable_id": variable_id})
@nameable_op
@@ -156,8 +142,4 @@ def read_value(init_value: NodeInput, variable_id: str, name: Optional[str] = No
:param name: Optional name for output node.
:return: ReadValue node
"""
return _get_node_factory_opset6().create(
"ReadValue",
[as_node(init_value)],
{"variable_id": variable_id}
)
return _get_node_factory_opset6().create("ReadValue", [as_node(init_value)], {"variable_id": variable_id})
@@ -46,28 +46,23 @@ _get_node_factory_opset7 = partial(_get_node_factory, "opset7")
@nameable_op
def einsum(
inputs: List[Node],
equation: str
) -> Node:
def einsum(inputs: List[Node], equation: str) -> Node:
"""Return a node which performs Einsum operation.
:param inputs: The list of input nodes
:param equation: Einsum equation
:return: The new node performing Einsum operation on the inputs
"""
attributes = {
"equation": equation
}
attributes = {"equation": equation}
return _get_node_factory_opset7().create("Einsum", as_nodes(*inputs), attributes)
@nameable_op
def gelu(
data: Node,
approximation_mode: str,
name: Optional[str] = None,
data: Node,
approximation_mode: str,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs Gelu activation function.
@@ -78,18 +73,16 @@ def gelu(
"""
inputs = as_nodes(data)
attributes = {
"approximation_mode": approximation_mode
}
attributes = {"approximation_mode": approximation_mode}
return _get_node_factory_opset7().create("Gelu", inputs, attributes)
@nameable_op
def roll(
data: NodeInput,
shift: NodeInput,
axes: NodeInput,
data: NodeInput,
shift: NodeInput,
axes: NodeInput,
) -> Node:
"""Return a node which performs Roll operation.
@@ -105,10 +98,10 @@ def roll(
@nameable_op
def gather(
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
) -> Node:
"""Return a node which performs Gather.
@@ -119,16 +112,14 @@ def gather(
:return: The new node which performs Gather
"""
inputs = as_nodes(data, indices, axis)
attributes = {
"batch_dims": batch_dims
}
attributes = {"batch_dims": batch_dims}
return _get_node_factory_opset7().create("Gather", inputs, attributes)
def dft(
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
) -> Node:
"""Return a node which performs DFT operation.
@@ -147,9 +138,9 @@ def dft(
@nameable_op
def idft(
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
) -> Node:
"""Return a node which performs IDFT operation.
@@ -35,19 +35,19 @@ _get_node_factory_opset8 = partial(_get_node_factory, "opset8")
@nameable_op
def deformable_convolution(
data: NodeInput,
offsets: NodeInput,
filters: NodeInput,
strides: List[int],
pads_begin: List[int],
pads_end: List[int],
dilations: List[int],
mask: Optional[NodeInput] = None,
auto_pad: str = "EXPLICIT",
group: int = 1,
deformable_group: int = 1,
bilinear_interpolation_pad: bool = False,
name: Optional[str] = None,
data: NodeInput,
offsets: NodeInput,
filters: NodeInput,
strides: List[int],
pads_begin: List[int],
pads_end: List[int],
dilations: List[int],
mask: Optional[NodeInput] = None,
auto_pad: str = "EXPLICIT",
group: int = 1,
deformable_group: int = 1,
bilinear_interpolation_pad: bool = False,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs deformable convolution operation.
@@ -84,16 +84,13 @@ 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,
},
)
@nameable_op
def adaptive_avg_pool(
data: NodeInput,
output_shape: NodeInput
) -> Node:
def adaptive_avg_pool(data: NodeInput, output_shape: NodeInput) -> Node:
"""Return a node which performs AdaptiveAvgPool operation.
:param data: The list of input nodes
@@ -105,11 +102,7 @@ def adaptive_avg_pool(
@nameable_op
def adaptive_max_pool(
data: NodeInput,
output_shape: NodeInput,
index_element_type: str = "i64"
) -> Node:
def adaptive_max_pool(data: NodeInput, output_shape: NodeInput, index_element_type: str = "i64") -> Node:
"""Return a node which performs AdaptiveMaxPool operation.
:param data: The list of input nodes
@@ -128,18 +121,18 @@ def adaptive_max_pool(
@nameable_op
def multiclass_nms(
boxes: NodeInput,
scores: NodeInput,
sort_result_type: str = "none",
sort_result_across_batch: bool = False,
output_type: str = "i64",
iou_threshold: float = 0.0,
score_threshold: float = 0.0,
nms_top_k: int = -1,
keep_top_k: int = -1,
background_class: int = -1,
nms_eta: float = 1.0,
normalized: bool = True
boxes: NodeInput,
scores: NodeInput,
sort_result_type: str = "none",
sort_result_across_batch: bool = False,
output_type: str = "i64",
iou_threshold: float = 0.0,
score_threshold: float = 0.0,
nms_top_k: int = -1,
keep_top_k: int = -1,
background_class: int = -1,
nms_eta: float = 1.0,
normalized: bool = True,
) -> Node:
"""Return a node which performs MulticlassNms.
@@ -176,7 +169,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)
@@ -184,19 +177,19 @@ def multiclass_nms(
@nameable_op
def matrix_nms(
boxes: NodeInput,
scores: NodeInput,
sort_result_type: str = "none",
sort_result_across_batch: bool = False,
output_type: str = "i64",
score_threshold: float = 0.0,
nms_top_k: int = -1,
keep_top_k: int = -1,
background_class: int = -1,
decay_function: str = "linear",
gaussian_sigma: float = 2.0,
post_threshold: float = 0.0,
normalized: bool = True
boxes: NodeInput,
scores: NodeInput,
sort_result_type: str = "none",
sort_result_across_batch: bool = False,
output_type: str = "i64",
score_threshold: float = 0.0,
nms_top_k: int = -1,
keep_top_k: int = -1,
background_class: int = -1,
decay_function: str = "linear",
gaussian_sigma: float = 2.0,
post_threshold: float = 0.0,
normalized: bool = True,
) -> Node:
"""Return a node which performs MatrixNms.
@@ -237,7 +230,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)
@@ -245,10 +238,10 @@ def matrix_nms(
@nameable_op
def gather(
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
) -> Node:
"""Return a node which performs Gather with support of negative indices.
@@ -260,25 +253,23 @@ def gather(
:return: The new node which performs Gather
"""
inputs = as_nodes(data, indices, axis)
attributes = {
"batch_dims": batch_dims
}
attributes = {"batch_dims": batch_dims}
return _get_node_factory_opset8().create("Gather", inputs, attributes)
@nameable_op
def max_pool(
data: NodeInput,
strides: List[int],
dilations: List[int],
pads_begin: List[int],
pads_end: List[int],
kernel_shape: TensorShape,
rounding_type: str = "floor",
auto_pad: Optional[str] = None,
index_element_type: Optional[str] = "i64",
axis: Optional[int] = 0,
name: Optional[str] = None,
data: NodeInput,
strides: List[int],
dilations: List[int],
pads_begin: List[int],
pads_end: List[int],
kernel_shape: TensorShape,
rounding_type: str = "floor",
auto_pad: Optional[str] = None,
index_element_type: Optional[str] = "i64",
axis: Optional[int] = 0,
name: Optional[str] = None,
) -> Node:
"""Perform max pooling operation and return both values and indices of the selected elements.
@@ -322,14 +313,7 @@ def max_pool(
@nameable_op
def random_uniform(
output_shape: NodeInput,
min_val: NodeInput,
max_val: NodeInput,
output_type: str,
global_seed: int = 0,
op_seed: int = 0
) -> Node:
def random_uniform(output_shape: NodeInput, min_val: NodeInput, max_val: NodeInput, output_type: str, global_seed: int = 0, op_seed: int = 0) -> Node:
"""Return a node which generates sequence of random values from uniform distribution.
:param output_shape: Tensor with shape of the output tensor.
@@ -359,12 +343,12 @@ def random_uniform(
@nameable_op
def if_op(
condition: NodeInput,
inputs: List[Node],
bodies: Tuple[GraphBody, GraphBody],
input_desc: Tuple[List[TensorIteratorInvariantInputDesc], List[TensorIteratorInvariantInputDesc]],
output_desc: Tuple[List[TensorIteratorBodyOutputDesc], List[TensorIteratorBodyOutputDesc]],
name: Optional[str] = None,
condition: NodeInput,
inputs: List[Node],
bodies: Tuple[GraphBody, GraphBody],
input_desc: Tuple[List[TensorIteratorInvariantInputDesc], List[TensorIteratorInvariantInputDesc]],
output_desc: Tuple[List[TensorIteratorBodyOutputDesc], List[TensorIteratorBodyOutputDesc]],
name: Optional[str] = None,
) -> Node:
"""Execute one of the bodies depending on condtion value.
@@ -387,20 +371,19 @@ def if_op(
"then_inputs": {"invariant_input_desc": [desc.serialize() for desc in input_desc[0]]},
"else_inputs": {"invariant_input_desc": [desc.serialize() for desc in input_desc[1]]},
"then_outputs": {"body_output_desc": [desc.serialize() for desc in output_desc[0]]},
"else_outputs": {"body_output_desc": [desc.serialize() for desc in output_desc[1]]}
"else_outputs": {"body_output_desc": [desc.serialize() for desc in output_desc[1]]},
}
return _get_node_factory_opset8().create("If", as_nodes(condition, *inputs),
attributes)
return _get_node_factory_opset8().create("If", as_nodes(condition, *inputs), attributes)
@nameable_op
def slice(
data: NodeInput,
start: NodeInput,
stop: NodeInput,
step: NodeInput,
axes: Optional[NodeInput] = None,
name: Optional[str] = None,
data: NodeInput,
start: NodeInput,
stop: NodeInput,
step: NodeInput,
axes: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which generates Slice operation.
@@ -422,10 +405,10 @@ def slice(
@nameable_op
def gather_nd(
data: NodeInput,
indices: NodeInput,
batch_dims: Optional[int] = 0,
name: Optional[str] = None,
data: NodeInput,
indices: NodeInput,
batch_dims: Optional[int] = 0,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs GatherND.
@@ -436,16 +419,12 @@ def gather_nd(
"""
inputs = as_nodes(data, indices)
attributes = {
"batch_dims": batch_dims
}
attributes = {"batch_dims": batch_dims}
return _get_node_factory_opset8().create("GatherND", inputs, attributes)
def prior_box(
layer_shape: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None
) -> Node:
def prior_box(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.
Available attributes are:
@@ -553,10 +532,10 @@ def prior_box(
@nameable_op
def i420_to_bgr(
arg: NodeInput,
arg_u: Optional[NodeInput] = None,
arg_v: Optional[NodeInput] = None,
name: Optional[str] = None,
arg: NodeInput,
arg_u: Optional[NodeInput] = None,
arg_v: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs I420toBGR operation.
@@ -571,19 +550,17 @@ def i420_to_bgr(
elif arg_u is not None and arg_v is not None:
inputs = as_nodes(arg, arg_u, arg_v)
else:
raise UserInputError(
"Operation I420toBGR must have one (single plane) or three (separate planes) inputs provided."
)
raise UserInputError("Operation I420toBGR must have one (single plane) or three (separate planes) inputs provided.")
return _get_node_factory_opset8().create("I420toBGR", inputs)
@nameable_op
def i420_to_rgb(
arg: NodeInput,
arg_u: Optional[NodeInput] = None,
arg_v: Optional[NodeInput] = None,
name: Optional[str] = None,
arg: NodeInput,
arg_u: Optional[NodeInput] = None,
arg_v: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs I420toRGB operation.
@@ -598,18 +575,16 @@ def i420_to_rgb(
elif arg_u is not None and arg_v is not None:
inputs = as_nodes(arg, arg_u, arg_v)
else:
raise UserInputError(
"Operation I420toRGB must have one (single plane) or three (separate planes) inputs provided."
)
raise UserInputError("Operation I420toRGB must have one (single plane) or three (separate planes) inputs provided.")
return _get_node_factory_opset8().create("I420toRGB", inputs)
@nameable_op
def nv12_to_bgr(
arg: NodeInput,
arg_uv: Optional[NodeInput] = None,
name: Optional[str] = None,
arg: NodeInput,
arg_uv: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs NV12toBGR operation.
@@ -628,9 +603,9 @@ def nv12_to_bgr(
@nameable_op
def nv12_to_rgb(
arg: NodeInput,
arg_uv: Optional[NodeInput] = None,
name: Optional[str] = None,
arg: NodeInput,
arg_uv: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs NV12toRGB operation.
@@ -649,13 +624,13 @@ def nv12_to_rgb(
@nameable_op
def detection_output(
box_logits: NodeInput,
class_preds: NodeInput,
proposals: NodeInput,
attrs: dict,
aux_class_preds: Optional[NodeInput] = None,
aux_box_preds: Optional[NodeInput] = None,
name: Optional[str] = None,
box_logits: NodeInput,
class_preds: NodeInput,
proposals: NodeInput,
attrs: dict,
aux_class_preds: Optional[NodeInput] = None,
aux_box_preds: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Generate the detection output using information on location and confidence predictions.
@@ -25,12 +25,12 @@ _get_node_factory_opset9 = partial(_get_node_factory, "opset9")
@nameable_op
def eye(
num_rows: NodeInput,
num_columns: NodeInput,
diagonal_index: NodeInput,
output_type: str,
batch_shape: Optional[NodeInput] = None,
name: Optional[str] = None,
num_rows: NodeInput,
num_columns: NodeInput,
diagonal_index: NodeInput,
output_type: str,
batch_shape: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs eye operation.
@@ -153,9 +153,9 @@ def softsign(node: NodeInput, name: Optional[str] = None) -> Node:
@nameable_op
def rdft(
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
) -> Node:
"""Return a node which performs RDFT operation.
@@ -174,9 +174,9 @@ def rdft(
@nameable_op
def irdft(
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
) -> Node:
"""Return a node which performs IRDFT operation.
@@ -195,19 +195,19 @@ def irdft(
@nameable_op
def multiclass_nms(
boxes: NodeInput,
scores: NodeInput,
roisnum: Optional[NodeInput] = None,
sort_result_type: Optional[str] = "none",
sort_result_across_batch: Optional[bool] = False,
output_type: Optional[str] = "i64",
iou_threshold: Optional[float] = 0.0,
score_threshold: Optional[float] = 0.0,
nms_top_k: Optional[int] = -1,
keep_top_k: Optional[int] = -1,
background_class: Optional[int] = -1,
nms_eta: Optional[float] = 1.0,
normalized: Optional[bool] = True
boxes: NodeInput,
scores: NodeInput,
roisnum: Optional[NodeInput] = None,
sort_result_type: Optional[str] = "none",
sort_result_across_batch: Optional[bool] = False,
output_type: Optional[str] = "i64",
iou_threshold: Optional[float] = 0.0,
score_threshold: Optional[float] = 0.0,
nms_top_k: Optional[int] = -1,
keep_top_k: Optional[int] = -1,
background_class: Optional[int] = -1,
nms_eta: Optional[float] = 1.0,
normalized: Optional[bool] = True,
) -> Node:
"""Return a node which performs MulticlassNms.
@@ -249,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,18 +294,13 @@ 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)
def grid_sample(
data: NodeInput,
grid: NodeInput,
attributes: dict,
name: Optional[str] = None
) -> Node:
def grid_sample(data: NodeInput, grid: NodeInput, attributes: dict, name: Optional[str] = None) -> Node:
"""Return a node which performs GridSample operation.
:param data: The input image.
@@ -1,9 +1,8 @@
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
import logging
from typing import List
from typing import List, Optional
import ngraph as ng
from ngraph.impl import AxisSet, Node
@@ -12,9 +11,7 @@ from ngraph.utils.types import NodeInput, TensorShape, get_dtype, make_constant_
log = logging.getLogger(__name__)
def get_broadcast_axes(
output_shape: TensorShape, input_shape: TensorShape, axis: int = None
) -> AxisSet:
def get_broadcast_axes(output_shape: TensorShape, input_shape: TensorShape, axis: Optional[int] = None) -> AxisSet:
"""Generate a list of broadcast axes for ngraph++ broadcast.
Informally, a broadcast "adds" axes to the input tensor,
@@ -38,17 +38,9 @@ def _check_value(op_name, attr_key, value, val_type, cond=None):
:return: 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
)
)
raise UserInputError('{} operator attribute "{}" value must by of type {}.'.format(op_name, attr_key, 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
)
)
raise UserInputError('{} operator attribute "{}" value does not satisfy provided condition.'.format(op_name, attr_key))
return True
@@ -71,11 +63,7 @@ def check_valid_attribute(op_name, attr_dict, attr_key, val_type, cond=None, req
result = True
if required and attr_key not in attr_dict:
raise UserInputError(
'Provided dictionary is missing {} operator required attribute "{}"'.format(
op_name, attr_key
)
)
raise UserInputError('Provided dictionary is missing {} operator required attribute "{}"'.format(op_name, attr_key))
if attr_key not in attr_dict:
return result
@@ -48,11 +48,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('Error: cannot create "{}" op without arguments.'.format(op_type_name))
if attributes is None:
attributes = {}
@@ -101,9 +97,11 @@ class NodeFactory(object):
if issubclass(type(argument), Output):
outputs.append(argument)
else:
log.warning("Op arguments were passed as Node, please avoid passing arguments in "
"this manner, and pass Output(s) instead, because accepting Nodes will "
"be deprecated in a future release.")
log.warning(
"Op arguments were passed as Node, please avoid passing arguments in "
"this manner, and pass Output(s) instead, because accepting Nodes will "
"be deprecated in a future release."
)
outputs.extend(argument.outputs())
return outputs
@@ -12,7 +12,11 @@ from ngraph.impl.op import Parameter
class GraphBody(object):
"""Class containing graph parameters and results."""
def __init__(self, parameters: List[Parameter], results: List[Node],) -> None:
def __init__(
self,
parameters: List[Parameter],
results: List[Node],
) -> None:
self.parameters = parameters
self.results = results
@@ -27,7 +31,11 @@ class GraphBody(object):
class TensorIteratorInputDesc(object):
"""Represents a generic input descriptor for TensorIterator operator."""
def __init__(self, input_idx: int, body_parameter_idx: int,) -> None:
def __init__(
self,
input_idx: int,
body_parameter_idx: int,
) -> None:
self.input_idx = input_idx
self.body_parameter_idx = body_parameter_idx
@@ -76,7 +84,12 @@ class TensorIteratorMergedInputDesc(TensorIteratorInputDesc):
Later on, this input value is computed inside graph body.
"""
def __init__(self, input_idx: int, body_parameter_idx: int, body_value_idx: int,) -> None:
def __init__(
self,
input_idx: int,
body_parameter_idx: int,
body_value_idx: int,
) -> None:
super().__init__(input_idx, body_parameter_idx)
self.body_value_idx = body_value_idx
@@ -90,14 +103,22 @@ class TensorIteratorMergedInputDesc(TensorIteratorInputDesc):
class TensorIteratorInvariantInputDesc(TensorIteratorInputDesc):
"""Represents a TensorIterator graph body input that has invariant value during iteration."""
def __init__(self, input_idx: int, body_parameter_idx: int,) -> None:
def __init__(
self,
input_idx: int,
body_parameter_idx: int,
) -> None:
super().__init__(input_idx, body_parameter_idx)
class TensorIteratorOutputDesc(object):
"""Represents a generic output descriptor for TensorIterator operator."""
def __init__(self, body_value_idx: int, output_idx: int,) -> None:
def __init__(
self,
body_value_idx: int,
output_idx: int,
) -> None:
self.body_value_idx = body_value_idx
self.output_idx = output_idx
@@ -112,7 +133,12 @@ class TensorIteratorOutputDesc(object):
class TensorIteratorBodyOutputDesc(TensorIteratorOutputDesc):
"""Represents an output from a specific iteration."""
def __init__(self, body_value_idx: int, output_idx: int, iteration: int = -1,) -> None:
def __init__(
self,
body_value_idx: int,
output_idx: int,
iteration: int = -1,
) -> None:
super().__init__(body_value_idx, output_idx)
self.iteration = iteration
@@ -1,11 +1,10 @@
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Functions related to converting between Python and numpy types and ngraph types."""
import logging
from typing import List, Union
from typing import List, Union, Optional
import numpy as np
@@ -64,9 +63,7 @@ def get_element_type(data_type: NumericType) -> NgraphType:
log.warning("Converting float type of undefined bitwidth to 32-bit ngraph float.")
return NgraphType.f32
ng_type = next(
(ng_type for (ng_type, np_type) in ngraph_to_numpy_types_map if np_type == data_type), None
)
ng_type = next((ng_type for (ng_type, np_type) in ngraph_to_numpy_types_map if np_type == data_type), None)
if ng_type:
return ng_type
@@ -122,7 +119,7 @@ def get_shape(data: NumericData) -> TensorShape:
return []
def make_constant_node(value: NumericData, dtype: NumericType = None) -> Constant:
def make_constant_node(value: NumericData, dtype: Optional[NumericType] = None) -> Constant:
"""Return an ngraph Constant node with the specified value."""
ndarray = get_ndarray(value)
if dtype:
@@ -5,9 +5,11 @@
# flake8: noqa
from openvino.utils import add_openvino_libs_to_path
add_openvino_libs_to_path()
from openvino._pyopenvino import get_version
__version__ = get_version()
from openvino._pyopenvino._offline_transformations import apply_fused_names_cleanup
@@ -9,9 +9,11 @@ Low level wrappers for the FrontEnd C++ API.
# flake8: noqa
from openvino.utils import add_openvino_libs_to_path
add_openvino_libs_to_path()
from openvino._pyopenvino import get_version
__version__ = get_version()
# main classes
@@ -16,5 +16,4 @@ try:
from openvino.frontend.onnx.py_onnx_frontend import ConversionExtensionONNX as ConversionExtension
from openvino.frontend.onnx.py_onnx_frontend import OpExtensionONNX as OpExtension
except ImportError as err:
raise ImportError("OpenVINO ONNX frontend is not available, please make sure the frontend is built. "
"{}".format(err))
raise ImportError("OpenVINO ONNX frontend is not available, please make sure the frontend is built. " "{}".format(err))
@@ -16,5 +16,4 @@ add_openvino_libs_to_path()
try:
from openvino.frontend.paddle.py_paddle_frontend import ConversionExtensionPaddle as ConversionExtension
except ImportError as err:
raise ImportError("OpenVINO Paddle frontend is not available, please make sure the frontend is built."
"{}".format(err))
raise ImportError("OpenVINO Paddle frontend is not available, please make sure the frontend is built." "{}".format(err))
@@ -16,5 +16,4 @@ try:
from openvino.frontend.tensorflow.py_tensorflow_frontend import ConversionExtensionTensorflow as ConversionExtension
from openvino.frontend.tensorflow.py_tensorflow_frontend import OpExtensionTensorflow as OpExtension
except ImportError as err:
raise ImportError("OpenVINO Tensorflow frontend is not available, please make sure the frontend is built. "
"{}".format(err))
raise ImportError("OpenVINO Tensorflow frontend is not available, please make sure the frontend is built. " "{}".format(err))
@@ -23,20 +23,17 @@ def pack_data(array: np.ndarray, type: Type) -> np.ndarray:
:param type: Type to interpret the array values. Type must be u1, u4 or i4.
:type type: openvino.runtime.Type
"""
assert type in [Type.u1, Type.u4, Type.i4], "Packing algorithm for the" \
"data types stored in 1, 2 or 4 bits"
assert type in [Type.u1, Type.u4, Type.i4], "Packing algorithm for the" "data types stored in 1, 2 or 4 bits"
minimum_regular_dtype = np.int8 if type == Type.i4 else np.uint8
casted_to_regular_type = array.astype(dtype=minimum_regular_dtype, casting="unsafe")
if not np.array_equal(casted_to_regular_type, array):
raise RuntimeError(f'The conversion of array "{array}" to dtype'
f' "{casted_to_regular_type}" results in rounding')
raise RuntimeError(f'The conversion of array "{array}" to dtype' f' "{casted_to_regular_type}" results in rounding')
data_size = casted_to_regular_type.size
num_bits = type.bitwidth
assert num_bits < 8 and 8 % num_bits == 0, "Packing algorithm for the" \
"data types stored in 1, 2 or 4 bits"
assert num_bits < 8 and 8 % num_bits == 0, "Packing algorithm for the" "data types stored in 1, 2 or 4 bits"
num_values_fitting_into_uint8 = 8 // num_bits
pad = (-data_size) % num_values_fitting_into_uint8
@@ -65,8 +62,7 @@ def unpack_data(array: np.ndarray, type: Type, shape: Union[list, Shape]) -> np.
:param shape: the new shape for the unpacked array.
:type shape: Union[list, openvino.runtime.Shape]
"""
assert type in [Type.u1, Type.u4, Type.i4], "Unpacking algorithm for the" \
"data types stored in 1, 2 or 4 bits"
assert type in [Type.u1, Type.u4, Type.i4], "Unpacking algorithm for the" "data types stored in 1, 2 or 4 bits"
unpacked = np.unpackbits(array.view(np.uint8))
shape = list(shape)
if type.bitwidth == 1:
@@ -7,12 +7,15 @@
import warnings
warnings.warn(message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future, use `openvino.runtime.passes` instead!",
category=FutureWarning)
warnings.warn(
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future, use `openvino.runtime.passes` instead!",
category=FutureWarning,
)
from openvino.utils import add_openvino_libs_to_path, deprecated
add_openvino_libs_to_path()
from openvino._pyopenvino import get_version
@@ -22,97 +25,66 @@ import openvino._pyopenvino._offline_transformations as _base
__version__ = get_version()
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future, use `openvino.runtime.passes` instead!")
@deprecated(
version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future, use `openvino.runtime.passes` instead!",
)
def serialize(model, xml_path, bin_path, version):
_base_serialize(model, xml_path, bin_path, version)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def apply_fused_names_cleanup(model):
_base.apply_fused_names_cleanup(model)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def apply_moc_transformations(model, cf):
_base.apply_moc_transformations(model, cf)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def apply_moc_legacy_transformations(model, params_with_custom_types):
_base.apply_moc_legacy_transformations(model, params_with_custom_types)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def apply_pot_transformations(model, device):
_base.apply_pot_transformations(model, device)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def apply_low_latency_transformation(model, use_const_initializer):
_base.apply_low_latency_transformation(model, use_const_initializer)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def apply_pruning_transformation(model):
_base.apply_pruning_transformation(model)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def generate_mapping_file(model, path, extract_names):
_base.generate_mapping_file(model, path, extract_names)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def apply_make_stateful_transformation(model, param_res_names):
_base.apply_make_stateful_transformation(model, param_res_names)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def compress_model_transformation(model):
_base.compress_model_transformation(model)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def compress_quantize_weights_transformation(model):
_base.compress_quantize_weights_transformation(model)
@deprecated(version="2023.1",
message="The module is private and following namespace "
"`offline_transformations` will be removed in "
"the future.")
@deprecated(version="2023.1", message="The module is private and following namespace " "`offline_transformations` will be removed in " "the future.")
def convert_sequence_to_tensor_iterator_transformation(model):
_base.convert_sequence_to_tensor_iterator_transformation(model)
@@ -9,9 +9,11 @@ Low level wrappers for the PrePostProcessing C++ API.
# flake8: noqa
from openvino.utils import add_openvino_libs_to_path
add_openvino_libs_to_path()
from openvino._pyopenvino import get_version
__version__ = get_version()
# main classes
@@ -7,8 +7,6 @@
import warnings
warnings.warn(message="The module is private and following namespace "
"`pyopenvino` will be removed in the future",
category=FutureWarning)
warnings.warn(message="The module is private and following namespace " "`pyopenvino` will be removed in the future", category=FutureWarning)
from openvino._pyopenvino import *
@@ -6,9 +6,11 @@
# noqa: F401
from openvino.utils import add_openvino_libs_to_path
add_openvino_libs_to_path()
from openvino._pyopenvino import get_version
__version__ = get_version()
# Openvino pybind bindings and python extended classes
@@ -1,10 +1,9 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
from functools import singledispatch
from typing import Any, Iterable, Union, Dict
from typing import Any, Iterable, Union, Dict, Optional
from pathlib import Path
import numpy as np
@@ -77,7 +76,9 @@ 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,
)
@@ -148,8 +149,7 @@ class InferRequest(InferRequestBase):
# If inputs are list or tuple, enumarate inputs and save them as dictionary.
# 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)}))
return super().infer(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)
@@ -202,8 +202,7 @@ class InferRequest(InferRequestBase):
elif isinstance(inputs, dict):
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)
super().start_async(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)):
@@ -266,7 +265,7 @@ class CompiledModel(CompiledModelBase):
# overloaded functions of InferRequest class
return self.create_infer_request().infer(inputs)
def __call__(self, inputs: Union[dict, list] = None) -> dict:
def __call__(self, inputs: Optional[Union[dict, list]] = None) -> dict:
"""Callable infer wrapper for CompiledModel.
Take a look at `infer_new_request` for reference.
@@ -281,6 +280,7 @@ class AsyncInferQueue(AsyncInferQueueBase):
InferRequests and provides synchronization functions to control flow of
a simple pipeline.
"""
def __iter__(self) -> Iterable[InferRequest]:
"""Allows to iterate over AsyncInferQueue.
@@ -331,7 +331,8 @@ 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(
@@ -363,7 +364,10 @@ class Core(CoreBase):
"""
def compile_model(
self, model: Union[Model, str, Path], device_name: str = None, config: dict = None,
self,
model: Union[Model, str, Path],
device_name: Optional[str] = None,
config: Optional[dict] = None,
) -> CompiledModel:
"""Creates a compiled model.
@@ -396,7 +400,10 @@ class Core(CoreBase):
)
def import_model(
self, model_stream: bytes, device_name: str, config: dict = None,
self,
model_stream: bytes,
device_name: str,
config: Optional[dict] = None,
) -> CompiledModel:
"""Imports a compiled model from a previously exported one.
@@ -439,7 +446,9 @@ 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,
),
)
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Factory functions for all openvino ops."""
from typing import List, Optional, Union
@@ -78,7 +77,9 @@ def add(
:return: The node performing element-wise addition.
"""
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()},
)
@@ -240,7 +241,9 @@ 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()},
)
@@ -261,7 +264,9 @@ 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},
)
@@ -308,7 +313,9 @@ 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},
)
@@ -356,7 +363,9 @@ 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()},
)
@@ -586,7 +595,7 @@ def deformable_psroi_pooling(
@nameable_op
def depth_to_space(node: Node, mode: str, block_size: int = 1, name: str = None) -> Node:
def depth_to_space(node: Node, mode: str, block_size: int = 1, name: Optional[str] = None) -> Node:
"""Rearranges input tensor from depth into blocks of spatial data.
Values from the height and width dimensions are moved to the depth dimension.
@@ -797,7 +806,9 @@ 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()},
)
@@ -835,7 +846,9 @@ 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()},
)
@@ -935,13 +948,18 @@ 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.
@@ -1010,7 +1028,9 @@ 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()},
)
@@ -1170,7 +1190,10 @@ def group_convolution_backprop_data(
@nameable_op
def hard_sigmoid(
data: Node, alpha: NodeInput, beta: NodeInput, name: Optional[str] = None,
data: Node,
alpha: NodeInput,
beta: NodeInput,
name: Optional[str] = None,
) -> Node:
"""Perform Hard Sigmoid operation element-wise on data from input node.
@@ -1191,7 +1214,10 @@ def hard_sigmoid(
@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.
@@ -1284,7 +1310,9 @@ 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()},
)
@@ -1306,7 +1334,9 @@ 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()},
)
@@ -1372,7 +1402,9 @@ 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()},
)
@@ -1432,9 +1464,9 @@ def lstm_cell(
R: NodeInput,
B: NodeInput,
hidden_size: int,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
@@ -1505,9 +1537,9 @@ def lstm_sequence(
B: NodeInput,
hidden_size: int,
direction: str,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
@@ -1664,7 +1696,9 @@ def maximum(
:return: The node performing element-wise maximum operation.
"""
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()},
)
@@ -1685,7 +1719,9 @@ def minimum(
:return: The node performing element-wise minimum operation.
"""
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()},
)
@@ -1705,7 +1741,9 @@ 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()},
)
@@ -1726,7 +1764,9 @@ def multiply(
:return: The node performing element-wise multiplication.
"""
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()},
)
@@ -1798,7 +1838,9 @@ 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},
)
@@ -1819,7 +1861,9 @@ 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()},
)
@@ -1846,7 +1890,9 @@ 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},
)
@@ -1913,7 +1959,9 @@ 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()},
)
@@ -1940,7 +1988,10 @@ 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.
@@ -2020,13 +2071,18 @@ 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.
@@ -2138,7 +2194,9 @@ def prior_box(
check_valid_attributes("PriorBox", attrs, requirements)
return _get_node_factory_opset1().create(
"PriorBox", [layer_shape, as_node(image_shape)], attrs,
"PriorBox",
[layer_shape, as_node(image_shape)],
attrs,
)
@@ -2366,7 +2424,9 @@ 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},
)
@@ -2386,7 +2446,9 @@ 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},
)
@@ -2405,7 +2467,9 @@ 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},
)
@@ -2425,7 +2489,9 @@ 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},
)
@@ -2444,7 +2510,9 @@ 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},
)
@@ -2464,7 +2532,9 @@ 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},
)
@@ -2484,7 +2554,9 @@ 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},
)
@@ -2498,7 +2570,7 @@ def region_yolo(
mask: List[int],
axis: int,
end_axis: int,
anchors: List[float] = None,
anchors: Optional[List[float]] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which produces the RegionYolo operation.
@@ -2555,7 +2627,9 @@ def reshape(
:return: The node reshaping an input tensor.
"""
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},
)
@@ -2613,7 +2687,9 @@ 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()},
)
@@ -2633,7 +2709,8 @@ def selu(
: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),
"Selu",
as_nodes(data, alpha, lambda_value),
)
@@ -2703,7 +2780,7 @@ def softmax(data: NodeInput, axis: int, name: Optional[str] = None) -> Node:
@nameable_op
def space_to_depth(data: Node, mode: str, block_size: int = 1, name: str = None) -> Node:
def space_to_depth(data: Node, mode: str, block_size: int = 1, name: Optional[str] = None) -> Node:
"""Perform SpaceToDepth operation on the input tensor.
SpaceToDepth rearranges blocks of spatial data into depth.
@@ -2737,7 +2814,9 @@ 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},
)
@@ -2771,7 +2850,9 @@ 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()},
)
@@ -2843,7 +2924,9 @@ 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,
)
@@ -2864,7 +2947,9 @@ 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()},
)
@@ -2970,5 +3055,6 @@ def variadic_split(
:return: VariadicSplit node
"""
return _get_node_factory_opset1().create(
"VariadicSplit", as_nodes(data, axis, split_lengths),
"VariadicSplit",
as_nodes(data, axis, split_lengths),
)
@@ -76,9 +76,7 @@ def interpolate(
attrs["pads_begin"] = [] if pads_begin is None else pads_begin
attrs["pads_end"] = [] if pads_end is None else pads_end
inputs = as_nodes(image, output_shape, scales) if axes is None else as_nodes(image,
output_shape,
scales, axes)
inputs = as_nodes(image, output_shape, scales) if axes is None else as_nodes(image, output_shape, scales, axes)
# This is an update of the operator version, so even though this is opset 10,
# the operator is taken from opset 4.
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Factory functions for all openvino ops."""
from typing import Callable, Iterable, List, Optional, Set, Union
@@ -59,7 +58,8 @@ 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),
)
@@ -86,7 +86,7 @@ def mvn(
across_channels: bool = False,
normalize_variance: bool = False,
eps: float = 1e-9,
name: str = None,
name: Optional[str] = None,
) -> Node:
r"""Perform Mean Variance Normalization operation on data from input node.
@@ -177,5 +177,6 @@ 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),
)
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Factory functions for all openvino ops."""
from typing import Callable, Iterable, List, Optional, Set, Union
@@ -78,7 +77,9 @@ 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()},
)
@@ -124,7 +125,9 @@ 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},
)
@@ -254,9 +257,9 @@ def gru_cell(
R: NodeInput,
B: NodeInput,
hidden_size: int,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
linear_before_reset: bool = False,
name: Optional[str] = None,
@@ -509,13 +512,18 @@ 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.
@@ -597,7 +605,9 @@ 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},
)
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Factory functions for all openvino ops."""
from typing import Callable, Iterable, List, Optional, Set, Union
@@ -201,11 +200,11 @@ def atanh(node: NodeInput, name: Optional[str] = None) -> Node:
@nameable_op
def proposal(
class_probs: Node,
bbox_deltas: Node,
image_shape: NodeInput,
attrs: dict,
name: Optional[str] = None,
class_probs: Node,
bbox_deltas: Node,
image_shape: NodeInput,
attrs: dict,
name: Optional[str] = None,
) -> Node:
"""Filter bounding boxes and outputs only those with the highest prediction confidence.
@@ -318,13 +317,18 @@ 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.
@@ -335,13 +339,18 @@ 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.
@@ -352,7 +361,9 @@ 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},
)
@@ -365,9 +376,9 @@ def lstm_cell(
R: NodeInput,
B: NodeInput,
hidden_size: int,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
"""Factory functions for all openvino ops."""
from typing import Callable, Iterable, List, Optional, Set, Union
@@ -135,11 +134,20 @@ 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 = {
@@ -167,20 +175,20 @@ def round(data: NodeInput, mode: str = "half_to_even", name: Optional[str] = Non
@nameable_op
def lstm_sequence(
X: NodeInput,
initial_hidden_state: NodeInput,
initial_cell_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
clip: float = 0.0,
name: Optional[str] = None,
X: NodeInput,
initial_hidden_state: NodeInput,
initial_cell_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs LSTMSequence operation.
@@ -240,20 +248,20 @@ def hsigmoid(data: NodeInput, name: Optional[str] = None) -> Node:
@nameable_op
def gru_sequence(
X: NodeInput,
initial_hidden_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
clip: float = 0.0,
linear_before_reset: bool = False,
name: Optional[str] = None,
X: NodeInput,
initial_hidden_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
linear_before_reset: bool = False,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs GRUSequence operation.
@@ -304,19 +312,19 @@ def gru_sequence(
@nameable_op
def rnn_sequence(
X: NodeInput,
initial_hidden_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: List[str] = None,
activations_alpha: List[float] = None,
activations_beta: List[float] = None,
clip: float = 0.0,
name: Optional[str] = None,
X: NodeInput,
initial_hidden_state: NodeInput,
sequence_lengths: NodeInput,
W: NodeInput,
R: NodeInput,
B: NodeInput,
hidden_size: int,
direction: str,
activations: Optional[List[str]] = None,
activations_alpha: Optional[List[float]] = None,
activations_beta: Optional[List[float]] = None,
clip: float = 0.0,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs RNNSequence operation.
@@ -40,13 +40,13 @@ _get_node_factory_opset6 = partial(_get_node_factory, "opset6")
@nameable_op
def ctc_greedy_decoder_seq_len(
data: NodeInput,
sequence_length: NodeInput,
blank_index: Optional[NodeInput] = None,
merge_repeated: bool = True,
classes_index_type: str = "i32",
sequence_length_type: str = "i32",
name: Optional[str] = None,
data: NodeInput,
sequence_length: NodeInput,
blank_index: Optional[NodeInput] = None,
merge_repeated: bool = True,
classes_index_type: str = "i32",
sequence_length_type: str = "i32",
name: Optional[str] = None,
) -> Node:
"""Return a node which performs CTCGreedyDecoderSeqLen.
@@ -40,8 +40,8 @@ _get_node_factory_opset7 = partial(_get_node_factory, "opset7")
@nameable_op
def einsum(
inputs: List[Node],
equation: str,
inputs: List[Node],
equation: str,
) -> Node:
"""Return a node which performs Einsum operation.
@@ -58,9 +58,9 @@ def einsum(
@nameable_op
def gelu(
data: Node,
approximation_mode: str,
name: Optional[str] = None,
data: Node,
approximation_mode: str,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs Gelu activation function.
@@ -80,9 +80,9 @@ def gelu(
@nameable_op
def roll(
data: NodeInput,
shift: NodeInput,
axes: NodeInput,
data: NodeInput,
shift: NodeInput,
axes: NodeInput,
) -> Node:
"""Return a node which performs Roll operation.
@@ -98,10 +98,10 @@ def roll(
@nameable_op
def gather(
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
) -> Node:
"""Return a node which performs Gather.
@@ -119,9 +119,9 @@ def gather(
def dft(
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
) -> Node:
"""Return a node which performs DFT operation.
@@ -140,9 +140,9 @@ def dft(
@nameable_op
def idft(
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
) -> Node:
"""Return a node which performs IDFT operation.
@@ -32,19 +32,19 @@ _get_node_factory_opset8 = partial(_get_node_factory, "opset8")
@nameable_op
def deformable_convolution(
data: NodeInput,
offsets: NodeInput,
filters: NodeInput,
strides: List[int],
pads_begin: List[int],
pads_end: List[int],
dilations: List[int],
mask: Optional[NodeInput] = None,
auto_pad: str = "EXPLICIT",
group: int = 1,
deformable_group: int = 1,
bilinear_interpolation_pad: bool = False,
name: Optional[str] = None,
data: NodeInput,
offsets: NodeInput,
filters: NodeInput,
strides: List[int],
pads_begin: List[int],
pads_end: List[int],
dilations: List[int],
mask: Optional[NodeInput] = None,
auto_pad: str = "EXPLICIT",
group: int = 1,
deformable_group: int = 1,
bilinear_interpolation_pad: bool = False,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs deformable convolution operation.
@@ -88,8 +88,8 @@ def deformable_convolution(
@nameable_op
def adaptive_avg_pool(
data: NodeInput,
output_shape: NodeInput,
data: NodeInput,
output_shape: NodeInput,
) -> Node:
"""Return a node which performs AdaptiveAvgPool operation.
@@ -103,9 +103,9 @@ def adaptive_avg_pool(
@nameable_op
def adaptive_max_pool(
data: NodeInput,
output_shape: NodeInput,
index_element_type: str = "i64",
data: NodeInput,
output_shape: NodeInput,
index_element_type: str = "i64",
) -> Node:
"""Return a node which performs AdaptiveMaxPool operation.
@@ -125,18 +125,18 @@ def adaptive_max_pool(
@nameable_op
def multiclass_nms(
boxes: NodeInput,
scores: NodeInput,
sort_result_type: str = "none",
sort_result_across_batch: bool = False,
output_type: str = "i64",
iou_threshold: float = 0.0,
score_threshold: float = 0.0,
nms_top_k: int = -1,
keep_top_k: int = -1,
background_class: int = -1,
nms_eta: float = 1.0,
normalized: bool = True,
boxes: NodeInput,
scores: NodeInput,
sort_result_type: str = "none",
sort_result_across_batch: bool = False,
output_type: str = "i64",
iou_threshold: float = 0.0,
score_threshold: float = 0.0,
nms_top_k: int = -1,
keep_top_k: int = -1,
background_class: int = -1,
nms_eta: float = 1.0,
normalized: bool = True,
) -> Node:
"""Return a node which performs MulticlassNms.
@@ -181,19 +181,19 @@ def multiclass_nms(
@nameable_op
def matrix_nms(
boxes: NodeInput,
scores: NodeInput,
sort_result_type: str = "none",
sort_result_across_batch: bool = False,
output_type: str = "i64",
score_threshold: float = 0.0,
nms_top_k: int = -1,
keep_top_k: int = -1,
background_class: int = -1,
decay_function: str = "linear",
gaussian_sigma: float = 2.0,
post_threshold: float = 0.0,
normalized: bool = True,
boxes: NodeInput,
scores: NodeInput,
sort_result_type: str = "none",
sort_result_across_batch: bool = False,
output_type: str = "i64",
score_threshold: float = 0.0,
nms_top_k: int = -1,
keep_top_k: int = -1,
background_class: int = -1,
decay_function: str = "linear",
gaussian_sigma: float = 2.0,
post_threshold: float = 0.0,
normalized: bool = True,
) -> Node:
"""Return a node which performs MatrixNms.
@@ -242,10 +242,10 @@ def matrix_nms(
@nameable_op
def gather(
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
data: NodeInput,
indices: NodeInput,
axis: NodeInput,
batch_dims: Optional[int] = 0,
) -> Node:
"""Return a node which performs Gather with support of negative indices.
@@ -265,17 +265,17 @@ def gather(
@nameable_op
def max_pool(
data: NodeInput,
strides: List[int],
dilations: List[int],
pads_begin: List[int],
pads_end: List[int],
kernel_shape: TensorShape,
rounding_type: str = "floor",
auto_pad: Optional[str] = None,
index_element_type: Optional[str] = "i64",
axis: Optional[int] = 0,
name: Optional[str] = None,
data: NodeInput,
strides: List[int],
dilations: List[int],
pads_begin: List[int],
pads_end: List[int],
kernel_shape: TensorShape,
rounding_type: str = "floor",
auto_pad: Optional[str] = None,
index_element_type: Optional[str] = "i64",
axis: Optional[int] = 0,
name: Optional[str] = None,
) -> Node:
"""Perform max pooling operation and return both values and indices of the selected elements.
@@ -320,12 +320,12 @@ def max_pool(
@nameable_op
def random_uniform(
output_shape: NodeInput,
min_val: NodeInput,
max_val: NodeInput,
output_type: str,
global_seed: int = 0,
op_seed: int = 0,
output_shape: NodeInput,
min_val: NodeInput,
max_val: NodeInput,
output_type: str,
global_seed: int = 0,
op_seed: int = 0,
) -> Node:
"""Return a node which generates sequence of random values from uniform distribution.
@@ -357,12 +357,12 @@ def random_uniform(
@nameable_op
def slice(
data: NodeInput,
start: NodeInput,
stop: NodeInput,
step: NodeInput,
axes: Optional[NodeInput] = None,
name: Optional[str] = None,
data: NodeInput,
start: NodeInput,
stop: NodeInput,
step: NodeInput,
axes: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which generates Slice operation.
@@ -384,10 +384,10 @@ def slice(
@nameable_op
def gather_nd(
data: NodeInput,
indices: NodeInput,
batch_dims: Optional[int] = 0,
name: Optional[str] = None,
data: NodeInput,
indices: NodeInput,
batch_dims: Optional[int] = 0,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs GatherND.
@@ -407,7 +407,10 @@ 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.
@@ -521,10 +524,10 @@ def prior_box(
@nameable_op
def i420_to_bgr(
arg: NodeInput,
arg_u: Optional[NodeInput] = None,
arg_v: Optional[NodeInput] = None,
name: Optional[str] = None,
arg: NodeInput,
arg_u: Optional[NodeInput] = None,
arg_v: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs I420toBGR operation.
@@ -548,10 +551,10 @@ def i420_to_bgr(
@nameable_op
def i420_to_rgb(
arg: NodeInput,
arg_u: Optional[NodeInput] = None,
arg_v: Optional[NodeInput] = None,
name: Optional[str] = None,
arg: NodeInput,
arg_u: Optional[NodeInput] = None,
arg_v: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs I420toRGB operation.
@@ -575,9 +578,9 @@ def i420_to_rgb(
@nameable_op
def nv12_to_bgr(
arg: NodeInput,
arg_uv: Optional[NodeInput] = None,
name: Optional[str] = None,
arg: NodeInput,
arg_uv: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs NV12toBGR operation.
@@ -596,9 +599,9 @@ def nv12_to_bgr(
@nameable_op
def nv12_to_rgb(
arg: NodeInput,
arg_uv: Optional[NodeInput] = None,
name: Optional[str] = None,
arg: NodeInput,
arg_uv: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs NV12toRGB operation.
@@ -617,13 +620,13 @@ def nv12_to_rgb(
@nameable_op
def detection_output(
box_logits: NodeInput,
class_preds: NodeInput,
proposals: NodeInput,
attrs: dict,
aux_class_preds: Optional[NodeInput] = None,
aux_box_preds: Optional[NodeInput] = None,
name: Optional[str] = None,
box_logits: NodeInput,
class_preds: NodeInput,
proposals: NodeInput,
attrs: dict,
aux_class_preds: Optional[NodeInput] = None,
aux_box_preds: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Generate the detection output using information on location and confidence predictions.
@@ -25,12 +25,12 @@ _get_node_factory_opset9 = partial(_get_node_factory, "opset9")
@nameable_op
def eye(
num_rows: NodeInput,
num_columns: NodeInput,
diagonal_index: NodeInput,
output_type: str,
batch_shape: Optional[NodeInput] = None,
name: Optional[str] = None,
num_rows: NodeInput,
num_columns: NodeInput,
diagonal_index: NodeInput,
output_type: str,
batch_shape: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs eye operation.
@@ -153,9 +153,9 @@ def softsign(node: NodeInput, name: Optional[str] = None) -> Node:
@nameable_op
def rdft(
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
) -> Node:
"""Return a node which performs RDFT operation.
@@ -174,9 +174,9 @@ def rdft(
@nameable_op
def irdft(
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
data: NodeInput,
axes: NodeInput,
signal_size: Optional[NodeInput] = None,
) -> Node:
"""Return a node which performs IRDFT operation.
@@ -195,19 +195,19 @@ def irdft(
@nameable_op
def multiclass_nms(
boxes: NodeInput,
scores: NodeInput,
roisnum: Optional[NodeInput] = None,
sort_result_type: Optional[str] = "none",
sort_result_across_batch: Optional[bool] = False,
output_type: Optional[str] = "i64",
iou_threshold: Optional[float] = 0.0,
score_threshold: Optional[float] = 0.0,
nms_top_k: Optional[int] = -1,
keep_top_k: Optional[int] = -1,
background_class: Optional[int] = -1,
nms_eta: Optional[float] = 1.0,
normalized: Optional[bool] = True,
boxes: NodeInput,
scores: NodeInput,
roisnum: Optional[NodeInput] = None,
sort_result_type: Optional[str] = "none",
sort_result_across_batch: Optional[bool] = False,
output_type: Optional[str] = "i64",
iou_threshold: Optional[float] = 0.0,
score_threshold: Optional[float] = 0.0,
nms_top_k: Optional[int] = -1,
keep_top_k: Optional[int] = -1,
background_class: Optional[int] = -1,
nms_eta: Optional[float] = 1.0,
normalized: Optional[bool] = True,
) -> Node:
"""Return a node which performs MulticlassNms.
@@ -302,10 +302,10 @@ def generate_proposals(
def grid_sample(
data: NodeInput,
grid: NodeInput,
attributes: dict,
name: Optional[str] = None,
data: NodeInput,
grid: NodeInput,
attributes: dict,
name: Optional[str] = None,
) -> Node:
"""Return a node which performs GridSample operation.
@@ -4,8 +4,16 @@
# flake8: noqa
from openvino._pyopenvino.passes import ModelPass, Matcher, MatcherPass, PassBase, WrapType, Or, AnyInput
from openvino._pyopenvino.passes import consumers_count, has_static_dim, has_static_dims, has_static_shape,\
has_static_rank, rank_equals, type_matches, type_matches_any
from openvino._pyopenvino.passes import (
consumers_count,
has_static_dim,
has_static_dims,
has_static_shape,
has_static_rank,
rank_equals,
type_matches,
type_matches_any,
)
from openvino._pyopenvino.passes import Serialize, ConstantFolding, VisualizeTree, MakeStateful, LowLatency2, ConvertFP32ToFP16
from openvino.runtime.passes.manager import Manager
from openvino.runtime.passes.graph_rewrite import GraphRewrite, BackwardGraphRewrite
@@ -9,6 +9,7 @@ from openvino._pyopenvino.passes import BackwardGraphRewrite as BackwardGraphRew
class GraphRewrite(GraphRewriteBase):
"""GraphRewrite that additionally holds python transformations objects."""
def __init__(self) -> None:
super().__init__()
self.passes_list = [] # need to keep python instances alive
@@ -21,6 +22,7 @@ class GraphRewrite(GraphRewriteBase):
class BackwardGraphRewrite(BackwardGraphRewriteBase):
"""BackwardGraphRewriteBase that additionally holds python transformations objects."""
def __init__(self) -> None:
super().__init__()
self.passes_list = [] # need to keep python instances alive
@@ -8,6 +8,7 @@ from openvino._pyopenvino.passes import PassBase
class Manager(ManagerBase):
"""Manager that additionally holds transformations objects."""
def __init__(self) -> None:
super().__init__()
self.passes_list = [] # need to keep python instances alive
@@ -1,10 +1,9 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors # noqa: E800
import logging
from typing import List
from typing import List, Optional
from openvino.runtime import AxisSet, Node
from openvino.runtime.utils.types import (
@@ -18,7 +17,9 @@ log = logging.getLogger(__name__)
def get_broadcast_axes(
output_shape: TensorShape, input_shape: TensorShape, axis: int = None,
output_shape: TensorShape,
input_shape: TensorShape,
axis: Optional[int] = None,
) -> AxisSet:
"""Generate a list of broadcast axes for openvino broadcast.
@@ -55,6 +55,7 @@ def binary_op(node_factory_function: Callable) -> Callable:
def custom_preprocess_function(custom_function: Callable) -> Callable:
"""Convert Node returned from custom_function to Output."""
@wraps(custom_function)
def wrapper(node: Node) -> Output:
return Output._from_node(custom_function(node))
@@ -64,7 +64,8 @@ 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
@@ -38,12 +38,16 @@ def deprecated(version: str = "", message: str = "") -> Callable[..., Any]:
:param version: The version in which the code will be removed.
:param message: A message explaining why the function is deprecated and/or what to use instead.
"""
def decorator(wrapped: Callable[..., Any]) -> Callable[..., Any]:
@wraps(wrapped)
def wrapper(*args: Any, **kwargs: Any) -> Callable[..., Any]:
# it must be imported here; otherwise, there are errors with no loaded DLL for Windows
from openvino._pyopenvino.util import deprecation_warning
deprecation_warning(wrapped.__name__, version, message)
return wrapped(*args, **kwargs)
return wrapper
return decorator