Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrupt or cancel a CUDA kernel from host code

Tags:

c++

cuda

gpu

nvidia

I am working with CUDA and I am trying to stop my kernels work (i.e. terminate all running threads) after a certain if block is being hit. How can I do that? I am really stuck in here.

like image 205
MD Kamal Hossain Shajal Avatar asked Jan 25 '16 09:01

MD Kamal Hossain Shajal


People also ask

Which is the correct way to launch a CUDA kernel?

In order to run a kernel on the CUDA threads, we need two things. First, in the main() function of the program, we call the function to be executed by each thread on the GPU. This invocation is called Kernel Launch and with it we need provide the number of threads and their grouping.

What is threadIdx in CUDA?

When a kernel is started, the number of blocks per grid and the number of threads per block are fixed ( gridDim and blockDim ). CUDA makes four pieces of information available to each thread: The thread index ( threadIdx )

What is kernel function in CUDA?

Figure 1 shows that the CUDA kernel is a function that gets executed on GPU. The parallel portion of your applications is executed K times in parallel by K different CUDA threads, as opposed to only one time like regular C/C++ functions. Figure 1. The kernel is a function executed on the GPU.

How to terminate a kernel using CUDA?

Note that since cuda 2.0 you can use assert () to terminate a kernel! A different approach could be the following ( I haven't tried the code!) where the kernel stopMe keeps running until someone from the host side sets up the flag to false.

What happens when you interrupt a kernel in Linux?

Interrupting the kernel stops the code from running but doesn’t remove the variable you have stored in memory. How do you know your code is running? You can tell a code is currently running by looking at the Circle in the top right corner of the notebook.

How does CUDA know which functions run on the CPU and GPU?

Since a CUDA program is running code on both the CPU and the GPU, there's got to be a way for the developer and the program itself to identify which functions are supposed to run on the CPU and which run on the GPU. CUDA calls code that is slated to run on the CPU host code, and functions that are bound for the GPU device code.

How do you stop code from running in Linux?

Every now and then you will run code that either runs forever (infinite loop) or has errors you identified and want to stop. To stop code from running you must interrupt the kernel. Interrupting the kernel stops the code from running but doesn’t remove the variable you have stored in memory. How do you know your code is running?


2 Answers

The CUDA execution model doesn't allow for inter-block communication by design. That can potentially make this sort of kernel abort on condition operation difficult to achieve reliably without resorting to the assert or trap type approaches which can potentially result in context destruction and loss of data which isn't what you probably want.

If your kernel design involves a small number of blocks with "resident" threads, then the only approach is some sort of atomic spinlock, which is hard to get to work reliably, and which will greatly degrade memory controller performance and achievable bandwidth.

If, on the other hand, your kernel design has rather large grids with a lot of blocks, and your main goal is to stop blocks which are not yet scheduled from running, then you could try something like this:

#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;
}

Here I have a simple kernel which is searching for a magic word in a large array. To get the early exit behaviour, I use a single global word, which is set atomically by those threads which "win" or trigger the termination condition. Every new block checks the state of this global word, and if it is set, they return without doing any work.

If I compile and run this on a moderate sized Kepler device:

$ 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

you can see that a large number of blocks in the grid saw the change in the global word and early terminated without running the search code. This might be the best you can do without a severely invasive spinlock approach which will greatly harm performance.

like image 200
4 revs Avatar answered Oct 13 '22 00:10

4 revs


I assume you want to stop a running kernel (not a single thread).

The simplest approach (and the one that I suggest) is to set up a global memory flag which is been tested by the kernel. You can set the flag using cudaMemcpy() (or without if using unified memory).

Like the following:

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

ams("trap;") will stop all running thread

Note that since cuda 2.0 you can use assert() to terminate a kernel!

A different approach could be the following (I haven't tried the code!)

__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 %i\n",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 %d\n", 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("END\n");


} 

where the kernel stopMe keeps running until someone from the host side sets up the flag to false. Note that your kernel could be much more complicated than this and the effort to synchronize all threads in order to execute the return could be much more than this (and can affect performance). Hope this helped.

More info here

like image 28
Davide Spataro Avatar answered Oct 12 '22 23:10

Davide Spataro