近期初学taichi,可能是我教程没有看全,我目前没有找到类似 cuda中"__syncthreads"的或其它方式实现"barrier"的函数,ti.sync()在ti.kernel内不齐作用。测试代码如下:
import taichi as ti
import numpy as np
import random
length = 50000+1
ti.init(arch=ti.cuda)
boxes = ti.field(ti.f32, length)
lis = [i for i in range(length)]
# random.shuffle(lis)
lisnp = np.array(lis)
boxes.from_numpy(lisnp)
boxes_cache = ti.field(ti.f32, length)
@ti.kernel
def com_max(boxes: ti.template(), boxes_cache: ti.template(), length: int) -> ti.f32:
# ti.block_local(boxes_cache)
for tid in range(length):
stride = length // 2
length = length - stride
boxes_cache[tid] = boxes[tid]
ti.sync()
while stride > tid:
a = boxes_cache[tid]
b = boxes_cache[tid + stride]
ti.sync()
boxes_cache[tid] = a if a > b else b
stride = length // 2
length = length - stride
return boxes_cache[0]
a = com_max(boxes, boxes_cache, length)
# ======> output
print(lisnp.max()) # output: 50000
print(a) # output: 47269.0
这个求最大值的代码在cpu和cuda下面都无法返回正确的结果,不知道taichi中有没有实现barrier功能,因为这个对于并行应该是挺重要的。