From CPU array to GPU result
Change the input length and follow allocation, copies and the kernel launch.
Before you run
The input array x starts in CPU memory. The CPU reserves separate GPU input and output arrays, copies x to the GPU input and launches runKernel. After the kernel writes the GPU output, the CPU copies those results into array y.
Definitions
- Host
- The CPU side of a CUDA program.
- Device
- The GPU side of a CUDA program.
- Allocation
- A request for enough storage to hold the data.
Read the starter excerpts
Read-only CUDA C++ · main() · host excerpt
CUDA_CHECK(cudaMalloc(&d_x, sizeof(x)));
CUDA_CHECK(cudaMalloc(&d_y, sizeof(y)));
CUDA_CHECK(cudaMemcpy(
d_x, x, sizeof(x),
cudaMemcpyHostToDevice));
cudaMalloc reserves GPU storage for d_x and d_y. cudaMemcpy copies sizeof(x) bytes from CPU array x to d_x. The later kernel launch passes n elements, and a device-to-host copy fills CPU array y before it is printed.
The program calculates n, the number of input elements, from x automatically. sizeof(x) gives the input size in bytes: five FP32 values occupy 20 bytes. Appending values to x updates both quantities for the next run.
In each cudaMemcpy call, the arguments give the destination address, source address, byte count and copy direction, in that order. cudaMemcpyHostToDevice selects CPU-to-GPU copying; cudaMemcpyDeviceToHost selects GPU-to-CPU copying. CUDA_CHECK reports CUDA errors; keep these supplied checks unchanged.
CUDA C++ · launch inside main()
runKernel<<<blocks, threadsPerBlock>>>(
d_x, d_y, n);The settings inside <<< >>> give the block count and threads per block. Parentheses pass the arguments to the kernel. These read-only excerpts show the starter. The CUDA source editor contains the storage and launch settings.
Edit and run CUDA
The CUDA source editor opens with the complete starter or your saved draft. To run the starter again, use Editor tools → Restore starter. Choose Undo restore there to recover the previous draft.
Click Compile and run with the starter. In Console, find the five values in Output. Open Trace CUDA calls and find the two cudaMemcpy lines, each with 20 bytes, and the line for 2 blocks × 4 threads.
Change the source
In main() in the CUDA source editor, append 6.0f, 7.0f, 8.0f and 9.0f to array x. Predict the bytes per copy and the block count and click Compile and run again. In Trace CUDA calls, compare the cudaMemcpy byte counts and blocks × threads line with the starter. How many values does Console’s Output contain?
Read the starter’s execution diagram
- CPU input xThe host copies values to the GPU.
- GPU input d_xThreads with i < n read their input elements.
- GPU output d_yThose threads write matching output elements.
- CPU output yThe host copies the completed results back.
Allocation creates the GPU storage. The two copies move values across the CPU–GPU boundary.
Hardware context
CPU arrays live in system RAM. Device arrays live in GPU device memory. Allocation reserves storage; copying moves values, and the SM executes the calculation.
CPU side · CUDA host
Host ↔ device · copies move data; launches request execution
GPU device
GPU compute chip
SM · streaming multiprocessor
Logical groups using this SM’s resources
Can run other blocks.
Blocks may be assigned to different SMs.
Chip ↔ device memory · data transfers
Simplified NVIDIA-style architecture. Boundaries show containment; arrows name relationships. Unit counts, block placement and timing vary by GPU. A thread is not a dedicated physical processor.
Explore the model: allocation and copies
Trace the model inputs and outputs
Try it
With Number of inputs set to 5, click Run model. Use Next step to inspect Allocate GPU arrays, Copy input to the GPU, Run the kernel and Copy results to the CPU. Set Number of inputs to 9 and predict bytes per GPU array and the block count. Click Run model again and step through the same phases. How do the allocation sizes, copy sizes and block count change?
These controls change only this model and its displayed source excerpt. They do not edit or run the CUDA program above.
CUDA C++ · input and allocation
const float x[] = {
1.0f, 2.0f, 3.0f, 4.0f, 5.0f
};
const int n = sizeof(x) / sizeof(x[0]);
float y[n];
float *d_x, *d_y;
CUDA_CHECK(cudaMalloc(&d_x, sizeof(x)));
CUDA_CHECK(cudaMalloc(&d_y, sizeof(y)));n is the number of elements in x. sizeof(x) gives its size in bytes. cudaMalloc reserves storage, and cudaMemcpy moves the values between the host and device.
Input [1.0, 2.0, 3.0, 4.0, 5.0]
Run to see the result.
Read the complete model program
CUDA C++ · complete program
// CUDA C++ Lab · hello.cu
#include <cuda_runtime.h>
#include <cstdio>
#include <cstdlib>
void check(cudaError_t status) {
if (status != cudaSuccess) {
std::fprintf(stderr, "%s\n", cudaGetErrorString(status));
std::exit(1);
}
}
#define CUDA_CHECK(call) check(call)
__global__ void runKernel(
const float* input, float* output, int n
) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
output[i] = input[i] * 2.0f;
}
}
int main() {
const float x[] = {
1.0f, 2.0f, 3.0f, 4.0f, 5.0f
};
const int n = sizeof(x) / sizeof(x[0]);
float y[n];
float *d_x, *d_y;
CUDA_CHECK(cudaMalloc(&d_x, sizeof(x)));
CUDA_CHECK(cudaMalloc(&d_y, sizeof(y)));
CUDA_CHECK(cudaMemcpy(
d_x, x, sizeof(x),
cudaMemcpyHostToDevice));
const int threadsPerBlock = 4;
const int blocks =
(n + threadsPerBlock - 1) / threadsPerBlock;
runKernel<<<blocks, threadsPerBlock>>>(
d_x, d_y, n);
CUDA_CHECK(cudaGetLastError());
CUDA_CHECK(cudaDeviceSynchronize());
CUDA_CHECK(cudaMemcpy(
y, d_y, sizeof(y),
cudaMemcpyDeviceToHost));
std::printf("Output: [");
for (int i = 0; i < n; ++i) {
std::printf("%s%g", i ? ", " : "", static_cast<double>(y[i]));
}
std::printf("]\n");
CUDA_CHECK(cudaFree(d_x));
CUDA_CHECK(cudaFree(d_y));
}
Apply what you saw
With nine inputs, when can the CPU first read the results from y?
Compare your explanation
After the device-to-host copy. The kernel has written nine results to the GPU output array before that copy fills the CPU array y.
Further practice: Learn to check every GPU result.
Follow values across two memory domains 2 min · Video walkthrough, captions and transcript
Use fullscreen to inspect the code and diagram labels.
Read the transcript
The CPU and GPU arrays are separate
The five starting values live in a CPU array in system RAM. GPU execution needs a device input array and a device output array. Follow one value across these separate memory domains.
Allocation reserves storage
cudaMalloc reserves device storage. Reserving an address does not copy the CPU input into it. Five FP32 values need twenty bytes in each device array. FP32 means a four-byte floating-point value here.
The input copy supplies the values
The host-to-device copy fills the GPU input array from the CPU array. The original CPU array remains a separate object. The kernel receives the address of the device array, not the CPU array.
The SM performs the calculation
An SM executes the thread instructions. The thread reads its device input, multiplies the value and writes the device output. A CPU output variable has not received that result merely because the GPU wrote its own array.
Copy back before the CPU prints
The supplied device-to-host copy fills the CPU output array before main prints it. This copy connects GPU-produced values to CPU observation. It is a separate data movement from the kernel’s arithmetic.
Now prepare nine inputs
Consider an input array containing nine FP32 values. Pause and predict the size of each device array and the size of each complete array copy. Does doubling the values require doubling that byte count again?
Count elements and bytes separately
Each nine-value array needs thirty-six bytes. The input copy and the result copy each move thirty-six payload bytes. Multiplying by two changes the values, not how many FP32 elements the arrays hold. Allocation, copying and computation solve different jobs.
References explicit memory management · kernel launches
The browser exercises need no installed CUDA documentation version. For local execution, use the documentation matching your toolkit. External references need internet access.
- CUDA · explicit memory management (new tab)
An FP32 value occupies four bytes. Allocation reserves storage; a separate copy supplies its contents.
Seven FP32 values need how many bytes? Does allocating those bytes also copy the CPU inputs?
Compare your answer
Seven four-byte values need 28 bytes. Allocation reserves storage; a separate copy or other initialisation supplies its contents.
- CUDA · kernel launches (new tab)
The launch gives blocks and threads per block. Kernel arguments supply data and array bounds.
For nine values and four threads per block, what launch covers the input, and what must the kernel still check?
Compare your answer
Three blocks cover twelve thread indices. Pass n = 9 separately and guard array accesses with i < n; the launch does not allocate storage.
Further GPU investigation Run this CUDA example on an NVIDIA GPU
In the CUDA source editor, open Editor tools and choose Export .cu to save the complete program. Use an NVIDIA GPU and a matching CUDA toolkit to run it outside the browser.
Browser simulation checks program behaviour; physical GPU timing requires a hardware measurement.
Enable JavaScript to save completion.