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 os 16import numpy as np 17import pytest 18 19import mindspore.nn as nn 20from mindspore import context 21from mindspore.common.tensor import Tensor 22from mindspore.common import dtype as mstype 23from mindspore.train.serialization import export, load 24 25ZERO = Tensor([0], mstype.int32) 26ONE = Tensor([1], mstype.int32) 27 28 29class RecrusiveNet(nn.Cell): 30 def construct(self, x, z): 31 def f(x, z): 32 y = ZERO 33 if x < 0: 34 y = ONE 35 elif x < 3: 36 y = x * f(x - 1, z) 37 elif x < 5: 38 y = x * f(x - 2, z) 39 else: 40 y = f(x - 4, z) 41 z = y + 1 + z 42 return z 43 44 return f(x, z) 45 46 47@pytest.mark.level0 48@pytest.mark.platform_x86_ascend_training 49@pytest.mark.platform_arm_ascend_training 50@pytest.mark.env_onecard 51def test_recrusive(): 52 context.set_context(mode=context.GRAPH_MODE) 53 network = RecrusiveNet() 54 55 x = Tensor(np.array([1]).astype(np.float32)) 56 y = Tensor(np.array([2]).astype(np.float32)) 57 origin_out = network(x, y) 58 59 file_name = "recrusive_net" 60 export(network, x, y, file_name=file_name, file_format='MINDIR') 61 mindir_name = file_name + ".mindir" 62 assert os.path.exists(mindir_name) 63 64 graph = load(mindir_name) 65 loaded_net = nn.GraphCell(graph) 66 outputs_after_load = loaded_net(x, y) 67 assert origin_out == outputs_after_load 68