Perform vector addition using cuda.core API. Parameters ---------- num_elements : int Number of elements in each vector device_id : int CUDA device ID to use verify : bool Whether to verify the result Returns ------- bool True if
(num_elements=50000, device_id=0, verify=True)
| 68 | |
| 69 | |
| 70 | def vector_add_cuda_core(num_elements=50000, device_id=0, verify=True): |
| 71 | """ |
| 72 | Perform vector addition using cuda.core API. |
| 73 | |
| 74 | Parameters |
| 75 | ---------- |
| 76 | num_elements : int |
| 77 | Number of elements in each vector |
| 78 | device_id : int |
| 79 | CUDA device ID to use |
| 80 | verify : bool |
| 81 | Whether to verify the result |
| 82 | |
| 83 | Returns |
| 84 | ------- |
| 85 | bool |
| 86 | True if successful, False otherwise |
| 87 | """ |
| 88 | try: |
| 89 | # Initialize device |
| 90 | print("[Vector addition using CUDA Core API]") |
| 91 | device = Device(device_id) |
| 92 | device.set_current() |
| 93 | |
| 94 | print(f"Device: {device.name}") |
| 95 | print(f"Compute Capability: sm_{device.arch}") |
| 96 | |
| 97 | stream = device.create_stream() |
| 98 | |
| 99 | # Compile kernel |
| 100 | print("Compiling kernel 'vectorAdd<float>'...") |
| 101 | program_options = ProgramOptions(std="c++17", arch=f"sm_{device.arch}") |
| 102 | program = Program(VECTOR_ADD_KERNEL, code_type="c++", options=program_options) |
| 103 | module = program.compile("cubin", name_expressions=("vectorAdd<float>",)) |
| 104 | kernel = module.get_kernel("vectorAdd<float>") |
| 105 | print("Kernel compiled successfully") |
| 106 | |
| 107 | # Allocate and initialize vectors |
| 108 | print(f"[Vector addition of {num_elements} elements]") |
| 109 | dtype = cp.float32 |
| 110 | |
| 111 | a = cp.random.rand(num_elements).astype(dtype) |
| 112 | b = cp.random.rand(num_elements).astype(dtype) |
| 113 | c = cp.empty(num_elements, dtype=dtype) |
| 114 | |
| 115 | # Synchronize before kernel launch |
| 116 | device.sync() |
| 117 | |
| 118 | # Configure and launch kernel |
| 119 | threads_per_block = 256 |
| 120 | blocks_per_grid = (num_elements + threads_per_block - 1) // threads_per_block |
| 121 | |
| 122 | print( |
| 123 | f"CUDA kernel launch with {blocks_per_grid} blocks " |
| 124 | f"of {threads_per_block} threads" |
| 125 | ) |
| 126 | |
| 127 | config = LaunchConfig(grid=blocks_per_grid, block=threads_per_block) |
no test coverage detected