forked from PaddlePaddle/Paddle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_logcumsumexp_op.py
207 lines (160 loc) · 6.7 KB
/
test_logcumsumexp_op.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# Copyright (c) 2018 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.
from __future__ import print_function
from typing import Optional
import unittest
import itertools
import numpy as np
import paddle
import paddle.fluid.core as core
import paddle.fluid as fluid
from paddle.fluid import compiler, Program, program_guard
from paddle.fluid.framework import _test_eager_guard
from op_test import OpTest
def np_naive_logcumsumexp(x: np.ndarray, axis: Optional[int]=None):
return np.log(np.cumsum(np.exp(x), axis=axis))
def np_logcumsumexp(x: np.ndarray,
axis: Optional[int]=None,
reverse: bool=False,
exclusive: bool=False):
x = np.copy(x)
if axis is None:
x = x.flatten()
axis = 0
if reverse:
x = np.flip(x, axis)
dimensions = [range(dim) for dim in x.shape[:axis]]
if exclusive:
x = np.roll(x, 1, axis)
for prefix_dim in itertools.product(*dimensions):
x[prefix_dim][0] = np.finfo(x.dtype).min
for prefix_dim in itertools.product(*dimensions):
arr = x[prefix_dim]
for dim in range(1, arr.shape[0]):
arr[dim] = np.logaddexp(arr[dim - 1], arr[dim])
if reverse:
x = np.flip(x, axis)
return x
class TestLogcumsumexp(unittest.TestCase):
def run_imperative(self):
data_np = np.arange(12, dtype=np.float32).reshape(3, 4)
data = paddle.to_tensor(data_np)
y = paddle.logcumsumexp(data)
z = np_logcumsumexp(data_np)
self.assertTrue(np.allclose(z, y.numpy()))
y = paddle.logcumsumexp(data, axis=0)
z = np_logcumsumexp(data_np, axis=0)
self.assertTrue(np.allclose(z, y.numpy()))
y = paddle.logcumsumexp(data, axis=-1)
z = np_logcumsumexp(data_np, axis=-1)
self.assertTrue(np.allclose(z, y.numpy()))
y = paddle.logcumsumexp(data, dtype='float64')
self.assertTrue(y.dtype == core.VarDesc.VarType.FP64)
y = paddle.logcumsumexp(data, axis=-2)
z = np_logcumsumexp(data_np, axis=-2)
self.assertTrue(np.allclose(z, y.numpy()))
with self.assertRaises(IndexError):
y = paddle.logcumsumexp(data, axis=-3)
with self.assertRaises(IndexError):
y = paddle.logcumsumexp(data, axis=2)
data_np = np.arange(10000, 10024, dtype=np.float32)
data = paddle.to_tensor(data_np)
y = paddle.logcumsumexp(data)
z = np_naive_logcumsumexp(data_np)
# check that naive algorithm overflows
self.assertTrue(all(z == np.inf))
z = np_logcumsumexp(data_np)
# check that our algorithm doesn't overflow
self.assertTrue(all(z != np.inf))
self.assertTrue(np.allclose(z, y.numpy()))
def run_static(self, use_gpu=False):
with fluid.program_guard(fluid.Program()):
data_np = np.random.random((100, 100)).astype(np.float32)
x = paddle.static.data('X', [100, 100])
y = paddle.logcumsumexp(x)
y2 = paddle.logcumsumexp(x, axis=0)
y3 = paddle.logcumsumexp(x, axis=-1)
y4 = paddle.logcumsumexp(x, dtype='float64')
y5 = paddle.logcumsumexp(x, axis=-2)
place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
out = exe.run(feed={'X': data_np},
fetch_list=[
y.name,
y2.name,
y3.name,
y4.name,
y5.name,
])
z = np_logcumsumexp(data_np)
self.assertTrue(np.allclose(z, out[0]))
z = np_logcumsumexp(data_np, axis=0)
self.assertTrue(np.allclose(z, out[1]))
z = np_logcumsumexp(data_np, axis=-1)
self.assertTrue(np.allclose(z, out[2]))
self.assertTrue(out[3].dtype == np.float64)
z = np_logcumsumexp(data_np, axis=-2)
self.assertTrue(np.allclose(z, out[4]))
def test_cpu(self):
paddle.disable_static(paddle.fluid.CPUPlace())
self.run_imperative()
paddle.enable_static()
self.run_static()
def test_gpu(self):
if not fluid.core.is_compiled_with_cuda():
return
paddle.disable_static(paddle.fluid.CUDAPlace(0))
self.run_imperative()
paddle.enable_static()
self.run_static(use_gpu=True)
def test_name(self):
with fluid.program_guard(fluid.Program()):
x = paddle.static.data('x', [3, 4])
y = paddle.logcumsumexp(x, name='out')
self.assertTrue('out' in y.name)
def test_type_error(self):
with fluid.program_guard(fluid.Program()):
with self.assertRaises(TypeError):
data_np = np.random.random((100, 100), dtype=np.int32)
x = paddle.static.data('X', [100, 100], dtype='int32')
y = paddle.logcumsumexp(x)
place = fluid.CUDAPlace(0)
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
out = exe.run(feed={'X': data_np}, fetch_list=[y.name])
class BaseOpTest(OpTest):
def setUp(self):
self.op_type = "logcumsumexp"
input, attrs = self.input_and_attrs()
self.inputs = {'X': input}
self.attrs = attrs
self.outputs = {'Out': np_logcumsumexp(input)}
def test_check_output(self):
self.check_output()
def test_check_grad(self):
self.check_grad(['X'], 'Out')
def input_and_attrs(self):
raise NotImplementedError()
def TestLogcumsumexpOp1(BaseOpTest):
def input_and_attrs(self):
return np.random.randn(20, 6), {'axis': 0, 'flatten': True, 'reverse': True}
def TestLogcumsumexpOp2(BaseOpTest):
def input_and_attrs(self):
return np.random.randn(20, 6), {'axis': 1, 'flatten': False, 'reverse': True}
def TestLogcumsumexpOp3(BaseOpTest):
def input_and_attrs(self):
return np.random.randn(20, 6), {'axis': 1, 'flatten': False, 'reverse': False}
if __name__ == '__main__':
unittest.main()