关于人工智能:MindSpore-报错-Should-not-use-Python-in-runtime

4次阅读

共计 1223 个字符,预计需要花费 4 分钟才能阅读完成。

1 报错形容
1.1 零碎环境
ardware Environment(Ascend/GPU/CPU): CPU
Software Environment:
– MindSpore version (source or binary): 1.7.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 脚本
此案例是应用 MindSpore JIT Fallback 性能在 mindspore 中调用应用 Numpy 的逻辑

import numpy as np
import mindspore.nn as nn
from mindspore import Tensor, ms_function, context

context.set_context(mode=context.GRAPH_MODE)

def test_validate():
@ms_function
def Func():

x = np.array([1])
if x >= 1:
  x = x * 2
return x

res = Func()
print(“res:”, res)
1.2.2 报错
RuntimeError: mindspore/ccsrc/pipeline/jit/validator.cc:141 ValidateValueNode] Should not use Python object in runtime, node: ValueNode<InterpretedObject> InterpretedObject: ‘[2]’.
Line: In file /home/llg/workspace/mindspore/mindspore/test.py(15)
E if x >= 1:
2 起因剖析以及解决办法
这个是因为 MindSpore 编译器在编译完结后进行校验时,发现了函数外部依然还有一些解释类型的节点,导致的报错。查看代码后发现,函数返回了一个 numpy 类型的数据,这些数据并没有转换成 MindSpore 的 Tensor 导致无奈进入后端运行时进行计算从而引发报错。能够将 numpy array 包装成 Tensor 后计算再将其返回。在函数内部利用 Tensor.asnumpy()将其转换为 numpy array 类型数据,进行其余 numpy 的相干操作。

3 总结
MindSpore 的函数是通过 JIT Fallback 的形式来实现函数对 numpy 类型操作的,这种形式只能在编译时刻实现推导和执行,不能传递到运行时。且不能作为最终的函数返回值返回,否则传递到运行时会引发报错。能够将 numpy array 包装成 Tensor 后将其返回。在函数内部利用 Tensor.asnumpy() 将其转换为 numpy array 类型数据,进行其余 numpy 的相干操作。

正文完
 0