test_squeeze2_op.py 8.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2019 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.

15
import os
16
import unittest
17

18
import numpy as np
19
from eager_op_test import OpTest, convert_float_to_uint16
20
from test_attribute_var import UnittestBase
21

22
import paddle
23
from paddle.fluid import core
24 25
from paddle.fluid.framework import Program, program_guard

26
paddle.enable_static()
27 28 29 30 31 32


# Correct: General.
class TestSqueezeOp(OpTest):
    def setUp(self):
        self.op_type = "squeeze2"
33
        self.prim_op_type = "comp"
34
        self.python_api = paddle.squeeze
35
        self.public_python_api = paddle.squeeze
36 37 38
        self.python_out_sig = [
            "Out"
        ]  # python out sig is customized output signature.
39
        self.init_test_case()
40 41 42 43 44 45 46 47
        self.init_dtype()
        self.if_enable_cinn()
        x = np.random.random(self.ori_shape).astype("float64")
        xshape = np.random.random(self.ori_shape).astype("float64")
        if hasattr(self, "dtype") and self.dtype == np.uint16:
            x = convert_float_to_uint16(x.astype(np.float32))
            xshape = convert_float_to_uint16(xshape.astype(np.float32))
        self.inputs = {"X": x}
48 49 50
        self.init_attrs()
        self.outputs = {
            "Out": self.inputs["X"].reshape(self.new_shape),
51
            "XShape": xshape,
52 53
        }

54 55 56
    def if_enable_cinn(self):
        pass

57
    def test_check_output(self):
W
wanghuancoder 已提交
58
        self.check_output(no_check_set=['XShape'], check_prim=True)
59 60

    def test_check_grad(self):
W
wanghuancoder 已提交
61
        self.check_grad(["X"], "Out", check_prim=True)
62

63 64 65
    def init_dtype(self):
        self.dtype = np.float64

66
    def init_test_case(self):
Z
zhupengyang 已提交
67
        self.ori_shape = (1, 3, 1, 40)
68
        self.axes = (0, 2)
Z
zhupengyang 已提交
69
        self.new_shape = (3, 40)
70 71 72 73 74

    def init_attrs(self):
        self.attrs = {"axes": self.axes}


75 76 77 78 79 80 81 82 83 84
@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestSqueezeOpBF16OP(TestSqueezeOp):
    def init_dtype(self):
        self.dtype = np.uint16


85 86 87
# Correct: There is mins axis.
class TestSqueezeOp1(TestSqueezeOp):
    def init_test_case(self):
Z
zhupengyang 已提交
88
        self.ori_shape = (1, 20, 1, 5)
89
        self.axes = (0, -2)
Z
zhupengyang 已提交
90
        self.new_shape = (20, 5)
91 92


93 94 95 96 97 98 99 100 101 102
@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestSqueezeOp1BF16Op(TestSqueezeOp):
    def init_dtype(self):
        self.dtype = np.uint16


103 104
# Correct: No axes input.
class TestSqueezeOp2(TestSqueezeOp):
105 106 107 108
    def setUp(self):
        self.op_type = "squeeze2"
        self.prim_op_type = "comp"
        self.python_api = paddle.squeeze
109
        self.public_python_api = paddle.squeeze
110 111 112 113
        self.python_out_sig = [
            "Out"
        ]  # python out sig is customized output signature.
        self.init_test_case()
114 115 116 117 118 119 120 121
        self.init_dtype()
        self.if_enable_cinn()
        x = np.random.random(self.ori_shape).astype("float64")
        xshape = np.random.random(self.ori_shape).astype("float64")
        if hasattr(self, "dtype") and self.dtype == np.uint16:
            x = convert_float_to_uint16(x.astype(np.float32))
            xshape = convert_float_to_uint16(xshape.astype(np.float32))
        self.inputs = {"X": x}
122 123 124
        self.init_attrs()
        self.outputs = {
            "Out": self.inputs["X"].reshape(self.new_shape),
125
            "XShape": xshape,
126 127
        }

128 129 130 131 132 133
    def if_enable_cinn(self):
        pass

    def init_dtype(self):
        self.dtype = np.float64

134
    def init_test_case(self):
Z
zhupengyang 已提交
135
        self.ori_shape = (1, 20, 1, 5)
136
        self.axes = ()
Z
zhupengyang 已提交
137
        self.new_shape = (20, 5)
138 139


140 141 142 143 144 145 146 147 148 149
@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestSqueezeOp2BF16Op(TestSqueezeOp):
    def init_dtype(self):
        self.dtype = np.uint16


150
# Correct: Just part of axes be squeezed.
151 152
class TestSqueezeOp3(TestSqueezeOp):
    def init_test_case(self):
Z
zhupengyang 已提交
153
        self.ori_shape = (6, 1, 5, 1, 4, 1)
154
        self.axes = (1, -1)
Z
zhupengyang 已提交
155
        self.new_shape = (6, 5, 1, 4)
156 157


158 159 160 161 162 163 164 165 166 167
@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and do not support bfloat16",
)
class TestSqueezeOp3BF16Op(TestSqueezeOp):
    def init_dtype(self):
        self.dtype = np.uint16


168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
class TestSqueeze2AxesTensor(UnittestBase):
    def init_info(self):
        self.shapes = [[2, 3, 4]]
        self.save_path = os.path.join(self.temp_dir.name, 'squeeze_tensor')

    def test_static(self):
        main_prog = Program()
        starup_prog = Program()
        with program_guard(main_prog, starup_prog):
            fc = paddle.nn.Linear(4, 10)
            x = paddle.randn([2, 3, 4])
            x.stop_gradient = False
            feat = fc(x)  # [2,3,10]
            feat = paddle.unsqueeze(feat, [0, 2])  # [1, 2, 3, 1, 10]
            # axes is a Variable
            axes = paddle.assign([0, 2])
            out = paddle.squeeze(feat, axes)
185
            out2 = paddle.squeeze(feat, axes)
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

            sgd = paddle.optimizer.SGD()
            sgd.minimize(paddle.mean(out))
            self.assertTrue("Var[" in str(main_prog))

            exe = paddle.static.Executor()
            exe.run(starup_prog)
            res = exe.run(fetch_list=[feat, out, out2])
            self.assertEqual(res[0].shape, (1, 2, 1, 3, 10))
            self.assertEqual(res[1].shape, (2, 3, 10))
            self.assertEqual(res[2].shape, (2, 3, 10))

            paddle.static.save_inference_model(self.save_path, [x], [out], exe)
            # Test for Inference Predictor
            infer_out = self.infer_prog()
            self.assertEqual(infer_out.shape, (2, 3, 10))


class TestSqueeze2AxesTensorList(UnittestBase):
    def init_info(self):
        self.shapes = [[2, 3, 4]]
        self.save_path = os.path.join(self.temp_dir.name, 'squeeze_tensor')

    def test_static(self):
        main_prog = Program()
        starup_prog = Program()
        with program_guard(main_prog, starup_prog):
            fc = paddle.nn.Linear(4, 10)
            x = paddle.randn([2, 3, 4])
            x.stop_gradient = False
            feat = fc(x)  # [2,3,10]
            feat = paddle.unsqueeze(feat, [0, 2])  # [1, 2, 3, 1, 10]
            # axes is a list[Variable]
            axes = [
                paddle.full([1], 0, dtype='int32'),
221
                paddle.full([1], 2, dtype='int32'),
222 223
            ]
            out = paddle.squeeze(feat, axes)
224
            out2 = paddle.squeeze(feat, axes)
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

            sgd = paddle.optimizer.SGD()
            sgd.minimize(paddle.mean(out))
            self.assertTrue("Vars[" in str(main_prog))

            exe = paddle.static.Executor()
            exe.run(starup_prog)
            res = exe.run(fetch_list=[feat, out, out2])
            self.assertEqual(res[0].shape, (1, 2, 1, 3, 10))
            self.assertEqual(res[1].shape, (2, 3, 10))
            self.assertEqual(res[2].shape, (2, 3, 10))

            paddle.static.save_inference_model(self.save_path, [x], [out], exe)
            # Test for Inference Predictor
            infer_out = self.infer_prog()
            self.assertEqual(infer_out.shape, (2, 3, 10))


H
heliqi 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
# test api
class TestSqueezeAPI(unittest.TestCase):
    def setUp(self):
        self.executed_api()

    def executed_api(self):
        self.squeeze = paddle.squeeze

    def test_api(self):
        paddle.disable_static()
        input_data = np.random.random([3, 2, 1]).astype("float32")
        x = paddle.to_tensor(input_data)
        out = self.squeeze(x, axis=2)
        out.backward()

        self.assertEqual(out.shape, [3, 2])

        paddle.enable_static()

    def test_error(self):
        def test_axes_type():
            x2 = paddle.static.data(name="x2", shape=[2, 1, 25], dtype="int32")
            self.squeeze(x2, axis=2.1)

        self.assertRaises(TypeError, test_axes_type)


class TestSqueezeInplaceAPI(TestSqueezeAPI):
    def executed_api(self):
        self.squeeze = paddle.squeeze_


275 276
if __name__ == "__main__":
    unittest.main()