op_test.py 36.1 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

B
baojun 已提交
17
import os
18
import unittest
19
import warnings
20
import numpy as np
21
import random
M
minqiyang 已提交
22
import six
23
import time
24
import itertools
Y
Yu Yang 已提交
25
import collections
M
minqiyang 已提交
26
from collections import defaultdict
27 28 29

import paddle.fluid as fluid
import paddle.fluid.core as core
30 31 32
from paddle.fluid.backward import append_backward
from paddle.fluid.op import Operator
from paddle.fluid.executor import Executor
33
from paddle.fluid.framework import Program, OpProtoHolder, Variable
34
from testsuite import create_op, set_input, append_input_output, append_loss_ops
35 36


37 38 39 40
def randomize_probability(batch_size, class_num, dtype='float32'):
    prob = np.random.uniform(
        0.1, 1.0, size=(batch_size, class_num)).astype(dtype)
    prob_sum = prob.sum(axis=1)
M
minqiyang 已提交
41
    for i in six.moves.xrange(len(prob)):
42 43 44 45
        prob[i] /= prob_sum[i]
    return prob


46 47
def get_numeric_gradient(place,
                         scope,
48 49 50
                         op,
                         inputs,
                         input_to_check,
Y
Yancey 已提交
51
                         output_names,
52
                         delta=0.005,
C
chengduo 已提交
53
                         in_place=False):
Y
Yu Yang 已提交
54
    # FIXME: change this method by compile time concepts
55
    set_input(scope, op, inputs, place)
56 57

    def product(dim):
M
minqiyang 已提交
58
        return six.moves.reduce(lambda a, b: a * b, dim, 1)
59 60

    tensor_to_check = scope.find_var(input_to_check).get_tensor()
Y
yuyang18 已提交
61 62
    tensor_size = product(tensor_to_check.shape())
    tensor_to_check_dtype = tensor_to_check._dtype()
63
    if tensor_to_check_dtype == core.VarDesc.VarType.FP32:
64
        tensor_to_check_dtype = np.float32
65
    elif tensor_to_check_dtype == core.VarDesc.VarType.FP64:
66
        tensor_to_check_dtype = np.float64
D
dzhwinter 已提交
67 68 69 70
    elif tensor_to_check_dtype == core.VarDesc.VarType.FP16:
        tensor_to_check_dtype = np.float16
        # set delta as np.float16, will automatic convert to float32, float64
        delta = np.array(delta).astype(np.float16)
71 72 73 74
    else:
        raise ValueError("Not supported data type " + str(
            tensor_to_check_dtype))

C
chengduo 已提交
75 76 77 78 79 80 81 82 83
    def get_output():
        sum = []
        op.run(scope, place)
        for output_name in output_names:
            sum.append(
                np.array(scope.find_var(output_name).get_tensor()).astype(
                    tensor_to_check_dtype).mean())
        return tensor_to_check_dtype(np.array(sum).sum() / len(output_names))

84 85 86
    gradient_flat = np.zeros(shape=(tensor_size, ), dtype=tensor_to_check_dtype)

    def __get_elem__(tensor, i):
D
dzhwinter 已提交
87 88 89 90 91
        if tensor_to_check_dtype == np.float16:
            numpy_tensor = np.array(tensor).astype(np.float16)
            numpy_tensor = numpy_tensor.flatten()
            return numpy_tensor[i]
        elif tensor_to_check_dtype == np.float32:
Y
yuyang18 已提交
92
            return tensor._get_float_element(i)
93
        else:
Y
yuyang18 已提交
94
            return tensor._get_double_element(i)
95 96

    def __set_elem__(tensor, i, e):
D
dzhwinter 已提交
97 98 99 100 101 102 103 104
        if tensor_to_check_dtype == np.float16:
            numpy_tensor = np.array(tensor).astype(np.float16)
            shape = numpy_tensor.shape
            numpy_tensor = numpy_tensor.flatten()
            numpy_tensor[i] = e
            numpy_tensor = numpy_tensor.reshape(shape).view(np.uint16)
            tensor.set(numpy_tensor, place)
        elif tensor_to_check_dtype == np.float32:
Y
yuyang18 已提交
105
            tensor._set_float_element(i, e)
106
        else:
Y
yuyang18 已提交
107
            tensor._set_double_element(i, e)
108

109 110
    # we only compute gradient of one element each time.
    # we use a for loop to compute the gradient of every element.
M
minqiyang 已提交
111
    for i in six.moves.xrange(tensor_size):
112
        if in_place:
113
            set_input(scope, op, inputs, place)
114 115

        # get one input element throw it's index i.
116
        origin = __get_elem__(tensor_to_check, i)
117 118
        # add delta to it, run op and then get the sum of the result tensor.
        x_pos = origin + delta
119
        __set_elem__(tensor_to_check, i, x_pos)
120 121 122
        y_pos = get_output()

        if in_place:
123
            set_input(scope, op, inputs, place)
124 125

        x_neg = origin - delta
126
        __set_elem__(tensor_to_check, i, x_neg)
127 128
        y_neg = get_output()

129
        __set_elem__(tensor_to_check, i, origin)
130 131
        gradient_flat[i] = (y_pos - y_neg) / delta / 2

Y
yuyang18 已提交
132
    return gradient_flat.reshape(tensor_to_check.shape())
133 134 135


class OpTest(unittest.TestCase):
136 137 138 139 140
    @classmethod
    def setUpClass(cls):
        '''Fix random seeds to remove randomness from tests'''
        cls._np_rand_state = np.random.get_state()
        cls._py_rand_state = random.getstate()
141 142 143
        cls.call_once = False
        cls.dtype = "float32"
        cls.outputs = {}
144 145 146 147 148 149

        np.random.seed(123)
        random.seed(124)

    @classmethod
    def tearDownClass(cls):
Y
yuyang18 已提交
150
        """Restore random seeds"""
151 152 153
        np.random.set_state(cls._np_rand_state)
        random.setstate(cls._py_rand_state)

154 155 156 157
    def try_call_once(self, data_type):
        if not self.call_once:
            self.call_once = True
            self.dtype = data_type
D
dzhwinter 已提交
158 159 160 161 162
            # See the comment of np_dtype_to_fluid_dtype
            # If the input type is uint16, we assume use float16
            # for lodtensor dtype.
            if self.dtype == np.uint16:
                self.dtype == np.float16
163 164 165 166 167 168

    def infer_dtype_from_inputs_outputs(self, inputs, outputs):
        def infer_dtype(numpy_dict):
            assert isinstance(
                numpy_dict,
                dict), "self.inputs, self.outputs must be numpy_dict"
M
minqiyang 已提交
169
            for var_name, var_value in six.iteritems(numpy_dict):
170 171 172 173 174 175 176 177 178 179 180 181 182 183
                if isinstance(var_value, (np.ndarray, np.generic)):
                    self.try_call_once(var_value.dtype)
                elif isinstance(var_value, (list, tuple)):
                    # the case of self.inputs = {"X": [("x0", x0), ("x1", x1), ("x2", x2)]}
                    if len(var_value) > 1 and isinstance(var_value[1], (
                            np.ndarray, np.generic)):
                        instance = var_value[1]
                        self.try_call_once(instance[1].dtype)
                else:
                    self.try_call_once("float32")

        infer_dtype(inputs)
        infer_dtype(outputs)

Y
Yang Yang(Tony) 已提交
184 185 186 187 188 189
    def feed_var(self, input_vars, place):
        feed_map = {}
        for var_name in input_vars:
            if isinstance(input_vars[var_name], list):
                for name, np_value in self.inputs[var_name]:
                    tensor = core.LoDTensor()
190
                    if isinstance(np_value, tuple):
D
dzhwinter 已提交
191 192
                        tensor.set(
                            OpTest.np_value_to_fluid_value(np_value[0]), place)
193
                        tensor.set_recursive_sequence_lengths(np_value[1])
194
                    else:
D
dzhwinter 已提交
195 196
                        tensor.set(
                            OpTest.np_value_to_fluid_value(np_value), place)
Y
Yang Yang(Tony) 已提交
197 198 199 200
                    feed_map[name] = tensor
            else:
                tensor = core.LoDTensor()
                if isinstance(self.inputs[var_name], tuple):
D
dzhwinter 已提交
201 202 203
                    tensor.set(
                        OpTest.np_value_to_fluid_value(self.inputs[var_name][
                            0]), place)
204 205
                    tensor.set_recursive_sequence_lengths(self.inputs[var_name][
                        1])
Y
Yang Yang(Tony) 已提交
206
                else:
D
dzhwinter 已提交
207 208 209
                    tensor.set(
                        OpTest.np_value_to_fluid_value(self.inputs[var_name]),
                        place)
Y
Yang Yang(Tony) 已提交
210 211 212 213
                feed_map[var_name] = tensor

        return feed_map

214
    def _append_ops(self, block):
Y
Yang Yang(Tony) 已提交
215
        op_proto = OpProtoHolder.instance().get_op_proto(self.op_type)
216 217 218 219 220 221
        "infer datatype from inputs and outputs for this test case"
        self.infer_dtype_from_inputs_outputs(self.inputs, self.outputs)
        inputs = append_input_output(block, op_proto, self.inputs, True,
                                     self.dtype)
        outputs = append_input_output(block, op_proto, self.outputs, False,
                                      self.dtype)
P
phlrain 已提交
222 223 224 225 226 227 228 229 230

        if hasattr(self, "cache_name_list"):
            for name in self.cache_name_list:
                inputs[name] = block.create_var(
                    name=name,
                    persistable=True,
                    type=core.VarDesc.VarType.RAW,
                    stop_gradient=True)

Y
Yang Yang(Tony) 已提交
231 232 233 234 235
        op = block.append_op(
            type=self.op_type,
            inputs=inputs,
            outputs=outputs,
            attrs=self.attrs if hasattr(self, "attrs") else dict())
236
        # infer variable type and infer shape in compile-time 
Q
QI JUN 已提交
237 238
        op.desc.infer_var_type(block.desc)
        op.desc.infer_shape(block.desc)
Y
Yang Yang(Tony) 已提交
239

240 241
        return op

242 243
    def _get_io_vars(self, block, numpy_inputs):
        inputs = {}
M
minqiyang 已提交
244
        for name, value in six.iteritems(numpy_inputs):
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
            if isinstance(value, list):
                var_list = [
                    block.var(sub_name) for sub_name, sub_value in value
                ]
                inputs[name] = var_list
            else:
                inputs[name] = block.var(name)
        return inputs

    def _get_inputs(self, block):
        return self._get_io_vars(block, self.inputs)

    def _get_outputs(self, block):
        return self._get_io_vars(block, self.outputs)

    def calc_output(self, place):
        outs, _ = self._calc_output(place)
        return outs

M
minqiyang 已提交
264 265 266 267
    def _create_var_from_numpy(self, value):
        if isinstance(value, tuple):
            data = value[0]
            lod = value[1]
L
lujun 已提交
268
            v = fluid.dygraph.base.to_variable(value=data)
M
minqiyang 已提交
269 270 271
            v._ivar.value().get_tensor().set_recursive_sequence_lengths(lod)
            return v
        else:
L
lujun 已提交
272
            return fluid.dygraph.base.to_variable(value)
M
minqiyang 已提交
273

L
lujun 已提交
274 275
    def _calc_dygraph_output(self, place, parallel=False, no_check_set=None):
        with fluid.dygraph.base.guard(place=place):
M
minqiyang 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
            block = fluid.default_main_program().global_block()

            # prepare input variable
            inputs = defaultdict(list)
            for name, np_value in six.iteritems(self.inputs):
                if not isinstance(np_value, list):
                    np_value = [np_value]

                for i in range(len(np_value)):
                    inputs[name].append(
                        self._create_var_from_numpy(np_value[i]))

            # prepare output variable
            outputs = defaultdict(list)
            for name, np_value in six.iteritems(self.outputs):
                if not isinstance(np_value, list):
                    np_value = [np_value]

                for i in range(len(np_value)):
                    value = np_value[i]
                    if isinstance(value, tuple):
                        v = block.create_var(
                            name="%s_out%d" % (name, i),
                            dtype=value[0].dtype,
                            type=core.VarDesc.VarType.LOD_TENSOR,
                            persistable=False,
                            stop_gradient=False)
                        v._ivar.value().get_tensor(
                        ).set_recursive_sequence_lengths(value[1])
                    else:
                        v = block.create_var(
                            name="%s_out%d" % (name, i),
                            dtype=value.dtype,
                            type=core.VarDesc.VarType.LOD_TENSOR,
                            persistable=False,
                            stop_gradient=False)
                    outputs[name].append(v)

            block.append_op(
                type=self.op_type,
                inputs=inputs,
                outputs=outputs,
                attrs=self.attrs)

            return outputs
321

322 323 324 325 326 327 328
    def _calc_output(self,
                     place,
                     parallel=False,
                     no_check_set=None,
                     loss=None,
                     enable_inplace=None,
                     for_inplace_grad_test=None):
329 330 331 332 333 334 335 336
        program = Program()
        block = program.global_block()
        self._append_ops(block)

        inputs = self._get_inputs(block)
        outputs = self._get_outputs(block)
        feed_map = self.feed_var(inputs, place)

337 338 339 340 341 342 343 344
        if for_inplace_grad_test is not None:
            # Some variables' tensors hold no buffer (tensor's _holder is NULL), like XShape in reshape2 op, 
            # and the shapes of those variables contain 0 (eg. Xshape.shape = [0, 2, 5]). 
            # Set persistable for those variables in order to get them from global_scope for inplace grad test directly other than feed them,
            # since feed op calls check_memory_size() which fails when tensor's holder_ is NULL.
            for name, var in block.vars.items():
                if 0 in var.shape:
                    var.persistable = True
345 346
        if parallel:
            use_cuda = False
347
            if isinstance(place, fluid.CUDAPlace):
348
                use_cuda = True
349 350 351
            compiled_prog = fluid.CompiledProgram(program).with_data_parallel(
                loss_name=loss.name if loss else None, places=place)
            program = compiled_prog
352 353 354 355
        fetch_list = getattr(self, "fetch_list", [])
        # if the fetch_list is customized by user, we use it directly.
        # if not, fill the fetch_list by the user configured outputs in test.
        if len(fetch_list) == 0:
M
minqiyang 已提交
356
            for var_name, var in six.iteritems(outputs):
357 358
                if no_check_set is not None and var_name in no_check_set:
                    continue
Y
Yang Yang(Tony) 已提交
359 360 361 362 363
                if isinstance(var, list):
                    for v in var:
                        fetch_list.append(v)
                else:
                    fetch_list.append(var)
364 365 366 367 368
        # if the fetch_list still empty, fill the fetch_list by the operator output.
        if len(fetch_list) == 0:
            for out_name, out_dup in Operator.get_op_outputs(self.op_type):
                fetch_list.append(str(out_name))
        # fetch_list = map(block.var, fetch_list)
W
Wu Yi 已提交
369
        if not isinstance(fetch_list[0], fluid.framework.Variable):
370
            fetch_list = list(map(block.var, fetch_list))
371 372 373 374 375 376 377 378 379

        if enable_inplace is not None:
            build_strategy = fluid.BuildStrategy()
            build_strategy.enable_inplace = enable_inplace

            compiled_prog = fluid.CompiledProgram(program).with_data_parallel(
                build_strategy=build_strategy, places=place)
            program = compiled_prog

380
        executor = Executor(place)
381 382 383 384
        outs = executor.run(program,
                            feed=feed_map,
                            fetch_list=fetch_list,
                            return_numpy=False)
385
        return outs, fetch_list
Y
Yang Yang(Tony) 已提交
386

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    def check_inplace_output_with_place(self,
                                        place,
                                        no_check_set=None,
                                        inplace_atol=None):
        # can`t enable inplace 
        if not fluid.core.has_infer_inplace(self.op_type):
            return
        expect_outs, fetch_list = self._calc_output(
            place, no_check_set=no_check_set, enable_inplace=False)
        actual_outs, fetch_list = self._calc_output(
            place, no_check_set=no_check_set, enable_inplace=True)

        # compare expect_outs and actual_outs
        for i, out in enumerate(fetch_list):
            if inplace_atol is not None:
                self.assertTrue(
                    np.allclose(
                        np.array(expect_outs[i]),
                        np.array(actual_outs[i]),
                        atol=inplace_atol),
                    "Output (" + out.name + ") has diff at " + str(place) +
                    " when using and not using inplace" + "\nExpect " +
                    str(expect_outs[i]) + "\n" + "But Got" + str(actual_outs[i])
                    + " in class " + self.__class__.__name__)
            else:
                self.assertTrue(
                    np.array_equal(
                        np.array(expect_outs[i]), np.array(actual_outs[i])),
                    "Output (" + out.name + ") has diff at " + str(place) +
                    " when using and not using inplace" + "\nExpect " +
                    str(expect_outs[i]) + "\n" + "But Got" + str(actual_outs[i])
                    + " in class " + self.__class__.__name__ + '\n')

    def check_inplace_grad_output_with_place(self,
                                             place,
                                             no_check_set=None,
                                             inplace_atol=None):
        # create forward program to get forward vars
        program = Program()
        block = program.global_block()
        op = self._append_ops(block)
        inputs = self._get_inputs(block)
        outputs = self._get_outputs(block)
        feed_map = self.feed_var(inputs, place)

        # get grad_op 
        if not fluid.core.has_grad_op_maker(op.desc.type()):
            return
        grad_op_desc_list, op_grad_to_var = core.get_grad_op_desc(op.desc,
                                                                  set(), [])
        # has grad_op_maker but no grad_op 
        if not grad_op_desc_list:
            return

        for i, grad_op_desc in enumerate(grad_op_desc_list):
            # grad_op can not inplace
            if not fluid.core.has_infer_inplace(grad_op_desc.type()):
                continue
            # get forward outs
            forward_outs, fetch_list = self._calc_output(
                place, no_check_set=no_check_set, for_inplace_grad_test=True)

            # create grad program
            grad_program = Program()
            grad_block = grad_program.global_block()
            new_op_desc = grad_block.desc.append_op()
            new_op_desc.copy_from(grad_op_desc)
            grad_program._sync_with_cpp()

            # create grad vars based on forward vars (shape and dtype)
            for arg in grad_op_desc.input_arg_names(
            ) + grad_op_desc.output_arg_names():
                forward_var_name = op_grad_to_var.get(arg, None)
                if forward_var_name is None:
                    forward_var_name = arg
                forward_var = block.vars.get(forward_var_name)
                assert forward_var is not None, "{} cannot be found".format(
                    forward_var_name)
                grad_var = grad_block.create_var(
                    name=arg,
                    dtype=forward_var.dtype,
                    shape=forward_var.shape,
                    type=forward_var.type,
                    persistable=False)
                # some variables' tensors hold no buffer (tensor's _holder is NULL), like XShape in reshape2 op, 
                # and the shapes of those variables contain 0 (eg. Xshape.shape = [0, 2, 5]). 
                # set persistable for those variables in order to get them from global_scope for inplace grad test directly other than feed them,
                # since feed op calls check_memory_size() which fails when tensor's holder_ is NULL.
                if 0 in grad_var.shape:
                    grad_var.persistable = True
            grad_program._sync_with_cpp()
            grad_fetch_list = grad_op_desc.output_arg_names()

            def _calc_grad_output(enable_inplace=None):
                # generate feed_map for grad_program
                # since we don`t really check gradient accuracy, but the consistency when using and not using inplace
                # we use forward outs (also inputs sometimes) as grad (fake) feeds
                p = core.Place()
                p.set_place(place)
                grad_feed_map = {}
                for arg in grad_op_desc.input_arg_names():
                    if arg in feed_map.keys():
                        grad_feed_map[arg] = feed_map[arg]._copy(p)
                    else:
                        forward_var_name = op_grad_to_var.get(arg, None)
                        if forward_var_name is None:
                            forward_var_name = arg
                        for i, out in enumerate(fetch_list):
                            if out.name == forward_var_name:
                                # don't feed variables whose tensors hold no buffer (shape contains 0 like shape = [0,2,5] and holder_ is NULL), like XShape in reshape2 op.
                                # get them from global_scope directly since we have set them persistable in forward execution
                                if 0 in out.shape:
                                    continue
                                else:
                                    grad_feed_map[arg] = forward_outs[i]._copy(
                                        p)

                exe = Executor(place)
                build_strategy = fluid.BuildStrategy()
                build_strategy.enable_inplace = enable_inplace
                compiled_program = fluid.CompiledProgram(
                    grad_program).with_data_parallel(
509 510 511
                        loss_name="",
                        build_strategy=build_strategy,
                        places=place)
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
                outs = exe.run(compiled_program,
                               feed=grad_feed_map,
                               fetch_list=grad_fetch_list,
                               return_numpy=False)
                return outs

            expect_outs = _calc_grad_output(enable_inplace=False)
            actual_outs = _calc_grad_output(enable_inplace=True)

            # compare expect_outs and actual_outs
            for i, out_name in enumerate(grad_fetch_list):
                if inplace_atol is not None:
                    self.assertTrue(
                        np.allclose(
                            np.array(expect_outs[i]),
                            np.array(actual_outs[i]),
                            atol=inplace_atol),
                        "Output (" + out_name + ") has diff at " + str(place) +
                        " when using and not using inplace" + "\nExpect " +
                        str(expect_outs[i]) + "\n" + "But Got" +
                        str(actual_outs[i]) + " in class " +
                        self.__class__.__name__)
                else:
                    self.assertTrue(
                        np.array_equal(
                            np.array(expect_outs[i]), np.array(actual_outs[i])),
                        "Output (" + out_name + ") has diff at " + str(place) +
                        " when using and not using inplace" + "\nExpect " +
                        str(expect_outs[i]) + "\n" + "But Got" +
                        str(actual_outs[i]) + " in class " +
                        self.__class__.__name__)

544 545 546 547
    def check_output_with_place(self,
                                place,
                                atol,
                                no_check_set=None,
M
minqiyang 已提交
548
                                equal_nan=False,
549 550
                                check_dygraph=False,
                                inplace_atol=None):
L
lujun 已提交
551 552
        if check_dygraph:
            dygraph_outs = self._calc_dygraph_output(
M
minqiyang 已提交
553
                place, no_check_set=no_check_set)
554
        outs, fetch_list = self._calc_output(place, no_check_set=no_check_set)
M
minqiyang 已提交
555

Y
Yang Yang(Tony) 已提交
556
        for out_name, out_dup in Operator.get_op_outputs(self.op_type):
557 558
            if out_name not in self.outputs:
                continue
559 560
            if no_check_set is not None and out_name in no_check_set:
                continue
561

Y
Yang Yang(Tony) 已提交
562 563 564 565 566 567 568 569 570 571
            def find_actual(target_name, fetch_list):
                found = [
                    i for i, var in enumerate(fetch_list)
                    if var.name == target_name
                ]
                self.assertTrue(
                    len(found) == 1, "Found {} {}".format(
                        len(found), target_name))
                return found[0]

572 573
            if out_dup:
                sub_out = self.outputs[out_name]
Y
Yancey 已提交
574 575 576
                if not isinstance(sub_out, list):
                    raise AssertionError("sub_out type %s is not list",
                                         type(sub_out))
577 578
                for item in sub_out:
                    sub_out_name, expect = item[0], item[1]
L
lujun 已提交
579 580
                    if check_dygraph:
                        imperative_actual = dygraph_outs[sub_out_name][0]
M
minqiyang 已提交
581 582
                        imperative_actual_t = np.array(
                            imperative_actual._ivar.value().get_tensor())
Y
Yang Yang(Tony) 已提交
583
                    idx = find_actual(sub_out_name, fetch_list)
Q
QI JUN 已提交
584 585
                    actual = outs[idx]
                    actual_t = np.array(actual)
586 587
                    expect_t = expect[0] \
                        if isinstance(expect, tuple) else expect
588 589
                    self.assertTrue(
                        np.allclose(
590
                            actual_t, expect_t, atol=atol, equal_nan=equal_nan),
Y
Yang Yang(Tony) 已提交
591 592
                        "Output (" + sub_out_name + ") has diff at " +
                        str(place))
L
lujun 已提交
593
                    if check_dygraph:
M
minqiyang 已提交
594 595 596 597 598 599 600
                        self.assertTrue(
                            np.allclose(
                                imperative_actual_t,
                                expect_t,
                                atol=atol,
                                equal_nan=equal_nan),
                            "Output (" + sub_out_name + ") has diff at " +
L
lujun 已提交
601
                            str(place) + " in dygraph mode")
602 603
                    if isinstance(expect, tuple):
                        self.assertListEqual(
604 605
                            actual.recursive_sequence_lengths(), expect[1],
                            "Output (" + sub_out_name +
Q
QI JUN 已提交
606
                            ") has different lod at " + str(place))
L
lujun 已提交
607
                    if check_dygraph:
M
minqiyang 已提交
608 609 610 611
                        self.assertListEqual(
                            imperative_actual._ivar.value().get_tensor()
                            .recursive_sequence_lengths(), expect[1],
                            "Output (" + out_name + ") has different lod at " +
L
lujun 已提交
612
                            str(place) + " in dygraph mode")
613
            else:
L
lujun 已提交
614 615
                if check_dygraph:
                    imperative_actual = dygraph_outs[out_name][0]
M
minqiyang 已提交
616 617
                    imperative_actual_t = np.array(
                        imperative_actual._ivar.value().get_tensor())
Y
Yang Yang(Tony) 已提交
618
                idx = find_actual(out_name, fetch_list)
Q
QI JUN 已提交
619 620
                actual = outs[idx]
                actual_t = np.array(actual)
621
                expect = self.outputs[out_name]
622
                expect_t = expect[0] if isinstance(expect, tuple) else expect
623 624
                self.assertTrue(
                    np.allclose(
625
                        actual_t, expect_t, atol=atol, equal_nan=equal_nan),
E
emailweixu 已提交
626
                    "Output (" + out_name + ") has diff at " + str(place) +
D
dzhwinter 已提交
627
                    "\nExpect " + str(expect_t) + "\n" + "But Got" +
628
                    str(actual_t) + " in class " + self.__class__.__name__)
L
lujun 已提交
629
                if check_dygraph:
M
minqiyang 已提交
630 631 632 633 634 635 636 637 638 639
                    self.assertTrue(
                        np.allclose(
                            imperative_actual_t,
                            expect_t,
                            atol=atol,
                            equal_nan=equal_nan),
                        "Output (" + out_name + ") has diff at " + str(place) +
                        "\nExpect " + str(expect_t) + "\n" + "But Got" +
                        str(imperative_actual_t) + " in class " +
                        self.__class__.__name__)
640
                if isinstance(expect, tuple):
641 642
                    self.assertListEqual(actual.recursive_sequence_lengths(),
                                         expect[1], "Output (" + out_name +
643
                                         ") has different lod at " + str(place))
L
lujun 已提交
644
                    if check_dygraph:
M
minqiyang 已提交
645 646
                        self.assertListEqual(
                            imperative_actual._ivar.value().get_tensor()
M
minqiyang 已提交
647 648
                            .recursive_sequence_lengths(), expect[1],
                            "Output (" + out_name + ") has different lod at " +
L
lujun 已提交
649
                            str(place) + " in dygraph mode")
650

651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
        # inplace_atol only used when op doesn't ensure computational consistency
        if inplace_atol is not None:
            warnings.warn(
                "By default, inplace_atol should not be set, please check it")
        self.check_inplace_output_with_place(
            place, no_check_set=no_check_set, inplace_atol=inplace_atol)

        # TODO(zhiqiu): enhance inplace_grad test for ops (sum and activation) using mkldnn
        # skip use_mkldnn currently
        flags_use_mkldnn = fluid.core.get_flags_use_mkldnn()
        attrs_use_mkldnn = hasattr(
            self, 'attrs') and bool(self.attrs.get('use_mkldnn', False))
        if flags_use_mkldnn or attrs_use_mkldnn:
            warnings.warn(
                "check inplace_grad for ops using mkldnn is not supported")
            return
        self.check_inplace_grad_output_with_place(
            place, no_check_set=no_check_set, inplace_atol=inplace_atol)

670
    def _get_places(self):
D
dzhwinter 已提交
671 672 673 674 675 676
        if self.dtype == np.float16:
            if core.is_compiled_with_cuda() and core.op_support_gpu(
                    self.op_type):
                place = core.CUDAPlace(0)
                if core.is_float16_supported(place):
                    return [place]
W
Wu Yi 已提交
677 678
                else:
                    return []
D
dzhwinter 已提交
679 680
            else:
                return []
681
        places = [fluid.CPUPlace()]
682
        cpu_only = self._cpu_only if hasattr(self, '_cpu_only') else False
683 684
        use_ngraph = fluid.core.is_compiled_with_ngraph(
        ) and fluid.core.get_flags_use_ngraph()
B
baojun 已提交
685 686
        if use_ngraph:
            cpu_only = True
687 688
        if core.is_compiled_with_cuda() and core.op_support_gpu(self.op_type)\
           and not cpu_only:
D
dzhwinter 已提交
689
            places.append(core.CUDAPlace(0))
690 691
        return places

M
minqiyang 已提交
692 693 694 695
    def check_output(self,
                     atol=1e-5,
                     no_check_set=None,
                     equal_nan=False,
696 697
                     check_dygraph=False,
                     inplace_atol=None):
698
        places = self._get_places()
Q
qijun 已提交
699
        for place in places:
M
minqiyang 已提交
700
            self.check_output_with_place(place, atol, no_check_set, equal_nan,
L
lujun 已提交
701
                                         check_dygraph)
Q
qijun 已提交
702

703
    def check_output_customized(self, checker):
704
        places = self._get_places()
705 706 707
        for place in places:
            outs = self.calc_output(place)
            outs = [np.array(out) for out in outs]
708
            outs.sort(key=len)
709 710
            checker(outs)

D
Dun 已提交
711 712
    def _assert_is_close(self, numeric_grads, analytic_grads, names,
                         max_relative_error, msg_prefix):
713

M
minqiyang 已提交
714
        for a, b, name in six.moves.zip(numeric_grads, analytic_grads, names):
715 716 717 718 719 720 721 722
            abs_a = np.abs(a)
            abs_a[abs_a < 1e-3] = 1

            diff_mat = np.abs(a - b) / abs_a
            max_diff = np.max(diff_mat)

            def err_msg():
                offset = np.argmax(diff_mat > max_relative_error)
723
                return ("%s Variable %s max gradient diff %f over limit %f, "
D
dzhwinter 已提交
724 725 726
                        "the first error element is %d, expected %f, but got %f"
                        ) % (msg_prefix, name, max_diff, max_relative_error,
                             offset, a.flatten()[offset], b.flatten()[offset])
727 728 729 730 731

            self.assertLessEqual(max_diff, max_relative_error, err_msg())

    def check_grad(self,
                   inputs_to_check,
Y
Yancey 已提交
732
                   output_names,
733
                   no_grad_set=None,
734
                   numeric_grad_delta=0.005,
735
                   in_place=False,
Q
Qiao Longfei 已提交
736
                   max_relative_error=0.005,
C
chengduo 已提交
737
                   user_defined_grads=None):
738
        places = self._get_places()
739 740 741 742
        for place in places:
            self.check_grad_with_place(place, inputs_to_check, output_names,
                                       no_grad_set, numeric_grad_delta,
                                       in_place, max_relative_error,
C
chengduo 已提交
743
                                       user_defined_grads)
744 745 746 747 748 749 750 751 752

    def check_grad_with_place(self,
                              place,
                              inputs_to_check,
                              output_names,
                              no_grad_set=None,
                              numeric_grad_delta=0.005,
                              in_place=False,
                              max_relative_error=0.005,
C
chengduo 已提交
753
                              user_defined_grads=None):
754
        self.scope = core.Scope()
Q
qijun 已提交
755
        op_inputs = self.inputs if hasattr(self, "inputs") else dict()
756
        op_outputs = self.outputs if hasattr(self, "outputs") else dict()
Q
qijun 已提交
757
        op_attrs = self.attrs if hasattr(self, "attrs") else dict()
P
phlrain 已提交
758 759 760 761 762 763 764 765 766 767 768

        cache_list = None
        if hasattr(self, "cache_name_list"):
            cache_list = self.cache_name_list
        self.op = create_op(
            self.scope,
            self.op_type,
            op_inputs,
            op_outputs,
            op_attrs,
            cache_list=cache_list)
Y
Yu Yang 已提交
769

770 771 772
        if no_grad_set is None:
            no_grad_set = set()

Y
Yancey 已提交
773 774 775
        if not type(output_names) is list:
            output_names = [output_names]

Q
Qiao Longfei 已提交
776
        numeric_grads = user_defined_grads or [
777
            get_numeric_gradient(
778
                place,
779 780 781 782
                self.scope,
                self.op,
                self.inputs,
                input_to_check,
Y
Yancey 已提交
783
                output_names,
784
                delta=numeric_grad_delta,
C
chengduo 已提交
785
                in_place=in_place) for input_to_check in inputs_to_check
786
        ]
787 788 789
        analytic_grads = self._get_gradient(inputs_to_check, place,
                                            output_names, no_grad_set)

D
Dun 已提交
790 791 792
        self._assert_is_close(numeric_grads, analytic_grads, inputs_to_check,
                              max_relative_error,
                              "Gradient Check On %s" % str(place))
Q
qijun 已提交
793

Y
Yu Yang 已提交
794 795 796 797 798
    @staticmethod
    def _numpy_to_lod_tensor(np_value, lod, place):
        tensor = core.LoDTensor()
        tensor.set(np_value, place)
        if lod is not None:
799
            tensor.set_recursive_sequence_lengths(lod)
Y
Yu Yang 已提交
800 801
        return tensor

K
Kexin Zhao 已提交
802
    @staticmethod
K
Kexin Zhao 已提交
803 804
    def np_dtype_to_fluid_dtype(input):
        """Change the dtype of float16 numpy array
K
Kexin Zhao 已提交
805

806
        numpy float16 is binded to paddle::platform::float16
K
Kexin Zhao 已提交
807
        in tensor_py.h via the help of uint16 data type since
808
        the internal memory representation of float16 is
K
Kexin Zhao 已提交
809 810
        uint16_t in paddle and np.uint16 in numpy, which are
        themselves binded together by pybind.
K
Kexin Zhao 已提交
811 812 813 814 815

        Args:
            input: input numpy array

        Returns:
816
            input: The dtype of input will be changed to np.uint16 if
K
Kexin Zhao 已提交
817
                it is originally np.float16, such that the internal memory
818
                of input will be reinterpreted as of dtype np.uint16.
K
Kexin Zhao 已提交
819 820
        """
        if input.dtype == np.float16:
K
Kexin Zhao 已提交
821 822
            input.dtype = np.uint16
        return input
K
Kexin Zhao 已提交
823

D
dzhwinter 已提交
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
    @staticmethod
    def fluid_dtype_to_np_dtype(self, dtype):
        """
        See above, convert the dtype to normal type.
        """
        if dtype == np.uint16:
            dtype = np.float16
        return dtype

    @staticmethod
    def np_value_to_fluid_value(input):
        if input.dtype == np.float16:
            input = input.view(np.uint16)
        return input

839 840 841 842 843 844
    def _get_gradient(self,
                      input_to_check,
                      place,
                      output_names,
                      no_grad_set,
                      parallel=False):
Y
Yu Yang 已提交
845 846
        prog = Program()
        block = prog.global_block()
847 848
        self._append_ops(block)
        loss = append_loss_ops(block, output_names)
F
fengjiayi 已提交
849
        param_grad_list = append_backward(
Y
Yu Yang 已提交
850 851
            loss=loss, parameter_list=input_to_check, no_grad_set=no_grad_set)

852 853
        inputs = self._get_inputs(block)
        feed_dict = self.feed_var(inputs, place)
Y
Yu Yang 已提交
854 855

        fetch_list = [g for p, g in param_grad_list]
856 857
        if parallel:
            use_cuda = False
858
            if isinstance(place, fluid.CUDAPlace):
859
                use_cuda = True
860 861 862 863
            compiled_prog = fluid.CompiledProgram(prog).with_data_parallel(
                loss_name=loss.name, places=place)
            prog = compiled_prog
        executor = fluid.Executor(place)
864 865 866
        return list(
            map(np.array,
                executor.run(prog, feed_dict, fetch_list, return_numpy=False)))