You Write What target Did for You
On Nov 23 one pragma made the compiler write the trip to the GPU and the loop on it. Today you write both yourself, in CUDA. One method, four steps, run on one loop, one size, one machine. Then you try it on launches that go wrong, and on a program where it does not apply at all.
Concept map
One idea, one worked example, then your turn. Every box is a section of this page.
Where the numbers come from: Nov 23's OpenMP run and a CUDA run of this same program, both on one Cardinal H100. Anything computed from the deck's arithmetic or a model is labelled as such.
Nov 23's words, CUDA's words
Nothing new, just spelled out. Each row is something the OpenMP version did for you and the CUDA version makes you write.
| Nov 23: OpenMP target | Today: CUDA | What it is |
|---|---|---|
#pragma omp target teams distribute parallel for | a kernel (a function marked __global__) plus a launch: <<<blocks, threads per block>>> | The loop, run by many GPU threads. There is no loop in the kernel: the grid of threads is the loop. |
map(to: x) map(tofrom: y) | cudaMalloc (room on the GPU) plus cudaMemcpy (the copy, each direction) | The trip: bytes crossing the road. CUDA makes you write every crossing. |
| No GPU: the loop quietly runs on the CPU | No GPU: an error | CUDA has no fallback, so a CUDA timing is always a GPU timing. |
Three words, the same ones as Nov 23. The trip is copying the arrays across the road to the GPU, and copying the results back. The road is the link between CPU memory and GPU memory. A pass is one full run of the loop over the array.
ON_DEVICE 0, ran the target loop on the CPU, and gave the right answer. A CUDA program on a machine with no GPU: what does it do? There is no fallback. cudaMalloc fails and the program stops with a message, so you cannot mistake a CPU run for a GPU run. Every call in the program is wrapped in CUDA_OK, which prints the failing call and exits. A CUDA timing is always a GPU timing.
The method: write the loop for the GPU by hand
Four steps. The next four sections run all of them on one program, one size, one machine: SAXPY, 100 million floats, 256 threads per block, one Cardinal GPU node.
Put the data on the GPU.
Allocate room there, copy the arrays over. This is the trip, written by hand.
Choose the grid.
Blocks = n ÷ threads per block, rounded up, so every element gets a thread.
Write the kernel.
Each thread computes its own index, and checks that it is inside the array.
Copy back, and check.
Bring the result home and check every element against the answer. Then time the pieces.
| Word | Plain meaning |
|---|---|
| thread | one worker. In this program, one thread handles one element of the array. |
| block | a group of threads. We use 256 per block. In OpenMP's words (Nov 23) a block is a team: threads that can share fast memory and wait for each other. |
| grid | all the blocks of one launch. |
| the trip | copying the arrays across the road to the GPU, and copying the results back. |
| the road | the link between CPU memory and GPU memory. |
| a pass | one full run of the loop over the array. |
The grid for the worked example, drawn from the arithmetic in Step 2: 100,000,000 elements, 256 threads per block.
Step 1: put the data on the GPU
Branch lecture14, cuda/src/main.cu, saxpyRun(). Abridged with ...: the loop that fills the arrays and the warm-up line are left out.
float* hx = nullptr; float* hy = nullptr; hx = new float[n]; hy = new float[n]; ... float* dx = nullptr; // device pointers: not usable on the host float* dy = nullptr; CUDA_OK(cudaMalloc(&dx, n * sizeof(float))); CUDA_OK(cudaMalloc(&dy, n * sizeof(float))); ... CUDA_OK(cudaMemcpy(dx, hx, n * sizeof(float), cudaMemcpyHostToDevice)); CUDA_OK(cudaMemcpy(dy, hy, n * sizeof(float), cudaMemcpyHostToDevice));
| Word | What it does |
|---|---|
hx, hy | ordinary CPU arrays from new. The letter h is for host, the CPU. |
dx, dy | addresses inside the GPU's memory. The letter d is for device, the GPU. Reading dx[0] on the CPU crashes. |
cudaMalloc | room on the GPU |
cudaMemcpy | the trip over, one array per call |
CUDA_OK | wraps every call: if it failed, print which call and stop |
Two memories again: each rank had its own memory in Week 3, and here the CPU and the GPU do, inside one node.
100,000,000 floats × 4 bytes = 400,000,000 bytes = 0.4 GB per array. Over: x and y, 2 × 0.4 = 0.8 GB. Back: y only, 0.4 GB. These are the same bytes as Nov 23's trip. The 1.2 GB that one pass reads and writes (12 bytes per element: read x, read y, write y) is a different number from what crosses the road. Do not mix them.
The trip, one line of code at a time. Step through it and watch which memory each array is in, and what has crossed the road so far.
cudaMemcpy is a crossing, and you wrote it.Step 2: choose the grid, rounding up
Threads per block is our choice: 256. Blocks is one division. Here it is for the worked example.
| Quantity | Arithmetic | Result |
|---|---|---|
| Threads per block (our choice) | 256 | |
| Blocks, rounded up | 100,000,000 ÷ 256 = 390,625 exactly | 390,625 |
| Threads launched | 390,625 × 256 | 100,000,000 |
| Elements with no thread | 100,000,000 − 100,000,000 | 0 |
The launch, from saxpyRun():
const int B = 256; long blocks = (n + B - 1) / B; saxpy<<<blocks, B>>>(n, 2.0f, dx, dy);LAUNCH_OK();
(n + B - 1) / B is a round-up in whole-number arithmetic. A launch returns nothing, so LAUNCH_OK() asks afterwards (it calls cudaGetLastError); a bad launch configuration is silent otherwise. This is Week 4's block partition again: the first element of rank r was r × n ÷ p, and the first element of block b is b × 256. Same formula, block for rank.
256 × 390,625 = 100,000,000, so the division is exact and rounding up changes nothing here: 390,625 blocks, 100,000,000 threads, one per element, none left over. The rule says round up anyway. Why, the try-it section shows.
Change n and the threads per block. This calculator rounds up and keeps the bounds check, which is the method. (Step 3 explains the check.) Computed in your browser from the table above.
Step 3: write the kernel
cuda/src/main.cu, saxpy(). A kernel is the function every thread runs. Every one of the 100 million threads runs this same function.
__global__ void saxpy(long n, float a, const float* x, float* y) { long i = blockIdx.x * (long)blockDim.x + threadIdx.x; if (i < n) { y[i] = a * x[i] + y[i]; } }
| Word | What it is |
|---|---|
blockIdx.x | which block this thread is in |
blockDim.x | threads per block: 256 |
threadIdx.x | which thread this is, inside its block |
i | the element this thread works on. There is no loop: the grid is the loop. |
if (i < n) | the bounds check. The grid is rounded up to whole blocks, so the last block can have threads past the end of the array. The check sends them home. Today's n has none, and the habit is not optional. |
(long) | makes the multiply 64-bit. Without it the product wraps at 4 billion. |
Same SAXPY as Nov 23: y = a × x + y with a = 2. Per element: read x (4 bytes), read y (4), write y (4), so 12 bytes and 1.2 GB per pass at n = 100 million.
i = 7 × 256 + 100 = 1,792 + 100 = 1,892. Blocks 0 to 6 hold elements 0 to 1,791, and this thread is the 101st of block 7. "107" adds instead of multiplying. "25,607" multiplies the wrong pair.
Pick any block and thread. The index is computed with the line above (n = 100,000,000, 256 threads per block). The worked example from the lecture is block 2, thread 5.
Step 4: copy back, check, and time the three pieces
The trip back is one more cudaMemcpy. Then the program compares every element of y with the answer and prints a CHECK line. Read the CHECK before any timing: if it says WRONG, stop and debug.
// the trip back CUDA_OK(cudaMemcpy(hy, dy, n * sizeof(float), cudaMemcpyDeviceToHost)); // then a loop over all n elements compares hy[i] with the answer
Each phase is timed with CUDA events, which are timestamps taken on the GPU: T_H2D (host to device, both copies over), T_KERNEL (one pass) and T_D2H (device to host, the trip back). The first CUDA call in a process pays a start-up cost, so the program makes a cudaFree(0) call before the timer starts. The program prints, in this order:
BLOCKS <blocks> x 256 threads = <threads> threads for n = <n> T_H2D <ms> ms (<GB/s> GB/s) T_KERNEL <ms> ms (<GB/s> GB/s) T_D2H <ms> ms (<GB/s> GB/s) CHECK saxpy ok
For n = 100,000,000 the first line is arithmetic you can confirm now: 390,625 blocks × 256 = 100,000,000 threads.
cudaMemcpy.Ordinary memory is what new gives you: the operating system may move it. Pinned memory is allocated with cudaMallocHost: the system promises never to move it. Same times as Nov 23? Is pinned faster? Write two numbers, in milliseconds: the trip over from ordinary memory, and the trip over from pinned memory.
The measurement table. All on one Cardinal H100. The Nov 23 column is the OpenMP target version, minimum of five trials. The two CUDA columns are the CUDA program of this lecture, one run each (job 17107699, cuda/12.4.1), so treat small differences with care.
Verdict. Pinned memory made the trip over about 5 times faster (14.49 ms against 72.78 ms, 55 GB/s) and the trip back about 2 times faster (9.231 ms against 18.2 ms). Ordinary memory written by hand came out close to what OpenMP target got on Nov 23: 72.78 ms over against 91.9 ms.
Why pinned is faster is the staging story: ordinary memory can be moved by the operating system, so a copy from it goes through a second, locked buffer, which costs an extra copy. Pinned memory is locked in place, so the copy engine reads it directly. Pinned over the road ran at 55 GB/s, close to the 50 GB/s the model assumed. The model's wrong speed was the ordinary-memory one. This run did not look inside the copy, so the staging explanation is the likely reason, not something this table proves.
What speed does a trip time imply? The road moves 0.8 GB over and 0.4 GB back, so speed = bytes ÷ time. Both boxes start at Nov 23's numbers; type your own once you have them.
Why it works: neighbours touch neighbours
First a model, then a measurement of it. This section explains why the kernel gives thread i the element i, and not some other element.
A group of 32 threads, called a warp, loads together. Memory answers in 32-byte pieces. A piece holds 8 four-byte ints. The model counts pieces. Thread t of the group reads element t × s, where s is the stride: how many elements apart neighbouring threads read. The writes stay adjacent: 4 pieces.
32 threads can touch at most 32 pieces, one each. Stride 8 already does. Stride 32 is the same 32 pieces, so the model is flat from stride 8 on. The model's relative time is (pieces read + 4 written) ÷ 8, which is (min(s, 8) + 1) ÷ 2.
Drag the stride. Highlighted pieces are the ones the group of 32 threads must fetch. Computed in your browser from the model above. Once you have answered the measurement question further down, this also shows the measured value at the six strides that were timed.
| Elements between the ones neighbouring threads read | Pieces the 32-thread group touches | Relative time: read, plus the adjacent write |
|---|---|---|
| 1 (thread i reads element i) | 4 | 1 (the baseline) |
| 2 | 8 | 1.5 |
| 4 | 16 | 2.5 |
| 8 | 32 | 4.5 |
| 32 | 32 | 4.5 (no worse: it cannot touch more) |
This is Oct 14's cache line, with a 32-byte piece in place of a 64-byte line: you pay for the piece, not the byte. Adjacent threads, adjacent addresses. Struct-of-arrays instead of array-of-structs is the same rule. The table above is the model: nothing in it was timed.
coalesce method times the real thing: out[i] = in[i * s] at strides 1, 2, 4, 8, 16 and 32, best of five launches each, as a ratio to stride 1. The model says the time rises to 4.5 times at stride 8 and then stays flat. Where does the measured time stop rising?One run on one Cardinal H100, measured only at these six strides:
| stride | model, relative time | measured, relative time |
|---|---|---|
| 1 | 1.00 | 1.00 |
| 2 | 1.50 | 1.33 |
| 4 | 2.50 | 2.19 |
| 8 | 4.50 | 3.83 |
| 16 | 4.50 | 7.23 |
| 32 | 4.50 | 7.30 |
The model said flat from stride 8, at 4.5 times. The measurement goes flat from stride 16, at 7.3 times, and is below the model until then.
Open question, left open. What would make the piece twice as big? One candidate, a hypothesis and not a result: memory is fetched in 64-byte pieces, not 32. Nothing on this page tests it. Decide what you would change in the model, and what measurement would tell you.
Pinned memory changes how the trip is carried out: Communication. The data does not live somewhere else, so it is not Locality; pinned is about how the bytes move, not where they sit.
| Concept | On the GPU | Where you saw it today |
|---|---|---|
| Decomposition | grid, block, thread: one thread per element | Steps 2 and 3 |
| Communication | the trip between CPU and GPU memory | Steps 1 and 4: the table of three pieces |
| Locality | neighbours in the grid touch neighbours in memory | The stride model and its measurement |
You try it: which launch is right?
Three launches of the same kernel, 256 threads per block. For each, work out the blocks, the threads launched, and which elements get a thread. Then say: right, wrong, or lucky? Do the arithmetic on paper first. Cases B and C are arithmetic. Case A was also run on Cardinal.
| Array size n | Blocks of 256 threads | Bounds check in the kernel | |
|---|---|---|---|
| A | 1,000,000 | n ÷ 256, whole-number division (rounds down) | kept |
| B | 1,000,000 | rounded up | deleted |
| C | 100,000,000 | n ÷ 256, whole-number division (rounds down) | kept |
1,000,000 ÷ 256 = 3,906.25. Whole-number division gives 3,906 blocks. 3,906 × 256 = 999,936 threads. Elements 999,936 through 999,999 have no thread: 1,000,000 − 999,936 = 64 elements, untouched. The bounds check cannot help: a thread that was never launched cannot check anything. No error, no warning. Wrong, silently.
The real run on Cardinal, ./CUDA saxpy_bug 1e6 (one run, one H100):
BLOCKS 3906 x 256 threads = 999936 threads for n = 1000000
CHECK saxpy_bug WRONG (64 of 1000000 elements, first at i = 999936)
The arithmetic predicted exactly this. All 64 are counted because x is never 0 in the program (x = i % 7 + 1), so every skipped element differs from the right answer. Week 4 had the same silence: n = 1000 across 3 ranks, 333 each, 999 total, one element dropped.
(1,000,000 + 255) ÷ 256 rounded down is 3,907 blocks (3,906.25 rounded up). 3,907 × 256 = 1,000,192 threads. The last 192 threads (1,000,192 − 1,000,000) have an index of 1,000,000 or more. With the check deleted, each writes y[i] past the end of the array: memory that belongs to something else, or to nothing. It may crash, it may corrupt a neighbour, it may look fine.
Every element of y is right, so a check of y alone passes. That is why this bug survives.
100,000,000 ÷ 256 = 390,625 exactly, rounded down or up. 390,625 blocks, 100,000,000 threads, one per element, none left over. Right because 256 divides 100 million, not because the formula is right. Change n to 100,000,001 and it is Case A again.
Check your arithmetic, after you have chosen. The three presets are the three cases; the controls are free. Computed in your browser. Then try n = 100,000,001.
Case D: add up the array. Where the method does not apply
A different program: the sum of all the elements. Six lines of blockSum in main.cu: 256 threads add up one block's numbers in shared memory, a small array that every thread of one block can see.
for (int h = blockDim.x / 2; h > 0; h >>= 1) { if (threadIdx.x < h) { s[threadIdx.x] += s[threadIdx.x + h]; } if (SYNC) { // NOT inside the if: every thread must reach it __syncthreads(); } }
SYNC is true in the method reduce and false in reduce_nosync, the same kernel with the wait deleted. The highlighted line is a wait: every thread of the block stops there until all of them have arrived.
Steps 1 to 4 assume one thread per element and no thread waiting on another. A sum breaks that: thread 0 cannot finish until threads 1 to 255 have written theirs.
What it takes instead. Threads in one block can wait for each other, so each block adds up its own 256 numbers in rounds: 128 threads add pairs, then 64, and so on, with a wait after every round, because each round reads what other threads wrote in the round before. Blocks cannot wait for each other, so each block leaves one total behind, and the block totals are added in a second step (in the program, on the CPU).
The wait is what keeps the answer right. Deleting it makes the answer depend on which warp happens to run first. It can be wrong on some runs and right on others, and nothing reports it. It is the race from Week 10, with a barrier as the fix.
One block, 256 threads, eight rounds. Each cell is a thread. In round r the threads with threadIdx.x < h are active, and each adds the number held by the thread h places along. Slide through the rounds. Computed from the loop above.
reduce and reduce_nosync each run the block sum 20 times and compare the total with the right answer. reduce_nosync is the same kernel with the wait deleted. Predict: in how many of its 20 runs is the total wrong?Measured on Cardinal, one H100, one run of each method:
reduce:
CHECK reduce ok (20 of 20 runs)
reduce_nosync:
run 0: got 16537191, expected 16777215
CHECK reduce_nosync WRONG (20 of 20 runs)
With the wait, all 20 runs were right. Without it, all 20 were wrong, and run 0 came out 240,024 short (16,777,215 minus 16,537,191). A race does not have to fail every time: on another GPU or another size it could pass, and nothing would report it. Here it failed every time, and the check of the total is what caught it.
Run it on Cardinal
Branch lecture14, folder cuda/. The program was run on Cardinal on Mon Nov 23 (job 17107699, one H100): one run per method, so yours will differ a little. Predict first, then open the box.
-
The lecture branch
git clone -o class git@gitlab.com:cs4540-spring-2019/cs-4170-5170-fall-2026/openmp.git openmpif you have not cloned yet, then:ssh <your-username>@cardinal.osc.edu cd openmp git fetch class git checkout -b lecture14 class/fa2026-openmp/lecture14
If you already made
lecture14on Nov 23, rungit checkout lecture14and thengit merge --ff-only class/fa2026-openmp/lecture14to bring it up to date. -
Predict first
Before you run anything, write down: the trip over from ordinary memory, the trip over from pinned memory, and how many elements
saxpy_buggets wrong. Use Nov 23's numbers and the try-it arithmetic, and say which you used.
Experiments
A · The three pieces, as a batch job
The job script loads the CUDA module, builds, prints the GPU's details, and runs every method once, writing results/*.txt. A GPU request sends the job to a GPU node.
cd ~/openmp/cuda module load cuda/12.4.1 make sbatch jobScript.slurm squeue -u $USER
When the job has left the queue:
cd ~/openmp/cuda grep -H CHECK results/*.txt cat results/saxpy.txt results/saxpy_pinned.txt
What you should see
The two result files each have a BLOCKS line, then T_H2D, T_KERNEL, T_D2H, a CHECK line and ELAPSED. Read the CHECK first; if it says WRONG, stop. On Nov 23 (one run each):
results/saxpy.txt BLOCKS 390625 x 256 threads = 100000000 threads for n = 100000000 T_H2D 72.78 ms (11 GB/s) T_KERNEL 0.7614 ms (1.58e+03 GB/s) T_D2H 18.2 ms (22 GB/s) CHECK saxpy ok results/saxpy_pinned.txt BLOCKS 390625 x 256 threads = 100000000 threads for n = 100000000 T_H2D 14.49 ms (55.2 GB/s) T_KERNEL 0.7243 ms (1.66e+03 GB/s) T_D2H 9.231 ms (43.3 GB/s) CHECK saxpy_pinned ok
Compare with your prediction and with Nov 23's OpenMP numbers: 91.9 ms, 0.599 ms and 35.2 ms. Which piece is furthest from your prediction, and which assumption does that name?
B · Live, with one GPU
Min of five: run it five times and take the best of each timing.
salloc --nodes=1 --ntasks=1 --cpus-per-task=8 --gpus-per-node=1 --time=00:15:00 -A PCS0313 module load cuda/12.4.1 cd ~/openmp/cuda make ./CUDA info for t in 1 2 3 4 5; do ./CUDA saxpy 1e8; done for t in 1 2 3 4 5; do ./CUDA saxpy_pinned 1e8; done
Confirmed on Nov 23: the module cuda/12.4.1 and --gpus-per-node=1 work, with no -p gpu needed, and the job script runs ./CUDA directly inside the batch job. Running it by hand inside salloc has not been tried; if ./CUDA finds no device there, use the batch job in A.
What you should see
./CUDA info printed this on Nov 23:
DEVICES 1 visible NAME NVIDIA H100 (compute capability 9.0) SMS 132 WARP 32 threads THREADS_PER_SM 2048 (= 64 warps) THREADS_PER_BLOCK 1024 SHARED_PER_SM 228 KB GLOBAL_MEM 99.9 GB CHECK info ok
132 processor clusters (SMs). The timings are the ones in experiment A. Your five runs of each give you a best of five; Nov 23's table is one run.
C · The launch bug, Case A
Predict first: how many elements, and where does the first wrong one sit?
./CUDA saxpy_bug 1e6
What you should see
The arithmetic predicts it, and Nov 23's run agrees:
BLOCKS 3906 x 256 threads = 999936 threads for n = 1000000
CHECK saxpy_bug WRONG (64 of 1000000 elements, first at i = 999936)
If your run disagrees with the arithmetic, that is a finding: say which assumption broke.
D · Stride, and the block sum
Predict first. For coalesce: the time ratio at each stride next to the model's 1, 1.5, 2.5, 4.5. For reduce_nosync: how many of 20 runs are wrong.
./CUDA coalesce ./CUDA reduce ./CUDA reduce_nosync
What you should see
On Nov 23, one run of each. coalesce prints the measured time ratio beside the model's:
STRIDE 1 0.07238 ms 1854 GB/s useful time x1.00 (model x1.00) STRIDE 2 0.09606 ms 1397 GB/s useful time x1.33 (model x1.50) STRIDE 4 0.1583 ms 848 GB/s useful time x2.19 (model x2.50) STRIDE 8 0.2769 ms 485 GB/s useful time x3.83 (model x4.50) STRIDE 16 0.5233 ms 256 GB/s useful time x7.23 (model x4.50) STRIDE 32 0.5285 ms 254 GB/s useful time x7.30 (model x4.50) CHECK coalesce ok
reduce ended CHECK reduce ok (20 of 20 runs). reduce_nosync printed run 0: got 16537191, expected 16777215 and CHECK reduce_nosync WRONG (20 of 20 runs). The measured stride curve is flat from 16, not from 8 as the model said. Why is an open question: what would make the piece twice as big?
Check yourself
Six questions, instant feedback, nothing recorded.
cudaMemcpy, and one comes back. How many bytes cross the road each way?(n + B - 1) / B with whole-number division gives how many blocks, and why is that the right rule?LAUNCH_OK() asks for the last error and stops the program if there is one. Note that a launch can be configured correctly and still be the wrong grid for n: that is Case A, and only the check of every element catches it.__syncthreads() do in the block sum?