imperative_test_utils.py 9.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#   copyright (c) 2021 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 numpy as np
import logging

import paddle
import paddle.fluid as fluid
from paddle.fluid import core
from paddle.fluid.dygraph.container import Sequential
from paddle.nn import ReLU, ReLU6, LeakyReLU, Sigmoid, Softmax, PReLU
from paddle.nn import Linear, Conv2D, Softmax, BatchNorm2D, MaxPool2D
X
XGZhang 已提交
23
from paddle.nn import BatchNorm1D
24 25 26

from paddle.fluid.log_helper import get_logger

27 28 29
_logger = get_logger(
    __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s'
)
30 31 32 33 34 35 36 37 38 39


def fix_model_dict(model):
    fixed_state = {}
    for name, param in model.named_parameters():
        p_shape = param.numpy().shape
        p_value = param.numpy()
        if name.endswith("bias"):
            value = np.zeros_like(p_value).astype('float32')
        else:
40 41 42 43 44
            value = (
                np.random.normal(loc=0.0, scale=0.01, size=np.product(p_shape))
                .reshape(p_shape)
                .astype('float32')
            )
45 46 47 48 49
        fixed_state[name] = value
    model.set_dict(fixed_state)
    return model


X
XGZhang 已提交
50
def pre_hook(layer, input):
51
    input_return = input[0] * 2
X
XGZhang 已提交
52 53 54 55 56 57 58
    return input_return


def post_hook(layer, input, output):
    return output * 2


59 60 61 62 63
def train_lenet(lenet, reader, optimizer):
    loss_list = []
    lenet.train()

    for batch_id, data in enumerate(reader()):
64 65 66
        x_data = np.array([x[0].reshape(1, 28, 28) for x in data]).astype(
            'float32'
        )
67 68 69 70 71 72 73
        y_data = np.array([x[1] for x in data]).astype('int64').reshape(-1, 1)

        img = paddle.to_tensor(x_data)
        label = paddle.to_tensor(y_data)

        out = lenet(img)
        loss = fluid.layers.cross_entropy(out, label)
74
        avg_loss = paddle.mean(loss)
75 76 77 78 79 80 81 82 83 84 85 86 87 88
        avg_loss.backward()

        optimizer.minimize(avg_loss)
        lenet.clear_gradients()

        if batch_id % 100 == 0:
            loss_list.append(avg_loss.numpy()[0])
            _logger.info('{}: {}'.format('loss', avg_loss.numpy()))

    return loss_list


class ImperativeLenet(fluid.dygraph.Layer):
    def __init__(self, num_classes=10):
89
        super().__init__()
90 91 92 93 94 95 96 97 98 99
        conv2d_w1_attr = fluid.ParamAttr(name="conv2d_w_1")
        conv2d_w2_attr = fluid.ParamAttr(name="conv2d_w_2")
        fc_w1_attr = fluid.ParamAttr(name="fc_w_1")
        fc_w2_attr = fluid.ParamAttr(name="fc_w_2")
        fc_w3_attr = fluid.ParamAttr(name="fc_w_3")
        conv2d_b2_attr = fluid.ParamAttr(name="conv2d_b_2")
        fc_b1_attr = fluid.ParamAttr(name="fc_b_1")
        fc_b2_attr = fluid.ParamAttr(name="fc_b_2")
        fc_b3_attr = fluid.ParamAttr(name="fc_b_3")
        self.features = Sequential(
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
            Conv2D(
                in_channels=1,
                out_channels=6,
                kernel_size=3,
                stride=1,
                padding=1,
                weight_attr=conv2d_w1_attr,
                bias_attr=False,
            ),
            BatchNorm2D(6),
            ReLU(),
            MaxPool2D(kernel_size=2, stride=2),
            Conv2D(
                in_channels=6,
                out_channels=16,
                kernel_size=5,
                stride=1,
                padding=0,
                weight_attr=conv2d_w2_attr,
                bias_attr=conv2d_b2_attr,
            ),
            BatchNorm2D(16),
            PReLU(),
123
            MaxPool2D(kernel_size=2, stride=2),
124
        )
125 126

        self.fc = Sequential(
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
            Linear(
                in_features=400,
                out_features=120,
                weight_attr=fc_w1_attr,
                bias_attr=fc_b1_attr,
            ),
            LeakyReLU(),
            Linear(
                in_features=120,
                out_features=84,
                weight_attr=fc_w2_attr,
                bias_attr=fc_b2_attr,
            ),
            Sigmoid(),
            Linear(
                in_features=84,
                out_features=num_classes,
                weight_attr=fc_w3_attr,
                bias_attr=fc_b3_attr,
            ),
            Softmax(),
        )
149
        self.add = paddle.nn.quant.add()
150
        self.quant_stub = paddle.nn.quant.QuantStub()
151 152

    def forward(self, inputs):
153 154
        x = self.quant_stub(inputs)
        x = self.features(x)
155 156 157 158 159 160 161 162 163

        x = fluid.layers.flatten(x, 1)
        x = self.add(x, paddle.to_tensor(0.0))  # For CI
        x = self.fc(x)
        return x


class ImperativeLenetWithSkipQuant(fluid.dygraph.Layer):
    def __init__(self, num_classes=10):
164
        super().__init__()
165 166 167 168 169 170 171 172 173 174 175

        conv2d_w1_attr = fluid.ParamAttr(name="conv2d_w_1")
        conv2d_w2_attr = fluid.ParamAttr(name="conv2d_w_2")
        fc_w1_attr = fluid.ParamAttr(name="fc_w_1")
        fc_w2_attr = fluid.ParamAttr(name="fc_w_2")
        fc_w3_attr = fluid.ParamAttr(name="fc_w_3")
        conv2d_b1_attr = fluid.ParamAttr(name="conv2d_b_1")
        conv2d_b2_attr = fluid.ParamAttr(name="conv2d_b_2")
        fc_b1_attr = fluid.ParamAttr(name="fc_b_1")
        fc_b2_attr = fluid.ParamAttr(name="fc_b_2")
        fc_b3_attr = fluid.ParamAttr(name="fc_b_3")
176 177 178 179 180 181 182 183 184
        self.conv2d_0 = Conv2D(
            in_channels=1,
            out_channels=6,
            kernel_size=3,
            stride=1,
            padding=1,
            weight_attr=conv2d_w1_attr,
            bias_attr=conv2d_b1_attr,
        )
185 186 187 188 189
        self.conv2d_0.skip_quant = True

        self.batch_norm_0 = BatchNorm2D(6)
        self.relu_0 = ReLU()
        self.pool2d_0 = MaxPool2D(kernel_size=2, stride=2)
190 191 192 193 194 195 196 197 198
        self.conv2d_1 = Conv2D(
            in_channels=6,
            out_channels=16,
            kernel_size=5,
            stride=1,
            padding=0,
            weight_attr=conv2d_w2_attr,
            bias_attr=conv2d_b2_attr,
        )
199 200 201 202 203
        self.conv2d_1.skip_quant = False

        self.batch_norm_1 = BatchNorm2D(16)
        self.relu6_0 = ReLU6()
        self.pool2d_1 = MaxPool2D(kernel_size=2, stride=2)
204 205 206 207 208 209
        self.linear_0 = Linear(
            in_features=400,
            out_features=120,
            weight_attr=fc_w1_attr,
            bias_attr=fc_b1_attr,
        )
210 211 212
        self.linear_0.skip_quant = True

        self.leaky_relu_0 = LeakyReLU()
213 214 215 216 217 218
        self.linear_1 = Linear(
            in_features=120,
            out_features=84,
            weight_attr=fc_w2_attr,
            bias_attr=fc_b2_attr,
        )
219 220 221
        self.linear_1.skip_quant = False

        self.sigmoid_0 = Sigmoid()
222 223 224 225 226 227
        self.linear_2 = Linear(
            in_features=84,
            out_features=num_classes,
            weight_attr=fc_w3_attr,
            bias_attr=fc_b3_attr,
        )
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        self.linear_2.skip_quant = False
        self.softmax_0 = Softmax()

    def forward(self, inputs):
        x = self.conv2d_0(inputs)
        x = self.batch_norm_0(x)
        x = self.relu_0(x)
        x = self.pool2d_0(x)
        x = self.conv2d_1(x)
        x = self.batch_norm_1(x)
        x = self.relu6_0(x)
        x = self.pool2d_1(x)

        x = fluid.layers.flatten(x, 1)

        x = self.linear_0(x)
        x = self.leaky_relu_0(x)
        x = self.linear_1(x)
        x = self.sigmoid_0(x)
        x = self.linear_2(x)
        x = self.softmax_0(x)

        return x
X
XGZhang 已提交
251 252 253 254


class ImperativeLinearBn(fluid.dygraph.Layer):
    def __init__(self):
255
        super().__init__()
X
XGZhang 已提交
256 257 258

        fc_w_attr = paddle.ParamAttr(
            name="fc_weight",
259 260
            initializer=paddle.nn.initializer.Constant(value=0.5),
        )
X
XGZhang 已提交
261 262
        fc_b_attr = paddle.ParamAttr(
            name="fc_bias",
263 264
            initializer=paddle.nn.initializer.Constant(value=1.0),
        )
X
XGZhang 已提交
265 266
        bn_w_attr = paddle.ParamAttr(
            name="bn_weight",
267 268 269 270 271 272 273 274 275
            initializer=paddle.nn.initializer.Constant(value=0.5),
        )

        self.linear = Linear(
            in_features=10,
            out_features=10,
            weight_attr=fc_w_attr,
            bias_attr=fc_b_attr,
        )
X
XGZhang 已提交
276 277 278 279 280 281 282 283 284 285 286
        self.bn = BatchNorm1D(10, weight_attr=bn_w_attr)

    def forward(self, inputs):
        x = self.linear(inputs)
        x = self.bn(x)

        return x


class ImperativeLinearBn_hook(fluid.dygraph.Layer):
    def __init__(self):
287
        super().__init__()
X
XGZhang 已提交
288 289 290

        fc_w_attr = paddle.ParamAttr(
            name="linear_weight",
291 292
            initializer=paddle.nn.initializer.Constant(value=0.5),
        )
X
XGZhang 已提交
293

294 295 296
        self.linear = Linear(
            in_features=10, out_features=10, weight_attr=fc_w_attr
        )
X
XGZhang 已提交
297 298 299 300 301 302 303 304 305 306
        self.bn = BatchNorm1D(10)

        forward_pre = self.linear.register_forward_pre_hook(pre_hook)
        forward_post = self.bn.register_forward_post_hook(post_hook)

    def forward(self, inputs):
        x = self.linear(inputs)
        x = self.bn(x)

        return x