stft_op.h 6.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/tensor.h"
K
KP 已提交
20
#include "paddle/fluid/operators/elementwise/elementwise_op_function.h"
21
#include "paddle/fluid/operators/spectral_op.h"
C
Charles-hit 已提交
22
#include "paddle/phi/kernels/funcs/frame_functor.h"
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

template <typename DeviceContext, typename T>
class StftKernel : public framework::OpKernel<T> {
 public:
  /*
    Batch Signals (N, T) -> Frames (N, n_fft, num_frames) -> FFTR2C -> (N,
    n_fft/2 + 1, num_frames) or (N, n_fft, num_frames)
  */
  void Compute(const framework::ExecutionContext& ctx) const override {
    using C = paddle::platform::complex<T>;
    const Tensor* x = ctx.Input<Tensor>("X");
K
KP 已提交
39
    const Tensor* window = ctx.Input<Tensor>("Window");
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    Tensor* out = ctx.Output<Tensor>("Out");
    out->mutable_data<C>(ctx.GetPlace());

    const size_t x_rank = x->dims().size();
    const size_t out_rank = out->dims().size();

    const int n_fft = ctx.Attr<int>("n_fft");
    const int hop_length = ctx.Attr<int>("hop_length");
    const bool normalized = ctx.Attr<bool>("normalized");
    const bool onesided = ctx.Attr<bool>("onesided");

    const int n_frames = out->dims()[out_rank - 1];
    const int seq_length = x->dims()[x_rank - 1];

    auto& dev_ctx = ctx.device_context<DeviceContext>();

    std::vector<int64_t> axes = {1};

    // Frame
    Tensor frames;
    framework::DDim frames_dims(out->dims());
    frames_dims.at(axes.back()) = n_fft;
    frames.mutable_data<T>(frames_dims, ctx.GetPlace());
C
Charles-hit 已提交
63 64 65 66 67 68 69 70
    phi::funcs::FrameFunctor<DeviceContext, T>()(dev_ctx,
                                                 x,
                                                 &frames,
                                                 seq_length,
                                                 n_fft,
                                                 n_frames,
                                                 hop_length,
                                                 /*is_grad*/ false);
71

K
KP 已提交
72 73 74 75 76 77
    // Window
    Tensor frames_w;
    frames_w.mutable_data<T>(frames_dims, ctx.GetPlace());
    ElementwiseComputeEx<MulFunctor<T>, DeviceContext, T>(
        ctx, &frames, window, axes.back(), MulFunctor<T>(), &frames_w);

78 79 80 81 82 83 84 85 86 87
    // FFTR2C
    FFTNormMode normalization;
    if (normalized) {
      normalization = get_norm_from_string("ortho", true);
    } else {
      normalization = get_norm_from_string("backward", true);
    }
    FFTR2CFunctor<DeviceContext, T, C> fft_r2c_func;

    if (onesided) {
K
KP 已提交
88
      fft_r2c_func(dev_ctx, &frames_w, out, axes, normalization, true);
89 90 91 92 93 94
    } else {
      framework::DDim onesided_dims(out->dims());
      const int64_t onesided_axis_size = out->dims().at(axes.back()) / 2 + 1;
      onesided_dims.at(axes.back()) = onesided_axis_size;
      Tensor onesided_out;
      onesided_out.mutable_data<C>(onesided_dims, ctx.GetPlace());
95 96
      fft_r2c_func(
          dev_ctx, &frames_w, &onesided_out, axes, normalization, true);
97 98 99 100 101 102 103 104 105 106 107 108
      fill_conj<DeviceContext, C>(dev_ctx, &onesided_out, out, axes);
    }
  }
};

template <typename DeviceContext, typename T>
class StftGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    using C = paddle::platform::complex<T>;
    auto& dev_ctx = ctx.device_context<DeviceContext>();

K
KP 已提交
109
    const Tensor* window = ctx.Input<Tensor>("Window");
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    const auto* dy = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<Tensor>(framework::GradVarName("X"));
    dx->mutable_data<T>(ctx.GetPlace());

    const size_t dy_rank = dy->dims().size();
    const size_t dx_rank = dx->dims().size();

    const int n_fft = ctx.Attr<int>("n_fft");
    const int hop_length = ctx.Attr<int>("hop_length");
    const bool normalized = ctx.Attr<bool>("normalized");
    const bool onesided = ctx.Attr<bool>("onesided");
    const int n_frames = dy->dims()[dy_rank - 1];
    const int seq_length = dx->dims()[dx_rank - 1];

    std::vector<int64_t> axes = {1};
K
KP 已提交
125
    Tensor d_frames_w;
126 127
    framework::DDim d_frames_dims(dy->dims());
    d_frames_dims.at(axes.back()) = n_fft;
K
KP 已提交
128
    d_frames_w.mutable_data<T>(d_frames_dims, ctx.GetPlace());
129

K
KP 已提交
130 131
    Tensor complex_d_frames_w;
    complex_d_frames_w.mutable_data<C>(d_frames_dims, ctx.GetPlace());
132

K
KP 已提交
133
    // dy -> d_frames_w
134 135 136 137 138 139 140 141 142
    FFTNormMode normalization;
    if (normalized) {
      normalization = get_norm_from_string("ortho", true);
    } else {
      normalization = get_norm_from_string("backward", true);
    }
    FFTC2CFunctor<DeviceContext, C, C> fft_c2c_func;

    if (!onesided) {
143 144
      fft_c2c_func(
          dev_ctx, dy, &complex_d_frames_w, axes, normalization, false);
145 146 147 148 149 150 151 152 153 154 155
    } else {
      Tensor full_dy;
      full_dy.mutable_data<C>(d_frames_dims, ctx.GetPlace());
      auto zero_length = static_cast<int>(full_dy.dims().at(axes.back()) -
                                          dy->dims().at(axes.back()));
      auto rank = dy->dims().size();

      std::vector<int> pads(rank * 2, 0);
      pads[axes.back() * 2 + 1] = zero_length;

      phi::funcs::PaddingFunctor<DeviceContext, C>(
156 157 158 159 160 161 162 163
          rank,
          ctx.template device_context<DeviceContext>(),
          pads,
          static_cast<C>(0),
          *dy,
          &full_dy);
      fft_c2c_func(
          dev_ctx, &full_dy, &complex_d_frames_w, axes, normalization, false);
164 165
    }
    framework::TransComplexToReal(
K
KP 已提交
166 167
        framework::TransToProtoVarType(d_frames_w.dtype()),
        framework::TransToProtoVarType(complex_d_frames_w.dtype()),
168 169
        complex_d_frames_w,
        &d_frames_w);
K
KP 已提交
170 171 172 173 174 175

    // d_frames_w -> d_frames
    Tensor d_frames;
    d_frames.mutable_data<T>(d_frames_dims, ctx.GetPlace());
    ElementwiseComputeEx<MulFunctor<T>, DeviceContext, T>(
        ctx, &d_frames_w, window, axes.back(), MulFunctor<T>(), &d_frames);
176 177

    // d_frames -> dx
C
Charles-hit 已提交
178 179 180 181 182 183 184 185
    phi::funcs::FrameFunctor<DeviceContext, T>()(dev_ctx,
                                                 &d_frames,
                                                 dx,
                                                 seq_length,
                                                 n_fft,
                                                 n_frames,
                                                 hop_length,
                                                 /*is_grad*/ true);
186 187 188 189 190
  }
};

}  // namespace operators
}  // namespace paddle