[Solved] MindSpore Error: Should not use Python in runtime

1 Error description

1.1 System Environment

ardware Environment(Ascend/GPU/CPU): CPU
Software Environment:
– MindSpore version (source or binary): 1.7.0
– Python version (eg, Python 3.7.5): 3.7.6
– OS platform and distribution (eg, Linux Ubuntu 16.04): Ubuntu 4.15.0-74-generic
– GCC/Compiler version (if compiled from source):

1.2 Basic information

1.2.1 Script

This case is to use the MindSpore JIT Fallback function to call the logic of using Numpy in mindspore

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 Error reporting

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 Reason analysis and solution

This is because the MindSpore compiler found that there were still some nodes of interpretation type inside the function when it checked after the compilation, resulting in an error. After viewing the code, it is found that the function returns a numpy type of data, which has not been converted into MindSpore’s Tensor, so that it cannot enter the back-end runtime for calculation, resulting in an error. You can wrap the numpy array into a Tensor and calculate it before returning it. Use Tensor.asnumpy() outside the function to convert it to numpy array type data, and perform other numpy related operations.

3 Summary

MindSpore’s functions operate on numpy types through JIT Fallback, which can only be deduced and executed at compile time and cannot be passed to runtime. And it cannot be returned as the final function return value, otherwise it will cause an error when passed to the runtime. You can wrap a numpy array into a Tensor and return it. Use Tensor.asnumpy() outside the function to convert it to numpy array type data, and perform other numpy related operations.

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *