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_clip_grad.py 2.4 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. import platform
  9. import weakref
  10. import numpy as np
  11. import pytest
  12. import megengine as mge
  13. import megengine.autodiff as ad
  14. import megengine.functional as F
  15. import megengine.module as M
  16. import megengine.optimizer as optim
  17. class Net(M.Module):
  18. def __init__(self):
  19. super().__init__()
  20. self.conv1 = M.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
  21. self.bn1 = M.BatchNorm2d(64)
  22. self.avgpool = M.AvgPool2d(kernel_size=5, stride=5, padding=0)
  23. self.fc = M.Linear(64, 10)
  24. def forward(self, x):
  25. x = self.conv1(x)
  26. x = self.bn1(x)
  27. x = F.relu(x)
  28. x = self.avgpool(x)
  29. x = F.avg_pool2d(x, 22)
  30. x = F.flatten(x, 1)
  31. x = self.fc(x)
  32. return x
  33. def save_grad_value(net):
  34. for param in net.parameters():
  35. param.grad_backup = param.grad.numpy().copy()
  36. def test_clip_grad_norm():
  37. net = Net()
  38. x = mge.tensor(np.random.randn(10, 3, 224, 224))
  39. gm = ad.GradManager().attach(net.parameters())
  40. opt = optim.SGD(net.parameters(), 1e-3, momentum=0.9)
  41. with gm:
  42. loss = net(x).sum()
  43. gm.backward(loss)
  44. save_grad_value(net)
  45. max_norm = 1.0
  46. original_norm = optim.clip_grad_norm(net.parameters(), max_norm=max_norm, ord=2)
  47. scale = max_norm / original_norm
  48. for param in net.parameters():
  49. np.testing.assert_almost_equal(param.grad.numpy(), param.grad_backup * scale)
  50. opt.step().clear_grad()
  51. def test_clip_grad_value():
  52. net = Net()
  53. x = np.random.randn(10, 3, 224, 224).astype("float32")
  54. gm = ad.GradManager().attach(net.parameters())
  55. opt = optim.SGD(net.parameters(), 1e-3, momentum=0.9)
  56. with gm:
  57. y = net(x)
  58. y = y.mean()
  59. gm.backward(y)
  60. save_grad_value(net)
  61. max_val = 5
  62. min_val = -2
  63. optim.clip_grad_value(net.parameters(), lower=min_val, upper=max_val)
  64. for param in net.parameters():
  65. np.testing.assert_almost_equal(
  66. param.grad.numpy(),
  67. np.maximum(np.minimum(param.grad_backup, max_val), min_val),
  68. )
  69. opt.step().clear_grad()

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