Skip to content

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

[PT FE] support aten::kthvalue (#31397)

Mahdi JafariRaviz85ca5fa34fa8
diff --git a/src/frontends/pytorch/src/op/kthvalue.cpp b/src/frontends/pytorch/src/op/kthvalue.cpp
new file mode 100644
index 00000000000..b49039e9c55
--- /dev/null
+++ b/src/frontends/pytorch/src/op/kthvalue.cpp
@@ -0,0 +1,57 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <openvino/op/gather.hpp>
+#include <openvino/op/subtract.hpp>
+#include <openvino/op/topk.hpp>
+#include <openvino/op/unsqueeze.hpp>
+
+#include "openvino/frontend/pytorch/node_context.hpp"
+#include "utils.hpp"
+
+namespace ov {
+namespace frontend {
+namespace pytorch {
+namespace op {
+using namespace ov::op;
+
+OutputVector translate_kthvalue(const NodeContext& context) {
+ // aten::kthvalue(Tensor input, int k, int dim=None, bool keepdim) -> (Tensor values, Tensor indices)
+ num_inputs_check(context, 2, 4);
+ auto x = context.get_input(0);
+ auto k = context.get_input(1);
+
+ int64_t dim = -1;
+ if (!context.input_is_none(2)) {
+ dim = context.const_input<int64_t>(2);
+ }
+
+ bool keepdim = false;
+ if (!context.input_is_none(3)) {
+ keepdim = context.const_input<bool>(3);
+ }
+
+ auto axis_const = context.mark_node(v0::Constant::create(element::i64, Shape{}, {dim}));
+
+ auto smallest_k = context.mark_node(
+ std::make_shared<v11::TopK>(x, k, dim, v3::TopK::Mode::MIN, v3::TopK::SortType::SORT_VALUES, element::i64));
+
+ auto k_minus_1 =
+ context.mark_node(std::make_shared<v1::Subtract>(k, v0::Constant::create(k.get_element_type(), {}, {1})));
+
+ auto kth_value = context.mark_node(std::make_shared<v8::Gather>(smallest_k->output(0), k_minus_1, axis_const));
+ auto kth_index = context.mark_node(std::make_shared<v8::Gather>(smallest_k->output(1), k_minus_1, axis_const));
+
+ if (keepdim) {
+ kth_value = context.mark_node(std::make_shared<v0::Unsqueeze>(kth_value, axis_const));
+ kth_index = context.mark_node(std::make_shared<v0::Unsqueeze>(kth_index, axis_const));
+ }
+
+ return {kth_value, kth_index};
+}
+
+} // namespace op
+} // namespace pytorch
+} // namespace frontend
+} // namespace ov
\ No newline at end of file
diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cpp
index 2ad462b2d18..2f72ba91eb6 100644
--- a/src/frontends/pytorch/src/op_table.cpp
+++ b/src/frontends/pytorch/src/op_table.cpp
@@ -141,6 +141,7 @@ OP_CONVERTER(translate_int);
OP_CONVERTER(translate_inverse);
OP_CONVERTER(translate_istft);
OP_CONVERTER(translate_is_nonzero);
+OP_CONVERTER(translate_kthvalue);
OP_CONVERTER(translate_layer_norm);
OP_CONVERTER(translate_len);
OP_CONVERTER(translate_lerp);
@@ -565,6 +566,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {
{"aten::is_grad_enabled", op::return_false_scalar},
{"aten::istft", op::translate_istft},
{"aten::is_nonzero", op::translate_is_nonzero},
+ {"aten::kthvalue", op::translate_kthvalue},
{"aten::isfinite", op::translate_1to1_match_1_inputs<opset10::IsFinite>},
{"aten::isinf", op::translate_1to1_match_1_inputs<opset10::IsInf>},
{"aten::isnan", op::translate_1to1_match_1_inputs<opset10::IsNaN>},
diff --git a/tests/layer_tests/pytorch_tests/test_kthvalue.py b/tests/layer_tests/pytorch_tests/test_kthvalue.py
new file mode 100644
index 00000000000..c403b766305
--- /dev/null
+++ b/tests/layer_tests/pytorch_tests/test_kthvalue.py
@@ -0,0 +1,55 @@
+# Copyright (C) 2018-2025 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import numpy as np
+import pytest
+import torch
+
+from pytorch_layer_test_class import PytorchLayerTest
+
+
+class aten_kthvalue(torch.nn.Module):
+ def __init__(self, k, dim, keepdim):
+ super().__init__()
+ self.k = k
+ self.dim = dim
+ self.keepdim = keepdim
+
+ def forward(self, x):
+ kwargs = {}
+ if self.dim is not None:
+ kwargs["dim"] = self.dim
+ if self.keepdim is not None:
+ kwargs["keepdim"] = self.keepdim
+ return torch.kthvalue(x, self.k, **kwargs)
+
+
+class TestKthValue(PytorchLayerTest):
+ def _prepare_input(self, shape, dtype):
+ size = np.prod(shape)
+ data = np.arange(size, dtype=dtype)
+ np.random.shuffle(data)
+ data = data.reshape(shape)
+ return (data,)
+
+ @pytest.mark.parametrize("shape, k, dim", [
+ ([2, 3], 2, 1),
+ ([4, 5, 6], 3, 0),
+ ([4, 5, 6], 4, -2),
+ ([2, 3, 4], 3, None),
+ ([10], 1, 0),
+ ([3, 8, 4], 8, 1),
+ ([3, 8, 4, 2, 2, 2], 8, 1),
+ ])
+ @pytest.mark.parametrize("keepdim", [False, True])
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64, np.int32, np.int64])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_kthvalue(self, shape, k, dim, keepdim, dtype, ie_device, precision, ir_version):
+ self._test(aten_kthvalue(k, dim, keepdim),
+ None,
+ "aten::kthvalue",
+ ie_device, precision, ir_version,
+ kwargs_to_prepare_input={"shape": shape, "dtype": dtype},
+ trace_model=True,
+ )