|
| 1 | +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import print_function |
| 16 | + |
| 17 | +import contextlib |
| 18 | +import unittest |
| 19 | +import numpy as np |
| 20 | +import six |
| 21 | + |
| 22 | +import paddle |
| 23 | +import paddle.fluid as fluid |
| 24 | +from paddle.fluid import core |
| 25 | +from paddle.fluid.optimizer import SGDOptimizer |
| 26 | +from paddle.fluid.dygraph.nn import Conv2D, Pool2D, FC |
| 27 | +from paddle.fluid.dygraph.base import to_variable |
| 28 | +from test_imperative_base import new_program_scope |
| 29 | + |
| 30 | + |
| 31 | +class SimpleImgConvPool(fluid.dygraph.Layer): |
| 32 | + def __init__(self, |
| 33 | + name_scope, |
| 34 | + num_channels, |
| 35 | + num_filters, |
| 36 | + filter_size, |
| 37 | + pool_size, |
| 38 | + pool_stride, |
| 39 | + pool_padding=0, |
| 40 | + pool_type='max', |
| 41 | + global_pooling=False, |
| 42 | + conv_stride=1, |
| 43 | + conv_padding=0, |
| 44 | + conv_dilation=1, |
| 45 | + conv_groups=1, |
| 46 | + act=None, |
| 47 | + use_cudnn=False, |
| 48 | + param_attr=None, |
| 49 | + bias_attr=None): |
| 50 | + super(SimpleImgConvPool, self).__init__(name_scope) |
| 51 | + |
| 52 | + self._conv2d = Conv2D( |
| 53 | + self.full_name(), |
| 54 | + num_channels=num_channels, |
| 55 | + num_filters=num_filters, |
| 56 | + filter_size=filter_size, |
| 57 | + stride=conv_stride, |
| 58 | + padding=conv_padding, |
| 59 | + dilation=conv_dilation, |
| 60 | + groups=conv_groups, |
| 61 | + param_attr=None, |
| 62 | + bias_attr=None, |
| 63 | + use_cudnn=use_cudnn) |
| 64 | + |
| 65 | + self._pool2d = Pool2D( |
| 66 | + self.full_name(), |
| 67 | + pool_size=pool_size, |
| 68 | + pool_type=pool_type, |
| 69 | + pool_stride=pool_stride, |
| 70 | + pool_padding=pool_padding, |
| 71 | + global_pooling=global_pooling, |
| 72 | + use_cudnn=use_cudnn) |
| 73 | + |
| 74 | + def forward(self, inputs): |
| 75 | + x = self._conv2d(inputs) |
| 76 | + x = self._pool2d(x) |
| 77 | + return x |
| 78 | + |
| 79 | + |
| 80 | +class MNIST(fluid.dygraph.Layer): |
| 81 | + def __init__(self, name_scope): |
| 82 | + super(MNIST, self).__init__(name_scope) |
| 83 | + |
| 84 | + self._simple_img_conv_pool_1 = SimpleImgConvPool( |
| 85 | + self.full_name(), 1, 20, 5, 2, 2, act="relu") |
| 86 | + |
| 87 | + self._simple_img_conv_pool_2 = SimpleImgConvPool( |
| 88 | + self.full_name(), 20, 50, 5, 2, 2, act="relu") |
| 89 | + |
| 90 | + pool_2_shape = 50 * 4 * 4 |
| 91 | + SIZE = 10 |
| 92 | + scale = (2.0 / (pool_2_shape**2 * SIZE))**0.5 |
| 93 | + self._fc = FC(self.full_name(), |
| 94 | + 10, |
| 95 | + param_attr=fluid.param_attr.ParamAttr( |
| 96 | + initializer=fluid.initializer.NormalInitializer( |
| 97 | + loc=0.0, scale=scale)), |
| 98 | + act="softmax") |
| 99 | + |
| 100 | + def forward(self, inputs): |
| 101 | + x = self._simple_img_conv_pool_1(inputs) |
| 102 | + x = self._simple_img_conv_pool_2(x) |
| 103 | + x = self._fc(x) |
| 104 | + return x |
| 105 | + |
| 106 | + |
| 107 | +class TestDygraphMultiForward(unittest.TestCase): |
| 108 | + def test_mnist_forward_float32(self): |
| 109 | + seed = 90 |
| 110 | + epoch_num = 1 |
| 111 | + with fluid.dygraph.guard(): |
| 112 | + fluid.default_startup_program().random_seed = seed |
| 113 | + fluid.default_main_program().random_seed = seed |
| 114 | + |
| 115 | + mnist = MNIST("mnist") |
| 116 | + sgd = SGDOptimizer(learning_rate=1e-3) |
| 117 | + train_reader = paddle.batch( |
| 118 | + paddle.dataset.mnist.train(), batch_size=128, drop_last=True) |
| 119 | + |
| 120 | + dy_param_init_value = {} |
| 121 | + mnist.eval() |
| 122 | + for epoch in range(epoch_num): |
| 123 | + for batch_id, data in enumerate(train_reader()): |
| 124 | + dy_x_data = np.array( |
| 125 | + [x[0].reshape(1, 28, 28) |
| 126 | + for x in data]).astype('float32') |
| 127 | + y_data = np.array( |
| 128 | + [x[1] for x in data]).astype('int64').reshape(128, 1) |
| 129 | + |
| 130 | + img = to_variable(dy_x_data) |
| 131 | + label = to_variable(y_data) |
| 132 | + label.stop_gradient = True |
| 133 | + |
| 134 | + cost = mnist(img) |
| 135 | + loss = fluid.layers.cross_entropy(cost, label) |
| 136 | + avg_loss = fluid.layers.mean(loss) |
| 137 | + |
| 138 | + dy_out = avg_loss.numpy() |
| 139 | + |
| 140 | + if epoch == 0 and batch_id == 0: |
| 141 | + for param in mnist.parameters(): |
| 142 | + dy_param_init_value[param.name] = param.numpy() |
| 143 | + |
| 144 | + with new_program_scope(): |
| 145 | + fluid.default_startup_program().random_seed = seed |
| 146 | + fluid.default_main_program().random_seed = seed |
| 147 | + |
| 148 | + exe = fluid.Executor(fluid.CPUPlace( |
| 149 | + ) if not core.is_compiled_with_cuda() else fluid.CUDAPlace(0)) |
| 150 | + |
| 151 | + mnist = MNIST("mnist") |
| 152 | + sgd = SGDOptimizer(learning_rate=1e-3) |
| 153 | + train_reader = paddle.batch( |
| 154 | + paddle.dataset.mnist.train(), batch_size=128, drop_last=True) |
| 155 | + |
| 156 | + img = fluid.layers.data( |
| 157 | + name='pixel', shape=[1, 28, 28], dtype='float32') |
| 158 | + label = fluid.layers.data(name='label', shape=[1], dtype='int64') |
| 159 | + cost = mnist(img) |
| 160 | + loss = fluid.layers.cross_entropy(cost, label) |
| 161 | + avg_loss = fluid.layers.mean(loss) |
| 162 | + |
| 163 | + # initialize params and fetch them |
| 164 | + static_param_init_value = {} |
| 165 | + static_param_name_list = [] |
| 166 | + for param in mnist.parameters(): |
| 167 | + static_param_name_list.append(param.name) |
| 168 | + |
| 169 | + out = exe.run(fluid.default_startup_program(), |
| 170 | + fetch_list=static_param_name_list) |
| 171 | + |
| 172 | + for i in range(len(static_param_name_list)): |
| 173 | + static_param_init_value[static_param_name_list[i]] = out[i] |
| 174 | + |
| 175 | + for epoch in range(epoch_num): |
| 176 | + for batch_id, data in enumerate(train_reader()): |
| 177 | + static_x_data = np.array( |
| 178 | + [x[0].reshape(1, 28, 28) |
| 179 | + for x in data]).astype('float32') |
| 180 | + y_data = np.array( |
| 181 | + [x[1] for x in data]).astype('int64').reshape([128, 1]) |
| 182 | + |
| 183 | + fetch_list = [avg_loss.name] |
| 184 | + out = exe.run( |
| 185 | + fluid.default_main_program(), |
| 186 | + feed={"pixel": static_x_data, |
| 187 | + "label": y_data}, |
| 188 | + fetch_list=fetch_list) |
| 189 | + |
| 190 | + static_out = out[0] |
| 191 | + |
| 192 | + self.assertTrue(np.allclose(dy_x_data.all(), static_x_data.all())) |
| 193 | + |
| 194 | + for key, value in six.iteritems(static_param_init_value): |
| 195 | + self.assertTrue(np.allclose(value, dy_param_init_value[key])) |
| 196 | + |
| 197 | + self.assertTrue(np.allclose(static_out, dy_out)) |
| 198 | + |
| 199 | + |
| 200 | +if __name__ == '__main__': |
| 201 | + unittest.main() |
0 commit comments