test_correctness_mnistnet.py 8.5 KB
Newer Older
1 2 3
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
4
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
5 6 7 8 9 10 11 12 13 14 15 16 17
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import os
import re
import subprocess
import sys

import numpy as np
import pytest

import megengine as mge
18
import megengine.autodiff as ad
19
import megengine.functional as F
20
from megengine import jit
21
from megengine.core._trace_option import set_symbolic_shape
22
from megengine.core.ops import builtin
23
from megengine.core.tensor.utils import make_shape_tuple
24
from megengine.functional.debug_param import set_execution_strategy
25
from megengine.jit import SublinearMemoryConfig
26 27 28 29 30 31 32 33
from megengine.module import (
    AdaptiveAvgPool2d,
    AvgPool2d,
    BatchNorm2d,
    Conv2d,
    Linear,
    Module,
)
34 35 36
from megengine.optimizer import SGD
from megengine.tensor import Tensor

37 38
Strategy = builtin.ops.Convolution.Strategy

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

def get_gpu_name():
    try:
        gpu_info = subprocess.check_output(
            ["nvidia-smi", "--query-gpu=gpu_name", "--format=csv,noheader"]
        )
        gpu_info = gpu_info.decode("ascii").split("\n")[0]
    except:
        gpu_info = "None"
    return gpu_info


def get_cpu_name():
    cpu_info = "None"
    try:
        cpu_info = subprocess.check_output(["cat", "/proc/cpuinfo"]).decode("ascii")
        for line in cpu_info.split("\n"):
            if "model name" in line:
                return re.sub(".*model name.*:", "", line, 1).strip()
    except:
        pass
    return cpu_info


def get_xpu_name():
    if mge.is_cuda_available():
        return get_gpu_name()
    else:
        return get_cpu_name()


class MnistNet(Module):
71
    def __init__(self, has_bn=False, use_adaptive_pooling=False):
72 73
        super().__init__()
        self.conv0 = Conv2d(1, 20, kernel_size=5, bias=True)
74 75 76 77
        if use_adaptive_pooling:
            self.pool0 = AdaptiveAvgPool2d(12)
        else:
            self.pool0 = AvgPool2d(2)
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
        self.conv1 = Conv2d(20, 20, kernel_size=5, bias=True)
        self.pool1 = AvgPool2d(2)
        self.fc0 = Linear(20 * 4 * 4, 500, bias=True)
        self.fc1 = Linear(500, 10, bias=True)
        self.bn0 = None
        self.bn1 = None
        if has_bn:
            self.bn0 = BatchNorm2d(20)
            self.bn1 = BatchNorm2d(20)

    def forward(self, x):
        x = self.conv0(x)
        if self.bn0:
            x = self.bn0(x)
        x = F.relu(x)
        x = self.pool0(x)
        x = self.conv1(x)
        if self.bn1:
            x = self.bn1(x)
        x = F.relu(x)
        x = self.pool1(x)
        x = F.flatten(x, 1)
        x = self.fc0(x)
        x = F.relu(x)
        x = self.fc1(x)
        return x


106
def train(data, label, net, opt, gm):
M
Megvii Engine Team 已提交
107
    with gm:
108
        pred = net(data)
109
        loss = F.nn.cross_entropy(pred, label)
110
        gm.backward(loss)
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    return loss


def update_model(model_path):
    """
    Update the dumped model with test cases for new reference values.

    The model with pre-trained weights is trained for one iter with the test data attached.
    The loss and updated net state dict is dumped.

    .. code-block:: python

        from test_correctness import update_model
        update_model('mnist_model_with_test.mge') # for gpu
        update_model('mnist_model_with_test_cpu.mge') # for cpu

    """
    net = MnistNet(has_bn=True)
    checkpoint = mge.load(model_path)
    net.load_state_dict(checkpoint["net_init"])
    lr = checkpoint["sgd_lr"]
    opt = SGD(net.parameters(), lr=lr)
M
Megvii Engine Team 已提交
133
    gm = ad.GradManager().attach(net.parameters())
134 135 136 137

    data = Tensor(checkpoint["data"], dtype=np.float32)
    label = Tensor(checkpoint["label"], dtype=np.int32)

138 139
    opt.clear_grad()
    loss = train(data, label, net, opt, gm)
140 141 142 143 144 145 146 147 148 149
    opt.step()

    xpu_name = get_xpu_name()

    checkpoint.update(
        {"net_updated": net.state_dict(), "loss": loss.numpy(), "xpu": xpu_name}
    )
    mge.save(checkpoint, model_path)


150
def run_train(
151 152 153 154 155 156
    model_path,
    use_jit,
    use_symbolic,
    sublinear_memory_config=None,
    max_err=None,
    use_adaptive_pooling=False,
157 158 159 160 161 162 163 164 165 166 167
):

    """
    Load the model with test cases and run the training for one iter.
    The loss and updated weights are compared with reference value to verify the correctness.

    Dump a new file with updated result by calling update_model
    if you think the test fails due to numerical rounding errors instead of bugs.
    Please think twice before you do so.

    """
168
    net = MnistNet(has_bn=True, use_adaptive_pooling=use_adaptive_pooling)
169 170 171 172
    checkpoint = mge.load(model_path)
    net.load_state_dict(checkpoint["net_init"])
    lr = checkpoint["sgd_lr"]
    opt = SGD(net.parameters(), lr=lr)
M
Megvii Engine Team 已提交
173
    gm = ad.GradManager().attach(net.parameters())
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

    data = Tensor(checkpoint["data"], dtype=np.float32)
    label = Tensor(checkpoint["label"], dtype=np.int32)

    if max_err is None:
        max_err = 1e-5

    train_func = train
    if use_jit:
        train_func = jit.trace(
            train_func,
            symbolic=use_symbolic,
            sublinear_memory_config=sublinear_memory_config,
        )

189 190
    opt.clear_grad()
    loss = train_func(data, label, net, opt, gm)
191 192
    opt.step()

193
    np.testing.assert_allclose(loss.numpy(), checkpoint["loss"], atol=max_err)
194 195 196 197 198

    for param, param_ref in zip(
        net.state_dict().items(), checkpoint["net_updated"].items()
    ):
        assert param[0] == param_ref[0]
199 200 201 202 203
        if "bn" in param[0]:
            ref = param_ref[1].reshape(param[1].shape)
            np.testing.assert_allclose(param[1], ref, atol=max_err)
        else:
            np.testing.assert_allclose(param[1], param_ref[1], atol=max_err)
204 205


206
def run_eval(
207 208 209 210 211
    model_path,
    use_symbolic,
    sublinear_memory_config=None,
    max_err=None,
    use_adaptive_pooling=False,
212 213 214 215 216 217 218 219 220 221 222
):

    """
    Load the model with test cases and run the training for one iter.
    The loss and updated weights are compared with reference value to verify the correctness.

    Dump a new file with updated result by calling update_model
    if you think the test fails due to numerical rounding errors instead of bugs.
    Please think twice before you do so.

    """
223
    net = MnistNet(has_bn=True, use_adaptive_pooling=use_adaptive_pooling)
224 225 226 227 228 229 230 231 232 233 234 235 236 237
    checkpoint = mge.load(model_path)
    net.load_state_dict(checkpoint["net_init"])

    data = Tensor(checkpoint["data"], dtype=np.float32)

    def eval_fun(data, *, net=None):
        pred = net(data)
        return pred

    refer_value = eval_fun(data, net=net)
    eval_fun = jit.trace(eval_fun, symbolic=use_symbolic)

    for _ in range(3):
        new_value = eval_fun(data, net=net)
238
        np.testing.assert_allclose(new_value.numpy(), refer_value.numpy(), atol=max_err)
239 240


241
@pytest.mark.skip(reason="close it when cu111 ci")
242 243 244 245 246 247
def test_correctness():
    if mge.is_cuda_available():
        model_name = "mnist_model_with_test.mge"
    else:
        model_name = "mnist_model_with_test_cpu.mge"
    model_path = os.path.join(os.path.dirname(__file__), model_name)
248
    set_execution_strategy(Strategy.HEURISTIC | Strategy.REPRODUCIBLE)
249

250
    run_train(model_path, False, False, max_err=1e-5)
251 252
    run_train(model_path, True, False, max_err=1e-5)
    run_train(model_path, True, True, max_err=1e-5)
253 254

    # sublinear
255 256 257 258
    config = SublinearMemoryConfig(genetic_nr_iter=10)
    run_train(
        model_path, True, True, sublinear_memory_config=config, max_err=1e-5,
    )
259 260

    run_eval(model_path, False, max_err=1e-7)
261
    run_eval(model_path, True, max_err=1e-7)
262 263


264
@pytest.mark.skip(reason="close it when cu111 ci")
265 266 267 268 269 270
def test_correctness_use_adaptive_pooling():
    if mge.is_cuda_available():
        model_name = "mnist_model_with_test.mge"
    else:
        model_name = "mnist_model_with_test_cpu.mge"
    model_path = os.path.join(os.path.dirname(__file__), model_name)
271
    set_execution_strategy("HEURISTIC_REPRODUCIBLE")
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

    run_train(model_path, False, False, max_err=1e-5, use_adaptive_pooling=True)
    run_train(model_path, True, False, max_err=1e-5, use_adaptive_pooling=True)
    run_train(model_path, True, True, max_err=1e-5, use_adaptive_pooling=True)

    # sublinear
    config = SublinearMemoryConfig(genetic_nr_iter=10)
    run_train(
        model_path,
        True,
        True,
        sublinear_memory_config=config,
        max_err=1e-5,
        use_adaptive_pooling=True,
    )

    run_eval(model_path, False, max_err=1e-7, use_adaptive_pooling=True)
    run_eval(model_path, True, max_err=1e-7, use_adaptive_pooling=True)