如何从主机代码中断或取消 CUDA 内核

How to interrupt or cancel a CUDA kernel from host code

本文关键字:取消 CUDA 内核 中断 代码 主机      更新时间:2023-10-16

我正在使用 CUDA,我正在尝试在命中某个if块后停止我的内核工作(即终止所有正在运行的线程)。我该怎么做?我真的被困在这里。

CUDA 执行模型在设计上不允许块间通信。如果不诉诸asserttrap类型的方法,这可能会使这种内核中止,条件操作难以可靠地实现,这可能会导致上下文破坏和数据丢失,这可能不是您想要的。

如果您的内核设计涉及少量具有"驻留"线程的块,那么唯一的方法是某种原子自旋锁,这很难可靠地工作,并且会大大降低内存控制器的性能和可实现的带宽。

另一方面,如果你的内核设计有相当大的网格和很多块,并且你的主要目标是阻止尚未调度的块运行,那么你可以尝试这样的事情:

#include <iostream>
#include <vector>
__device__ unsigned int found_idx;
__global__ void setkernel(unsigned int *indata)
{
    indata[115949] = 0xdeadbeef;
    indata[119086] = 0xdeadbeef;
    indata[60534] = 0xdeadbeef;
    indata[37072] = 0xdeadbeef;
    indata[163107] = 0xdeadbeef;
}
__global__ void searchkernel(unsigned int *indata, unsigned int *outdata)
{
    if (found_idx > 0) {
        return;
    } else if (threadIdx.x == 0) {
        outdata[blockIdx.x] = blockIdx.x;
    };
    unsigned int tid = threadIdx.x + blockIdx.x * blockDim.x;
    if (indata[tid] == 0xdeadbeef) {
        unsigned int oldval = atomicCAS(&found_idx, 0, 1+tid);
    }
}
int main()
{
    const unsigned int N = 1 << 19;
    unsigned int* in_data;
    cudaMalloc((void **)&in_data, sizeof(unsigned int) * size_t(N));
    cudaMemset(in_data, 0, sizeof(unsigned int) * size_t(N));
    setkernel<<<1,1>>>(in_data);
    cudaDeviceSynchronize();
    unsigned int block_size = 1024;
    unsigned int grid_size = N / block_size;
    unsigned int* out_data;
    cudaMalloc((void **)&out_data, sizeof(unsigned int) * size_t(grid_size));
    cudaMemset(out_data, 0xf0, sizeof(unsigned int) * size_t(grid_size));
    const unsigned int zero = 0;
    cudaMemcpyToSymbol(found_idx, &zero, sizeof(unsigned int));
    searchkernel<<<grid_size, block_size>>>(in_data, out_data);
    std::vector<unsigned int> output(grid_size);
    cudaMemcpy(&output[0], out_data, sizeof(unsigned int) * size_t(grid_size), cudaMemcpyDeviceToHost); 
    cudaDeviceReset();
    std::cout << "The following blocks did not run" << std::endl;
    for(int i=0, j=0; i<grid_size; i++) {
        if (output[i] == 0xf0f0f0f0) {
            std::cout << " " << i;
            if (j++ == 20) {
                std::cout << std::endl;
                j = 0;
            }
        }
    }
    std::cout << std::endl;
    return 0;
}

在这里,我有一个简单的内核,它正在一个大数组中搜索一个魔术词。为了获得提前退出行为,我使用了一个全局词,该词由那些"获胜"或触发终止条件的线程原子设置。每个新块都会检查这个全局单词的状态,如果设置了,它们将返回而不做任何工作。

如果我在中等大小的开普勒设备上编译并运行它:

$ nvcc -arch=sm_30 -o blocking blocking.cu 
$ ./blocking 
The following blocks did not run
 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
 504 505 506 507 508 509 510 511

您可以看到网格中的大量块看到了全局单词的变化,并在没有运行搜索代码的情况下提前终止。这可能是您在没有严重侵入性自旋锁方法的情况下可以做的最好的事情,这种方法会极大地损害性能。

我假设你想停止一个正在运行的内核(而不是单个线程)。

最简单的方法(也是我建议的方法)是设置一个由内核测试的全局内存标志。您可以使用 cudaMemcpy() 设置标志(如果使用统一内存,则不使用)。

如下所示:

if (gm_flag) {
  __threadfence();         // ensure store issued before trap
  asm("trap;");            // kill kernel with error
}

ams("trap;") 将停止所有正在运行的线程

请注意,从 cuda 2.0 开始,您可以使用 assert() 来终止内核!

不同的方法如下(我还没有尝试过代码!

__device__ bool go(int val){
    return true;
}
__global__ void stopme(bool* flag, int* val, int size){
    int idx= blockIdx.x *blockDim.x + threadIdx.x;
    if(idx < size){
        bool canContinue = true;
        while(canContinue && (flag[0])){
            printf("HELLO from %in",idx);
            if(!(*flag)){
                return;
            }
            else{
                //do some computation
                val[idx]++;
                val[idx]%=100;
            }
             canContinue = go(val[idx]);
        }
    }
}
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess)
   {
      fprintf(stderr,"GPUassert: %s %s %dn", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}
int main(void)
{
    int size = 128;
    int* h_val = (int*)malloc(sizeof(int)*size);
    bool * h_flag = new bool;
    *h_flag=true;
    bool* d_flag;
    cudaMalloc(&d_flag,sizeof(bool));
    cudaMemcpy(d_flag,h_flag,1,cudaMemcpyHostToDevice);
    int* d_val;
    cudaMalloc(&d_val,sizeof(int)*size );
    for(int i=0;i<size;i++){
        h_val[i] = i;
    }
    cudaMemcpy(d_val,h_val,size,cudaMemcpyHostToDevice);
    int BSIZE=32;
    int nblocks =size/BSIZE;
    printf("%i,%i",nblocks,BSIZE);
    stopme<<<nblocks,BSIZE>>>(d_flag,d_val,size);
    //--------------sleep for a while --------------------------
    *h_flag=false;
    cudaMemcpy(d_flag,h_flag,1,cudaMemcpyHostToDevice);
    cudaDeviceSynchronize();
    gpuErrchk( cudaPeekAtLastError() );
    printf("ENDn");

} 

内核stopMe继续运行,直到主机端的某人将标志设置为 false。请注意,您的内核可能比这复杂得多,同步所有线程以执行return的努力可能远不止于此(并且可能会影响性能)。希望这有帮助。

更多信息在这里