test_autodiff.py 9.7 KB
Newer Older
1 2 3 4 5 6 7 8
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# 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.
9
import gc
10
import platform
11 12 13 14 15 16 17
import weakref

import numpy as np
import pytest

import megengine as mge
import megengine.distributed as dist
18
import megengine.functional as F
19
from megengine.core._imperative_rt import CompNode, TensorAttr, imperative
20
from megengine.core._imperative_rt.core2 import TensorWeakRef, apply, sync
21 22
from megengine.core.autodiff.grad import Grad
from megengine.core.ops.builtin import Elemwise
23
from megengine.distributed.helper import get_device_count_by_fork
24 25 26 27
from megengine.functional.distributed import remote_recv, remote_send


def _elwise(mode):
28
    op = Elemwise(mode)
29 30 31 32 33 34 35 36

    def f(*args):
        (result,) = apply(op, *args)
        return result

    return f


37 38 39 40
add = _elwise(Elemwise.Mode.ADD)
mul = _elwise(Elemwise.Mode.MUL)
cos = _elwise(Elemwise.Mode.COS)
relu = _elwise(Elemwise.Mode.RELU)
41 42 43


def as_tensor(x):
44
    return mge.Tensor(x)
45 46 47


def save_to(self, name="grad"):
48
    def callback(grad):
49 50 51 52 53
        setattr(self, name, grad)

    return callback


54 55 56
@pytest.mark.skipif(
    platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
)
57 58 59
@pytest.mark.skipif(
    platform.system() == "Windows", reason="windows disable MGB_ENABLE_OPR_MM"
)
60 61
@pytest.mark.skipif(get_device_count_by_fork("gpu") < 2, reason="need more gpu device")
@pytest.mark.isolated_distributed
62 63 64
def test_dist_grad():
    world_size = 2
    x_np = np.random.rand(10).astype("float32")
65 66 67 68 69 70 71 72 73 74

    @dist.launcher
    def worker():
        rank = dist.get_rank()
        if rank == 0:
            grad = Grad()

            x = as_tensor(x_np)
            grad.wrt(x, callback=save_to(x))
            # need a placeholder to trace operator
75
            remote_send(x, 1)
76 77 78 79 80 81 82 83 84
            recv_x = remote_recv(1, x_np.shape, x_np.dtype)
            y = recv_x * recv_x

            grad([y], [as_tensor(np.ones_like(x_np))])
            np.testing.assert_almost_equal(x.grad.numpy(), x.numpy() * 2)
        elif rank == 1:
            grad = Grad()

            recv_x = remote_recv(0, x_np.shape, x_np.dtype)
85
            remote_send(recv_x, 0)
86 87 88 89

            grad([], [])

    worker()
90

91

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
def test_grad():
    x_np = np.random.rand(10).astype("float32")
    x = as_tensor(x_np)

    grad = Grad().wrt(x, callback=save_to(x))

    y = cos(x)

    grad(y, as_tensor(np.ones_like(x_np)))
    np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np))


def test_grad_2():
    x_np = np.random.rand(10).astype("float32")
    x = as_tensor(x_np)

    grad = Grad().wrt(x, callback=save_to(x))

    y = mul(x, x)
    y = mul(y, y)

    grad(y, as_tensor(np.ones_like(x_np)))
    np.testing.assert_almost_equal(x.grad.numpy(), 4 * x_np ** 3, decimal=6)


@pytest.mark.skip(reason="high order gradient was not implemented yet")
def test_2nd_grad():
    x_np = np.random.rand(10).astype("float32")
    x = as_tensor(x_np)
    ones = as_tensor(np.ones_like(x_np))

    grad = Grad().wrt(x, callback=save_to(x))
    grad2 = Grad().wrt(x, callback=save_to(x))

    y = cos(x)

    grad(y, ones)
    np.testing.assert_almost_equal(x.grad.numpy(), -np.sin(x_np), decimal=5)

    grad2(x.grad, ones)
    np.testing.assert_almost_equal(x.grad.numpy(), -np.cos(x_np))


def test_grad_with_tensor_wrapper():
    x_np = np.random.rand(10).astype("float32")
137
    x = mge.Tensor(x_np)
138 139 140 141 142 143

    grad = Grad().wrt(x, callback=save_to(x))

    y = mul(x, x)
    y = mul(y, y)

144
    grad(y, mge.Tensor(np.ones_like(x_np)))
145 146 147
    np.testing.assert_almost_equal(x.grad.numpy(), 4 * x_np ** 3, decimal=6)


148 149 150 151
def test_release():
    def check(f):
        n = 0
        d = None
152 153 154 155 156 157 158 159 160 161
        gc.disable()
        try:
            for i in range(3):
                f()
                m = len(gc.get_objects())
                d = m - n
                n = m
            assert d == 0
        finally:
            gc.enable()
162

163 164
    x = mge.Tensor([0.0])
    dy = mge.Tensor(np.ones_like(x.numpy()))
165 166 167 168 169 170 171 172 173

    @check
    def _():
        g = Grad().wrt(x)
        y = x * x
        g(y, dy)

    @check
    def _():
174
        with Grad().wrt(x):
175 176 177 178
            pass

    @check
    def _():
179
        with Grad().wrt(x):
180 181 182
            y = x * x


183 184
def test_grad_inplace():
    x_np = np.random.rand(10).astype("float32")
185
    x = mge.Tensor(x_np)
186 187 188 189 190 191

    grad = Grad().wrt(x, callback=save_to(x))

    y = mul(x, x)
    y *= y

192
    grad(y, mge.Tensor(np.ones_like(x_np)))
193 194 195 196 197 198 199
    np.testing.assert_almost_equal(x.grad.numpy(), 4 * x_np ** 3, decimal=6)


def test_elemwise_add():
    x_np = np.random.rand(10).astype("float32")
    y_np = np.random.rand(10, 10).astype("float32")
    dz_np = np.random.rand(10, 10).astype("float32")
200 201 202
    x = mge.Tensor(x_np)
    y = mge.Tensor(y_np)
    dz = mge.Tensor(dz_np)
203 204 205 206 207

    refs = {}

    def f(x, y):
        x = x * 2
208 209
        refs["x"] = TensorWeakRef(x)
        refs["y"] = TensorWeakRef(y)
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        return x + y

    grad = Grad().wrt(x, callback=save_to(x))

    z = f(x, y)
    del y

    for k, r in refs.items():
        assert r() is None

    grad(z, dz)
    np.testing.assert_almost_equal(x.grad.numpy(), dz_np.sum(0) * 2, decimal=5)


def test_elemwise_relu():
    x_np = [1.0, -1.0]
    dz_np = [1.0]
227 228
    x = mge.Tensor(x_np)
    dz = mge.Tensor(dz_np)
229 230 231 232 233

    refs = {}

    def f(x):
        x = x * 2
234
        refs["x"] = TensorWeakRef(x)
235 236 237 238 239 240 241 242 243 244 245 246 247
        return relu(x)

    grad = Grad().wrt(x, callback=save_to(x))

    z = f(x)

    assert refs["x"]() is None

    grad(z, dz)
    np.testing.assert_almost_equal(x.grad.numpy(), [2.0, 0])


def test_elemwise_relu_backward_fn():
248
    op = Elemwise(Elemwise.Mode.RELU)
249 250 251 252 253 254
    attr = TensorAttr()
    attr.dtype = "float32"
    attr.comp_node = "xpux"
    result = imperative.make_backward_graph(op, [attr], [True], [True])
    backward_graph, save_for_backward_mask, input_has_grad = result
    assert save_for_backward_mask == [False, True, True], save_for_backward_mask
255 256 257 258


def test_reshape():
    x_np = np.random.rand(2, 5).astype("float32")
259
    x = mge.Tensor(x_np)
260 261

    grad = Grad().wrt(x, callback=save_to(x))
262 263 264 265 266 267 268 269 270 271 272 273

    refs = {}

    def f(x):
        x = x * 1
        y = x.reshape(5, 2)
        refs["x"] = TensorWeakRef(x)
        return y

    y = f(x)
    for _, r in refs.items():
        assert r() is None
274 275 276 277 278 279 280

    grad(y, F.ones_like(y))
    np.testing.assert_equal(np.ones((2, 5), dtype=np.float32), x.grad.numpy())


def test_subtensor():
    x_np = np.random.rand(3, 3).astype("float32")
281
    x = mge.Tensor(x_np)
282 283

    grad = Grad().wrt(x, callback=save_to(x))
284 285 286 287 288 289 290 291 292 293 294 295

    refs = {}

    def f(x):
        x = x * 1
        y = x[1:-1, :2]
        refs["x"] = TensorWeakRef(x)
        return y

    y = f(x)
    for _, r in refs.items():
        assert r() is None
296 297 298 299 300 301 302 303 304

    grad(y, F.ones_like(y))
    np.testing.assert_equal(
        np.array([[0, 0, 0], [1, 1, 0], [0, 0, 0]], dtype=np.float32), x.grad.numpy()
    )


def test_IndexingMultiAxisVec():
    x_np = np.random.rand(3, 3).astype("float32")
305
    x = mge.Tensor(x_np)
306 307

    grad = Grad().wrt(x, callback=save_to(x))
308 309 310 311 312 313 314 315 316 317 318 319

    refs = {}

    def f(x):
        x = x * 1
        y = x[[0, 2], [0, 2]]
        refs["x"] = TensorWeakRef(x)
        return y

    y = f(x)
    for _, r in refs.items():
        assert r() is None
320 321 322 323 324 325 326 327 328

    grad(y, F.ones_like(y))
    np.testing.assert_equal(
        np.array([[1, 0, 0], [0, 0, 0], [0, 0, 1]], dtype=np.float32), x.grad.numpy()
    )


def test_AxisAddRemove():
    x_np = np.random.rand(1, 5).astype("float32")
329
    x = mge.Tensor(x_np)
330 331

    grad = Grad().wrt(x, callback=save_to(x))
332 333 334 335 336 337 338 339 340 341 342 343

    refs = {}

    def f(x):
        x = x * 1
        y = F.squeeze(F.expand_dims(x, 2), 0)
        refs["x"] = TensorWeakRef(x)
        return y

    y = f(x)
    for _, r in refs.items():
        assert r() is None
344 345 346 347 348 349 350 351 352

    grad(y, F.ones_like(y))
    np.testing.assert_equal(
        np.array([[1, 1, 1, 1, 1]], dtype=np.float32), x.grad.numpy()
    )


def test_Broadcast():
    x_np = np.random.rand(3, 3, 1).astype("float32")
353
    x = mge.Tensor(x_np)
354 355

    grad = Grad().wrt(x, callback=save_to(x))
356
    y = F.broadcast_to(x, (3, 3, 10))
357 358 359 360 361 362 363

    grad(y, F.ones_like(y))
    np.testing.assert_equal(np.ones((3, 3, 1), dtype=np.float32) * 10, x.grad.numpy())


def test_Reduce_sum():
    x_np = np.random.rand(3, 3).astype("float32")
364
    x = mge.Tensor(x_np)
365 366 367 368 369 370 371 372 373 374

    grad = Grad().wrt(x, callback=save_to(x))
    y = x.sum(axis=0)

    grad(y, F.ones_like(y))
    np.testing.assert_equal(np.ones((3, 3), dtype=np.float32), x.grad.numpy())


def test_Reduce_mean():
    x_np = np.random.rand(3, 3).astype("float32")
375
    x = mge.Tensor(x_np)
376 377 378 379 380 381

    grad = Grad().wrt(x, callback=save_to(x))
    y = x.mean(axis=0)

    grad(y, F.ones_like(y))
    np.testing.assert_equal(np.ones((3, 3), dtype=np.float32) / 3, x.grad.numpy())
382 383 384 385 386 387 388


def test_addAxis():
    x_np = np.random.rand(3, 3).astype("float32")
    x = mge.Tensor(x_np)

    grad = Grad().wrt(x, callback=save_to(x))
389 390 391 392 393 394 395 396 397 398 399 400

    refs = {}

    def f(x):
        x = x * 1
        y = F.expand_dims(x, [2, 3])
        refs["x"] = TensorWeakRef(x)
        return y

    y = f(x)
    for _, r in refs.items():
        assert r() is None
401 402 403 404 405 406 407 408 409 410

    grad(y, F.ones_like(y))
    np.testing.assert_equal(np.ones((3, 3), dtype=np.float32), x.grad.numpy())


def test_removeAxis():
    x_np = np.random.rand(3, 3, 1, 1).astype("float32")
    x = mge.Tensor(x_np)

    grad = Grad().wrt(x, callback=save_to(x))
411 412 413 414 415 416 417 418 419 420 421 422

    refs = {}

    def f(x):
        x = x * 1
        y = F.squeeze(x, [2, 3])
        refs["x"] = TensorWeakRef(x)
        return y

    y = f(x)
    for _, r in refs.items():
        assert r() is None
423 424 425

    grad(y, F.ones_like(y))
    np.testing.assert_equal(np.ones((3, 3, 1, 1), dtype=np.float32), x.grad.numpy())