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_matmul_dropout.py 4.5 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # Copyright 2019 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. import numpy as np
  15. import mindspore as ms
  16. import mindspore.nn as nn
  17. from mindspore import Tensor
  18. from mindspore import context
  19. import mindspore.common.dtype as mstype
  20. from mindspore.common.seed import _get_graph_seed
  21. from mindspore.common.api import _executor
  22. from mindspore._checkparam import Validator
  23. from mindspore.ops.primitive import constexpr
  24. from mindspore.ops import composite as C
  25. from mindspore.ops import operations as P
  26. from tests.ut.python.ops.test_math_ops import VirtualLoss
  27. grad_all = C.GradOperation(get_all=True)
  28. class NetWithLoss(nn.Cell):
  29. def __init__(self, network):
  30. super(NetWithLoss, self).__init__()
  31. self.loss = VirtualLoss()
  32. self.network = network
  33. def construct(self, x, y, b):
  34. predict = self.network(x, y, b)
  35. return self.loss(predict)
  36. class GradWrap(nn.Cell):
  37. def __init__(self, network):
  38. super(GradWrap, self).__init__()
  39. self.network = network
  40. def construct(self, x, y, b):
  41. return grad_all(self.network)(x, y, b)
  42. @constexpr
  43. def _is_float_dtype(dtype):
  44. if dtype in [mstype.float32, mstype.float16]:
  45. return True
  46. return False
  47. class Dropout(nn.Cell):
  48. def __init__(self, keep_prob=0.5, dtype=mstype.float32):
  49. super(Dropout, self).__init__()
  50. if keep_prob <= 0 or keep_prob > 1:
  51. raise ValueError("dropout probability should be a number in range (0, 1], but got {}".format(keep_prob))
  52. Validator.check_subclass("dtype", dtype, mstype.number_type, self.cls_name)
  53. Validator.check_value_type('keep_prob', keep_prob, [float], self.cls_name)
  54. self.keep_prob = keep_prob
  55. seed0, seed1 = _get_graph_seed(0, "dropout")
  56. self.seed0 = seed0
  57. self.seed1 = seed1
  58. self.dtype = dtype
  59. self.get_shape = P.Shape()
  60. self.dropout_gen_mask = P.DropoutGenMask(Seed0=self.seed0, Seed1=self.seed1)
  61. self.dropout_do_mask = P.DropoutDoMask()
  62. self.cast = P.Cast()
  63. self.is_gpu = context.get_context('device_target') in ["GPU"]
  64. self.dropout = P.Dropout(keep_prob)
  65. def construct(self, x):
  66. if not self.training:
  67. return x
  68. if self.is_gpu:
  69. out, _ = self.dropout(x)
  70. return out
  71. if self.keep_prob == 1:
  72. return x
  73. shape = self.get_shape(x)
  74. dtype = P.DType()(x)
  75. if _is_float_dtype(dtype):
  76. keep_prob = self.cast(self.keep_prob, dtype)
  77. else:
  78. keep_prob = self.cast(self.keep_prob, mstype.float16)
  79. output = self.dropout_gen_mask(shape, keep_prob)
  80. return self.dropout_do_mask(x, output, keep_prob)
  81. def extend_repr(self):
  82. return 'keep_prob={}, dtype={}'.format(self.keep_prob, self.dtype)
  83. # model_parallel test
  84. def test_two_matmul_dropout():
  85. class Net(nn.Cell):
  86. def __init__(self, strategy1, strategy2, strategy3):
  87. super().__init__()
  88. self.matmul1 = P.MatMul().shard(strategy1)
  89. self.dropout = Dropout()
  90. self.dropout.dropout_do_mask.shard(strategy2)
  91. self.dropout.dropout_gen_mask.shard(strategy2)
  92. self.matmul2 = P.MatMul().shard(strategy3)
  93. def construct(self, x, y, b):
  94. out = self.matmul1(x, y)
  95. out = self.dropout(out)
  96. out = self.matmul2(out, b)
  97. return out
  98. context.set_auto_parallel_context(device_num=8, global_rank=0)
  99. strategy1 = ((4, 2), (2, 1))
  100. strategy2 = ((8, 1),)
  101. strategy3 = ((1, 8), (8, 1))
  102. net = GradWrap(NetWithLoss(Net(strategy1, strategy2, strategy3)))
  103. context.set_auto_parallel_context(parallel_mode="semi_auto_parallel")
  104. net.set_auto_parallel()
  105. x = Tensor(np.ones([128, 32]), dtype=ms.float32)
  106. y = Tensor(np.ones([32, 64]), dtype=ms.float32)
  107. b = Tensor(np.ones([64, 64]), dtype=ms.float32)
  108. net.set_train()
  109. _executor.compile(net, x, y, b)