Demonstrate printing from a Numba CUDA kernel. This example uses numba.cuda.grid(3) as the primary indexing mechanism (recommended modern style), and also prints the equivalent blockId / threadId used in the CUDA C++ printf sample for side-by-side comparison. Uses cuda.core AP
(device, test_value=10)
| 186 | |
| 187 | |
| 188 | def run_numba_kernel(device, test_value=10): |
| 189 | """ |
| 190 | Demonstrate printing from a Numba CUDA kernel. |
| 191 | |
| 192 | This example uses numba.cuda.grid(3) as the primary indexing mechanism |
| 193 | (recommended modern style), and also prints the equivalent blockId / |
| 194 | threadId used in the CUDA C++ printf sample for side-by-side comparison. |
| 195 | |
| 196 | Uses cuda.core APIs for stream management, demonstrating interoperability |
| 197 | between Numba CUDA kernels and cuda.core infrastructure. |
| 198 | """ |
| 199 | print("\n") |
| 200 | print("=" * 70) |
| 201 | print("METHOD 2: Numba CUDA Kernel (Pythonic / modern indexing)") |
| 202 | print("=" * 70) |
| 203 | print("Advantage: Uses numba.cuda.grid(3) for global indexing,") |
| 204 | print(" while still showing classic CUDA C++ IDs for reference.") |
| 205 | print(" Uses cuda.core for stream management (interoperability).") |
| 206 | print() |
| 207 | |
| 208 | # Same launch configuration as the C++ version |
| 209 | grid_x, grid_y = 2, 2 |
| 210 | block_x, block_y, block_z = 2, 2, 2 |
| 211 | |
| 212 | print("Kernel configuration:") |
| 213 | print(f" Grid: ({grid_x}, {grid_y})") |
| 214 | print(f" Block: ({block_x}, {block_y}, {block_z})") |
| 215 | print(f" Total threads: {grid_x * grid_y * block_x * block_y * block_z}") |
| 216 | print() |
| 217 | |
| 218 | # Use cuda.core stream (same as C++ example) instead of numba.cuda.stream() |
| 219 | stream = device.create_stream() |
| 220 | |
| 221 | print(f"Launching Numba kernel (grid(3) + classic IDs) with value={test_value}:") |
| 222 | print("Uses numba.cuda.grid(3) to get global (x, y, z),") |
| 223 | print("and prints the corresponding blockId/threadId like the C++ sample.") |
| 224 | print("Stream managed by cuda.core for consistency with C++ example.\n") |
| 225 | |
| 226 | try: |
| 227 | # Launch Numba kernel on cuda.core stream |
| 228 | numba_print_kernel[(grid_x, grid_y), (block_x, block_y, block_z), stream]( |
| 229 | test_value |
| 230 | ) |
| 231 | |
| 232 | # Synchronize cuda.core stream (same as C++ example) |
| 233 | stream.sync() |
| 234 | print("\nNumba CUDA kernel execution complete.") |
| 235 | except Exception as e: |
| 236 | print(f"\nError during Numba kernel execution: {e}") |
| 237 | traceback.print_exc() |
| 238 | return 1 |
| 239 | finally: |
| 240 | # Cleanup |
| 241 | stream.close() |
| 242 | |
| 243 | return 0 |
| 244 | |
| 245 |