You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_pytorch.py 2.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import numpy as np
  10. import torch
  11. from helpers import randomTorch
  12. import megengine as mge
  13. import megengine._internal as mgb
  14. import megengine.functional
  15. from megengine import get_default_device, set_default_device
  16. from megengine.core import Parameter, tensor
  17. from megengine.module.pytorch import PyTorchModule
  18. from megengine.test import assertTensorClose
  19. def test_pytorch_forward():
  20. class APlusB(torch.nn.Module):
  21. def __init__(self):
  22. super(APlusB, self).__init__()
  23. def forward(self, a, b):
  24. return a + b
  25. a = randomTorch(15, 15)
  26. b = randomTorch(15, 15)
  27. def get_pytorch_forward():
  28. return APlusB()(a, b)
  29. def get_mge_forward():
  30. mge_module = PyTorchModule(APlusB())
  31. mge_a = tensor(a.numpy(), dtype=np.float32)
  32. mge_b = tensor(b.numpy(), dtype=np.float32)
  33. return mge_module(mge_a, mge_b)
  34. assertTensorClose(get_pytorch_forward().numpy(), get_mge_forward().numpy())
  35. def test_pytorch_backward():
  36. class APlusB(torch.nn.Module):
  37. def __init__(self):
  38. super(APlusB, self).__init__()
  39. def forward(self, a, b):
  40. return a + b
  41. a = randomTorch(15, 15)
  42. b = randomTorch(15, 15)
  43. def get_pytorch_backward():
  44. parameter_a = a.clone()
  45. parameter_a.requires_grad = True
  46. c = APlusB()(parameter_a, b)
  47. d = APlusB()(c, b)
  48. e = torch.sum(d)
  49. e.backward()
  50. return parameter_a.grad
  51. def get_mge_backward():
  52. mge_module = PyTorchModule(APlusB())
  53. mge_a = Parameter(a.numpy(), dtype=np.float32)
  54. mge_b = tensor(b.numpy(), dtype=np.float32)
  55. mge_c = mge_module(mge_a, mge_b)
  56. mge_d = mge_module(mge_c, mge_b)
  57. mge_e = mge.functional.sum(mge_d)
  58. return mge.functional.grad(mge_e, mge_a, use_virtual_grad=False)
  59. assertTensorClose(get_pytorch_backward().numpy(), get_mge_backward().numpy())

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台

Contributors (1)