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_sparse_feature_bprop.py 4.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """ test sparse feature bprop """
  16. import numpy as np
  17. import mindspore as ms
  18. import mindspore.nn as nn
  19. from mindspore import context
  20. from mindspore.common import dtype as mstype
  21. from mindspore.common.tensor import Tensor
  22. from mindspore.ops import composite as C
  23. from mindspore.ops.operations.comm_ops import AllReduce, _MirrorOperator
  24. from mindspore.ops._grad.grad_base import bprop_getters
  25. from mindspore._checkparam import Validator as validator
  26. from mindspore._checkparam import Rel
  27. from mindspore.ops.primitive import prim_attr_register, PrimitiveWithInfer
  28. from mindspore.common.api import _executor
  29. from mindspore.communication.management import HCCL_WORLD_COMM_GROUP
  30. class GradWrap(nn.Cell):
  31. def __init__(self, network):
  32. super(GradWrap, self).__init__()
  33. self.network = network
  34. def construct(self, x):
  35. return C.grad_all(self.network)(x)
  36. class VirtualGatherV2(PrimitiveWithInfer):
  37. @prim_attr_register
  38. def __init__(self):
  39. """init index_select"""
  40. super(VirtualGatherV2, self).__init__('VirtualGatherV2')
  41. self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output'])
  42. def __infer__(self, params, indices, axis):
  43. validator.check_subclass("params", params['dtype'], mstype.tensor, self.name)
  44. validator.check_tensor_type_same({"indices": indices['dtype']}, mstype.int_type, self.name)
  45. validator.check_subclass("axis", axis['dtype'], mstype.int_, self.name)
  46. axis_v = axis['value']
  47. params_shp = params['shape']
  48. rank = len(params_shp)
  49. validator.check_int_range("axis", axis_v, -rank, rank, Rel.INC_LEFT, self.name)
  50. if axis_v < 0:
  51. axis_v += rank
  52. out_shape = params_shp[:axis_v] + indices['shape'] + params_shp[axis_v + 1:]
  53. out = {'shape': out_shape,
  54. 'dtype': params['dtype'],
  55. 'value': None}
  56. return out
  57. @bprop_getters.register(VirtualGatherV2)
  58. def get_bprop_gather_v2(self):
  59. """Generate bprop for GatherV2"""
  60. def bprop(x, indices, axis, out, dout):
  61. return (indices, dout, x), axis, out
  62. return bprop
  63. def test_bprop_with_sparse_feature_allreduce():
  64. context.set_auto_parallel_context(device_num=8, global_rank=0, parallel_mode="hybrid_parallel")
  65. class Net(nn.Cell):
  66. def __init__(self, axis=0, shape=None):
  67. super(Net, self).__init__()
  68. if shape is None:
  69. shape = [8, 8]
  70. self.all_reduce = AllReduce()
  71. self.gatherv2 = VirtualGatherV2()
  72. self.index = Tensor(np.ones(shape), dtype=ms.int32)
  73. self.axis = axis
  74. def construct(self, x):
  75. out = self.all_reduce(x)
  76. out = self.gatherv2(out, self.index, self.axis)
  77. return out
  78. net = GradWrap(Net())
  79. x = Tensor(np.ones([64, 64]), dtype=ms.float32)
  80. _executor.compile(net, x)
  81. def test_bprop_with_sparse_feature_mirror():
  82. context.set_auto_parallel_context(device_num=8, global_rank=0, parallel_mode="hybrid_parallel")
  83. class Net(nn.Cell):
  84. def __init__(self, axis=0, shape=None):
  85. super(Net, self).__init__()
  86. if shape is None:
  87. shape = [8, 8]
  88. self.mirror = _MirrorOperator(group=HCCL_WORLD_COMM_GROUP)
  89. self.gatherv2 = VirtualGatherV2()
  90. self.index = Tensor(np.ones(shape), dtype=ms.int32)
  91. self.axis = axis
  92. def construct(self, x):
  93. out = self.mirror(x)
  94. out = self.gatherv2(out, self.index, self.axis)
  95. return out
  96. net = GradWrap(Net())
  97. x = Tensor(np.ones([64, 64]), dtype=ms.float32)
  98. _executor.compile(net, x)