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