mindspore.constexpr

View Source On Gitee
mindspore.constexpr(fn=None, get_instance=True, name=None, reuse_result=True, check=True)[source]

Used to calculate constant in graph copmpiling process and improve compile performance in GRAPH_MODE.

Parameters
  • fn (function) – A fn use as the infer_value of the output operator. Default: None .

  • get_instance (bool) – If True , return the instance of operator, otherwise return the operator class. Default: True .

  • name (str) – Defines the operator name. If name is None , use the function name as op name. Default: None .

  • reuse_result (bool) – If True , the operator will be executed once and reuse the result next time, otherwise the operator will always be executed. Default: True .

  • check (bool) – If True , the parameters will be checked and the warning message will raised if the parameter is not const value. Default: True .

Examples

>>> import mindspore as ms
>>> # define a constant calculate function with for loop inside and use use constexpr to accelerate the compile
>>> # process.
>>> @ms.constexpr
... def for_loop_calculate(range_num):
...     out = 0
...     for i in range(range_num):
...         if i %2 == 0 and i % 7 != 0:
...             out = out + i
...     return out // range_num
...
>>> # construct a net and run with GRAPH_MODE.
>>> @ms.jit
... def my_func(x):
...     new_shape = for_loop_calculate(100000)
...     return ms.ops.broadcast_to(x, (new_shape, ))
...
>>> out = my_func(ms.Tensor([1]))
>>> print(out.shape)
>>> (21428, )