construct方法名称错误引起损失函数执行报错:The 'sub' operation does not support the type [Tensor[Float32], None].

1 系统环境

硬件环境(Ascend/GPU/CPU): CPU
软件环境:MindSpore 版本: 1.8.0
执行模式: 静态图(GRAPH)
Python 版本: 3.7.6
操作系统平台: Windows

2 报错信息

2.1 问题描述

在自定义Cell网络中,construct函数名称错误定义了新的函数,导致基类Cell的construct没有实现引起报错。

2.2 报错信息

RuntimeError:The 'sub' operation does not support the type [Tensor[Float32], None].

2.3 脚本代码

from mindspore import nn, Tensor
import numpy as np
import mindspore
class Net(nn.Cell):
    def constuct(self, x):
        return x

def main():
    x = Tensor(np.array([1, 2, 3]), mindspore.float32)
    net = Net()
    y = net(x)
    loss = nn.MSELoss()
    out = loss(x, y)
    print("out=", out)

3 根因分析


看报错信息,WARNING Net没有重载’construct’方法。 代码里面写成了constuct
最终报错是sub不支持[Tensor[Float32], kMetaTypeNone]
如果Net没有重载’construct’方法,调用了父类的’construct’方法
父类的实现

也就是Net的返回值永远是None,然后将None传入到nn.MSELoss()中

313行 MSELoss会把两个入参相减,然后取平方。
两个参数一个是Tensor另一个是None,所以报sub操作类型不支持。
此时,切换到PYNATIVE_MODE跑下看看

PYNATIVE_MODE下整个流程更加清晰明了。

4 解决方案

解决方案说明:把constuct修改成construct
修改后代码:

from mindspore import nn, Tensor
import numpy as np
import mindspore
class Net(nn.Cell):
    def construct(self, x):
        return x

def main():
    x = Tensor(np.array([1, 2, 3]), mindspore.float32)
    net = Net()
    y = net(x)
    loss = nn.MSELoss()
    out = loss(x, y)
    print("out=", out)

正常执行结果out= 0.0