提问人:Eldar Sultanow 提问时间:1/11/2022 最后编辑:Eldar Sultanow 更新时间:1/22/2022 访问量:471
防止 (GPU) 优化方法(如 gmpy2 和 numba)中大整数溢出
Preventing overflow of large integers in (GPU) optimized methods such as gmpy2 and numba
问:
我正在尝试检查一个大整数是否是完美的平方,在 JIT 修饰(优化)例程中使用。此处的示例仅用于说明目的(从理论角度来看,此类方程或椭圆曲线可以得到不同/更好的处理)。我的代码似乎溢出了,因为它产生了不是真正解决方案的解决方案:gmpy2
numba
import numpy as np
from numba import jit
import gmpy2
from gmpy2 import mpz, xmpz
import time
import sys
@jit('void(uint64)')
def findIntegerSolutionsGmpy2(limit: np.uint64):
for x in np.arange(0, limit+1, dtype=np.uint64):
y = mpz(x**6-4*x**2+4)
if gmpy2.is_square(y):
print([x,gmpy2.sqrt(y),y])
def main() -> int:
limit = 100000000
start = time.time()
findIntegerSolutionsGmpy2(limit)
end = time.time()
print("Time elapsed: {0}".format(end - start))
return 0
if __name__ == '__main__':
sys.exit(main())
使用例程在大约 4 秒内完成。我移交给修饰函数的限制不会超过 64 位的无符号整数(这里似乎不是问题)。limit = 1000000000
我读到大整数不能与 numba 的 JIT 优化结合使用(参见此处的示例)。
我的问题:是否有可能在(GPU)优化代码中使用大整数?
答:
现在,我可以通过以下代码设法避免精度损失:
@jit('void(uint64)')
def findIntegerSolutionsGmpy2(limit: np.uint64):
for x in np.arange(0, limit+1, dtype=np.uint64):
x_ = mpz(int(x))**2
y = x_**3-mpz(4)*x_+mpz(4)
if gmpy2.is_square(y):
print([x,gmpy2.sqrt(y),y])
但是通过使用这个修正/固定的例程,不再在 4 秒内完成。现在花了 912 秒。很可能我们在精度和速度之间存在不可逾越的鸿沟。limit = 100000000
使用 CUDA 它变得更快,即 5 分钟(配备 128GB RAM、Intel Xeon CPU E5-2630 v4、2.20GHz 处理器和两张 Tesla V100 型显卡,每张 16GB RAM),但我再次获得了正确的结果和错误的结果。
%%time
from numba import jit, cuda
import numpy as np
from math import sqrt
@cuda.jit
def findIntegerSolutionsCuda(arr):
i=0
for x in range(0, 1000000000+1):
y = float(x**6-4*x**2+4)
sqr = int(sqrt(y))
if sqr*sqr == int(y):
arr[i][0]=x
arr[i][1]=sqr
arr[i][2]=y
i+=1
arr=np.zeros((10,3))
findIntegerSolutionsCuda[128, 255](arr)
print(arr)
错误结果的真正原因很简单,你忘了转换为 ,所以语句被提升为类型并用溢出计算(因为 in 语句是)。修复是微不足道的,只需添加:x
mpz
x ** 6 - 4 * x ** 2 + 4
np.uint64
x
np.uint64
x = mpz(x)
@jit('void(uint64)', forceobj = True)
def findIntegerSolutionsGmpy2(limit: np.uint64):
for x in np.arange(0, limit+1, dtype=np.uint64):
x = mpz(x)
y = mpz(x**6-4*x**2+4)
if gmpy2.is_square(y):
print([x,gmpy2.sqrt(y),y])
另外,您可能会注意到我添加了,这是为了在开始时抑制 Numba 编译警告。forceobj = True
修复后,一切正常,您不会看到错误的结果。
如果你的任务是检查表达式是否给出严格的平方,那么我决定为你发明并实现另一个解决方案,代码如下。
它的工作原理如下。您可能会注意到,如果一个数字是平方的,那么它也是任何数字的平方模数(取模量是运算)。x % N
我们可以取任何数,例如某些素数的乘积。现在我们可以做一个简单的滤波器,计算所有平方模 K,在位向量内标记这个平方,然后检查模 K 在这个滤波器位向量中有哪些数字。K = 2 * 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19
上面提到的滤波器 K(素数的乘积)只留下 1% 的正方形候选者。我们也可以做第二阶段,用其他素数应用相同的滤波器,例如.这将使它们过滤掉 3%。总的来说,我们将有剩余的初始候选人数量。K2 = 23 * 29 * 31 * 37 * 41
1% * 3% = 0.03%
经过两次过滤后,只剩下几个数字需要检查。它们可以很容易地快速检查。gmpy2.is_square()
过滤阶段可以很容易地包装成 Numba 函数,就像我在下面所做的那样,这个函数可以有额外的 Numba 参数,这将告诉 Numba 自动在所有 CPU 内核上并行运行所有 Numpy 操作。parallel = True
在我使用的代码中,这表示要检查的所有数字的限制,我使用 ,这表示一次要检查多少个数字,并行 Numba 函数。如果您有足够的内存,则可以设置更大的内存以更有效地占用所有 CPU 内核。大小块大约使用大约 1 GB 的内存。limit = 1 << 30
x
block = 1 << 26
block
1 << 26
在将我的想法与过滤一起使用并使用多核 CPU 后,我的代码解决与您相同的任务的速度快了一百倍。
import numpy as np, numba
@numba.njit('u8[:](u8[:], u8, u8, u1[:])', cache = True, parallel = True)
def do_filt(x, i, K, filt):
x += i; x %= K
x2 = x
x2 *= x2; x2 %= K
x6 = x2 * x2; x6 %= K
x6 *= x2; x6 %= K
x6 += np.uint64(4 * K + 4)
x2 <<= np.uint64(2)
x6 -= x2; x6 %= K
y = x6
#del x2
filt_y = filt[y]
filt_y_i = np.flatnonzero(filt_y).astype(np.uint64)
return filt_y_i
def main():
import math
gmpy2 = None
import gmpy2
Int = lambda x: (int(x) if gmpy2 is None else gmpy2.mpz(x))
IsSquare = lambda x: gmpy2.is_square(x)
Sqrt = lambda x: Int(gmpy2.sqrt(x))
Ks = [2 * 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19, 23 * 29 * 31 * 37 * 41]
filts = []
for i, K in enumerate(Ks):
a = np.arange(K, dtype = np.uint64)
a *= a
a %= K
filts.append((K, np.zeros((K,), dtype = np.uint8)))
filts[-1][1][a] = 1
print(f'filter {i} ratio', round(len(np.flatnonzero(filts[-1][1])) / K, 4))
limit = 1 << 30
block = 1 << 26
for i in range(0, limit, block):
print(f'i block {i // block:>3} (2^{math.log2(i + 1):>6.03f})')
x = np.arange(0, min(block, limit - i), dtype = np.uint64)
for ifilt, (K, filt) in enumerate(filts):
len_before = len(x)
x = do_filt(x, i, K, filt)
print(f'squares filtered by filter {ifilt}:', round(len(x) / len_before, 4))
x_to_check = x
print(f'remain to check {len(x_to_check)}')
sq_x = []
for x0 in x_to_check:
x = Int(i + x0)
y = x ** 6 - 4 * x ** 2 + 4
if not IsSquare(y):
continue
yr = Sqrt(y)
assert yr * yr == y
sq_x.append((int(x), int(yr)))
print('squares found', len(sq_x))
print(sq_x)
del x
if __name__ == '__main__':
main()
输出:
filter 0 ratio 0.0094
filter 1 ratio 0.0366
i block 0 (2^ 0.000)
squares filtered by filter 0: 0.0211
squares filtered by filter 1: 0.039
remain to check 13803
squares found 2
[(0, 2), (1, 1)]
i block 1 (2^24.000)
squares filtered by filter 0: 0.0211
squares filtered by filter 1: 0.0392
remain to check 13880
squares found 0
[]
i block 2 (2^25.000)
squares filtered by filter 0: 0.0211
squares filtered by filter 1: 0.0391
remain to check 13835
squares found 0
[]
i block 3 (2^25.585)
squares filtered by filter 0: 0.0211
squares filtered by filter 1: 0.0393
remain to check 13907
squares found 0
[]
...............................
评论
[128, 255]
numba
评论