Skip to content

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

[PT FE] Suport aten::where(cond) (#34536)

Maxim Vafin2ad8a3bb038c
diff --git a/src/frontends/pytorch/src/op/where.cpp b/src/frontends/pytorch/src/op/where.cpp
index 61207c0cee2..7a22fe75582 100644
--- a/src/frontends/pytorch/src/op/where.cpp
+++ b/src/frontends/pytorch/src/op/where.cpp
@@ -3,8 +3,12 @@
//
#include "openvino/frontend/pytorch/node_context.hpp"
+#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
+#include "openvino/op/non_zero.hpp"
#include "openvino/op/select.hpp"
+#include "openvino/op/split.hpp"
+#include "openvino/op/squeeze.hpp"
#include "utils.hpp"
namespace ov {
@@ -17,7 +21,24 @@ using namespace ov::op;
OutputVector translate_where(const NodeContext& context) {
num_inputs_check(context, 1, 3);
auto cond = context.get_input(0);
- PYTORCH_OP_CONVERSION_CHECK(!context.input_is_none(1), "aten::where(cond) unsupported");
+ if (context.input_is_none(1) && context.input_is_none(2)) {
+ // aten::where(cond) is equivalent to torch.nonzero(cond, as_tuple=True):
+ // returns a tuple of 1D index tensors, one per dimension of cond.
+ const auto& cond_shape = cond.get_partial_shape();
+ PYTORCH_OP_CONVERSION_CHECK(cond_shape.rank().is_static(),
+ "aten::where(cond) with input of dynamic rank is not supported");
+ const auto ndim = cond_shape.rank().get_length();
+ auto non_zero = context.mark_node(std::make_shared<v3::NonZero>(cond));
+ auto axis = context.mark_node(v0::Constant::create(element::i32, Shape{}, {0}));
+ OutputVector result;
+ if (ndim > 0) {
+ auto split = context.mark_node(std::make_shared<v1::Split>(non_zero, axis, ndim));
+ for (int64_t i = 0; i < ndim; ++i) {
+ result.push_back(context.mark_node(std::make_shared<v0::Squeeze>(split->output(i), axis)));
+ }
+ }
+ return {context.mark_node(make_list_construct(result))};
+ }
auto bool_cond = context.mark_node(std::make_shared<v0::Convert>(cond, element::boolean));
Output<Node> x;
Output<Node> y;
diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cpp
index 0f04d775ef9..36326c3a8d8 100644
--- a/src/frontends/pytorch/src/op_table.cpp
+++ b/src/frontends/pytorch/src/op_table.cpp
@@ -1142,6 +1142,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {
{"aten.view_copy.default", op::translate_reshape},
{"aten.view_as_complex.default", op::translate_view_as_complex},
{"aten.view_as_real.default", op::translate_view_as_real},
+ {"aten.where.default", op::translate_where},
{"aten.where.self", op::translate_where},
{"aten.zero.default", op::translate_zeros_like_fx},
{"aten.zeros.default", op::translate_zeros_fx},
diff --git a/tests/layer_tests/pytorch_tests/test_where.py b/tests/layer_tests/pytorch_tests/test_where.py
index 4bea5ebf7b1..371826e2f4d 100644
--- a/tests/layer_tests/pytorch_tests/test_where.py
+++ b/tests/layer_tests/pytorch_tests/test_where.py
@@ -8,14 +8,17 @@ from pytorch_layer_test_class import PytorchLayerTest, skip_if_export
class Testwhere(PytorchLayerTest):
- def _prepare_input(self, mask_fill='ones', mask_dtype=bool, return_x_y=False, x_dtype="float32", y_dtype=None):
+ def _prepare_input(self, mask_fill='ones', mask_dtype=bool, return_x_y=False, x_dtype="float32", y_dtype=None, scalar_cond=False):
input_shape = [2, 10]
- mask = np.zeros(input_shape).astype(mask_dtype)
- if mask_fill == 'ones':
- mask = np.ones(input_shape).astype(mask_dtype)
- if mask_fill == 'random':
- idx = self.random.choice(10, 5)
- mask[:, idx] = 1
+ if scalar_cond:
+ mask = np.array(0 if mask_fill == 'zeros' else 1).astype(mask_dtype)
+ else:
+ mask = np.zeros(input_shape).astype(mask_dtype)
+ if mask_fill == 'ones':
+ mask = np.ones(input_shape).astype(mask_dtype)
+ if mask_fill == 'random':
+ idx = self.random.choice(10, 5)
+ mask[:, idx] = 1
x = self.random.randn(*input_shape, dtype=x_dtype)
y = self.random.randn(*input_shape, dtype=y_dtype or x_dtype)
return (mask,) if not return_x_y else (mask, x, y)
@@ -46,7 +49,12 @@ class Testwhere(PytorchLayerTest):
def forward(self, cond):
return torch.where(cond)
+ class aten_where_as_nonzero_getitem(torch.nn.Module):
+ def forward(self, cond: torch.Tensor):
+ return torch.where(cond)[0]
+ if as_non_zero == 'scripted':
+ return aten_where_as_nonzero_getitem(), "aten::where"
if as_non_zero:
return aten_where_as_nonzero(), "aten::where"
return aten_where(torch_dtypes), "aten::where"
@@ -77,6 +85,10 @@ class Testwhere(PytorchLayerTest):
@pytest.mark.nightly
@pytest.mark.precommit
def test_where_as_nonzero(self, mask_fill, mask_dtype, x_dtype, ie_device, precision, ir_version):
+ # torch.jit.trace is used here (trace_model=True) so that example inputs annotate concrete
+ # shapes, giving translate_where a static input rank to split NonZero output into per-dim
+ # index tensors. Without example inputs torch.jit.script leaves rank dynamic and
+ # translate_where cannot determine the number of output tensors at conversion time.
self._test(*self.create_model(True),
ie_device, precision, ir_version,
kwargs_to_prepare_input={
@@ -86,3 +98,76 @@ class Testwhere(PytorchLayerTest):
"x_dtype": x_dtype,
},
trace_model=True)
+
+ @pytest.mark.parametrize(
+ "mask_fill", ['zeros', 'ones', 'random'])
+ @pytest.mark.parametrize("cond_dtype", [np.float32, np.int32])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_where_as_nonzero_nonbool_cond(self, mask_fill, cond_dtype, ie_device, precision, ir_version):
+ # aten::where(cond) must accept non-boolean condition tensors (float32, int32).
+ # NonZero treats zero as False and any nonzero value as True, matching PyTorch semantics.
+ self._test(*self.create_model(True),
+ ie_device, precision, ir_version,
+ kwargs_to_prepare_input={
+ 'mask_fill': mask_fill,
+ 'mask_dtype': cond_dtype,
+ 'return_x_y': False,
+ 'x_dtype': "float32",
+ },
+ trace_model=True)
+
+ @pytest.mark.parametrize(
+ "mask_fill", ['zeros', 'ones', 'random'])
+ @pytest.mark.parametrize("mask_dtype", [bool])
+ @pytest.mark.parametrize("x_dtype", ["float32", "int32"])
+ @pytest.mark.nightly
+ @pytest.mark.precommit_torch_export
+ def test_where_as_nonzero_export(self, mask_fill, mask_dtype, x_dtype, ie_device, precision, ir_version):
+ # torch.export produces aten.where.default which previously had no registered translator,
+ # causing OpConversionFailure.
+ self._test(*self.create_model(True),
+ ie_device, precision, ir_version,
+ kwargs_to_prepare_input={
+ 'mask_fill': mask_fill,
+ 'mask_dtype': mask_dtype,
+ 'return_x_y': False,
+ "x_dtype": x_dtype,
+ })
+
+ @pytest.mark.parametrize("cond_val", ['zeros', 'ones'])
+ @pytest.mark.parametrize("x_dtype", ["float32", "int32"])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ @pytest.mark.precommit_torch_export
+ def test_where_scalar_cond(self, cond_val, x_dtype, ie_device, precision, ir_version):
+ self._test(*self.create_model(False, dtypes=(x_dtype, x_dtype)),
+ ie_device, precision, ir_version,
+ kwargs_to_prepare_input={
+ 'mask_fill': cond_val,
+ 'mask_dtype': bool,
+ 'return_x_y': True,
+ 'x_dtype': x_dtype,
+ 'scalar_cond': True,
+ })
+
+ @pytest.mark.parametrize("mask_fill", ['zeros', 'ones', 'random'])
+ @pytest.mark.parametrize("x_dtype", ["float32", "int32"])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_where_as_nonzero_scripted(self, mask_fill, x_dtype, ie_device, precision, ir_version):
+ # Tests translate_where's input_is_none(1) branch via torch.jit.script.
+ # The model returns torch.where(cond)[0], producing aten::where → aten::__getitem__
+ self._test(*self.create_model('scripted'),
+ ie_device, precision, ir_version,
+ kwargs_to_prepare_input={
+ 'mask_fill': mask_fill,
+ 'mask_dtype': bool,
+ 'return_x_y': False,
+ 'x_dtype': x_dtype,
+ },
+ trace_model=False,
+ dynamic_shapes=False,
+ use_convert_model=True,
+ freeze_model=False)
+