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_param_pack.py 2.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 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 platform
  10. import numpy as np
  11. import pytest
  12. import megengine
  13. import megengine.autodiff as ad
  14. import megengine.distributed as dist
  15. import megengine.optimizer as optimizer
  16. from megengine import Parameter, tensor
  17. from megengine.module import Module
  18. from megengine.optimizer import SGD
  19. class Simple(Module):
  20. def __init__(self, param_shape):
  21. super().__init__()
  22. self.params = [
  23. Parameter(np.ones(param_shape), dtype=np.float32) for i in range(10)
  24. ]
  25. def forward(self, x):
  26. for p in self.params:
  27. x = x * p
  28. return x
  29. @pytest.mark.require_ngpu(2)
  30. @pytest.mark.isolated_distributed
  31. @pytest.mark.parametrize(
  32. "threshold", [0, 128, None], ids=["no_pack", "small_pack", "large_pack"]
  33. )
  34. @pytest.mark.parametrize("param_shape", [(16,), (128, 256), (2, 1024, 1024)])
  35. def test_param_pack(param_shape, threshold, n_iters=100):
  36. data = np.ones(param_shape, dtype="float32")
  37. @dist.launcher(n_gpus=2)
  38. def worker():
  39. net = Simple(param_shape)
  40. opt = SGD(net.parameters(), lr=0.1)
  41. allreduce_cb = dist.make_allreduce_cb("MEAN", dist.WORLD)
  42. if threshold is not None:
  43. allreduce_cb._param_pack_thd = threshold
  44. gm = ad.GradManager().attach(net.parameters(), callbacks=[allreduce_cb])
  45. def run():
  46. opt.clear_grad()
  47. with gm:
  48. x = tensor(data)
  49. loss = net(x)
  50. loss = loss.sum()
  51. gm.backward(loss)
  52. for i in range(n_iters):
  53. run()
  54. for p in net.params:
  55. np.testing.assert_equal(p.grad.numpy(), np.ones_like(p.grad.numpy()))
  56. worker()