check_nan_inf_base.py 3.4 KB
Newer Older
W
WangXi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
16

W
WangXi 已提交
17 18
import numpy as np

19
os.environ["FLAGS_check_nan_inf"] = "1"
W
WangXi 已提交
20 21

import paddle
22 23
from paddle import fluid
from paddle.fluid import core
W
WangXi 已提交
24

P
pangyoki 已提交
25 26
paddle.enable_static()

W
WangXi 已提交
27 28 29 30 31 32
np.random.seed(0)


def generator():
    batch_size = 5
    for i in range(5):
33 34 35
        curr_train_x = np.random.randint(
            batch_size, size=(batch_size, 3)
        ).astype("float32")
W
WangXi 已提交
36 37 38 39 40 41 42 43 44 45 46 47
        if i >= 2:
            curr_train_x[0, :] = np.nan
            curr_train_x[-1, :] = np.inf
        res = []
        for i in range(batch_size):
            y = i % 3
            res.append([y])
        y_label = np.array(res).astype('int64')
        yield [curr_train_x, y_label]


def net():
G
GGBond8488 已提交
48 49
    x = paddle.static.data(name="x", shape=[-1, 3], dtype='float32')
    y = paddle.static.data(name="y", shape=[-1, 1], dtype='int64')
W
WangXi 已提交
50 51

    # test int64 value
52
    zero = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=0)
W
WangXi 已提交
53 54

    # test float16 value
55
    fp16_zero = paddle.cast(zero, dtype='float16')
W
WangXi 已提交
56 57 58 59 60

    y = y + zero

    hidden = x

61
    hidden = paddle.static.nn.fc(x=hidden, size=400, activation="sigmoid")
W
WangXi 已提交
62

C
Charles-hit 已提交
63
    hidden = paddle.static.nn.fc(x=hidden, size=3)
64
    cost, y_predict = paddle.nn.functional.softmax_with_cross_entropy(
65 66
        hidden, y, return_softmax=True
    )
67
    acc_top1 = paddle.static.accuracy(input=y_predict, label=y, k=1)
68
    avg_cost = paddle.mean(cost)
W
WangXi 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

    sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.05)
    sgd_optimizer.minimize(avg_cost)
    return y_predict, avg_cost, acc_top1


def check(use_cuda):
    main = fluid.Program()
    startup = fluid.Program()
    scope = fluid.core.Scope()

    with fluid.scope_guard(scope):
        with fluid.program_guard(main, startup):
            y_predict, avg_cost, acc_top1 = net()

            place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
            exe = fluid.Executor(place)
            exe.run(startup)

            step = 0.0
            for train_data, y_label in generator():
                outs = exe.run(
                    main,
92 93 94
                    feed={'x': train_data, 'y': y_label},
                    fetch_list=[y_predict.name, avg_cost.name, acc_top1.name],
                )
W
WangXi 已提交
95
                step += 1
96
                print(f'iter={step:.0f},cost={outs[1]},acc1={outs[2]}')
W
WangXi 已提交
97 98 99


if __name__ == '__main__':
100 101
    try:
        check(use_cuda=False)
102
        raise AssertionError()
103 104 105 106 107
    except Exception as e:
        print(e)
        print(type(e))
        assert type(e) == RuntimeError

W
WangXi 已提交
108 109 110
    if core.is_compiled_with_cuda():
        try:
            check(use_cuda=True)
111
            raise AssertionError()
W
WangXi 已提交
112 113
        except Exception as e:
            print(e)
114 115 116
            print(type(e))
            # Note. Enforce in cuda kernel may not catch in paddle, and
            # Exception type will be RuntimeError
117
            assert type(e) == OSError or type(e) == RuntimeError