Learn / Lessons

CUDA intermediate

You know the layers. Now, how does code actually run on the chip?

Chapters

  1. 0:00Introduction
  2. 0:05With Server AI Hub: Your GPU
  3. 0:13What you gain: The benefits
  4. 0:21The alternative: By hand
  5. 0:29Where this fits: The AI stack
  6. 0:33Two sides: Host and device
  7. 0:45How it splits: Threads, blocks, grid
  8. 0:54A small kernel: Add two lists
  9. 1:02Try it: Is the compiler there?
  10. 1:17Memory: One shared pool
  11. 1:33Timing: Launches don't wait
  12. 1:41From Python: Ask PyTorch
  13. 1:50Recap: Code on the GPU
  14. 1:55Wrap up
Read the transcript

Introduction

You know the layers. Now, how does code actually run on the chip?

With Server AI Hub: Your GPU

With Server AI Hub, you see each Spark's GPU use, power, temperature and clock on one screen.

What you gain: The benefits

You can tell at once whether the GPU is working. Throttle events are listed, so slowness has a reason you can see.

The alternative: By hand

The other way is a Terminal, and your own code. To write CUDA you'll need it anyway, so here's how it works.

Where this fits: The AI stack

We're still near the bottom, where the maths happens.

Two sides: Host and device

A CUDA program has two sides. The host is the processor, which runs the main program. The device is the GPU. A function that runs there is called a kernel.

How it splits: Threads, blocks, grid

You launch a kernel with many threads, each doing its own small piece. Threads are grouped into blocks. And the blocks make up a grid.

A small kernel: Add two lists

This kernel adds two lists of numbers. Each thread works out its own position, checks it's inside the list, and adds one pair.

__global__ void add(int n, float* a,
                    float* b, float* c) {
  int i = blockIdx.x * blockDim.x
          + threadIdx.x;
  if (i < n) c[i] = a[i] + b[i];
}

Try it: Is the compiler there?

A Terminal is a window where you type commands. Check the CUDA compiler with nvcc --version. Then compile your file and run it. The file add.cu is your own, with the kernel and a main function.

nvcc --version
nvcc add.cu -o add
./add

Memory: One shared pool

Often, data is copied to the GPU, worked on, and copied back. On a DGX Spark, the processor and GPU share one memory. So nvidia-smi may show memory usage as not supported. That's expected.

Timing: Launches don't wait

A launch returns before the GPU has finished. Wait for it before you time it, and check each call for errors.

From Python: Ask PyTorch

From Python, ask PyTorch whether it can use CUDA. True means it can. False means check the driver and the PyTorch build.

python3
import torch
torch.cuda.is_available()

Recap: Code on the GPU

Kernels, threads, blocks and a grid. That's the shape of CUDA.

Wrap up

Learn how kernels work, and let Server AI Hub show you what they do to the GPU: use, power and heat on one screen, with no commands.

Sources

More lessons