Guide to AI and Data Courses · Lecture Notes

Chapter 37: GPU Programming and Parallel Computing

Two arrays of two million numbers have to be added element by element. A single processor core does it one element after another, yet every addition is independent of the others and all of them are the same operation. GPU programming is the course about spreading this kind of work over thousands of threads. But fast code is more than splitting the work: the data has to sit in the right memory, and the gain has to be measured honestly. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.

Learning outcomes

Thread organization
Compute the number of blocks for a given problem size and find the global index of a thread.
Memory hierarchy
Tell registers, shared memory and global memory apart by speed and size; explain coalesced access with an example.
Tiling
Count the global memory reads in a tiled matrix multiplication by hand and explain why they drop.
Speedup
Compute the expected speedup with Amdahl's law; show how data transfer lowers the speedup.
Place of the course
State what separates GPU programming from deep learning, big data systems, computer graphics and embedded AI.

37.1What question does the course ask?

How do thousands of cores share the same computation?

GPU programming studies data-parallel computation, which applies the same operation to thousands of data elements at once. Using a model such as CUDA, the course teaches how to organize threads, use the memory hierarchy efficiently and measure speedup; this is also the hardware that makes deep learning practical.

A CPU has a few powerful cores and tries to make every kind of work fast; it has complex branching and large caches. A GPU has thousands of simple cores and does one thing well: apply the same operation to many data elements at once. The course therefore turns the question "how do I make this faster?" into "which part of this work consists of independent, similar operations?"

The first skill of the course is finding parallelism. If every output element can be computed independently of the others (vector addition, a pixel filter), the work splits easily. If an element depends on the previous one (a running sum), or the work branches in very different directions across threads, splitting is harder, and separate patterns are learned for it.

37.1.1Compute or memory?

The second skill is asking where the time goes. The compute power of a GPU is very high, but fetching data from memory and copying between CPU and GPU cannot keep up with it. Most successful GPU programs get faster not by reducing computation but by organizing memory access. The Deep Learning course uses this hardware through ready-made libraries; this course teaches how to write the kernels beneath those libraries.

37.1.2At a glance

CriterionGPU Programming and Parallel Computing
Approachdata-parallel computation
Inputparallelizable algorithm
Outputaccelerated program
Success measurespeedup, memory bandwidth
Math loadlow-medium
Data needsnone

37.2A short history

YearMilestone
1966Flynn classifies computers as SISD, SIMD, MISD and MIMD.
1967Amdahl shows that the remaining sequential part limits parallel speedup (Amdahl's law).
1999NVIDIA GeForce 256 is marketed under the name "GPU".
2007NVIDIA releases CUDA: the GPU becomes general-purpose programmable in a C-like language.
2012AlexNet is trained on two GPUs and wins ImageNet; the GPU becomes the engine of deep learning.
2017The Volta architecture introduces tensor cores: hardware units dedicated to matrix multiplication.

37.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
SIMT and warps32 threads execute the same instruction together.
Thread organizationThe grid, block and thread hierarchy.
Memory hierarchyRegisters, shared memory, global memory.
Coalesced accessNeighboring threads should access neighboring addresses.
SynchronizationBarriers, atomic operations and race conditions.
Amdahl's lawThe sequential part caps the achievable speedup.
OccupancyEnough threads to keep the cores busy.
Parallel patternsMap, reduction, prefix sum, stencil.

37.4The thread model: grid, block, thread

In a model such as CUDA a program has two parts: host code that runs on the CPU and a kernel that runs on the GPU. The kernel is written once, but a large number of threads execute it at the same time. Threads are organized on three levels: threads are gathered into blocks and blocks into a grid. Every thread knows its block number and its number inside the block, and from them it computes which data element it handles.

Definition 37.1 (Global index and number of blocks)

In a one-dimensional layout the global index of a thread is i = blockIdx · blockDim + threadIdx. For n elements and blocks of B threads the number of blocks needed is ⌈n / B⌉ (rounded up).

Example 37.1: Adding vectors of two million elements

We want c[i] = a[i] + b[i] for arrays a and b of two million (n = 2,000,000) elements. One thread per element is used, with B = 256 threads per block.

  1. Number of blocks. 2,000,000 / 256 = 7812.5; rounded up, 7813 blocks.
  2. Total threads. 7813 · 256 = 2,000,128. So there are 128 extra threads; the kernel leaves them idle with an if (i < n) check.
  3. Index of one thread. In block 3 (blockIdx = 3) the thread with threadIdx = 5 adds element i = 3 · 256 + 5 = 773.
  4. Number of warps. A block is 256 / 32 = 8 warps. The last block (numbering starts at 0, so block 7812) handles only 2,000,000 − 7812 · 256 = 128 elements: 4 warps work and 4 warps are idle.

These 2 million additions are independent of each other; the GPU distributes them to its cores in blocks.

37.4.1Warps and branch divergence

The hardware executes threads in groups of 32 called warps; the 32 threads of a warp process the same instruction at the same time (SIMT). If an if/else makes threads of one warp choose different paths (branch divergence), the hardware runs one path first and the other afterwards, and the threads that did not choose the running path wait. The time of a diverging warp is therefore the sum of the times of the two paths. That is why decisions in kernels should be aligned with warp boundaries wherever possible.

Common mistake

Thinking that every thread behaves like an independent CPU core. The 32 threads of a warp execute the same instruction together; if half go one way and half the other, the two paths run one after the other and the gain is halved. Also, because the thread count is rounded up, forgetting the i < n check makes the kernel write outside the array.

37.5Memory hierarchy, coalescing and tiling

On a GPU computation is cheap and memory access is expensive. Data lives in three main places: registers private to each thread (fastest, very small); shared memory shared by the threads of one block (fast, a few tens of kilobytes per block); and global memory seen by the whole grid (large, but much slower). A good kernel goes to global memory as little as possible and reuses data in shared memory.

37.5.1Coalesced access

The 32 threads of a warp go to global memory at the same time. If neighboring threads access neighboring addresses, the hardware merges these 32 requests into a few large reads. In a simplified model (4-byte float, 128-byte read unit) it looks like this:

Access patternRange coveredReads needed
32 threads read 32 consecutive elements32 · 4 = 128 bytes1
Stride 2: every second element is read256 bytes2
One column of a row-major matrix with 1024 columns (elements 4096 bytes apart)32 separate locations32

Reading the same 32 elements can take 32 times the memory traffic; that is why keeping matrices row-major and giving neighboring threads neighboring elements is often the cheapest improvement.

37.5.2Tiled matrix multiplication

For C = A · B the naive method has each thread compute one C[i][j] and read a row of A and a column of B from global memory. Neighboring threads read the same A and B elements too, so the data is fetched many times for nothing. In tiling the matrices are cut into T × T tiles; at each step the block brings one tile of A and one tile of B into shared memory once, and all threads reuse it.

Example 37.2: 4 × 4 matrices, 2 × 2 tiles

A = [[1,2,3,4],[5,6,7,8],[1,0,1,0],[0,1,0,1]], B = [[1,0,2,1],[0,1,1,2],[3,1,0,0],[1,2,1,0]] and T = 2. Each thread computes one C element; there are 16 threads.

  1. Naive method. A C element reads 4 elements of A and 4 of B: 8 global reads. Total 16 · 8 = 128.
  2. Tiled. There are 4 / 2 = 2 steps. In each step a thread brings 1 element of A and 1 of B into shared memory: 2 reads per step, 2 · 2 = 4 per thread. The total is 16 · 4 = 64: reads fell by a factor of T, here half.
  3. Result. For C[0][0] the first pair of tiles gives [1, 2] and [1, 0]: 1·1 + 2·0 = 1. The second pair is [3, 4] and [3, 1]: 3·3 + 4·1 = 13. Total C[0][0] = 1 + 13 = 14.

At real sizes the gain is large: for a 1024 × 1024 matrix the naive method makes 2 · 1024 = 2048 reads per thread; with T = 16 tiles this becomes 2048 / 16 = 128.

Common mistake

Not placing a barrier after writing to shared memory. Each thread writes only part of the tile but reads what all of them wrote; if it reads before the writing is finished, it reads stale data. A barrier (__syncthreads) is needed in the block after the tile is loaded and before the next tile is loaded.

37.6Speedup and Amdahl's law

In GPU programming success is measured by speedup: S = Tseq / Tpar. But if the program cannot be parallelized entirely, the speedup is limited. If the parallelizable fraction of the run time is p and that part is made N times faster:

Definition 37.2 (Amdahl's law)

S(N) = 1 / ((1 − p) + p / N). As N → ∞, S → 1 / (1 − p): the sequential fraction 1 − p sets the upper bound on the speedup.

Example 37.3: A program that is 90% parallel

90% of a program's run time can be parallelized (p = 0.9).

  1. 10 times. S = 1 / (0.1 + 0.9/10) = 1 / 0.19 ≈ 5.26.
  2. 100 times. S = 1 / (0.1 + 0.009) ≈ 9.17.
  3. Unlimited. S → 1 / 0.1 = 10.

Making the parallel part 100 times faster instead of 10 times raised the total speedup only from 5.26 to 9.17. The most one can ever get is 10.

37.6.1Data transfer is part of the time

The sequential part in Amdahl's law is not only CPU code. Copying data from CPU memory to GPU memory and bringing the result back are part of the time as well. However fast the kernel is, the copy time does not change. Looking only at the kernel time in a measurement makes the speedup look far larger than it is.

Example 37.4: Speedup including copies (the values are illustrative)

The sequential CPU version takes 100 ms. In the GPU version, bringing the data takes 12 ms, the kernel 4 ms and taking the result back 9 ms.

  1. Kernel only. 100 / 4 = 25 times.
  2. Total time. 12 + 4 + 9 = 25 ms; 100 / 25 = 4 times.

Is the speedup of the same program 25 or 4? The second is right: the user waits for the copies too. That is why keeping data on the GPU and reusing it across several operations, and overlapping copies with computation (streams), are important improvements.

Common mistake

Reporting a speedup against a weak CPU version. A single-threaded CPU code with compiler optimization turned off makes the GPU look excellent. An honest measurement uses a well-written CPU version (parallel with OpenMP if needed) on the same input and includes the copy time.

37.7How is the course taught?

37.7.1A typical workflow

Findparallelismdata-parallelloopsCopydataCPU → GPUmemoryLaunchkernelgrid, block,threadCopybackGPU → CPUMeasure,optimizeprofiling,memory access
Figure 37.1: A typical workflow in GPU Programming and Parallel Computing

To add two vectors of two million elements, one thread is assigned to each element: the arrays are copied to GPU memory, the kernel is launched with 256-thread blocks and the result is copied back. Measurement often shows that the time goes into copying data, not into computing.

37.7.2Topics over the semester

  1. Parallel architectures: Flynn's taxonomy, CPU vs GPU
  2. The CUDA model: grids, blocks and threads
  3. Memory hierarchy and CPU-GPU data transfer
  4. Coalesced access and shared memory
  5. Warp execution, branch divergence, occupancy
  6. Synchronization, atomics and race conditions
  7. Parallel patterns: reduction and prefix sum
  8. Stencils, histograms and sparse matrix operations
  9. Tiled matrix multiplication and tensor cores
  10. Streams, asynchronous copies and multiple GPUs
  11. Profiling: Nsight and the roofline model
  12. OpenMP on the CPU, MPI on clusters

This is a typical semester; the order and coverage vary between universities.

37.7.3Skills you will gain

  • writing CUDA C kernels
  • finding bottlenecks with Nsight
  • Numba and CuPy in Python
  • CPU parallelism with OpenMP
  • measuring speedup correctly

37.7.4Try it yourself

The Try It: Add Thousands of Numbers at Once slide in the presentation lets you solve a typical problem of this course yourself: Computing a network's loss means adding millions of numbers; a GPU does it as a tree, adding pairs at the same time. Change the thread count and watch step by step; Amdahl's law shows the limit.

37.8Are you ready for this course?

37.8.1Prerequisites

CourseWhy it is needed
Programming with Cpointers, arrays and memory allocation: the basis of CUDA C
Operating Systemsthreads, synchronization and race conditions
Microprocessorsregisters, caches and the memory hierarchy

37.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you manage a dynamic array in C with pointers and malloc?A C programming course
Can you explain the race when two threads write the same variable?Threads and synchronization from operating systems
Can you explain the speed gap between cache and main memory?A microprocessors or computer architecture course
Can you write the product of two matrices with nested loops?Linear Algebra

37.9Neighboring courses

Deep LearningComputer GraphicsBig DataEmbedded AIGPU & Parallel Computing
subfieldbuilds onshares methodsapplication
Figure 37.2: Neighbors of GPU Programming and Parallel Computing and the kind of relation

37.9.1Where it overlaps

RelationCourseShared ground
builds onDeep Learning builds on this courseparallel training of large networks, tensor operations
shares methodsShares methods with Computer Graphicsgraphics pipeline, shaders
shares methodsShares methods with Big Data Systemsparallel and distributed computing
shares methodsShares methods with Embedded AIhardware accelerators

37.9.2Where it differs

  • Deep Learning: Deep learning uses the GPU through ready-made libraries; this course writes the kernels and memory access beneath them.
  • Big Data Systems: Big data systems spread work across many machines; this course makes efficient use of thousands of cores on one device.
  • Computer Graphics: Computer graphics programs the GPU with shaders to draw images; this course uses it for general-purpose computation.
  • Embedded AI: Embedded AI teaches making do with little power; this course teaches getting peak performance from the largest accelerator.

37.10In practice

37.10.1Applications

AreaWhat is done
Deep learningMatrix multiplication and convolution on tensor cores.
Scientific simulationFluids, climate and molecular dynamics.
Image and videoReal-time filters, encoding and decoding.
FinanceMonte Carlo risk and pricing.
BioinformaticsSequence alignment and protein structure computation.
Data analyticsTable and database operations on the GPU.

37.10.2Risks and ethics

RiskExplanation
Inflated speedupsLeaving out data transfer or comparing against a weak CPU baseline makes the speedup look far larger than it is.
Silent race bugsA kernel with missing synchronization is right on most runs and wrong on some; the bug is hard to catch.
Floating-point differencesParallel sums change the order of operations, so results differ slightly from the CPU and from run to run.
Energy and costGPU clusters that train large models draw a lot of power; inefficient code inflates that cost for nothing.

These issues are discussed in depth in Explainable AI and AI Ethics.

37.10.3Tools and datasets

Tools: CUDA, OpenCL, OpenMP, MPI, Numba, CuPy, NVIDIA Nsight.

Classic example problems: Vector addition, Matrix multiplication, Parallel reduction, Prefix sum (scan), Histogram, N-body simulation.

The metric is speedup: a sequential CPU version and a parallel GPU version of the same problem are compared on the same input.

37.11Common misconceptions

Common mistake

A GPU speeds up any program.

Only parts with many independent, similar operations speed up; branching and sequential parts do not.

Common mistake

Doubling the cores halves the run time.

Amdahl's law: the sequential part sets an upper bound on the achievable speedup.

Common mistake

Computation is the most expensive part.

In most GPU programs the bottleneck is memory bandwidth and data transfer between CPU and GPU.

Common mistake

Parallel programming is only for deep learning.

Simulation, graphics and scientific computing used GPUs long before deep learning.

37.12Summary

  • The GPU speeds up data-parallel computation, which applies the same operation to many data elements at once; the course teaches this with a model such as CUDA.
  • Threads are gathered into blocks and blocks into a grid; the global index is blockIdx · blockDim + threadIdx and the number of blocks is ⌈n / B⌉. The hardware works in warps of 32; branch divergence wastes time.
  • Memory is more expensive than computation: registers, shared memory, global memory. Coalesced access and tiling reduce global memory traffic.
  • Speedup is limited by S = 1 / ((1 − p) + p/N); the sequential part sets the upper bound.
  • Honest measurement counts data transfer and compares against a good CPU version; parallel code with missing synchronization produces silent bugs.

37.13Test Yourself

  1. A vector of n = 1000 elements is processed with 128 threads per block. How many blocks are needed and how many threads sit idle? What is the global index of the thread with threadIdx = 17 in block 5?

    Answer

    ⌈1000/128⌉ = ⌈7.8125⌉ = 8 blocks; 8 · 128 = 1024 threads, so 24 are idle. The index is 5 · 128 + 17 = 657.

  2. 80% of a program can be parallelized. What is the total speedup when the parallel part becomes 16 times faster? What is the most it could ever be with unlimited speedup?

    Answer

    S = 1 / (0.2 + 0.8/16) = 1 / 0.25 = 4. The upper bound is 1 / 0.2 = 5; 4 is already 80% of that bound.

  3. Compute the sum of the eight-element array [3, 1, 7, 0, 4, 1, 6, 3] with a binary-tree reduction: in each step element i is added to element i + s (s = 4, 2, 1). How many steps does it take?

    Answer

    Step s = 4: [7, 2, 13, 3]. Step s = 2: [20, 5]. Step s = 1: 25. The sum is 25 (3+1+7+0+4+1+6+3 = 25); log2 8 = 3 steps. A sequential sum would need 7 steps.

  4. The sequential version takes 120 ms. In the GPU version, bringing the data takes 12 ms, the kernel 8 ms and taking the result back 10 ms. What is the speedup by kernel only and by total time?

    Answer

    Kernel only: 120/8 = 15. Total time 12 + 8 + 10 = 30 ms: 120/30 = 4. The correct report is 4 times.

  5. In a warp, threads with even threadIdx go to a branch taking 10 cycles and odd ones to a branch taking 6 cycles. How long does the diverging warp take? What if the decision took the whole warp to the same branch (depending on the warp number)?

    Answer

    A diverging warp runs the two paths one after the other: 10 + 6 = 16 cycles. If the decision were aligned with warp boundaries, each warp would go to only one branch: 10 or 6 cycles.

  6. Thousands of threads write count = count + 1 to the same variable count. Why is the result smaller than expected, and how is it fixed?

    Answer

    Each thread reads the value, adds 1 and writes it back; if two threads read the same old value, one overwrites the other's update (a race condition). For example two threads that both read 0 both write 1, so the result is 1 instead of 2. The fix is an atomic operation (atomicAdd), or reducing inside the block first and doing only one atomic add per block.

37.14After this course

GPU programming opens up the engine beneath deep learning and graphics. From here you can move to systems topics such as distributed training, compilers and accelerator design, or to neighboring courses in the guide such as big data systems and embedded AI.

Courses that build on or extend this one: Deep Learning.

Related careers: GPU software engineer, High-performance computing (HPC) specialist, ML infrastructure engineer, Game and graphics engine developer, Scientific computing researcher.

37.15Further reading

  • D. B. Kirk, W. W. Hwu and I. El Hajj, Programming Massively Parallel Processors (4th ed., 2022): explains the thread model, coalesced access, tiled matrix multiplication and patterns such as reduction step by step.
  • J. Sanders and E. Kandrot, CUDA by Example (2010): a beginner-level introduction built on small, working CUDA C programs.
  • J. L. Hennessy and D. A. Patterson, Computer Architecture: A Quantitative Approach (6th ed., 2017): treats Amdahl's law and data-parallel architectures such as the GPU at textbook level.

37.16References

  1. Kirk, Hwu and El Hajj, Programming Massively Parallel Processors, 4th ed., Morgan Kaufmann, 2022.
  2. Sanders and Kandrot, CUDA by Example, Addison-Wesley, 2010.
  3. Hennessy and Patterson, Computer Architecture: A Quantitative Approach, 6th ed., Morgan Kaufmann, 2017.
  4. Amdahl, "Validity of the Single Processor Approach to Achieving Large Scale Computing Capabilities", AFIPS Conference Proceedings 30, 1967.

Related pages: Slides · Slides (PDF) · Course page