MindSpore报TypeError: Cannot joined the return values

1 报错描述
MindSpore报TypeError: Cannot joined the return values of different branches, perhaps you need to make them equal.
【MindSpore报TypeError: Cannot joined the return values】1.1 系统环境
*Hardware Environment(Ascend/GPU/CPU): Ascend/GPU/CPU
Software Environment:
– MindSpore version (source or binary): 1.6.0
– Python version (e.g., Python 3.7.5): 3.7.6
– OS platform and distribution (e.g., Linux Ubuntu 16.04): Ubuntu 4.15.0-74-generic
– GCC/Compiler version (if compiled from source):
1.2 基本信息
1.2.1 脚本
在控制流场景中,对同一个变量在不同分支赋不同类型的数据。
import mindspore as ms
import mindspore.nn as nn
from mindspore import ms_function, context
context.set_context(mode=context.GRAPH_MODE)
def test_join():
class JoinNet(nn.Cell):

def construct(self, x): out = [1, 2, 3] if x > 0: out = x return out

x = ms.Tensor([1])
net = JoinNet()
res = net(x)
print("res:", res)
1.2.2 报错
这里报错信息如下:
TypeError: mindspre/ccsrc/pipeline/jit/static_analysis/static_analysis.cc:780 ProcessEvalResults] Cannot join the return values of different branches, perhaps you need to make them equal.
Type Join Failed: Abstract type AbstractTensor cannot join with AbstractList.
In file ../test.py(11)
if x > 0:
^
原因分析:
我们看报错信息,在TypeError中,写到Cannot join the return values of different branches,意思是不支持两个不同分支的join操作,out在true分支被赋值为Tensor类型,在false分支被赋值为list类型,条件x > y为变量,因此在return out语句中无法确定out的数据类型,会导致图模式下的编译出现异常。
2 解决方法
基于上面已知的原因,很容易做出如下修改:
import mindspore as ms
import mindspore.nn as nn
from mindspore import ms_function, context
context.set_context(mode=context.GRAPH_MODE)
def test_join():
class JoinNet(nn.Cell):
def construct(self, x): out = Tensor([1, 2, 3]) if x > 0: out = x return out

x = ms.Tensor([1])
net = JoinNet()
res = net(x)
print("res:", res)
此时执行成功,输出如下:
res: [1]
3 总结
定位报错问题的步骤:
1、找到报错的用户代码行:if x > 0:
2、分析控制流的两个分支的out数据类型,将其调整成相同类型。关注变量定义、初始化的正确性。
4 参考文档
https://www.mindspore.cn/docs...

    推荐阅读