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_pynative.py 2.4 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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_sparse_pynative.py
  17. @Author:
  18. @Date : 2020-08-04
  19. @Desc : test mindspore sparse pynative
  20. """
  21. import mindspore as ms
  22. import mindspore.nn as nn
  23. from mindspore import context, Tensor, RowTensor, SparseTensor
  24. from mindspore.ops import composite as C
  25. context.set_context(mode=context.PYNATIVE_MODE, enable_sparse=True)
  26. grad_all = C.GradOperation('get_all', get_all=True)
  27. class GradWrap(nn.Cell):
  28. def __init__(self, network):
  29. super(GradWrap, self).__init__()
  30. self.network = network
  31. def construct(self, *args):
  32. grad = grad_all(self.network)(*args)
  33. return grad
  34. def test_row_tensor_attr():
  35. class RowTensorGetAttr(nn.Cell):
  36. def __init__(self, dense_shape):
  37. super(RowTensorGetAttr, self).__init__()
  38. self.dense_shape = dense_shape
  39. def construct(self, indices, values):
  40. x = RowTensor(indices, values, self.dense_shape)
  41. return x.values, x.indices, x.dense_shape
  42. indices = Tensor([0])
  43. values = Tensor([[1, 2]], dtype=ms.float32)
  44. RowTensorGetAttr((3, 2))(indices, values)
  45. GradWrap(RowTensorGetAttr((3, 2)))(indices, values)
  46. def test_sparse_tensor_attr():
  47. class SparseTensorGetAttr(nn.Cell):
  48. def __init__(self):
  49. super(SparseTensorGetAttr, self).__init__()
  50. self.dense_shape = (3, 4)
  51. def construct(self, indices, values):
  52. x = SparseTensor(indices, values, self.dense_shape)
  53. return x.values, x.indices, x.dense_shape
  54. indices = Tensor([[0, 1], [1, 2]])
  55. values = Tensor([1, 2], dtype=ms.float32)
  56. SparseTensorGetAttr()(indices, values)
  57. GradWrap(SparseTensorGetAttr())(indices, values)