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

1.系统环境

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

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] ME(173836:281472951834496,MainProcess):2022-08-16-10:23:45.508.861 [mindspore/nn/cell.py:559] The '' does not override the method 'construct', it will call the super class(Cell) 'construct'.

意思是有nn.Cell的类并没有自定义construct函数功能, 因此该类会自动调用Cell基类的construct函数
因此可以知道我们需要自定义Net的construct函数,但是参考代码发现用户将construct错误拼写为constuct导致错误

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)