test_log_softmax.py 5.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2020 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.

import unittest
import numpy as np
17
from paddle.fluid.tests.unittests.op_test import OpTest, convert_float_to_uint16
18
import paddle
19
import paddle.fluid.core as core
20
import paddle.nn.functional as F
21

22
np.random.seed(10)
23

24 25

def ref_log_softmax(x):
26
    shiftx = (x - np.max(x))
27 28
    out = shiftx - np.log(np.exp(shiftx).sum())
    return out
29 30


31 32 33 34 35 36 37 38 39
def ref_log_softmax_grad(x, axis):
    if axis < 0:
        axis += len(x.shape)
    out = np.apply_along_axis(ref_log_softmax, axis, x)
    axis_dim = x.shape[axis]
    dout = np.full_like(x, fill_value=1. / x.size)
    dx = dout - np.exp(out) * dout.copy().sum(axis=axis, keepdims=True).repeat(
        axis_dim, axis=axis)
    return dx
40 41


42
class TestLogSoftmaxOp(OpTest):
43
    def setUp(self):
44 45 46 47 48
        self.op_type = 'log_softmax'
        self.dtype = 'float64'
        self.shape = [2, 3, 4, 5]
        self.axis = -1
        self.set_attrs()
49

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
        x = np.random.uniform(0.1, 1., self.shape).astype(self.dtype)
        out = np.apply_along_axis(ref_log_softmax, self.axis, x)
        self.x_grad = ref_log_softmax_grad(x, self.axis)

        self.inputs = {'X': x}
        self.outputs = {'Out': out}
        self.attrs = {'axis': self.axis}

    def set_attrs(self):
        pass

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], ['Out'], user_defined_grads=[self.x_grad])


class TestLogSoftmaxShape(TestLogSoftmaxOp):
    def set_attrs(self):
        self.shape = [12, 10]
71 72


73 74 75 76 77
class TestLogSoftmaxAxis(TestLogSoftmaxOp):
    def set_attrs(self):
        self.axis = 1


78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
class TestLogSoftmaxBF16Op(OpTest):
    def setUp(self):
        self.op_type = 'log_softmax'
        self.dtype = np.uint16
        self.shape = [2, 3, 4, 5]
        self.axis = -1

        x = np.random.uniform(0.1, 1., self.shape).astype(np.float32)
        out = np.apply_along_axis(ref_log_softmax, self.axis, x)
        self.x_grad = ref_log_softmax_grad(x, self.axis)

        self.inputs = {'X': convert_float_to_uint16(x)}
        self.outputs = {'Out': convert_float_to_uint16(out)}
        self.attrs = {'axis': self.axis}

    def test_check_output(self):
        place = core.CUDAPlace(0)
        self.check_output_with_place(place)

    def test_check_grad(self):
        place = core.CUDAPlace(0)
        self.check_grad_with_place(
            place, ['X'], ['Out'], user_defined_grads=[self.x_grad])


105 106 107 108 109 110 111 112 113 114 115 116 117 118
class TestNNLogSoftmaxAPI(unittest.TestCase):
    def setUp(self):
        self.x_shape = [2, 3, 4, 5]
        self.x = np.random.uniform(-1., 1., self.x_shape).astype(np.float32)
        self.place = paddle.CUDAPlace(0) \
            if paddle.fluid.core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def check_api(self, axis=-1):
        ref_out = np.apply_along_axis(ref_log_softmax, axis, self.x)

        logsoftmax = paddle.nn.LogSoftmax(axis)
        # test static api
        with paddle.static.program_guard(paddle.static.Program()):
119
            x = paddle.fluid.data(name='x', shape=self.x_shape)
120 121 122
            y = logsoftmax(x)
            exe = paddle.static.Executor(self.place)
            out = exe.run(feed={'x': self.x}, fetch_list=[y])
123 124
        self.assertTrue(np.allclose(out[0], ref_out))

125 126
        # test dygrapg api
        paddle.disable_static()
Z
Zhou Wei 已提交
127
        x = paddle.to_tensor(self.x)
128
        y = logsoftmax(x)
129
        self.assertTrue(np.allclose(y.numpy(), ref_out))
130
        paddle.enable_static()
131 132

    def test_check_api(self):
133 134
        for axis in [-1, 1]:
            self.check_api(axis)
135 136 137 138 139 140


class TestNNFunctionalLogSoftmaxAPI(unittest.TestCase):
    def setUp(self):
        self.x_shape = [2, 3, 4, 5]
        self.x = np.random.uniform(-1, 1, self.x_shape).astype(np.float32)
141 142 143 144 145 146 147 148 149 150
        self.place = paddle.CUDAPlace(0) \
            if paddle.fluid.core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def check_api(self, axis=-1, dtype=None):
        x = self.x.copy()
        if dtype is not None:
            x = x.astype(dtype)
        ref_out = np.apply_along_axis(ref_log_softmax, axis, x)
        with paddle.static.program_guard(paddle.static.Program()):
151
            x = paddle.fluid.data(name='x', shape=self.x_shape)
152 153 154
            y = F.log_softmax(x, axis, dtype)
            exe = paddle.static.Executor(self.place)
            out = exe.run(feed={'x': self.x}, fetch_list=[y])
155 156
        self.assertTrue(np.allclose(out[0], ref_out))

157
        paddle.disable_static()
Z
Zhou Wei 已提交
158
        x = paddle.to_tensor(self.x)
159 160 161
        y = F.log_softmax(x, axis, dtype)
        self.assertTrue(np.allclose(y.numpy(), ref_out), True)
        paddle.enable_static()
162 163

    def test_check_api(self):
164 165 166 167 168 169
        for axis in [-1, 1]:
            self.check_api(axis)
        self.check_api(-1, 'float64')

    def test_errors(self):
        with paddle.static.program_guard(paddle.static.Program()):
170
            x = paddle.fluid.data(name='X1', shape=[100], dtype='int32')
171 172
            self.assertRaises(TypeError, F.log_softmax, x)

173
            x = paddle.fluid.data(name='X2', shape=[100], dtype='float32')
174
            self.assertRaises(TypeError, F.log_softmax, x, dtype='int32')
175 176 177


if __name__ == "__main__":
H
hong 已提交
178
    paddle.enable_static()
179
    unittest.main()