test_cvm_op.py 5.2 KB
Newer Older
H
heqiaozhi 已提交
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 unittest
H
heqiaozhi 已提交
16
from math import log
17 18

import numpy as np
H
heqiaozhi 已提交
19 20 21
from op_test import OpTest


T
tangwei12 已提交
22 23 24 25 26 27 28 29 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
def cvm_compute(X, item_width, use_cvm):
    cvm_offset = 0 if use_cvm else 2
    batch_size = X.shape[0]

    Y = np.ones([batch_size, item_width - cvm_offset], np.float32)

    for idx in range(batch_size):
        if use_cvm:
            Y[idx] = X[idx]
            Y[idx][0] = log(Y[idx][0] + 1)
            Y[idx][1] = log(Y[idx][1] + 1) - Y[idx][0]
        else:
            Y[idx] = X[idx][2:]

    return Y


def cvm_grad_compute(DY, CVM, item_width, use_cvm):
    batch_size = DY.shape[0]
    DX = np.ones([batch_size, item_width], np.float32)

    for idx in range(batch_size):
        DX[idx][0] = CVM[idx][0]
        DX[idx][1] = CVM[idx][1]

        if use_cvm:
            DX[idx][2:] = DY[idx][2:]
        else:
            DX[idx][2:] = DY[idx]
    return DX


class TestCVMOpWithLodTensor(OpTest):
H
heqiaozhi 已提交
55
    """
56
    Test cvm op with discrete one-hot labels.
H
heqiaozhi 已提交
57 58 59 60
    """

    def setUp(self):
        self.op_type = "cvm"
T
tangwei12 已提交
61 62
        self.use_cvm = True

H
hutuxian 已提交
63 64
        self.batch_size = 1
        self.item_width = 11
T
tangwei12 已提交
65

H
heqiaozhi 已提交
66 67
        lod = [[1]]
        self.inputs = {
68 69 70 71 72 73 74
            'X': (
                np.random.uniform(
                    0, 1, [self.batch_size, self.item_width]
                ).astype("float32"),
                lod,
            ),
            'CVM': np.array([[0.6, 0.4]]).astype("float32"),
H
heqiaozhi 已提交
75 76 77 78 79 80 81 82
        }
        self.attrs = {'use_cvm': False}
        out = []
        for index, emb in enumerate(self.inputs["X"][0]):
            out.append(emb[2:])
        self.outputs = {'Y': (np.array(out), lod)}

    def test_check_output(self):
H
hong 已提交
83
        self.check_output(check_dygraph=False)
H
heqiaozhi 已提交
84

H
hutuxian 已提交
85
    def test_check_grad(self):
86 87 88 89 90
        user_grads = (
            np.array([1.0 / (self.item_width - 2)] * self.item_width)
            .reshape((self.batch_size, self.item_width))
            .astype("float32")
        )
H
hutuxian 已提交
91 92
        user_grads[:, :2] = self.inputs['CVM'].reshape(self.batch_size, 2)
        user_grads = [user_grads]
93 94 95
        self.check_grad(
            ['X'], 'Y', user_defined_grads=user_grads, check_dygraph=False
        )
H
hutuxian 已提交
96

H
heqiaozhi 已提交
97

T
tangwei12 已提交
98 99 100 101 102 103 104 105 106
class TestCVMOpWithOutLodTensor1(OpTest):
    """
    Test cvm op with discrete one-hot labels.
    """

    def setUp(self):
        self.op_type = "cvm"
        self.use_cvm = True

H
hutuxian 已提交
107 108
        self.batch_size = 2
        self.item_width = 11
T
tangwei12 已提交
109

H
hutuxian 已提交
110
        input = np.random.uniform(
111 112
            0, 1, (self.batch_size, self.item_width)
        ).astype('float32')
H
hutuxian 已提交
113
        output = cvm_compute(input, self.item_width, self.use_cvm)
114 115 116 117 118
        cvm = (
            np.array([[0.6, 0.4] * self.batch_size])
            .reshape((self.batch_size, 2))
            .astype("float32")
        )
T
tangwei12 已提交
119 120 121 122 123 124

        self.inputs = {'X': input, 'CVM': cvm}
        self.attrs = {'use_cvm': self.use_cvm}
        self.outputs = {'Y': output}

    def test_check_output(self):
H
hong 已提交
125
        self.check_output(check_dygraph=False)
T
tangwei12 已提交
126

H
hutuxian 已提交
127 128
    def test_check_grad(self):
        numel = self.batch_size * self.item_width
129 130 131 132 133
        user_grads = (
            np.array([1.0 / numel] * numel)
            .reshape((self.batch_size, self.item_width))
            .astype("float32")
        )
H
hutuxian 已提交
134 135
        user_grads[:, :2] = self.inputs['CVM'].reshape(self.batch_size, 2)
        user_grads = [user_grads]
136 137 138
        self.check_grad(
            ['X'], 'Y', user_defined_grads=user_grads, check_dygraph=False
        )
H
hutuxian 已提交
139

T
tangwei12 已提交
140 141 142 143 144 145 146 147 148 149

class TestCVMOpWithOutLodTensor2(OpTest):
    """
    Test cvm op with discrete one-hot labels.
    """

    def setUp(self):
        self.op_type = "cvm"
        self.use_cvm = False

H
hutuxian 已提交
150 151
        self.batch_size = 2
        self.item_width = 11
T
tangwei12 已提交
152

H
hutuxian 已提交
153
        input = np.random.uniform(
154 155
            0, 1, (self.batch_size, self.item_width)
        ).astype('float32')
H
hutuxian 已提交
156
        output = cvm_compute(input, self.item_width, self.use_cvm)
157 158 159 160 161
        cvm = (
            np.array([[0.6, 0.4] * self.batch_size])
            .reshape((self.batch_size, 2))
            .astype("float32")
        )
T
tangwei12 已提交
162 163 164 165 166 167

        self.inputs = {'X': input, 'CVM': cvm}
        self.attrs = {'use_cvm': self.use_cvm}
        self.outputs = {'Y': output}

    def test_check_output(self):
H
hong 已提交
168
        self.check_output(check_dygraph=False)
T
tangwei12 已提交
169

H
hutuxian 已提交
170 171
    def test_check_grad(self):
        numel = self.batch_size * self.item_width
172 173 174 175 176
        user_grads = (
            np.array([1.0 / (self.batch_size * (self.item_width - 2))] * numel)
            .reshape((self.batch_size, self.item_width))
            .astype("float32")
        )
H
hutuxian 已提交
177 178
        user_grads[:, :2] = self.inputs['CVM'].reshape(self.batch_size, 2)
        user_grads = [user_grads]
179 180 181
        self.check_grad(
            ['X'], 'Y', user_defined_grads=user_grads, check_dygraph=False
        )
H
hutuxian 已提交
182

T
tangwei12 已提交
183

H
heqiaozhi 已提交
184 185
if __name__ == '__main__':
    unittest.main()