test_spectral_op.py 8.2 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
3 4 5
# 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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 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.

from __future__ import print_function
import unittest

import numpy as np
import paddle

import re
import sys
F
Feiyu Chan 已提交
23
from spectral_op_np import fft_c2c, fft_r2c, fft_c2r, fft_c2c_backward, fft_r2c_backward, fft_c2r_backward
24 25 26 27 28
import paddle.fluid.core as core
import paddle.fluid.dygraph as dg
import paddle.static as static
from numpy.random import random as rand
from paddle.fluid import Program, program_guard
F
Feiyu Chan 已提交
29
from paddle import _C_ops
30

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
sys.path.append("../")
from op_test import OpTest

paddle.enable_static()

TEST_CASE_NAME = 'test_case'


def parameterize(attrs, input_values=None):

    if isinstance(attrs, str):
        attrs = [attrs]
    input_dicts = (attrs if input_values is None else
                   [dict(zip(attrs, vals)) for vals in input_values])

    def decorator(base_class):
        test_class_module = sys.modules[base_class.__module__].__dict__
        for idx, input_dict in enumerate(input_dicts):
            test_class_dict = dict(base_class.__dict__)
            test_class_dict.update(input_dict)

            name = class_name(base_class, idx, input_dict)

            test_class_module[name] = type(name, (base_class, ),
                                           test_class_dict)

        for method_name in list(base_class.__dict__):
            if method_name.startswith("test"):
                delattr(base_class, method_name)
        return base_class

    return decorator


def to_safe_name(s):
    return str(re.sub("[^a-zA-Z0-9_]+", "_", s))


def class_name(cls, num, params_dict):
    suffix = to_safe_name(
        next((v for v in params_dict.values() if isinstance(v, str)), ""))
    if TEST_CASE_NAME in params_dict:
        suffix = to_safe_name(params_dict["test_case"])
    return "{}_{}{}".format(cls.__name__, num, suffix and "_" + suffix)


F
Feiyu Chan 已提交
77 78 79 80 81 82 83 84 85 86 87 88
def fft_c2c_python_api(x, axes, norm, forward):
    return _C_ops.final_state_fft_c2c(x, axes, norm, forward)


def fft_r2c_python_api(x, axes, norm, forward, onesided):
    return _C_ops.final_state_fft_r2c(x, axes, norm, forward, onesided)


def fft_c2r_python_api(x, axes, norm, forward, last_dim_size=0):
    return _C_ops.final_state_fft_c2r(x, axes, norm, forward, last_dim_size)


89 90 91 92 93 94
@parameterize(
    (TEST_CASE_NAME, 'x', 'axes', 'norm', 'forward'),
    [('test_axes_is_sqe_type', (np.random.random(
        (12, 14)) + 1j * np.random.random(
            (12, 14))).astype(np.complex128), [0, 1], 'forward', True),
     ('test_axis_not_last', (np.random.random(
F
Feiyu Chan 已提交
95 96
         (4, 8, 4)) + 1j * np.random.random(
             (4, 8, 4))).astype(np.complex128), (0, 1), "backward", False),
97 98 99 100 101 102
     ('test_norm_forward', (np.random.random((12, 14)) + 1j * np.random.random(
         (12, 14))).astype(np.complex128), (0, ), "forward", False),
     ('test_norm_backward', (np.random.random((12, 14)) + 1j * np.random.random(
         (12, 14))).astype(np.complex128), (0, ), "backward", True),
     ('test_norm_ortho', (np.random.random((12, 14)) + 1j * np.random.random(
         (12, 14))).astype(np.complex128), (1, ), "ortho", True)])
103 104 105 106
class TestFFTC2COp(OpTest):

    def setUp(self):
        self.op_type = "fft_c2c"
F
Feiyu Chan 已提交
107 108
        self.dtype = self.x.dtype
        self.python_api = fft_c2c_python_api
109 110 111 112 113 114 115 116 117 118 119

        out = fft_c2c(self.x, self.axes, self.norm, self.forward)

        self.inputs = {'X': self.x}
        self.attrs = {
            'axes': self.axes,
            'normalization': self.norm,
            "forward": self.forward
        }
        self.outputs = {'Out': out}

F
Feiyu Chan 已提交
120 121 122 123 124 125
        self.out_grad = (np.random.random(self.x.shape) +
                         1j * np.random.random(self.x.shape)).astype(
                             self.x.dtype)
        self.x_grad = fft_c2c_backward(self.out_grad, self.axes, self.norm,
                                       self.forward)

126
    def test_check_output(self):
F
Feiyu Chan 已提交
127 128 129 130 131 132 133 134
        self.check_output(check_eager=True)

    def test_check_grad(self):
        self.check_grad("X",
                        "Out",
                        user_defined_grads=[self.x_grad],
                        user_defined_grad_outputs=[self.out_grad],
                        check_eager=True)
135 136 137 138 139


@parameterize(
    (TEST_CASE_NAME, 'x', 'axes', 'norm', 'forward', 'last_dim_size'),
    [('test_axes_is_sqe_type', (np.random.random(
140 141 142
        (12, 14)) + 1j * np.random.random(
            (12, 14))).astype(np.complex128), [0, 1], 'forward', True, 26),
     ('test_axis_not_last', (np.random.random(
F
Feiyu Chan 已提交
143
         (4, 7, 4)) + 1j * np.random.random((4, 7, 4))).astype(np.complex128),
144
      (0, 1), "backward", False, None),
145 146 147
     ('test_norm_forward', (np.random.random((12, 14)) + 1j * np.random.random(
         (12, 14))).astype(np.complex128), (0, ), "forward", False, 22),
     ('test_norm_backward', (np.random.random((12, 14)) + 1j * np.random.random(
148 149 150
         (12, 14))).astype(np.complex128), (0, ), "backward", True, 22),
     ('test_norm_ortho', (np.random.random((12, 14)) + 1j * np.random.random(
         (12, 14))).astype(np.complex128), (1, ), "ortho", True, 26)])
151 152 153 154
class TestFFTC2ROp(OpTest):

    def setUp(self):
        self.op_type = "fft_c2r"
F
Feiyu Chan 已提交
155 156
        self.dtype = self.x.dtype
        self.python_api = fft_c2r_python_api
157 158 159 160 161 162 163 164 165 166 167 168 169

        out = fft_c2r(self.x, self.axes, self.norm, self.forward,
                      self.last_dim_size)

        self.inputs = {'X': self.x}
        self.attrs = {
            "axes": self.axes,
            "normalization": self.norm,
            "forward": self.forward,
            "last_dim_size": self.last_dim_size
        }
        self.outputs = {'Out': out}

F
Feiyu Chan 已提交
170 171 172 173 174
        self.out_grad = np.random.random(out.shape).astype(out.dtype)
        self.x_grad = fft_c2r_backward(self.x, self.out_grad, self.axes,
                                       self.norm, self.forward,
                                       self.last_dim_size)

175
    def test_check_output(self):
F
Feiyu Chan 已提交
176 177 178 179 180 181 182 183
        self.check_output(check_eager=True)

    def test_check_grad(self):
        self.check_grad(["X"],
                        "Out",
                        user_defined_grads=[self.x_grad],
                        user_defined_grad_outputs=[self.out_grad],
                        check_eager=True)
184 185 186 187


@parameterize(
    (TEST_CASE_NAME, 'x', 'axes', 'norm', 'forward', 'onesided'),
F
Feiyu Chan 已提交
188
    [('test_axes_is_sqe_type', np.random.randn(12, 18).astype(np.float64),
189
      (0, 1), 'forward', True, True),
F
Feiyu Chan 已提交
190
     ('test_axis_not_last', np.random.randn(4, 8, 4).astype(np.float64),
191
      (0, 1), "backward", False, True),
F
Feiyu Chan 已提交
192
     ('test_norm_forward', np.random.randn(12, 18).astype(np.float64),
193
      (0, 1), "forward", False, False),
F
Feiyu Chan 已提交
194
     ('test_norm_backward', np.random.randn(12, 18).astype(np.float64),
195
      (0, ), "backward", True, False),
F
Feiyu Chan 已提交
196
     ('test_norm_ortho', np.random.randn(12, 18).astype(np.float64),
197
      (1, ), "ortho", True, False)])
198 199 200 201
class TestFFTR2COp(OpTest):

    def setUp(self):
        self.op_type = "fft_r2c"
F
Feiyu Chan 已提交
202 203
        self.dtype = self.x.dtype
        self.python_api = fft_r2c_python_api
204 205 206 207 208 209 210 211 212 213 214 215

        out = fft_r2c(self.x, self.axes, self.norm, self.forward, self.onesided)

        self.inputs = {'X': self.x}
        self.attrs = {
            'axes': self.axes,
            'normalization': self.norm,
            "forward": self.forward,
            'onesided': self.onesided
        }
        self.outputs = {'Out': out}

F
Feiyu Chan 已提交
216 217 218 219
        self.out_grad = np.random.random(out.shape).astype(out.dtype)
        self.x_grad = fft_r2c_backward(self.x, self.out_grad, self.axes,
                                       self.norm, self.forward, self.onesided)

220
    def test_check_output(self):
F
Feiyu Chan 已提交
221 222 223 224 225 226 227 228
        self.check_output(check_eager=True)

    def test_check_grad(self):
        self.check_grad("X",
                        "Out",
                        user_defined_grads=[self.x_grad],
                        user_defined_grad_outputs=[self.out_grad],
                        check_eager=True)