通常のコンパイル時ではなく、実行時にグリッド/ブロックサイズを指定できるように、cuda カーネルを起動できるかどうかを知りたいです。
これに関するヘルプは非常に貴重です。
CUDA アプリケーションでは、グリッドに固定サイズを指定することはあまり役に立ちません。ほとんどの場合、ブロック サイズは固定され、グリッド サイズは動的に維持され、入力データ サイズに応じて変更されます。次のベクトル加算の例を考えてみましょう。
__global__ void kernel(float* a, float* b, float* c, int length)
{
int tid = blockIdx.x * blockDim.x + threadIdx.x;
//Bound checks inside the kernel
if(tid<length)
c[tid] = a[tid] + b[tid];
}
int addVectors(float* a, float* b, float* c, int length)
{
//a, b, c are allocated on the device
//Fix the block size to an appropriate value
dim3 block(128);
dim3 grid;
grid.x = (length + block.x - 1)/block.x;
//Grid size is dependent on the length of the vector.
//Total number of threads are rounded up to the nearest multiple of block size.
//It means total number of threads are at least equal to the length of the vector.
kernel<<<grid,block>>>(a,b,c,length);
return 0;
}
Cuda カーネルとデバイス関数は、blockDim.{ x,y,z
} を使用してブロック構成にアクセスしたり、gridDim.{ x,y,z
} を使用してグリッド構成にアクセスしたりできます。さまざまな構成に対応できるカーネル/デバイス機能がある場合は、カーネル ( myKernel<<<dimGrid,dimBlock>>>
) を任意dimGrid
の でdimBlock
起動するか、実行時に選択するだけで済みます。これは決して異常なことではないと思います。