Numba documentation specifies that other compiled functions can be inlined and called from other compiled functions.在编译ahead of time时,这似乎不正确。
例如:这里有两个函数来计算2个向量数组之间的内点积,其中一个用于实际产品,另一个在循环中进行内联调用:
# Module test.py
import numpy as np
from numba import njit, float64
@njit(float64(float64[:], float64[:]))
def product(a, b):
prod = 0
for i in range(a.size):
prod += a[i] * b[i]
return prod
@njit(float64[:](float64[:,:], float64[:,:]))
def n_inner1d(a, b):
prod = np.empty(a.shape[0])
for i in range(a.shape[0]):
prod[i] = product(a[i], b[i])
return prod
按原样,我可以import test
完全使用test.n_inner1d
。现在让我们做一些修改,这样就可以编译成.pyd
# Module test.py
import numpy as np
from numba import float64
from numba.pycc import CC
cc = CC('test')
cc.verbose = True
@cc.export('product','float64(float64[:], float64[:])')
def product(a, b):
prod = 0
for i in range(a.size):
prod += a[i] * b[i]
return prod
@cc.export('n_inner1d','float64[:](float64[:,:], float64[:,:])')
def n_inner1d(a, b):
prod = np.empty(a.shape[0])
for i in range(a.shape[0]):
prod[i] = product(a[i], b[i])
return prod
if __name__ == "__main__":
cc.compile()
尝试编译时,我收到以下错误:
# python test.py
Failed at nopython (nopython frontend)
Untyped global name 'product': cannot determine Numba type of <type 'function'>
File "test.py", line 20
对于编译为ahead of time
的模块,内部定义的函数是否可以相互调用并在内联使用?
答案 0 :(得分:3)
我联系了numba开发者,他们很友好地回答说在@njit
之后添加@cc.export
装饰器会使函数调用类型解析工作并解决。
例如:
@cc.export('product','float64(float64[:], float64[:])')
@njit
def product(a, b):
prod = 0
for i in range(a.size):
prod += a[i] * b[i]
return prod
将product
功能提供给其他人。需要注意的是,在某些情况下,内联函数最终可能会使用与声明的AOT类型签名不同的类型签名。