OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[PT FE] Support aten::bernoulli for SpeechT5 TTS model (#28585)
Roman Kazantsev50fa19a39003
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.pyindex 13b79b1cb5a..a9aec8f8aa9 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py@@ -449,6 +449,9 @@ class TorchScriptPythonDecoder(Decoder):return ivalue_to_constant(pt_value.toIValue(), shared_memory=self._shared_memory)if isinstance(pt_type, torch.ListType):return self._as_constant_list(pt_value)+ if isinstance(pt_type, torch._C.Type) and pt_type.annotation_str == "Generator":+ gen = pt_value.toIValue()+ return ivalue_to_constant(gen.initial_seed(), shared_memory=self._shared_memory)const = ivalue_to_constant(pt_value.toIValue(), shared_memory=self._shared_memory)if len(const) > 0:diff --git a/src/frontends/pytorch/src/op/bernoulli.cpp b/src/frontends/pytorch/src/op/bernoulli.cppnew file mode 100644index 00000000000..7a408fce610--- /dev/null+++ b/src/frontends/pytorch/src/op/bernoulli.cpp@@ -0,0 +1,82 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/frontend/pytorch/node_context.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert_like.hpp"+#include "openvino/op/less.hpp"+#include "openvino/op/random_uniform.hpp"+#include "openvino/op/shape_of.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace pytorch {+namespace op {++using namespace ov;+using namespace ov::op;++OutputVector translate_bernoulli(const NodeContext& context) {+ // supported signatures:+ // 1. aten::bernoulli(input, *, Generator? generator=None) -> Tensor+ // 2. aten::bernoulli(input, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)+ // 3. aten::bernoulli(input, float p, *, Generator? generator=None) -> Tensor+ num_inputs_check(context, 1, 3);+ uint64_t global_seed = 0;+ auto input = context.get_input(0);+ auto input_type = input.get_element_type().is_static() ? input.get_element_type() : element::f64;+ auto input_shape = context.mark_node(std::make_shared<v3::ShapeOf>(input, element::i32));+ auto probs_threshold = input;++ bool with_p = false;+ size_t gen_ind = 1;+ if (!context.input_is_none(1)) {+ auto p = context.get_input(1);+ with_p = p.get_element_type().is_real() ? true : false;+ if (with_p) {+ // need to override probs thresholds and samples type+ input_type = p.get_element_type().is_static() ? p.get_element_type() : element::f64;+ gen_ind = 2;+ probs_threshold = p;+ }+ }++ if (!context.input_is_none(gen_ind)) {+ // retrieve seed set to Generator+ auto gen_const = as_type_ptr<v0::Constant>(context.get_input(static_cast<int>(gen_ind)).get_node_shared_ptr());+ PYTORCH_OP_CONVERSION_CHECK(gen_const, "aten::bernoulli expects a constant representing a generator seed");+ auto seed = gen_const->cast_vector<uint64_t>();+ global_seed = seed.size() > 0 ? seed[0] : global_seed;+ }++ // generate tensor of input shape with elements sampled from u ~ RandomUniform(0, 1) distribution+ // I[u < input] will represent samples of bernoulli distribution with parameter `input`+ auto const_zero = context.mark_node(std::make_shared<v0::Constant>(input_type, Shape{}, 0.0f));+ auto const_one = context.mark_node(std::make_shared<v0::Constant>(input_type, Shape{}, 1.0f));+ auto ru_samples = context.mark_node(std::make_shared<v8::RandomUniform>(input_shape,+ const_zero,+ const_one,+ input_type,+ global_seed,+ 0,+ PhiloxAlignment::PYTORCH));+ if (!input.get_element_type().is_static()) {+ ru_samples = context.mark_node(std::make_shared<v1::ConvertLike>(ru_samples, probs_threshold));+ }+ auto bernoulli_samples = context.mark_node(std::make_shared<v1::Less>(ru_samples, probs_threshold));++ if (!with_p && !context.input_is_none(2)) {+ auto out = context.get_input(2);+ bernoulli_samples = context.mark_node(std::make_shared<v1::ConvertLike>(bernoulli_samples, out));+ context.mutate_input(2, bernoulli_samples);+ } else {+ bernoulli_samples = context.mark_node(std::make_shared<v1::ConvertLike>(bernoulli_samples, input));+ }+ return {bernoulli_samples};+};+} // namespace op+} // namespace pytorch+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 00e3a55b0bc..458ad679d8b 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -48,6 +48,7 @@ OP_CONVERTER(translate_avg_pool2d);OP_CONVERTER(translate_avg_pool3d);OP_CONVERTER(translate_bool);OP_CONVERTER(translate_batch_norm);+OP_CONVERTER(translate_bernoulli);OP_CONVERTER(translate_bitwise_and);OP_CONVERTER(translate_bitwise_not);OP_CONVERTER(translate_bitwise_or);@@ -408,6 +409,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::avg_pool3d", op::quantizable_op<op::translate_avg_pool3d>},{"aten::baddbmm", op::translate_addmm},{"aten::batch_norm", op::translate_batch_norm},+ {"aten::bernoulli", op::translate_bernoulli},{"aten::bitwise_and", op::translate_bitwise_and},{"aten::bitwise_not", op::translate_bitwise_not},{"aten::bitwise_or", op::translate_bitwise_or},diff --git a/tests/layer_tests/pytorch_tests/test_bernoulli.py b/tests/layer_tests/pytorch_tests/test_bernoulli.pynew file mode 100644index 00000000000..691ec7ed4da--- /dev/null+++ b/tests/layer_tests/pytorch_tests/test_bernoulli.py@@ -0,0 +1,99 @@+# 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 TestBernoulli(PytorchLayerTest):+ def _prepare_input(self, input, input_type, out):+ model_inputs = [input.astype(input_type)]+ if out:+ model_inputs.append(np.zeros_like(input).astype(np.int64))+ return model_inputs++ def create_model(self, out, seed):+ class aten_bernoulli(torch.nn.Module):+ def __init__(self, out, seed) -> None:+ super().__init__()+ gen = torch.Generator()+ gen.manual_seed(seed)+ self.gen = gen+ if not out:+ self.forward = self.bernoulli+ else:+ self.forward = self.bernoulli_out++ def bernoulli(self, input):+ bernoulli_res = torch.bernoulli(input, generator=self.gen)+ return bernoulli_res++ def bernoulli_out(self, input, out):+ bernoulli_res = torch.bernoulli(input, generator=self.gen, out=out)+ return bernoulli_res++ ref_net = None++ return aten_bernoulli(out, seed), ref_net, "aten::bernoulli"++ @pytest.mark.parametrize("input", [+ np.array([[0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]]),+ np.array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]),+ ])+ @pytest.mark.parametrize("input_type", [np.float32, np.float64])+ @pytest.mark.parametrize("out", [True, False])+ @pytest.mark.parametrize("seed", [1, 50, 1234])+ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_bernoulli(self, input, input_type, out, seed, ie_device, precision, ir_version):+ if input_type == np.float64:+ pytest.skip("156027: Incorrect specification or reference for RandomUniform for fp64 output type")+ self._test(*self.create_model(out, seed),+ ie_device, precision, ir_version,+ kwargs_to_prepare_input={"input": input,+ "input_type": input_type,+ "out": out})+++class TestBernoulliWithP(PytorchLayerTest):+ def _prepare_input(self, input, input_type):+ model_inputs = [input.astype(input_type)]+ return model_inputs++ def create_model(self, p, seed):+ class aten_bernoulli(torch.nn.Module):+ def __init__(self, p, seed) -> None:+ super().__init__()+ gen = torch.Generator()+ gen.manual_seed(seed)+ self.gen = gen+ self.p = p+ self.forward = self.bernoulli_with_p++ def bernoulli_with_p(self, input):+ bernoulli_res = torch.bernoulli(input, self.p, generator=self.gen)+ return bernoulli_res++ ref_net = None++ return aten_bernoulli(p, seed), ref_net, "aten::bernoulli"++ @pytest.mark.parametrize("input", [+ np.array([[0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]]),+ np.array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]),+ ])+ @pytest.mark.parametrize("input_type", [np.float32, np.int32, np.float64])+ @pytest.mark.parametrize("p", [0.0, 0.4, 1.0])+ @pytest.mark.parametrize("seed", [12])+ @pytest.mark.nightly+ @pytest.mark.precommit+ def test_bernoulli(self, input, input_type, p, seed, ie_device, precision, ir_version):+ if p not in [0.0, 1.0]:+ pytest.skip("156027: Incorrect specification or reference for RandomUniform for fp64 output type")+ self._test(*self.create_model(p, seed),+ ie_device, precision, ir_version,+ kwargs_to_prepare_input={"input": input,+ "input_type": input_type})