op_test.py 36.9 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
            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
320

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    def _compare_expect_and_actual_outputs(self,
                                           place,
                                           fetch_list,
                                           expect_outs,
                                           actual_outs,
                                           inplace_atol=None):
        # compare expect_outs and actual_outs
        for i, name 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 (" + 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 (" + 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')

348 349 350 351 352 353
    def _calc_output(self,
                     place,
                     parallel=False,
                     no_check_set=None,
                     loss=None,
                     enable_inplace=None,
354
                     for_inplace_test=None):
355 356
        program = Program()
        block = program.global_block()
357
        op = self._append_ops(block)
358 359 360 361 362

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

363
        if for_inplace_test:
364 365 366 367 368 369 370
            # 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
371
        original_program = program
372 373
        if parallel:
            use_cuda = False
374
            if isinstance(place, fluid.CUDAPlace):
375
                use_cuda = True
376 377 378
            compiled_prog = fluid.CompiledProgram(program).with_data_parallel(
                loss_name=loss.name if loss else None, places=place)
            program = compiled_prog
379 380 381 382
        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 已提交
383
            for var_name, var in six.iteritems(outputs):
384 385
                if no_check_set is not None and var_name in no_check_set:
                    continue
Y
Yang Yang(Tony) 已提交
386 387
                if isinstance(var, list):
                    for v in var:
388
                        fetch_list.append(v.name)
Y
Yang Yang(Tony) 已提交
389
                else:
390
                    fetch_list.append(var.name)
391 392 393 394
        # 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))
395 396 397 398 399 400 401 402 403

        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

404
        executor = Executor(place)
405 406 407 408
        outs = executor.run(program,
                            feed=feed_map,
                            fetch_list=fetch_list,
                            return_numpy=False)
409 410 411 412
        if for_inplace_test:
            return outs, fetch_list, feed_map, original_program, op.desc
        else:
            return outs, fetch_list
Y
Yang Yang(Tony) 已提交
413

414 415 416 417 418 419 420
    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
421 422 423 424 425 426 427 428 429 430
        expect_res = self._calc_output(
            place,
            no_check_set=no_check_set,
            enable_inplace=False,
            for_inplace_test=True)
        actual_res = self._calc_output(
            place,
            no_check_set=no_check_set,
            enable_inplace=True,
            for_inplace_test=True)
431 432

        # compare expect_outs and actual_outs
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        self._compare_expect_and_actual_outputs(
            place,
            expect_res[1],
            expect_res[0],
            actual_res[0],
            inplace_atol=inplace_atol)

        # check grad
        # 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
        use_ngraph = fluid.core.is_compiled_with_ngraph(
        ) and fluid.core.get_flags_use_ngraph()
        if use_ngraph:
            warnings.warn(
                "check inplace_grad for ops using ngraph is not supported")
            return
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
        fwd_outs = expect_res[0]
        fwd_fetch_list = expect_res[1]
        fwd_feed_map = expect_res[2]
        fwd_program = expect_res[3]
        fwd_op_desc = expect_res[4]
        self.check_inplace_grad_output_using_fwd_inputs_outputs(
            place,
            fwd_feed_map,
            fwd_fetch_list,
            fwd_outs,
            fwd_program,
            fwd_op_desc,
            no_check_set=no_check_set,
            inplace_atol=inplace_atol,
            depth=0)

    def check_inplace_grad_output_using_fwd_inputs_outputs(self,
                                                           place,
                                                           fwd_feed_map,
                                                           fwd_fetch_list,
                                                           fwd_outs,
                                                           fwd_program,
                                                           fwd_op_desc,
                                                           no_check_set=None,
                                                           inplace_atol=None,
                                                           depth=0):
        # depth=0 means grad
        # depth=1 means double_grad
        # depth=2 means triple_grad, which is not supported yet
        if depth >= 2:
            return
488
        # get grad_op 
489
        if not fluid.core.has_grad_op_maker(fwd_op_desc.type()):
490
            return
491
        grad_op_desc_list, op_grad_to_var = core.get_grad_op_desc(fwd_op_desc,
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
                                                                  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

            # 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()

508
            # create grad vars based on fwd vars (shape and dtype)
509 510
            for arg in grad_op_desc.input_arg_names(
            ) + grad_op_desc.output_arg_names():
511 512 513 514 515 516
                fwd_var_name = op_grad_to_var.get(arg, None)
                if fwd_var_name is None:
                    fwd_var_name = arg
                fwd_var = fwd_program.global_block().vars.get(fwd_var_name)
                assert fwd_var is not None, "{} cannot be found".format(
                    fwd_var_name)
517 518
                grad_var = grad_block.create_var(
                    name=arg,
519 520 521
                    dtype=fwd_var.dtype,
                    shape=fwd_var.shape,
                    type=fwd_var.type,
522 523 524 525 526 527 528 529 530 531
                    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()

532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
            # generate grad_feed_map for grad_program
            # since we don`t really check gradient accuracy, but the consistency when using and not using inplace
            # we use fwd 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 fwd_feed_map.keys():
                    grad_feed_map[arg] = fwd_feed_map[arg]._copy(p)
                else:
                    fwd_var_name = op_grad_to_var.get(arg, None)
                    if fwd_var_name is None:
                        fwd_var_name = arg

                    for i, out_name in enumerate(fwd_fetch_list):
                        if out_name == fwd_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 fwd execution
                            if 0 in fwd_program.global_block().var(
                                    out_name).shape:
                                continue
                            else:
                                grad_feed_map[arg] = fwd_outs[i]._copy(p)
555

556
            def _calc_grad_output(enable_inplace=None):
557 558 559 560 561
                exe = Executor(place)
                build_strategy = fluid.BuildStrategy()
                build_strategy.enable_inplace = enable_inplace
                compiled_program = fluid.CompiledProgram(
                    grad_program).with_data_parallel(
562 563 564
                        loss_name="",
                        build_strategy=build_strategy,
                        places=place)
565 566 567 568 569 570 571 572 573 574
                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
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
            self._compare_expect_and_actual_outputs(
                place,
                grad_fetch_list,
                expect_outs,
                actual_outs,
                inplace_atol=inplace_atol)

            # check grad of grad, recursively
            self.check_inplace_grad_output_using_fwd_inputs_outputs(
                place,
                grad_feed_map,
                grad_fetch_list,
                expect_outs,
                grad_program,
                grad_op_desc,
                no_check_set=no_check_set,
                inplace_atol=inplace_atol,
                depth=depth + 1)
593

594 595 596 597
    def check_output_with_place(self,
                                place,
                                atol,
                                no_check_set=None,
M
minqiyang 已提交
598
                                equal_nan=False,
599 600
                                check_dygraph=False,
                                inplace_atol=None):
L
lujun 已提交
601 602
        if check_dygraph:
            dygraph_outs = self._calc_dygraph_output(
M
minqiyang 已提交
603
                place, no_check_set=no_check_set)
604
        outs, fetch_list = self._calc_output(place, no_check_set=no_check_set)
Y
Yang Yang(Tony) 已提交
605
        for out_name, out_dup in Operator.get_op_outputs(self.op_type):
606 607
            if out_name not in self.outputs:
                continue
608 609
            if no_check_set is not None and out_name in no_check_set:
                continue
610

Y
Yang Yang(Tony) 已提交
611 612
            def find_actual(target_name, fetch_list):
                found = [
613 614
                    i for i, var_name in enumerate(fetch_list)
                    if var_name == target_name
Y
Yang Yang(Tony) 已提交
615 616 617 618 619 620
                ]
                self.assertTrue(
                    len(found) == 1, "Found {} {}".format(
                        len(found), target_name))
                return found[0]

621 622
            if out_dup:
                sub_out = self.outputs[out_name]
Y
Yancey 已提交
623 624 625
                if not isinstance(sub_out, list):
                    raise AssertionError("sub_out type %s is not list",
                                         type(sub_out))
626 627
                for item in sub_out:
                    sub_out_name, expect = item[0], item[1]
L
lujun 已提交
628 629
                    if check_dygraph:
                        imperative_actual = dygraph_outs[sub_out_name][0]
M
minqiyang 已提交
630 631
                        imperative_actual_t = np.array(
                            imperative_actual._ivar.value().get_tensor())
Y
Yang Yang(Tony) 已提交
632
                    idx = find_actual(sub_out_name, fetch_list)
Q
QI JUN 已提交
633 634
                    actual = outs[idx]
                    actual_t = np.array(actual)
635 636
                    expect_t = expect[0] \
                        if isinstance(expect, tuple) else expect
637 638
                    self.assertTrue(
                        np.allclose(
639
                            actual_t, expect_t, atol=atol, equal_nan=equal_nan),
Y
Yang Yang(Tony) 已提交
640 641
                        "Output (" + sub_out_name + ") has diff at " +
                        str(place))
L
lujun 已提交
642
                    if check_dygraph:
M
minqiyang 已提交
643 644 645 646 647 648 649
                        self.assertTrue(
                            np.allclose(
                                imperative_actual_t,
                                expect_t,
                                atol=atol,
                                equal_nan=equal_nan),
                            "Output (" + sub_out_name + ") has diff at " +
L
lujun 已提交
650
                            str(place) + " in dygraph mode")
651 652
                    if isinstance(expect, tuple):
                        self.assertListEqual(
653 654
                            actual.recursive_sequence_lengths(), expect[1],
                            "Output (" + sub_out_name +
Q
QI JUN 已提交
655
                            ") has different lod at " + str(place))
L
lujun 已提交
656
                    if check_dygraph:
M
minqiyang 已提交
657 658 659 660
                        self.assertListEqual(
                            imperative_actual._ivar.value().get_tensor()
                            .recursive_sequence_lengths(), expect[1],
                            "Output (" + out_name + ") has different lod at " +
L
lujun 已提交
661
                            str(place) + " in dygraph mode")
662
            else:
L
lujun 已提交
663 664
                if check_dygraph:
                    imperative_actual = dygraph_outs[out_name][0]
M
minqiyang 已提交
665 666
                    imperative_actual_t = np.array(
                        imperative_actual._ivar.value().get_tensor())
Y
Yang Yang(Tony) 已提交
667
                idx = find_actual(out_name, fetch_list)
Q
QI JUN 已提交
668 669
                actual = outs[idx]
                actual_t = np.array(actual)
670
                expect = self.outputs[out_name]
671
                expect_t = expect[0] if isinstance(expect, tuple) else expect
672 673
                self.assertTrue(
                    np.allclose(
674
                        actual_t, expect_t, atol=atol, equal_nan=equal_nan),
E
emailweixu 已提交
675
                    "Output (" + out_name + ") has diff at " + str(place) +
D
dzhwinter 已提交
676
                    "\nExpect " + str(expect_t) + "\n" + "But Got" +
677
                    str(actual_t) + " in class " + self.__class__.__name__)
L
lujun 已提交
678
                if check_dygraph:
M
minqiyang 已提交
679 680 681 682 683 684 685 686 687 688
                    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__)
689
                if isinstance(expect, tuple):
690 691
                    self.assertListEqual(actual.recursive_sequence_lengths(),
                                         expect[1], "Output (" + out_name +
692
                                         ") has different lod at " + str(place))
L
lujun 已提交
693
                    if check_dygraph:
M
minqiyang 已提交
694 695
                        self.assertListEqual(
                            imperative_actual._ivar.value().get_tensor()
M
minqiyang 已提交
696 697
                            .recursive_sequence_lengths(), expect[1],
                            "Output (" + out_name + ") has different lod at " +
L
lujun 已提交
698
                            str(place) + " in dygraph mode")
699

700 701 702 703 704 705 706
        # 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)

707
    def _get_places(self):
D
dzhwinter 已提交
708 709 710 711 712 713
        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 已提交
714 715
                else:
                    return []
D
dzhwinter 已提交
716 717
            else:
                return []
718
        places = [fluid.CPUPlace()]
719
        cpu_only = self._cpu_only if hasattr(self, '_cpu_only') else False
720 721
        use_ngraph = fluid.core.is_compiled_with_ngraph(
        ) and fluid.core.get_flags_use_ngraph()
B
baojun 已提交
722 723
        if use_ngraph:
            cpu_only = True
724 725
        if core.is_compiled_with_cuda() and core.op_support_gpu(self.op_type)\
           and not cpu_only:
D
dzhwinter 已提交
726
            places.append(core.CUDAPlace(0))
727 728
        return places

M
minqiyang 已提交
729 730 731 732
    def check_output(self,
                     atol=1e-5,
                     no_check_set=None,
                     equal_nan=False,
733 734
                     check_dygraph=False,
                     inplace_atol=None):
735
        places = self._get_places()
Q
qijun 已提交
736
        for place in places:
M
minqiyang 已提交
737
            self.check_output_with_place(place, atol, no_check_set, equal_nan,
L
lujun 已提交
738
                                         check_dygraph)
Q
qijun 已提交
739

740
    def check_output_customized(self, checker):
741
        places = self._get_places()
742 743 744
        for place in places:
            outs = self.calc_output(place)
            outs = [np.array(out) for out in outs]
745
            outs.sort(key=len)
746 747
            checker(outs)

D
Dun 已提交
748 749
    def _assert_is_close(self, numeric_grads, analytic_grads, names,
                         max_relative_error, msg_prefix):
750

M
minqiyang 已提交
751
        for a, b, name in six.moves.zip(numeric_grads, analytic_grads, names):
752 753 754 755 756 757 758 759
            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)
760
                return ("%s Variable %s max gradient diff %f over limit %f, "
D
dzhwinter 已提交
761 762 763
                        "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])
764 765 766 767 768

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

    def check_grad(self,
                   inputs_to_check,
Y
Yancey 已提交
769
                   output_names,
770
                   no_grad_set=None,
771
                   numeric_grad_delta=0.005,
772
                   in_place=False,
Q
Qiao Longfei 已提交
773
                   max_relative_error=0.005,
C
chengduo 已提交
774
                   user_defined_grads=None):
775
        places = self._get_places()
776 777 778 779
        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 已提交
780
                                       user_defined_grads)
781 782 783 784 785 786 787 788 789

    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 已提交
790
                              user_defined_grads=None):
791
        self.scope = core.Scope()
Q
qijun 已提交
792
        op_inputs = self.inputs if hasattr(self, "inputs") else dict()
793
        op_outputs = self.outputs if hasattr(self, "outputs") else dict()
Q
qijun 已提交
794
        op_attrs = self.attrs if hasattr(self, "attrs") else dict()
P
phlrain 已提交
795 796 797 798 799 800 801 802 803 804 805

        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 已提交
806

807 808 809
        if no_grad_set is None:
            no_grad_set = set()

Y
Yancey 已提交
810 811 812
        if not type(output_names) is list:
            output_names = [output_names]

Q
Qiao Longfei 已提交
813
        numeric_grads = user_defined_grads or [
814
            get_numeric_gradient(
815
                place,
816 817 818 819
                self.scope,
                self.op,
                self.inputs,
                input_to_check,
Y
Yancey 已提交
820
                output_names,
821
                delta=numeric_grad_delta,
C
chengduo 已提交
822
                in_place=in_place) for input_to_check in inputs_to_check
823
        ]
824 825 826
        analytic_grads = self._get_gradient(inputs_to_check, place,
                                            output_names, no_grad_set)

D
Dun 已提交
827 828 829
        self._assert_is_close(numeric_grads, analytic_grads, inputs_to_check,
                              max_relative_error,
                              "Gradient Check On %s" % str(place))
Q
qijun 已提交
830

Y
Yu Yang 已提交
831 832 833 834 835
    @staticmethod
    def _numpy_to_lod_tensor(np_value, lod, place):
        tensor = core.LoDTensor()
        tensor.set(np_value, place)
        if lod is not None:
836
            tensor.set_recursive_sequence_lengths(lod)
Y
Yu Yang 已提交
837 838
        return tensor

K
Kexin Zhao 已提交
839
    @staticmethod
K
Kexin Zhao 已提交
840 841
    def np_dtype_to_fluid_dtype(input):
        """Change the dtype of float16 numpy array
K
Kexin Zhao 已提交
842

843
        numpy float16 is binded to paddle::platform::float16
K
Kexin Zhao 已提交
844
        in tensor_py.h via the help of uint16 data type since
845
        the internal memory representation of float16 is
K
Kexin Zhao 已提交
846 847
        uint16_t in paddle and np.uint16 in numpy, which are
        themselves binded together by pybind.
K
Kexin Zhao 已提交
848 849 850 851 852

        Args:
            input: input numpy array

        Returns:
853
            input: The dtype of input will be changed to np.uint16 if
K
Kexin Zhao 已提交
854
                it is originally np.float16, such that the internal memory
855
                of input will be reinterpreted as of dtype np.uint16.
K
Kexin Zhao 已提交
856 857
        """
        if input.dtype == np.float16:
K
Kexin Zhao 已提交
858 859
            input.dtype = np.uint16
        return input
K
Kexin Zhao 已提交
860

D
dzhwinter 已提交
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
    @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

876 877 878 879 880 881
    def _get_gradient(self,
                      input_to_check,
                      place,
                      output_names,
                      no_grad_set,
                      parallel=False):
Y
Yu Yang 已提交
882 883
        prog = Program()
        block = prog.global_block()
884 885
        self._append_ops(block)
        loss = append_loss_ops(block, output_names)
F
fengjiayi 已提交
886
        param_grad_list = append_backward(
Y
Yu Yang 已提交
887 888
            loss=loss, parameter_list=input_to_check, no_grad_set=no_grad_set)

889 890
        inputs = self._get_inputs(block)
        feed_dict = self.feed_var(inputs, place)
Y
Yu Yang 已提交
891 892

        fetch_list = [g for p, g in param_grad_list]
893 894
        if parallel:
            use_cuda = False
895
            if isinstance(place, fluid.CUDAPlace):
896
                use_cuda = True
897 898 899 900
            compiled_prog = fluid.CompiledProgram(prog).with_data_parallel(
                loss_name=loss.name, places=place)
            prog = compiled_prog
        executor = fluid.Executor(place)
901 902 903
        return list(
            map(np.array,
                executor.run(prog, feed_dict, fetch_list, return_numpy=False)))