test_row_conv_op.py 5.0 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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 16
from __future__ import print_function

S
Siddharth Goyal 已提交
17 18
import unittest
import numpy as np
19
from op_test import OpTest
S
Siddharth Goyal 已提交
20 21 22 23


def row_conv_forward(x, lod, wt):
    out = np.zeros_like(x)
24 25 26 27
    num_sequences = len(lod[0])
    seq_info = [0]
    for seq_len in lod[0]:
        seq_info.append(seq_info[-1] + seq_len)
S
Siddharth Goyal 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    context_length = wt.shape[0]

    for i in range(num_sequences):  # loop over number of sequences
        start = seq_info[i]
        end = seq_info[i + 1]
        curinput = x[start:end, :]
        curoutput = out[start:end, :]

        cur_timesteps = end - start
        for j in range(cur_timesteps):  # loop over different timesteps
            for k in range(context_length):
                if j + k >= cur_timesteps:
                    continue
                curoutput[j, :] += curinput[j + k, :] * wt[k, :]

    return out


class TestRowConvOp1(OpTest):
    def setUp(self):

        self.op_type = "row_conv"
50 51
        lod = [[2, 3, 2]]
        T = sum(lod[0])
S
Siddharth Goyal 已提交
52
        D = 16
53
        context_length = 8
S
Siddharth Goyal 已提交
54 55 56 57 58 59 60 61 62

        x = np.random.random((T, D)).astype("float32")
        wt = np.random.random((context_length, D)).astype("float32")
        self.inputs = {'X': (x, lod), 'Filter': wt}

        out = row_conv_forward(x, lod, wt)
        self.outputs = {'Out': (out, lod)}

    def test_check_output(self):
H
hong 已提交
63
        self.check_output(check_dygraph=False)
S
Siddharth Goyal 已提交
64 65

    def test_check_grad_normal(self):
66
        self.check_grad(['X', 'Filter'], 'Out', check_dygraph=False)
S
Siddharth Goyal 已提交
67 68 69

    def test_check_grad_ignore_x(self):
        self.check_grad(
70
            ['Filter'], 'Out', no_grad_set=set('X'), check_dygraph=False)
S
Siddharth Goyal 已提交
71 72 73

    def test_check_grad_ignore_wt(self):
        self.check_grad(
74
            ['X'], 'Out', no_grad_set=set('Filter'), check_dygraph=False)
S
Siddharth Goyal 已提交
75 76 77 78 79 80


class TestRowConvOp2(OpTest):
    def setUp(self):

        self.op_type = "row_conv"
81 82
        lod = [[20, 30, 50]]
        T = sum(lod[0])
S
Siddharth Goyal 已提交
83 84 85 86 87 88 89 90 91 92 93
        D = 35
        context_length = 35

        x = np.random.random((T, D)).astype("float32")
        wt = np.random.random((context_length, D)).astype("float32")
        self.inputs = {'X': (x, lod), 'Filter': wt}

        out = row_conv_forward(x, lod, wt)
        self.outputs = {'Out': (out, lod)}

    def test_check_output(self):
H
hong 已提交
94
        self.check_output(check_dygraph=False)
S
Siddharth Goyal 已提交
95 96

    #max_relative_error is increased from 0.05 to 0.06 as for higher
97
    #dimensional input, the dX on CPU for some values has max_rel_error
S
Siddharth Goyal 已提交
98 99
    #slightly more than 0.05
    def test_check_grad_normal(self):
H
hong 已提交
100 101 102 103 104
        self.check_grad(
            ['X', 'Filter'],
            'Out',
            max_relative_error=0.06,
            check_dygraph=False)
S
Siddharth Goyal 已提交
105 106 107

    def test_check_grad_ignore_x(self):
        self.check_grad(
H
hong 已提交
108 109 110 111 112
            ['Filter'],
            'Out',
            max_relative_error=0.06,
            no_grad_set=set('X'),
            check_dygraph=False)
S
Siddharth Goyal 已提交
113 114 115

    def test_check_grad_ignore_wt(self):
        self.check_grad(
H
hong 已提交
116 117 118 119 120
            ['X'],
            'Out',
            max_relative_error=0.06,
            no_grad_set=set('Filter'),
            check_dygraph=False)
S
Siddharth Goyal 已提交
121 122


123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
def row_conv_foward_Tensor(x, wt):
    out = np.zeros_like(x)
    num_sequence = x.shape[0]
    timesteps = x.shape[1]
    context_length = wt.shape[0]
    for i in range(num_sequence):
        cur_in = x[i:i + 1, :][0]
        cur_out = out[i:i + 1, :][0]
        for j in range(timesteps):
            for k in range(context_length):
                if j + k >= timesteps:
                    continue
                cur_out[j, :] += cur_in[j + k, :] * wt[k, :]
    return out


class TestRowOpWithTensorInput(OpTest):
    def setUp(self):
        self.op_type = "row_conv"
142
        length = [1, 2, 3]
143 144
        B = 2
        T = sum(length)
145 146
        D = 20
        context_length = 6
147 148 149 150 151 152 153 154 155

        x = np.random.random((B, T, D)).astype("float32")
        wt = np.random.random((context_length, D)).astype("float32")
        self.inputs = {'X': x, 'Filter': wt}

        out = row_conv_foward_Tensor(x, wt)
        self.outputs = {'Out': out}

    def test_check_output(self):
H
hong 已提交
156
        self.check_output(check_dygraph=False)
157 158 159

    def test_check_grad_ignore_x(self):
        self.check_grad(
160
            ['Filter'], 'Out', no_grad_set=set('X'), check_dygraph=False)
161 162

    def test_check_grad_normal(self):
163
        self.check_grad(['X', 'Filter'], 'Out', check_dygraph=False)
164 165 166

    def test_check_grad_ignore_wt(self):
        self.check_grad(
167
            ['X'], 'Out', no_grad_set=set('Filter'), check_dygraph=False)
168 169


S
Siddharth Goyal 已提交
170 171
if __name__ == '__main__':
    unittest.main()