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_dynamic_shape_embedding.py 2.6 kB

5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. import numpy as np
  16. import pytest
  17. import mindspore.nn as nn
  18. from mindspore import Tensor, context
  19. from mindspore.nn import TrainOneStepCell, WithLossCell
  20. context.set_context(enable_sparse=True,
  21. mode=context.GRAPH_MODE)
  22. class NetWithEmbeddingLookUp(nn.Cell):
  23. def __init__(self, vocab_size, embedding_size, target="CPU"):
  24. super(NetWithEmbeddingLookUp, self).__init__()
  25. self.embedding_lookup = \
  26. nn.EmbeddingLookup(vocab_size=vocab_size,
  27. embedding_size=embedding_size,
  28. param_init="ones", target=target)
  29. def construct(self, indices):
  30. out = self.embedding_lookup(indices)
  31. return out
  32. @pytest.mark.level0
  33. @pytest.mark.platform_arm_ascend_training
  34. @pytest.mark.platform_x86_ascend_training
  35. @pytest.mark.platform_x86_gpu_training
  36. @pytest.mark.env_onecard
  37. def test_sit_embedding_lookup_net():
  38. indices = Tensor(np.array([0, 1, 2]).astype(np.int32))
  39. label = Tensor(np.random.randn(3, 8).astype(np.float32))
  40. net1 = NetWithEmbeddingLookUp(vocab_size=8, embedding_size=8, target="CPU")
  41. loss = nn.SoftmaxCrossEntropyWithLogits(reduction="mean")
  42. optimizer1 = nn.Adam(params=net1.trainable_params(), learning_rate=0.1)
  43. optimizer1.unique = True
  44. train_network1 = TrainOneStepCell(WithLossCell(net1, loss), optimizer1)
  45. train_network1.set_train()
  46. out1 = train_network1(indices, label)
  47. net2 = NetWithEmbeddingLookUp(vocab_size=8, embedding_size=8, target="CPU")
  48. optimizer2 = nn.Adam(params=net2.trainable_params(), learning_rate=0.1)
  49. optimizer2.unique = False
  50. optimizer2.target = "CPU"
  51. train_network2 = TrainOneStepCell(WithLossCell(net2, loss), optimizer2)
  52. train_network2.set_train()
  53. out2 = train_network2(indices, label)
  54. assert np.allclose(out1.asnumpy(), out2.asnumpy(), 0.001, 0.001)