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_row_tensor.py 18 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. """
  16. @File : test_row_tensor.py
  17. @Author:
  18. @Date : 2020-06-08
  19. @Desc : test mindspore row_tensor's operation
  20. """
  21. import numpy as np
  22. import pytest
  23. import mindspore as ms
  24. import mindspore.nn as nn
  25. from mindspore.ops import composite as C
  26. from mindspore.ops import functional as F
  27. from mindspore.ops import operations as P
  28. from mindspore.ops.composite.multitype_ops.zeros_like_impl import zeros_like
  29. from mindspore.ops.primitive import constexpr, PrimitiveWithInfer, prim_attr_register
  30. from mindspore.ops._grad.grad_base import bprop_getters
  31. from mindspore import Tensor, RowTensor, context
  32. from mindspore.common.parameter import Parameter, ParameterTuple
  33. from mindspore.common import dtype as mstype
  34. from mindspore._checkparam import Validator as validator
  35. from mindspore._checkparam import Rel
  36. from mindspore.nn import Optimizer
  37. from mindspore.nn import TrainOneStepCell, WithLossCell
  38. from mindspore.nn.optim import Momentum
  39. from mindspore.train import Model
  40. from ....dataset_mock import MindData
  41. context.set_context(mode=context.GRAPH_MODE, enable_sparse=True)
  42. reduce_sum = P.ReduceSum()
  43. unsorted_segment_sum = P.UnsortedSegmentSum()
  44. transpose = P.Transpose()
  45. shape_op = P.Shape()
  46. reshape = P.Reshape()
  47. size_op = P.Size()
  48. invert_permutation = P.InvertPermutation()
  49. logical_and = P.LogicalAnd()
  50. def get_axis(x):
  51. shape = shape_op(x)
  52. length = F.tuple_len(shape)
  53. perm = F.make_range(0, length)
  54. return perm
  55. class MSELoss(nn.Cell):
  56. def __init__(self):
  57. super(MSELoss, self).__init__()
  58. self.reduce_sum = P.ReduceSum()
  59. self.square = P.Square()
  60. self.reduce_mean = P.ReduceMean()
  61. def construct(self, data, label):
  62. diff = data - label
  63. return self.reduce_mean(self.square(diff), get_axis(diff))
  64. class MindDataSet(MindData):
  65. def __init__(self, dataset_types, dataset_shapes):
  66. super(MindDataSet, self).__init__(size=2, batch_size=32,
  67. np_types=dataset_types,
  68. output_shapes=dataset_shapes,
  69. input_indexs=(0, 1))
  70. def __next__(self):
  71. if self._size < self._iter_num:
  72. raise StopIteration
  73. self._iter_num += 1
  74. lst = []
  75. for shape_, type_ in zip(self._output_shapes, self._np_types):
  76. lst.append(Tensor(np.ones(shape_).astype(type_)))
  77. return tuple(lst)
  78. @constexpr
  79. def _generate_shape_index(out_shape, indices_shape, axis):
  80. out_rank = len(out_shape)
  81. ind_rank = len(indices_shape)
  82. if axis < 0:
  83. axis += out_rank - ind_rank + 1
  84. perm_part1 = tuple(range(axis, axis + ind_rank))
  85. index = tuple(range(out_rank))
  86. perm = perm_part1 + index[:axis] + index[axis + ind_rank:]
  87. return perm
  88. @constexpr
  89. def _generate_inverse_index(x_shape, axis):
  90. x_rank = len(x_shape)
  91. index = tuple(range(x_rank))
  92. if axis < 0:
  93. axis += x_rank
  94. perm = index[1:1 + axis] + (0,) + index[1 + axis:]
  95. return perm
  96. # pylint: disable=W0231
  97. class MySparseGatherV2(PrimitiveWithInfer):
  98. """
  99. For test
  100. """
  101. @prim_attr_register
  102. def __init__(self):
  103. """init index_select"""
  104. self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output'])
  105. def __infer__(self, params, indices, axis):
  106. validator.check_subclass("params", params['dtype'], mstype.tensor, self.name)
  107. validator.check_tensor_type_same({"indices": indices['dtype']}, mstype.int_type, self.name)
  108. validator.check_subclass("axis", axis['dtype'], mstype.int_, self.name)
  109. axis_v = axis['value']
  110. params_shp = params['shape']
  111. rank = len(params_shp)
  112. validator.check_int_range("axis", axis_v, -rank, rank, Rel.INC_LEFT, self.name)
  113. if axis_v < 0:
  114. axis_v += rank
  115. out_shape = params_shp[:axis_v] + indices['shape'] + params_shp[axis_v + 1:]
  116. out = {'shape': out_shape,
  117. 'dtype': params['dtype'],
  118. 'value': None}
  119. return out
  120. @bprop_getters.register(MySparseGatherV2)
  121. def get_bprop_sparse_gather_v2(self):
  122. """Generate bprop for MySparseGatherV2"""
  123. def bprop(x, indices, axis, out, dout):
  124. x_shp = shape_op(x)
  125. if axis == 0:
  126. indices_size = (size_op(indices),)
  127. x_tail_shp = x_shp[1:]
  128. values_shape = indices_size + x_tail_shp
  129. values = reshape(dout, values_shape)
  130. indices = reshape(indices, indices_size)
  131. return RowTensor(indices, values, x_shp), zeros_like(indices), zeros_like(axis)
  132. if F.rank(dout) == 0:
  133. dout = P.ExpandDims()(dout, -1)
  134. if F.rank(indices) == 0:
  135. indices = P.ExpandDims()(indices, -1)
  136. out_shp = shape_op(dout)
  137. ind_shp = shape_op(indices)
  138. # Example: out_shape:(3,2,3) axis 1 -> (1,0,2)
  139. perm_1 = _generate_shape_index(out_shp, ind_shp, axis)
  140. values_transpose = transpose(dout, perm_1)
  141. params_grad = unsorted_segment_sum(values_transpose, indices, shape_op(x)[axis])
  142. # Example: out_shape:(3,2,3) axis 2 -> (1,2,0)
  143. perm_2 = _generate_inverse_index(x_shp, axis)
  144. params_grad = transpose(params_grad, perm_2)
  145. return params_grad, zeros_like(indices), zeros_like(axis)
  146. return bprop
  147. adam_opt_for_map = C.MultitypeFuncGraph("adam_opt_for_map")
  148. @adam_opt_for_map.register("Tensor", "Tensor", "Tensor", "Tensor", "Tensor",
  149. "Tensor", "Tensor", "Tensor", "RowTensor", "Bool")
  150. def _update_run_op_for_map_row_tensor(beta1, beta2, eps, lr, weight_decay_tensor, param,
  151. m, v, gradient, decay_flag):
  152. return gradient.values
  153. @adam_opt_for_map.register("Tensor", "Tensor", "Tensor", "Tensor", "Tensor",
  154. "Tensor", "Tensor", "Tensor", "Tensor", "Bool")
  155. def _update_run_op_for_map_tensor(beta1, beta2, eps, lr, weight_decay_tensor, param,
  156. m, v, gradient, decay_flag):
  157. op_mul = P.Mul()
  158. op_square = P.Square()
  159. op_sqrt = P.Sqrt()
  160. op_cast = P.Cast()
  161. op_reshape = P.Reshape()
  162. op_shape = P.Shape()
  163. param_fp32 = op_cast(param, mstype.float32)
  164. m_fp32 = op_cast(m, mstype.float32)
  165. v_fp32 = op_cast(v, mstype.float32)
  166. gradient_fp32 = op_cast(gradient, mstype.float32)
  167. next_m = op_mul(beta1, m_fp32) + op_mul(op_cast(F.tuple_to_array((1.0,)), mstype.float32) - beta1, gradient_fp32)
  168. next_v = op_mul(beta2, v_fp32) + op_mul(op_cast(F.tuple_to_array((1.0,)), mstype.float32)
  169. - beta2, op_square(gradient_fp32))
  170. update = next_m / (op_sqrt(next_v) + eps)
  171. if decay_flag:
  172. update = update + op_mul(weight_decay_tensor, param_fp32)
  173. update_with_lr = op_mul(lr, update)
  174. next_param = param_fp32 - op_reshape(update_with_lr, op_shape(param_fp32))
  175. next_v = F.depend(next_v, F.assign(param, next_param))
  176. next_v = F.depend(next_v, F.assign(m, next_m))
  177. next_v = F.depend(next_v, F.assign(v, next_v))
  178. return next_v
  179. def _check_param_value(beta1, beta2, eps, weight_decay, prim_name):
  180. """Check the type of inputs."""
  181. validator.check_value_type("beta1", beta1, [float], prim_name)
  182. validator.check_value_type("beta2", beta2, [float], prim_name)
  183. validator.check_value_type("eps", eps, [float], prim_name)
  184. validator.check_value_type("weight_dacay", weight_decay, [float], prim_name)
  185. validator.check_number_range("beta1", beta1, 0.0, 1.0, Rel.INC_NEITHER, prim_name)
  186. validator.check_number_range("beta2", beta2, 0.0, 1.0, Rel.INC_NEITHER, prim_name)
  187. validator.check_number_range("eps", eps, 0.0, float("inf"), Rel.INC_NEITHER, prim_name)
  188. validator.check_number_range("weight_decay", weight_decay, 0.0, float("inf"), Rel.INC_LEFT, prim_name)
  189. class AdamWeightDecaySparse(Optimizer):
  190. def __init__(self, params, learning_rate=1e-3, beta1=0.9, beta2=0.999, eps=1e-6, weight_decay=0.0,
  191. decay_filter=lambda x: 'beta' not in x.name and 'gamma' not in x.name):
  192. super(AdamWeightDecaySparse, self).__init__(learning_rate, params)
  193. if self.is_group:
  194. raise RuntimeError(f"The {self.cls_name} optimizer cannot support group setting.")
  195. _check_param_value(beta1, beta2, eps, weight_decay, self.cls_name)
  196. self.beta1 = Tensor(np.array([beta1]).astype(np.float32))
  197. self.beta2 = Tensor(np.array([beta2]).astype(np.float32))
  198. self.eps = Tensor(np.array([eps]).astype(np.float32))
  199. self.weight_decay_tensor = Tensor(np.array([weight_decay]).astype(np.float32))
  200. self.params = self.parameters
  201. self.moments1 = self.params.clone(prefix="adam_m", init='zeros')
  202. self.moments2 = self.params.clone(prefix="adam_v", init='zeros')
  203. self.decay_flag = tuple(decay_filter(x) for x in self.params)
  204. self.map = C.Map()
  205. def construct(self, gradients):
  206. lr = self.get_lr()
  207. updated_velocity = self.map(F.partial(adam_opt_for_map, self.beta1, self.beta2, self.eps, lr,
  208. self.weight_decay_tensor),
  209. self.params, self.moments1, self.moments2, gradients, self.decay_flag)
  210. return updated_velocity
  211. def test_row_tensor_make_row_tensor():
  212. class MakeRowTensor(nn.Cell):
  213. def __init__(self):
  214. super(MakeRowTensor, self).__init__()
  215. self.dense_shape = (3, 2)
  216. def construct(self, indices, values):
  217. ret = (RowTensor(indices, values, self.dense_shape),)
  218. return ret[0]
  219. indices = Tensor([1, 2])
  220. values = Tensor([[0, 0], [1, 2]], dtype=ms.float32)
  221. MakeRowTensor()(indices, values)
  222. class RowTensorGetAttr(nn.Cell):
  223. def __init__(self, dense_shape):
  224. super(RowTensorGetAttr, self).__init__()
  225. self.dense_shape = dense_shape
  226. def construct(self, indices, values):
  227. x = RowTensor(indices, values, self.dense_shape)
  228. return x.values, x.indices, x.dense_shape
  229. def test_row_tensor_attr():
  230. indices = Tensor([0])
  231. values = Tensor([[1, 2]], dtype=ms.float32)
  232. RowTensorGetAttr((3, 2))(indices, values)
  233. def test_row_tensor_sparse_gatherv2_grad_all():
  234. grad_all = C.GradOperation(get_all=True)
  235. class GradWrap(nn.Cell):
  236. def __init__(self, network):
  237. super(GradWrap, self).__init__()
  238. self.network = network
  239. def construct(self, x, y):
  240. grad = grad_all(self.network)(x, y)
  241. return grad[0].indices, grad[0].values, grad[0].dense_shape
  242. class SparseGatherV2(nn.Cell):
  243. def __init__(self):
  244. super(SparseGatherV2, self).__init__()
  245. self.sparse_gatherv2 = MySparseGatherV2()
  246. self.axis = 0
  247. def construct(self, params, indices):
  248. return self.sparse_gatherv2(params, indices, self.axis)
  249. params = Tensor(np.ones([3, 1, 2]).astype(np.int32))
  250. indices = Tensor(np.array([0, 1]).astype(np.int32))
  251. GradWrap(SparseGatherV2())(params, indices)
  252. def test_row_tensor_sparse_gatherv2_grad_with_pram():
  253. grad_by_list = C.GradOperation(get_by_list=True)
  254. class GradWrap(nn.Cell):
  255. def __init__(self, network):
  256. super(GradWrap, self).__init__()
  257. self.network = network
  258. self.weights = ParameterTuple(filter(lambda x: x.requires_grad, network.get_parameters()))
  259. def construct(self, x):
  260. weights = self.weights
  261. grad = grad_by_list(self.network, weights)(x)
  262. x = grad[0]
  263. return x.values, x.indices, x.dense_shape
  264. class SparseGatherV2(nn.Cell):
  265. def __init__(self):
  266. super(SparseGatherV2, self).__init__()
  267. self.sparse_gatherv2 = MySparseGatherV2()
  268. self.axis = 0
  269. self.params = Parameter(Tensor(np.ones([3, 1, 2]).astype(np.int32)), name="params")
  270. def construct(self, indices):
  271. return self.sparse_gatherv2(self.params, indices, self.axis)
  272. indices = Tensor(np.array([0, 1]).astype(np.int32))
  273. network = GradWrap(SparseGatherV2())
  274. network(indices)
  275. def test_row_tensor_env_get():
  276. class Loss(nn.Cell):
  277. def __init__(self):
  278. super(Loss, self).__init__()
  279. def construct(self, base, target):
  280. return base
  281. class NetWithSparseGatherV2(nn.Cell):
  282. def __init__(self):
  283. super(NetWithSparseGatherV2, self).__init__()
  284. self.w1 = Parameter(Tensor(np.ones([3, 1, 2]).astype(np.float32)), name="w1")
  285. self.w2 = Parameter(Tensor(np.ones([2, 1, 2]).astype(np.float32)), name="w2")
  286. self.gatherv2 = MySparseGatherV2()
  287. self.axis = 0
  288. def construct(self, indices):
  289. return self.gatherv2(self.w1, indices, self.axis) * self.w2
  290. inputs = Tensor(np.array([0, 1]).astype(np.int32))
  291. label = Tensor(np.zeros([2, 1, 2]).astype(np.float32))
  292. net = NetWithSparseGatherV2()
  293. net.set_train()
  294. loss = Loss()
  295. optimizer = AdamWeightDecaySparse(net.trainable_params())
  296. net_with_loss = WithLossCell(net, loss)
  297. train_network = TrainOneStepCell(net_with_loss, optimizer)
  298. train_network(inputs, label)
  299. def test_row_tensor_model_train():
  300. class Net(nn.Cell):
  301. def __init__(self, in_features, out_features):
  302. super(Net, self).__init__()
  303. self.weight = Parameter(Tensor(np.ones([out_features, in_features]).astype(np.float32)), name="weight")
  304. self.add = P.TensorAdd()
  305. self.cast = P.Cast()
  306. self.flag = True
  307. def construct(self, inputs, label):
  308. x = self.add(inputs, self.weight)
  309. if self.flag:
  310. x = self.cast(x, mstype.float32)
  311. return x
  312. dataset_types = (np.float32, np.float32)
  313. dataset_shapes = ((16, 16), (16, 16))
  314. dataset = MindDataSet(dataset_types, dataset_shapes)
  315. net = Net(16, 16)
  316. net.set_train()
  317. optimizer = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  318. model = Model(net, optimizer=optimizer)
  319. model.train(2, dataset, dataset_sink_mode=False)
  320. def test_row_tensor_values_dim_greater_than_dense_shape_dim():
  321. indices = Tensor(np.array([0, 1], dtype=np.int32))
  322. values = Tensor(np.random.randn(2, 4, 5).astype(np.float32))
  323. dense_shape = (3, 4)
  324. with pytest.raises(TypeError):
  325. RowTensorGetAttr(dense_shape)(indices, values)
  326. def test_row_tensor_values_dim_less_than_dense_shape_dim():
  327. indices = Tensor(np.array([0, 1], dtype=np.int32))
  328. values = Tensor(np.random.randn(2, 4).astype(np.float32))
  329. dense_shape = (3, 4, 5)
  330. with pytest.raises(TypeError):
  331. RowTensorGetAttr(dense_shape)(indices, values)
  332. def test_row_tensor_value_and_dense_shape_illegal():
  333. indices = Tensor(np.array([0, 1], dtype=np.int32))
  334. values = Tensor(np.random.randn(2, 4).astype(np.float32))
  335. dense_shape = (3, 5)
  336. with pytest.raises(TypeError):
  337. RowTensorGetAttr(dense_shape)(indices, values)
  338. class RowTensorValuesDouble(nn.Cell):
  339. def __init__(self):
  340. super().__init__()
  341. def construct(self, x):
  342. indices = x.indices
  343. values = x.values * 2
  344. dense_shape = x.dense_shape
  345. return RowTensor(indices, values, dense_shape)
  346. class RowTensorValuesAdd2(nn.Cell):
  347. def __init__(self):
  348. super().__init__()
  349. def construct(self, x):
  350. indices = x.indices
  351. values = x.values + 2
  352. dense_shape = x.dense_shape
  353. return RowTensor(indices, values, dense_shape)
  354. class RowTensorWithControlIf(nn.Cell):
  355. def __init__(self, dense_shape):
  356. super().__init__()
  357. self.op1 = RowTensorValuesDouble()
  358. self.op2 = RowTensorValuesAdd2()
  359. self.dense_shape = dense_shape
  360. def construct(self, a, b, indices, values):
  361. x = RowTensor(indices, values, self.dense_shape)
  362. if a > b:
  363. x = self.op1(x)
  364. else:
  365. x = self.op2(x)
  366. return x.indices, x.values
  367. def test_row_tensor_with_control_flow_if():
  368. a = Tensor(np.array(0).astype(np.int32))
  369. b = Tensor(np.array(2).astype(np.int32))
  370. indices = Tensor(np.array([0, 2]).astype(np.int32))
  371. values = Tensor(np.ones([2, 2]).astype(np.float32))
  372. dense_shape = (5, 2)
  373. net = RowTensorWithControlIf(dense_shape)
  374. net(a, b, indices, values)
  375. class EmbeddingLookUpBnNet(nn.Cell):
  376. def __init__(self, vocab_size, embedding_size, target='CPU'):
  377. super().__init__()
  378. self.embedding_lookup = nn.EmbeddingLookup(vocab_size, embedding_size, param_init='ones', target=target)
  379. self.bn = nn.BatchNorm2d(num_features=3)
  380. self.mul = P.Mul()
  381. self.reshape = P.Reshape()
  382. self.relu = nn.PReLU()
  383. def construct(self, indices):
  384. x = self.embedding_lookup(indices)
  385. x = self.reshape(x, (2, 3, 2, 2))
  386. x = self.relu(x)
  387. x = self.bn(x)
  388. return x
  389. def test_embedding_lookup_with_mix_precision():
  390. data = Tensor(np.array([0, 1, 2]).astype(np.int32))
  391. label = Tensor(np.random.randn(*(2, 3, 2, 2)).astype(np.float32))
  392. net = EmbeddingLookUpBnNet(8, 8, target='CPU')
  393. criterion = nn.SoftmaxCrossEntropyWithLogits(reduction='mean')
  394. optimizer = nn.Adam(params=net.trainable_params(), learning_rate=0.1)
  395. optimizer.sparse_opt.add_prim_attr("primitive_target", "CPU")
  396. train_network = ms.amp.build_train_network(net, optimizer, criterion, level="O2")
  397. train_network.set_train()
  398. for _ in range(2):
  399. train_network(data, label)