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
[STFT] Pytorch FE enablement of STFT operation (#27186)
Katarzyna Mitrus08365f6fddc0
diff --git a/src/frontends/pytorch/src/op/stft.cpp b/src/frontends/pytorch/src/op/stft.cppnew file mode 100644index 00000000000..b7e4858c2f8--- /dev/null+++ b/src/frontends/pytorch/src/op/stft.cpp@@ -0,0 +1,93 @@+// Copyright (C) 2018-2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/stft.hpp"++#include "openvino/frontend/pytorch/node_context.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert_like.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace pytorch {+namespace op {++using namespace ov::op;++OutputVector translate_stft(const NodeContext& context) {+ // schema: aten::stft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool+ // normalized=False, bool? onesided=None, bool? return_complex=None) -> Tensor+ //+ // Note: aten::stft doesn't have "center" and "pad_mode" attrs like torch.stft, so the number of the inputs is lower+ // and index of any input after the "window" is smaller accordingly++ num_inputs_check(context, 2, 8);++ auto input = context.get_input(0);+ auto n_fft = context.get_input(1);++ ov::Output<ov::Node> hop_length;+ if (!context.input_is_none(2)) {+ hop_length = context.get_input(2);+ } else {+ // Defualt floor(n_fft / 4)+ const auto four = context.mark_node(std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, 4));+ const auto four_cast = context.mark_node(std::make_shared<ov::op::v1::ConvertLike>(four, n_fft));+ hop_length = context.mark_node(std::make_shared<ov::op::v1::Divide>(n_fft, four_cast));+ }++ ov::Output<ov::Node> win_length;+ if (!context.input_is_none(3)) {+ win_length = context.get_input(3);+ } else {+ win_length = n_fft;+ }++ ov::Output<ov::Node> window;+ if (!context.input_is_none(4)) {+ window = context.get_input(4);+ } else {+ const auto one = context.mark_node(std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{}, 1));+ const auto one_cast = context.mark_node(std::make_shared<ov::op::v1::ConvertLike>(one, input));+ const auto zero = context.mark_node(std::make_shared<ov::op::v0::Constant>(ov::element::i32, Shape{1}, 0));+ const auto win_length_cast =+ context.mark_node(std::make_shared<ov::op::v0::Convert>(win_length, ov::element::i64));+ const auto win_len_vec = context.mark_node(std::make_shared<ov::op::v0::Unsqueeze>(win_length_cast, zero));+ window = context.mark_node(std::make_shared<ov::op::v3::Broadcast>(one_cast, win_len_vec));+ }++ bool normalized = false;+ if (!context.input_is_none(5)) {+ normalized = context.const_input<bool>(5);+ }+ PYTORCH_OP_CONVERSION_CHECK(!normalized,+ "aten::stft conversion is currently supported with normalized=False only.");++ bool onesided = true;+ if (!context.input_is_none(6)) {+ onesided = context.const_input<bool>(6);+ }+ PYTORCH_OP_CONVERSION_CHECK(onesided, "aten::stft conversion is currently supported with onesided=True only.");++ bool return_complex = false;+ if (!context.input_is_none(7)) {+ return_complex = context.const_input<bool>(7);+ }+ PYTORCH_OP_CONVERSION_CHECK(!return_complex,+ "aten::stft conversion is currently supported with return_complex=False only.");++ // Perform STFT+ constexpr bool transpose_frames = true;+ auto stft = context.mark_node(std::make_shared<v15::STFT>(input, window, n_fft, hop_length, transpose_frames));+ return {stft};+};+} // 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 66c76e33032..9b7e6134cd2 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -220,6 +220,7 @@ OP_CONVERTER(translate_square);OP_CONVERTER(translate_squeeze);OP_CONVERTER(translate_std);OP_CONVERTER(translate_std_mean);+OP_CONVERTER(translate_stft);OP_CONVERTER(translate_sub);OP_CONVERTER(translate_sub_);OP_CONVERTER(translate_sum);@@ -649,6 +650,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {// aten::stack - Supported in limited set of patterns{"aten::std", op::translate_std},{"aten::std_mean", op::translate_std_mean},+ {"aten::stft", op::translate_stft},{"aten::sub", op::translate_sub},{"aten::sub_", op::translate_sub_},{"aten::sum", op::translate_sum},diff --git a/tests/layer_tests/pytorch_tests/test_stft.py b/tests/layer_tests/pytorch_tests/test_stft.pynew file mode 100644index 00000000000..29d6b94efbf--- /dev/null+++ b/tests/layer_tests/pytorch_tests/test_stft.py@@ -0,0 +1,156 @@+# Copyright (C) 2018-2024 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import pytest++from pytorch_layer_test_class import PytorchLayerTest+++class TestSTFT(PytorchLayerTest):+ def _prepare_input(self, win_length, signal_shape, rand_data=False, out_dtype="float32"):+ import numpy as np++ if rand_data:+ signal = np.random.randn(*signal_shape).astype(out_dtype)+ else:+ num_samples = signal_shape[-1]+ half_idx = num_samples // 2+ t = np.linspace(0, 1, num_samples)+ signal = np.sin(2 * np.pi * 5 * t)+ signal[half_idx:] += np.sin(2 * np.pi * 10 * t[half_idx:])+ signal = np.broadcast_to(signal, signal_shape).astype(out_dtype)++ window = np.hanning(win_length).reshape([win_length])++ return (signal, window.astype(out_dtype))++ def create_model(self, n_fft, hop_length, win_length):+ import torch++ class aten_stft(torch.nn.Module):++ def __init__(self, n_fft, hop_length, win_length):+ super(aten_stft, self).__init__()+ self.n_fft = n_fft+ self.hop_length = hop_length+ self.win_length = win_length++ def forward(self, x, window):+ return torch.stft(+ x,+ self.n_fft,+ hop_length=self.hop_length,+ win_length=self.win_length,+ window=window,+ center=False,+ pad_mode="reflect",+ normalized=False,+ onesided=True,+ return_complex=False,+ )++ ref_net = None++ return aten_stft(n_fft, hop_length, win_length), ref_net, "aten::stft"++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize(("trace_model"), [True, False])+ @pytest.mark.parametrize(("signal_shape"), [(1, 256), (2, 128), (128,)])+ @pytest.mark.parametrize(("n_fft", "hop_length", "window_size"), [+ [16, 4, 16],+ [32, 32, 32],+ [32, 16, 24],+ [24, 32, 20],+ [128, 128, 128],+ ])+ def test_stft(self, n_fft, hop_length, window_size, signal_shape, ie_device, precision, ir_version, trace_model):+ if ie_device == "GPU":+ pytest.xfail(reason="STFT op is not supported on GPU yet")+ if signal_shape == (128,):+ pytest.xfail(reason="STFT op is doesn't support 1D signal yet, please unsqueeze the input.")+ self._test(*self.create_model(n_fft, hop_length, window_size), ie_device, precision,+ ir_version, kwargs_to_prepare_input={"win_length": window_size, "signal_shape": signal_shape}, trace_model=trace_model)+++class TestSTFTAttrs(PytorchLayerTest):+ def _prepare_input(self, out=False, out_dtype="float32"):+ import numpy as np++ signal = np.random.randn(2, 512).astype(out_dtype)+ return (signal,)++ def create_model_with_attrs(self, n_fft, hop_length, win_length, center, pad_mode, normalized, onesided, return_complex):+ import torch++ class aten_stft_attrs(torch.nn.Module):++ def __init__(self, n_fft, hop_length, win_length, center, pad_mode, normalized, onesided, return_complex):+ super(aten_stft_attrs, self).__init__()+ self.n_fft = n_fft+ self.hop_length = hop_length+ self.win_length = win_length+ self.window = None # Default window+ self.center = center+ self.pad_mode = pad_mode+ self.normalized = normalized+ self.onesided = onesided+ self.return_complex = return_complex++ def forward(self, x):+ return torch.stft(+ x,+ self.n_fft,+ hop_length=self.hop_length,+ win_length=self.win_length,+ window=self.window,+ center=self.center,+ pad_mode=self.pad_mode,+ normalized=self.normalized,+ onesided=self.onesided,+ return_complex=self.return_complex,+ )++ ref_net = None++ return aten_stft_attrs(n_fft, hop_length, win_length, center, pad_mode, normalized, onesided, return_complex), ref_net, "aten::stft"++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize(("trace_model"), [True, False])+ @pytest.mark.parametrize(("n_fft", "hop_length", "win_length", "center", "pad_mode", "normalized", "onesided", "return_complex"), [+ [16, 4, 16, False, "reflect", False, True, False], # default window+ [16, 4, 14, True, "reflect", False, True, False], # center True+ [16, 4, 14, True, "reflect", False, True, False], # center True+ [16, 4, 14, True, "replicate", False, True, False], # center True+ [16, 4, 14, False, "replicate", False, True, False], # center False+ [16, None, 16, False, "reflect", False, True, False], # hop_length None+ [16, None, None, False, "reflect", False, True, False], # hop & win length None+ [16, 4, None, False, "reflect", False, True, False], # win_length None+ # Unsupported cases:+ [16, 4, 16, False, "reflect", True, True, False], # normalized True+ [16, 4, 16, False, "reflect", False, False, False], # onesided False+ [16, 4, 16, False, "reflect", False, True, True], # reutrn_complex True+ ])+ def test_stft_not_supported_attrs(self, n_fft, hop_length, win_length, center, pad_mode, normalized, onesided, return_complex, ie_device, precision, ir_version, trace_model):+ if ie_device == "GPU":+ pytest.xfail(reason="STFT op is not supported on GPU yet")++ if center is True and trace_model is False:+ pytest.xfail(+ reason="torch stft uses list() for `center` subgrpah before aten::stft, that leads to error: No conversion rule found for operations: aten::list")++ if normalized is True:+ pytest.xfail(+ reason="aten::stft conversion is currently supported with normalized=False only")++ if onesided is False:+ pytest.xfail(+ reason="aten::stft conversion is currently supported with onesided=True only")++ if return_complex is True:+ pytest.xfail(+ reason="aten::stft conversion is currently supported with return_complex=False only")++ self._test(*self.create_model_with_attrs(n_fft, hop_length, win_length, center, pad_mode, normalized, onesided, return_complex), ie_device, precision,+ ir_version, kwargs_to_prepare_input={}, trace_model=trace_model)