Skip to content

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

Extend TF FE with `SegmentMax-16` and fix an edge case bug (#30550)

Przemyslaw Wysocki4677a381ec06
diff --git a/src/core/reference/include/openvino/reference/segment_max.hpp b/src/core/reference/include/openvino/reference/segment_max.hpp
index d1d120e1714..d048e70f33d 100644
--- a/src/core/reference/include/openvino/reference/segment_max.hpp
+++ b/src/core/reference/include/openvino/reference/segment_max.hpp
@@ -23,22 +23,29 @@ void segment_max(const T* data,
const T empty_segment_value) {
const T_idx num_segments = output_shape[0];
const auto inner_dim_size = shape_size(data_shape.begin() + 1, data_shape.end());
+ const size_t total_output_size = num_segments * inner_dim_size;
- // Initialize output with empty_segment_value
- std::fill(out, out + num_segments * inner_dim_size, empty_segment_value);
-
- // Iterate over each element in the first dimension
+ const auto min_val = std::numeric_limits<T>::lowest();
+ std::fill(out, out + total_output_size, min_val);
+ std::vector<bool> has_element(total_output_size, false);
for (size_t i = 0; i < data_shape[0]; ++i) {
const T_idx segment_id = segment_ids[i];
if (segment_id >= num_segments) {
continue;
}
- // Iterate over each element in the inner dimensions
for (size_t j = 0; j < inner_dim_size; ++j) {
- const size_t index = i * inner_dim_size + j;
const size_t out_index = segment_id * inner_dim_size + j;
- // Update the maximum value for the current segment and inner dimension
- out[out_index] = std::max(out[out_index], data[index]);
+ const T value = data[i * inner_dim_size + j];
+ if (value > out[out_index]) {
+ out[out_index] = value;
+ }
+ has_element[out_index] = true;
+ }
+ }
+
+ for (size_t i = 0; i < total_output_size; ++i) {
+ if (!has_element[i]) {
+ out[i] = empty_segment_value;
}
}
}
diff --git a/src/core/src/op/segment_max.cpp b/src/core/src/op/segment_max.cpp
index 7b7e2276ba0..dc5f7555135 100644
--- a/src/core/src/op/segment_max.cpp
+++ b/src/core/src/op/segment_max.cpp
@@ -38,13 +38,15 @@ void SegmentMax::validate_and_infer_types() {
OV_OP_SCOPE(v16_SegmentMax_validate_and_infer_types);
const auto& segment_ids_element_type = get_input_element_type(1);
NODE_VALIDATION_CHECK(this,
- segment_ids_element_type == element::i32 || segment_ids_element_type == element::i64,
+ segment_ids_element_type.is_dynamic() || segment_ids_element_type == element::i32 ||
+ segment_ids_element_type == element::i64,
"The element type of the segment_ids input be i32 or i64. Got: ",
segment_ids_element_type);
if (inputs().size() == 3) {
const auto& num_segments_element_type = get_input_element_type(2);
NODE_VALIDATION_CHECK(this,
- num_segments_element_type == element::i32 || num_segments_element_type == element::i64,
+ num_segments_element_type.is_dynamic() || num_segments_element_type == element::i32 ||
+ num_segments_element_type == element::i64,
"The element type of the num_segments input be i32 or i64. Got: ",
num_segments_element_type);
}
diff --git a/src/frontends/tensorflow/docs/supported_ops.md b/src/frontends/tensorflow/docs/supported_ops.md
index 7dfbb16123f..acab089a608 100644
--- a/src/frontends/tensorflow/docs/supported_ops.md
+++ b/src/frontends/tensorflow/docs/supported_ops.md
@@ -1025,7 +1025,7 @@ A "supported operation" is one that TensorFlow Frontend can convert to the OpenV
| SdcaOptimizer | NO | |
| SdcaOptimizerV2 | NO | |
| SdcaShrinkL1 | NO | |
-| SegmentMax | NO | |
+| SegmentMax | YES | |
| SegmentMaxV2 | NO | |
| SegmentMean | NO | |
| SegmentMin | NO | |
diff --git a/src/frontends/tensorflow/src/op_table.cpp b/src/frontends/tensorflow/src/op_table.cpp
index d5a62632d94..bca1275228a 100644
--- a/src/frontends/tensorflow/src/op_table.cpp
+++ b/src/frontends/tensorflow/src/op_table.cpp
@@ -370,6 +370,7 @@ const std::map<std::string, CreatorFunction> get_supported_ops() {
{"Rsqrt", CreatorFunction(translate_rsqrt_op)},
{"SaveV2", CreatorFunction(translate_no_op)},
{"ScatterNd", CreatorFunction(translate_scatter_nd_op)},
+ {"SegmentMax", CreatorFunction(translate_segment_max_op)},
{"SegmentSum", CreatorFunction(translate_segment_sum_op)},
{"Select", CreatorFunction(translate_select_op)},
{"SelectV2", CreatorFunction(translate_select_v2_op)},
diff --git a/src/frontends/tensorflow_common/include/common_op_table.hpp b/src/frontends/tensorflow_common/include/common_op_table.hpp
index 9621e087c36..6f838ed1205 100644
--- a/src/frontends/tensorflow_common/include/common_op_table.hpp
+++ b/src/frontends/tensorflow_common/include/common_op_table.hpp
@@ -149,6 +149,7 @@ OP_CONVERTER(translate_roll_op);
OP_CONVERTER(translate_round_op);
OP_CONVERTER(translate_rsqrt_op);
OP_CONVERTER(translate_scatter_nd_op);
+OP_CONVERTER(translate_segment_max_op);
OP_CONVERTER(translate_segment_sum_op);
OP_CONVERTER(translate_space_to_batch_nd_op);
OP_CONVERTER(translate_sparse_segment_op);
diff --git a/src/frontends/tensorflow_common/src/op/segment_max.cpp b/src/frontends/tensorflow_common/src/op/segment_max.cpp
new file mode 100644
index 00000000000..e53971289b2
--- /dev/null
+++ b/src/frontends/tensorflow_common/src/op/segment_max.cpp
@@ -0,0 +1,19 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/op/segment_max.hpp"
+
+#include "common_op_table.hpp"
+#include "utils.hpp"
+
+namespace ov::frontend::tensorflow::op {
+OutputVector translate_segment_max_op(const NodeContext& node) {
+ default_op_checks(node, 2, {"SegmentMax"});
+ auto data = node.get_input(0);
+ auto segment_ids = node.get_input(1);
+ auto res = std::make_shared<ov::op::v16::SegmentMax>(data, segment_ids, ov::op::FillMode::ZERO);
+ set_node_name(node.get_name(), res);
+ return {res};
+}
+} // namespace ov::frontend::tensorflow::op
diff --git a/src/plugins/template/tests/functional/op_reference/segment_max.cpp b/src/plugins/template/tests/functional/op_reference/segment_max.cpp
index 7fe29aa6f75..ba580df2ed6 100644
--- a/src/plugins/template/tests/functional/op_reference/segment_max.cpp
+++ b/src/plugins/template/tests/functional/op_reference/segment_max.cpp
@@ -156,6 +156,17 @@ std::vector<SegmentMaxParams> generateSegmentMaxParams(ov::op::FillMode fillMode
std::vector<T_D>{1, 2, 3, 4, empty_segment_value, empty_segment_value}),
fillMode),
};
+ if constexpr (std::is_signed_v<T_D>) {
+ segmentMaxParams.emplace_back(
+ // All negative segments
+ SegmentMaxParams(
+ Tensor({4}, T, std::vector<T_D>{-5, -3, -2, -4}), // data
+ Tensor({4}, T_idx, std::vector<T_I>{0, 0, 1, 1}), // segmentIds
+ Tensor({}, T_idx, std::vector<T_I>{3}), // numSegments
+ Tensor({2}, T, std::vector<T_D>{-3, -2}), // expectedResult
+ Tensor({3}, T, std::vector<T_D>{-3, -2, empty_segment_value}), // expectedResultNumSegments
+ fillMode));
+ }
return segmentMaxParams;
}
diff --git a/tests/layer_tests/tensorflow_tests/test_tf_SegmentMax.py b/tests/layer_tests/tensorflow_tests/test_tf_SegmentMax.py
new file mode 100644
index 00000000000..89ac99675ab
--- /dev/null
+++ b/tests/layer_tests/tensorflow_tests/test_tf_SegmentMax.py
@@ -0,0 +1,100 @@
+# Copyright (C) 2018-2025 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import numpy as np
+import pytest
+import tensorflow as tf
+from common.tf_layer_test_class import CommonTFLayerTest
+
+rng = np.random.default_rng()
+
+class TestSegmentMax(CommonTFLayerTest):
+ def _prepare_input(self, inputs_info):
+ assert 'data:0' in inputs_info
+ assert 'segment_ids:0' in inputs_info
+ data_shape = inputs_info['data:0']
+ segment_ids_shape = inputs_info['segment_ids:0']
+ inputs_data = {}
+ data_type = getattr(self, 'data_type', np.float32)
+ segment_ids_type = getattr(self, 'segment_ids_type', np.int32)
+
+ inputs_data['data:0'] = rng.integers(-50, 50, data_shape).astype(data_type)
+ inputs_data['segment_ids:0'] = np.sort(rng.integers(0, data_shape[0], segment_ids_shape).astype(segment_ids_type))
+ return inputs_data
+
+ def create_segment_max_net(self, data_shape, segment_ids_shape, data_type=np.float32, segment_ids_type=np.int32):
+ self.data_type = data_type
+ self.segment_ids_type = segment_ids_type
+
+ tf.compat.v1.reset_default_graph()
+ with tf.compat.v1.Session() as sess:
+ data = tf.compat.v1.placeholder(data_type, data_shape, 'data')
+ segment_ids = tf.compat.v1.placeholder(segment_ids_type, segment_ids_shape, 'segment_ids')
+ tf.raw_ops.SegmentMax(data=data, segment_ids=segment_ids)
+
+ tf.compat.v1.global_variables_initializer()
+ tf_net = sess.graph_def
+
+ return tf_net, None
+
+ test_data_precommit = [
+ dict(data_shape=[10], segment_ids_shape=[10], data_type=np.float32, segment_ids_type=np.int32),
+ dict(data_shape=[5, 10], segment_ids_shape=[5], data_type=np.float64, segment_ids_type=np.int32),
+ dict(data_shape=[3, 4, 5], segment_ids_shape=[3], data_type=np.int32, segment_ids_type=np.int64),
+ ]
+
+ @pytest.mark.parametrize("params", test_data_precommit)
+ @pytest.mark.precommit
+ @pytest.mark.nightly
+ def test_segment_max(self, params, ie_device, precision, ir_version, temp_dir):
+ if ie_device == 'GPU':
+ pytest.skip("Operation SegmentMax is not supported on GPU")
+ self._test(*self.create_segment_max_net(**params), ie_device, precision, ir_version, temp_dir=temp_dir)
+
+ def create_segment_max_with_missing_ids_net(self, data_shape):
+ tf.compat.v1.reset_default_graph()
+ with tf.compat.v1.Session() as sess:
+ data = tf.compat.v1.placeholder(np.float32, data_shape, 'data')
+ segment_shape = [data_shape[0]]
+ segment_ids = tf.compat.v1.placeholder(np.int32, segment_shape, 'segment_ids')
+ tf.raw_ops.SegmentMax(data=data, segment_ids=segment_ids)
+
+ tf.compat.v1.global_variables_initializer()
+ tf_net = sess.graph_def
+
+ return tf_net, None
+
+ def _prepare_missing_segments_input(self, inputs_info):
+ assert 'data:0' in inputs_info
+ assert 'segment_ids:0' in inputs_info
+ data_shape = inputs_info['data:0']
+ segment_ids_shape = inputs_info['segment_ids:0']
+ inputs_data = {}
+ inputs_data['data:0'] = rng.integers(-50, 50, data_shape).astype(np.float32)
+
+ segments = np.zeros(segment_ids_shape, dtype=np.int32)
+
+ # Distribute data into segments, leaving some segments empty
+ segments[:data_shape[0]//3] = 0 # First third to segment 0
+ segments[data_shape[0]//3:2*data_shape[0]//3] = 2 # Second third to segment 2
+ segments[2*data_shape[0]//3:] = 4 # Last third to segment 4
+
+ inputs_data['segment_ids:0'] = segments
+ return inputs_data
+
+ test_missing_segments_data = [
+ dict(data_shape=[15]),
+ dict(data_shape=[20]),
+ ]
+
+ @pytest.mark.parametrize("params", test_missing_segments_data)
+ @pytest.mark.precommit
+ @pytest.mark.nightly
+ def test_segment_max_with_missing_ids(self, params, ie_device, precision, ir_version, temp_dir):
+ if ie_device == 'GPU':
+ pytest.skip("Operation SegmentMax is not supported on GPU")
+
+ original_prepare_input = self._prepare_input
+ self._prepare_input = self._prepare_missing_segments_input
+ self._test(*self.create_segment_max_with_missing_ids_net(**params), ie_device, precision, ir_version, temp_dir=temp_dir)
+ self._prepare_input = original_prepare_input