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""" test ADA_GRAD """ 16 17import pytest 18import numpy as np 19 20import mindspore.nn as nn 21from mindspore import Tensor, Parameter, context 22from mindspore.common.api import _cell_graph_executor 23from mindspore.nn import TrainOneStepCell, WithLossCell 24from mindspore.nn.optim import Adagrad 25from mindspore.ops import operations as P 26 27 28@pytest.fixture(scope="module", autouse=True) 29def setup_teardown(): 30 context.set_context(enable_sparse=True) 31 yield 32 context.set_context(enable_sparse=False) 33 34 35class Net(nn.Cell): 36 def __init__(self): 37 super(Net, self).__init__() 38 self.weight = Parameter(Tensor(np.ones([64, 10]).astype(np.float32)), name='weight') 39 self.bias = Parameter(Tensor(np.ones([10]).astype(np.float32)), name='bias') 40 self.matmul = P.MatMul() 41 self.biasAdd = P.BiasAdd() 42 43 def construct(self, x): 44 x = self.biasAdd(self.matmul(x, self.weight), self.bias) 45 return x 46 47 48def test_ada_grad(): 49 """ test_ada_grad """ 50 inputs = Tensor(np.ones([1, 64]).astype(np.float32)) 51 label = Tensor(np.zeros([1, 10]).astype(np.float32)) 52 net = Net() 53 net.set_train() 54 loss = nn.SoftmaxCrossEntropyWithLogits() 55 optimizer = Adagrad(net.trainable_params(), weight_decay=0.9, loss_scale=1024.0) 56 net_with_loss = WithLossCell(net, loss) 57 train_network = TrainOneStepCell(net_with_loss, optimizer) 58 _cell_graph_executor.compile(train_network, inputs, label) 59