Debian Codegraph @

examples/example_project/example.cu

raw
1 /*
2 * SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 /*
19 This is a simple example demonstrating the use of CCCL functionality from Thrust, CUB, and libcu++.
20
21 The example computes the sum of an array of integers using a simple parallel reduction. Each thread block
22 computes the sum of a subset of the array using cuB::BlockRecuce. The sum of each block is then reduced
23 to a single value using an atomic add via cuda::atomic_ref from libcu++. The result is stored in a device_vector
24 from Thrust. The sum is then printed to the console.
25 */
26
27 #include <cub/block/block_reduce.cuh>
28
29 #include <thrust/device_vector.h>
30
31 #include <cuda/atomic>
32
33 #include <cstdio>
34
35 constexpr int block_size = 256;
36
37 __global__ void sumKernel(int const* data, int* result, std::size_t N)
38 {
39 using BlockReduce = cub::BlockReduce<int, block_size>;
40
41 __shared__ typename BlockReduce::TempStorage temp_storage;
42
43 int index = threadIdx.x + blockIdx.x * blockDim.x;
44
45 int sum = 0;
46 if (index < N)
47 {
48 sum += data[index];
49 }
50
51 sum = BlockReduce(temp_storage).Sum(sum);
52
53 if (threadIdx.x == 0)
54 {
55 cuda::atomic_ref<int, cuda::thread_scope_device> atomic_result(*result);
56 atomic_result.fetch_add(sum, cuda::memory_order_relaxed);
57 }
58 }
59
60 int main()
61 {
62 std::size_t N = 1000;
63 thrust::device_vector<int> data(N, 1);
64 thrust::device_vector<int> result(1);
65
66 int num_blocks = (N + block_size - 1) / block_size;
67
68 sumKernel<<<num_blocks, block_size>>>(
69 thrust::raw_pointer_cast(data.data()), thrust::raw_pointer_cast(result.data()), N);
70
71 auto err = cudaDeviceSynchronize();
72 if (err != cudaSuccess)
73 {
74 std::cout << "Error: " << cudaGetErrorString(err) << std::endl;
75 return -1;
76 }
77
78 std::cout << "Sum: " << result[0] << std::endl;
79
80 assert(result[0] == N);
81
82 return 0;
83 }