报错:使用ops.nonzero算子报错TypeError
收藏回复举报
报错:使用ops.nonzero算子报错TypeError
发表于2022-12-01 16:58:16
0 查看

1 系统环境

硬件环境(Ascend/GPU/CPU): Ascend/GPU/CPU

MindSpore版本: mindspore=1.9.1

执行模式(动态图):GRAPH

Python版本: Python=3.7.5

操作系统平台: linux

2 报错信息

3.png

2.1 问题描述

It raised TypeError: Type Join Failed: dtype1 = Float32, dtype2 = Int64. in Graph mode. No problem in Pynative mode.

2.2 脚本代码

import numpy as np
import mindspore as ms
import mindspore.ops as ops
from mindspore import Tensor, nn, context

class Graph(nn.Cell):
    def __init__(self):
        super().__init__()
        self.net = nn.Dense(10, 1)
    def construct(self, x, y):
        logits = self.net(x)
        extra_output = ops.nonzero(y > 0)
        return logits, extra_output

def main():
    context.set_context(mode=context.GRAPH_MODE)
    net = Graph()
    x = Tensor(np.random.randn(16, 10), dtype=ms.float32)
    y = Tensor([0, 0, 1, 1])
    labels = Tensor(np.random.randn(16, 1), dtype=ms.float32)
    logit, extra_output = net(x, y)
    assert extra_output.shape == (2, 1)
    loss_fn = nn.MSELoss()
    def forward(x, y, labels):
        logits, extra_output = net(x, y)
        loss = loss_fn(logits, labels)
        return loss, logits, extra_output
    grad_fn = ops.value_and_grad(forward, grad_position=None, weights=net.trainable_params(), has_aux=True)
    # raised TypeError here
    (loss, logits, extra_output), inputs_gradient = grad_fn(x, y, labels)
    assert extra_output.shape == (2, 1)

if __name__ == '__main__':
    main()

3 根因分析

******此处由用户补充详细的定位过程******

报错生成的analyze_fail.dat,发现%5输出三个fp32的,但是%6需要两个fp32和一个int64的,ops.nonzero算子只支持int64输出。

4 解决方案

******此处由用户填写******

包含文字方案和最终脚本代码

代码格式,可上传附件

本帖最后由 匿名用户2022/12/02 09:36:38 编辑

我要发帖子