Skip to content

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

[PyOV] Extend Python API with `OneHot-16` and `AvgPool-16` (#32511)

Przemyslaw Wysocki0d4a14e3d4dd
diff --git a/src/bindings/python/src/openvino/opset16/__init__.py b/src/bindings/python/src/openvino/opset16/__init__.py
index 5f23ed843e1..3fb20d00ab8 100644
--- a/src/bindings/python/src/openvino/opset16/__init__.py
+++ b/src/bindings/python/src/openvino/opset16/__init__.py
@@ -7,6 +7,8 @@ from openvino.opset16.ops import identity
from openvino.opset16.ops import istft
from openvino.opset16.ops import segment_max
from openvino.opset16.ops import sparse_fill_empty_rows
+from openvino.opset16.ops import avg_pool
+from openvino.opset16.ops import one_hot
# Operators from previous opsets
# TODO (ticket: 156877): Add previous opset operators at the end of opset16 development
diff --git a/src/bindings/python/src/openvino/opset16/ops.py b/src/bindings/python/src/openvino/opset16/ops.py
index e2828dc8b30..07940788863 100644
--- a/src/bindings/python/src/openvino/opset16/ops.py
+++ b/src/bindings/python/src/openvino/opset16/ops.py
@@ -9,7 +9,7 @@ from typing import Optional, Literal
from openvino import Node
from openvino.utils.decorators import nameable_op
from openvino.utils.node_factory import _get_node_factory
-from openvino.utils.types import NodeInput, as_nodes
+from openvino.utils.types import NodeInput, as_nodes, as_node, TensorShape
_get_node_factory_opset16 = partial(_get_node_factory, "opset16")
@@ -122,3 +122,95 @@ def sparse_fill_empty_rows(
as_nodes(values, dense_shape, indices, default_value, name=name),
{},
)
+
+
+@nameable_op
+def avg_pool(
+ data_batch: NodeInput,
+ strides: list[int],
+ pads_begin: TensorShape,
+ pads_end: TensorShape,
+ kernel_shape: TensorShape,
+ exclude_pad: bool,
+ rounding_type: str = "floor",
+ auto_pad: Optional[str] = None,
+ dilations: Optional[list[int]] = None,
+ name: Optional[str] = None,
+) -> Node:
+ """Return average pooling node.
+
+ :param data_batch: The input node providing data.
+ :param strides: The window movement strides.
+ :param pads_begin: The number of pixels to add at the beginning along each axis.
+ :param pads_end: The number of pixels to add at the end along each axis.
+ :param kernel_shape: The pooling window shape.
+ :param exclude_pad: Whether or not to include zero padding in average computations.
+ :param rounding_type: Determines used rounding schema when computing output shape. Acceptable
+ values are: ['floor', 'ceil', 'ceil_torch']. Defaults to 'floor'.
+ :param auto_pad: Determines how the padding is calculated. Acceptable values:
+ [None, 'same_upper', 'same_lower', 'valid']. Defaults to None.
+ :param dilations: The index of the next pixel to select when pooling. If not provided,
+ defaults to [1, 1, ...] (no dilation).
+ :param name: Optional name for the new output node.
+
+ :return: New node with AvgPool operation applied on its data.
+ """
+ if auto_pad is None:
+ auto_pad = "explicit"
+
+ attributes = {
+ "strides": strides,
+ "pads_begin": pads_begin,
+ "pads_end": pads_end,
+ "kernel": kernel_shape,
+ "exclude-pad": exclude_pad,
+ "rounding_type": rounding_type.upper(),
+ "auto_pad": auto_pad.upper(),
+ }
+
+ if dilations is not None:
+ attributes["dilations"] = dilations
+
+ return _get_node_factory_opset16().create(
+ "AvgPool",
+ [as_node(data_batch, name=name)],
+ attributes,
+ )
+
+
+@nameable_op
+def one_hot(
+ indices: NodeInput,
+ depth: NodeInput,
+ on_value: NodeInput,
+ off_value: NodeInput,
+ axis: int,
+ negative_indices_mode: Optional[str] = None,
+ name: Optional[str] = None,
+) -> Node:
+ """Create node performing one-hot encoding on input data.
+
+ :param indices: Input tensor of rank N with indices of any supported integer data type.
+ :param depth: Scalar of any supported integer type that specifies number of classes and
+ the size of one-hot dimension.
+ :param on_value: Scalar of any type that is the value that the locations
+ in output tensor represented by indices in input take.
+ :param off_value: Scalar of any type that is the value that the locations not represented
+ by indices in input take.
+ :param axis: New axis position in the output shape to fill with one-hot values.
+ :param negative_indices_mode: Controls how negative indices are handled. Can be 'ignore_negative'
+ (negative indices are ignored and filled with off_value) or
+ 'normalize' (negative indices in range [-depth, -1] are normalized).
+ If not provided, defaults to 'ignore_negative'.
+ :param name: The optional name for new output node.
+ :return: New node performing one-hot operation.
+ """
+ attributes = {"axis": axis}
+ if negative_indices_mode is not None:
+ attributes["negative_indices_mode"] = negative_indices_mode
+
+ return _get_node_factory_opset16().create(
+ "OneHot",
+ as_nodes(indices, depth, on_value, off_value, name=name),
+ attributes,
+ )
diff --git a/src/bindings/python/src/openvino/runtime/opset16/__init__.py b/src/bindings/python/src/openvino/runtime/opset16/__init__.py
index f8a43ffd551..7eab97693ec 100644
--- a/src/bindings/python/src/openvino/runtime/opset16/__init__.py
+++ b/src/bindings/python/src/openvino/runtime/opset16/__init__.py
@@ -9,6 +9,8 @@ from openvino.opset16.ops import identity
from openvino.opset16.ops import istft
from openvino.opset16.ops import segment_max
from openvino.opset16.ops import sparse_fill_empty_rows
+from openvino.opset16.ops import avg_pool
+from openvino.opset16.ops import one_hot
# Operators from previous opsets
# TODO (ticket: 156877): Add previous opset operators at the end of opset16 development
diff --git a/src/bindings/python/src/openvino/runtime/opset16/ops/__init__.py b/src/bindings/python/src/openvino/runtime/opset16/ops/__init__.py
index 04e8f479dcd..27f98d21dc3 100644
--- a/src/bindings/python/src/openvino/runtime/opset16/ops/__init__.py
+++ b/src/bindings/python/src/openvino/runtime/opset16/ops/__init__.py
@@ -6,3 +6,5 @@ from openvino.opset16.ops import identity
from openvino.opset16.ops import istft
from openvino.opset16.ops import segment_max
from openvino.opset16.ops import sparse_fill_empty_rows
+from openvino.opset16.ops import avg_pool
+from openvino.opset16.ops import one_hot
diff --git a/src/bindings/python/tests/test_graph/test_pooling.py b/src/bindings/python/tests/test_graph/test_pooling.py
index bebfa8817a5..8f9bf8e80e4 100644
--- a/src/bindings/python/tests/test_graph/test_pooling.py
+++ b/src/bindings/python/tests/test_graph/test_pooling.py
@@ -6,6 +6,7 @@ import numpy as np
import pytest
import openvino.opset14 as ov
+import openvino.opset16 as ov16
from openvino import Type
@@ -236,3 +237,93 @@ def test_max_pool(op_params, input_shape, expected_output_shape, op_name):
assert list(node.get_output_shape(1)) == expected_output_shape
assert node.get_output_element_type(0) == Type.f32
assert node.get_output_element_type(1) == Type.i32
+
+
+avg_pooling_opset16_test_params = [
+ (
+ [
+ [2, 2], # strides
+ [0, 0], # pads_begin
+ [0, 0], # pads_end
+ [2, 2], # kernel_shape
+ True, # exclude_pad
+ "floor", # rounding_type
+ None, # auto_pad
+ [1, 1], # dilations
+ ],
+ [1, 1, 4, 4], # input_shape
+ [1, 1, 2, 2], # expected_output_shape
+ ),
+ (
+ [
+ [1, 1], # strides
+ [0, 0], # pads_begin
+ [0, 0], # pads_end
+ [2, 2], # kernel_shape
+ False, # exclude_pad
+ "floor", # rounding_type
+ None, # auto_pad
+ [2, 2], # dilations
+ ],
+ [1, 1, 5, 5], # input_shape
+ [1, 1, 3, 3], # expected_output_shape
+ ),
+ (
+ [
+ [2, 2], # strides
+ [1, 1], # pads_begin
+ [1, 1], # pads_end
+ [2, 2], # kernel_shape
+ False, # exclude_pad
+ "floor", # rounding_type
+ None, # auto_pad
+ [2, 2], # dilations
+ ],
+ [1, 3, 10, 10], # input_shape
+ [1, 3, 5, 5], # expected_output_shape
+ ),
+ (
+ [
+ [2, 2], # strides
+ [1, 1], # pads_begin
+ [1, 1], # pads_end
+ [2, 2], # kernel_shape
+ False, # exclude_pad
+ "ceil_torch", # rounding_type
+ None, # auto_pad
+ [1, 1], # dilations
+ ],
+ [1, 1, 5, 5], # input_shape
+ [1, 1, 3, 3], # expected_output_shape
+ ),
+]
+
+
+ ("op_params", "input_shape", "expected_output_shape"),
+ avg_pooling_opset16_test_params,
+)
[email protected]("op_name", ["avg_pool", "avgPool", "avgPoolOpset16"])
+def test_avg_pool_opset16_with_dilations(op_params, input_shape, expected_output_shape, op_name):
+ param = ov.parameter(input_shape, name="A", dtype=np.float32)
+ node = ov16.avg_pool(param, *op_params, name=op_name)
+ assert node.get_type_name() == "AvgPool"
+ assert node.get_friendly_name() == op_name
+ assert node.get_output_size() == 1
+ assert list(node.get_output_shape(0)) == expected_output_shape
+ assert node.get_output_element_type(0) == Type.f32
+
+
+ ("op_params", "input_shape", "expected_output_shape"),
+ avg_pooling_test_params,
+)
[email protected]("op_name", ["avg_pool", "avgPool", "avgPoolOpset16"])
+def test_avg_pool_opset16_backward_compatibility(op_params, input_shape, expected_output_shape, op_name):
+ param = ov.parameter(input_shape, name="A", dtype=np.float32)
+ node = ov16.avg_pool(param, *op_params, name=op_name)
+ assert node.get_type_name() == "AvgPool"
+ assert node.get_friendly_name() == op_name
+ assert node.get_output_size() == 1
+ assert list(node.get_output_shape(0)) == expected_output_shape
+ assert node.get_output_element_type(0) == Type.f32
diff --git a/src/bindings/python/tests/test_graph/test_sequence_processing.py b/src/bindings/python/tests/test_graph/test_sequence_processing.py
index 2a0aa77dc1b..f5aee41e19b 100644
--- a/src/bindings/python/tests/test_graph/test_sequence_processing.py
+++ b/src/bindings/python/tests/test_graph/test_sequence_processing.py
@@ -6,6 +6,7 @@ import numpy as np
import pytest
import openvino as ov
+import openvino.opset16 as ov16
@pytest.mark.parametrize(("depth", "on_value", "off_value", "axis", "expected_shape"), [
@@ -49,3 +50,25 @@ def test_range_4(destination_type, expected_type):
assert node.get_type_name() == "Range"
assert list(node.get_output_shape(0)) == [6]
assert node.get_element_type() == expected_type
+
+
[email protected](("depth", "on_value", "off_value", "axis", "negative_indices_mode", "expected_shape"), [
+ (3, 1, 0, -1, "ignore_negative", [3, 3]),
+ (3, 1, 0, 0, "ignore_negative", [3, 3]),
+ (3, 1, 0, -1, "normalize", [3, 3]),
+ (4, 5, 10, 1, "normalize", [3, 4]),
+])
+def test_one_hot_opset16_with_negative_indices_mode(depth, on_value, off_value, axis, negative_indices_mode, expected_shape):
+ param = ov.opset11.parameter([3], dtype=np.int32)
+ node = ov16.one_hot(param, depth, on_value, off_value, axis, negative_indices_mode)
+ assert node.get_output_size() == 1
+ assert node.get_type_name() == "OneHot"
+ assert list(node.get_output_shape(0)) == expected_shape
+
+
+def test_one_hot_opset16_without_negative_indices_mode():
+ param = ov.opset11.parameter([3], dtype=np.int32)
+ node = ov16.one_hot(param, depth=2, on_value=5, off_value=10, axis=-1)
+ assert node.get_output_size() == 1
+ assert node.get_type_name() == "OneHot"
+ assert list(node.get_output_shape(0)) == [3, 2]