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_allreduce_fusion.py 8.6 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. import numpy as np
  15. import mindspore as ms
  16. import mindspore.nn as nn
  17. from mindspore import Tensor, context
  18. from mindspore.common.api import _cell_graph_executor
  19. from mindspore.nn import TrainOneStepCell, WithLossCell
  20. from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
  21. from mindspore.nn.optim import Lamb
  22. from mindspore.nn.optim.momentum import Momentum
  23. from mindspore.ops import operations as P
  24. from mindspore.parallel import _cost_model_context as cost_model_context
  25. from mindspore.parallel._auto_parallel_context import auto_parallel_context
  26. from mindspore.train import Model
  27. from mindspore.context import ParallelMode
  28. from tests.dataset_mock import MindData
  29. context.set_context(mode=context.PYNATIVE_MODE, save_graphs=True)
  30. class Net(nn.Cell):
  31. """Net definition"""
  32. def __init__(self):
  33. super(Net, self).__init__()
  34. self.fc1 = nn.Dense(128, 768, activation='relu')
  35. self.fc2 = nn.Dense(128, 768, activation='relu')
  36. self.fc3 = nn.Dense(128, 768, activation='relu')
  37. self.fc4 = nn.Dense(768, 768, activation='relu')
  38. self.relu4 = nn.ReLU()
  39. self.relu5 = nn.ReLU()
  40. self.transpose = P.Transpose()
  41. self.matmul1 = P.MatMul()
  42. self.matmul2 = P.MatMul()
  43. def construct(self, x):
  44. q = self.fc1(x)
  45. k = self.fc2(x)
  46. v = self.fc3(x)
  47. k = self.transpose(k, (1, 0))
  48. c = self.relu4(self.matmul1(q, k))
  49. s = self.relu5(self.matmul2(c, v))
  50. s = self.fc4(s)
  51. return s
  52. class Dataset(MindData):
  53. def __init__(self, predict, label, length=3):
  54. super(Dataset, self).__init__(size=length)
  55. self.predict = predict
  56. self.label = label
  57. self.index = 0
  58. self.length = length
  59. def __iter__(self):
  60. return self
  61. def __next__(self):
  62. if self.index >= self.length:
  63. raise StopIteration
  64. self.index += 1
  65. return self.predict, self.label
  66. def reset(self):
  67. self.index = 0
  68. class DenseNet1(nn.Cell):
  69. def __init__(self, has_bias=True, activation='relu'):
  70. super(DenseNet1, self).__init__()
  71. self.fc1 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  72. self.fc2 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  73. self.fc3 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  74. self.fc4 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  75. def construct(self, x):
  76. q = self.fc1(x)
  77. k = self.fc2(q)
  78. v = self.fc3(k)
  79. s = self.fc4(v)
  80. return s
  81. class DenseNet2(nn.Cell):
  82. def __init__(self, has_bias=True, activation='relu'):
  83. super(DenseNet2, self).__init__()
  84. self.fc1 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  85. self.fc2 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  86. self.fc3 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  87. self.fc4 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  88. self.fc5 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  89. self.fc6 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  90. self.fc7 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  91. self.fc8 = nn.Dense(128, 128, has_bias=has_bias, activation=activation)
  92. def construct(self, x):
  93. q = self.fc1(x)
  94. k = self.fc2(q)
  95. v = self.fc3(k)
  96. s = self.fc4(v)
  97. t = self.fc5(s)
  98. u = self.fc6(t)
  99. w = self.fc7(u)
  100. z = self.fc8(w)
  101. return z
  102. class SimpleDMLNet(nn.Cell):
  103. def __init__(self, net1, net2):
  104. super(SimpleDMLNet, self).__init__()
  105. self.backbone1 = net1
  106. self.backbone2 = net2
  107. def construct(self, x):
  108. x1 = self.backbone1(x)
  109. x2 = self.backbone2(x)
  110. return x1 + x2
  111. def train_common(net):
  112. batch_size = 32
  113. learning_rate = 0.1
  114. momentum = 0.9
  115. epoch_size = 2
  116. device_num = 4
  117. context.set_auto_parallel_context(device_num=device_num, parameter_broadcast=False)
  118. context.set_context(mode=context.GRAPH_MODE)
  119. predict = Tensor(np.ones([batch_size, 128]), dtype=ms.float32)
  120. label = Tensor(np.ones([batch_size]), dtype=ms.int32)
  121. dataset = Dataset(predict, label, 2)
  122. loss = SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  123. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  124. model = Model(net, loss, opt)
  125. model.train(epoch_size, dataset, dataset_sink_mode=False)
  126. allreduce_fusion_dict = _cell_graph_executor._get_allreduce_fusion(model._train_network)
  127. print(allreduce_fusion_dict)
  128. return allreduce_fusion_dict
  129. def test_allreduce_fusion_auto():
  130. """
  131. Feature: test_allreduce_fusion in auto mode
  132. Description: allreduce fusion in auto mode
  133. Expectation: success
  134. """
  135. comm_fusion_dict = {"allreduce": {"mode": "auto", "config": None}}
  136. context.set_auto_parallel_context(parallel_mode=ParallelMode.SEMI_AUTO_PARALLEL, comm_fusion=comm_fusion_dict)
  137. net = SimpleDMLNet(DenseNet1(has_bias=False, activation=None), DenseNet2(has_bias=False, activation=None))
  138. allreduce_fusion_dict = train_common(net)
  139. expect_dict = {'backbone2.fc8.weight': 1,
  140. 'backbone2.fc7.weight': 1,
  141. 'backbone2.fc6.weight': 1,
  142. 'backbone1.fc4.weight': 1,
  143. 'backbone1.fc3.weight': 1,
  144. 'backbone1.fc2.weight': 1,
  145. 'backbone2.fc5.weight': 1,
  146. 'backbone2.fc4.weight': 1,
  147. 'backbone2.fc3.weight': 1,
  148. 'backbone2.fc2.weight': 1,
  149. 'backbone2.fc1.weight': 1,
  150. 'backbone1.fc1.weight': 1}
  151. assert allreduce_fusion_dict == expect_dict
  152. cost_model_context.reset_cost_model_context()
  153. def test_allreduce_fusion_size():
  154. """
  155. Feature: test_allreduce_fusion in size mode
  156. Description: allreduce fusion in size mode
  157. Expectation: success
  158. """
  159. comm_fusion_dict = {"allreduce": {"mode": "size", "config": 32}}
  160. context.set_auto_parallel_context(parallel_mode=ParallelMode.SEMI_AUTO_PARALLEL, comm_fusion=comm_fusion_dict)
  161. net = SimpleDMLNet(DenseNet1(has_bias=False, activation=None), DenseNet2(has_bias=False, activation=None))
  162. allreduce_fusion_dict = train_common(net)
  163. expect_dict = {'backbone2.fc8.weight': 1,
  164. 'backbone2.fc7.weight': 1,
  165. 'backbone2.fc6.weight': 1,
  166. 'backbone1.fc4.weight': 1,
  167. 'backbone1.fc3.weight': 1,
  168. 'backbone1.fc2.weight': 1,
  169. 'backbone2.fc5.weight': 1,
  170. 'backbone2.fc4.weight': 1,
  171. 'backbone2.fc3.weight': 1,
  172. 'backbone2.fc2.weight': 1,
  173. 'backbone2.fc1.weight': 1,
  174. 'backbone1.fc1.weight': 1}
  175. assert allreduce_fusion_dict == expect_dict
  176. cost_model_context.reset_cost_model_context()
  177. comm_fusion = auto_parallel_context().get_comm_fusion()
  178. assert comm_fusion_dict == comm_fusion
  179. def test_lamb_split_fusion_in_index():
  180. """
  181. Feature: test_allreduce_fusion in index mode
  182. Description: allreduce fusion in index mode
  183. Expectation: success
  184. """
  185. comm_fusion_dict = {"allreduce": {"mode": "index", "config": [2, 4, 6, 8]}}
  186. context.set_auto_parallel_context(parallel_mode="data_parallel", device_num=2, enable_parallel_optimizer=True,
  187. comm_fusion=comm_fusion_dict)
  188. inputs = Tensor(np.ones([32, 128]).astype(np.float32))
  189. label = Tensor(np.zeros([32, 768]).astype(np.float32))
  190. net = Net()
  191. net.set_train()
  192. loss = nn.SoftmaxCrossEntropyWithLogits()
  193. optimizer = Lamb(net.trainable_params(), learning_rate=0.1)
  194. net_with_loss = WithLossCell(net, loss)
  195. train_network = TrainOneStepCell(net_with_loss, optimizer)
  196. _cell_graph_executor.compile(train_network, inputs, label)
  197. context.reset_auto_parallel_context()