日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

适用于CUDA GPU的Numba例子

發(fā)布時間:2023/11/28 生活经验 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 适用于CUDA GPU的Numba例子 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

? 適用于CUDA GPU的Numba例子
矩陣乘法
這是使用CUDA內(nèi)核的矩陣乘法的簡單實現(xiàn):
@cuda.jit
def matmul(A, B, C):
“”“Perform square matrix multiplication of C = A * B
“””
i, j = cuda.grid(2)
if i < C.shape[0] and j < C.shape[1]:
tmp = 0.
for k in range(A.shape[1]):
tmp += A[i, k] * B[k, j]
C[i, j] = tmp
這種實現(xiàn)方式簡單直觀,但性能不佳,因為相同的矩陣元素將從設(shè)備內(nèi)存中多次加載,這很慢(某些設(shè)備可能具有透明的數(shù)據(jù)緩存,但它們可能不足以一次容納整個輸入)。
如果使用阻塞算法來減少對設(shè)備內(nèi)存的訪問,它將更快。CUDA為 塊中的線程提供快速共享內(nèi)存,以協(xié)作執(zhí)行任務(wù)。以下使用共享內(nèi)存實現(xiàn)了方陣乘法的更快版本:
from numba import cuda, float32

Controls threads per block and shared memory usage.

The computation will be done on blocks of TPBxTPB elements.

TPB = 16

@cuda.jit
def fast_matmul(A, B, C):
# Define an array in the shared memory
# The size and type of the arrays must be known at compile time
sA = cuda.shared.array(shape=(TPB, TPB), dtype=float32)
sB = cuda.shared.array(shape=(TPB, TPB), dtype=float32)

x, y = cuda.grid(2)tx = cuda.threadIdx.x
ty = cuda.threadIdx.y
bpg = cuda.gridDim.x    # blocks per gridif x >= C.shape[0] and y >= C.shape[1]:# Quit if (x, y) is outside of valid C boundaryreturn# Each thread computes one element in the result matrix.
# The dot product is chunked into dot products of TPB-long vectors.
tmp = 0.
for i in range(bpg):# Preload data into shared memorysA[tx, ty] = A[x, ty + i * TPB]sB[tx, ty] = B[tx + i * TPB, y]# Wait until all threads finish preloadingcuda.syncthreads()# Computes partial product on the shared memoryfor j in range(TPB):tmp += sA[tx, j] * sB[j, ty]# Wait until all threads finish computingcuda.syncthreads()C[x, y] = tmp

因為共享內(nèi)存是有限的資源,所以代碼一次從輸入數(shù)組中預(yù)加載小塊。然后,調(diào)用 syncthreads()以等待所有線程完成預(yù)加載,再對共享內(nèi)存進(jìn)行計算。計算之后,再次同步,以確保所有線程在共享內(nèi)存中的數(shù)據(jù)均已完成之后,在下一個循環(huán)迭代中將其覆蓋。

總結(jié)

以上是生活随笔為你收集整理的适用于CUDA GPU的Numba例子的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。