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