What Is CUDA? How One Line of PyTorch Reaches the GPU
· cuda, pytorch, gpu, deep-learning, nvidia
The short video above asks a fair question: you write PyTorch in Python, Python runs on the CPU, so how does the model train on the GPU? The answer is CUDA, walked as four layers — kernels, libraries (cuBLAS), the CUDA runtime, and the NVIDIA driver queue — after one line that moves the model onto the device. That map is a good one. This article keeps it, tightens a few simplifications, and shows the real calls, memory moves, and sync points you will hit when you train.
References: NVIDIA’s CUDA C++ Programming Guide, CUDA Runtime API, cuBLAS, and PyTorch’s CUDA semantics and Tensor.to. The 21,760 CUDA-core figure for the GeForce RTX 5090 is from NVIDIA’s 50-series specs. For a hosted notebook with a free accelerator, see the Kaggle GPU and TPU guide.
Why a GPU at all
Training a neural net is dominated by dense linear algebra: matrix multiplies (GEMM), plus attention, convolutions, normalizations, and elementwise kernels. Calling that “millions of small multiplications,” as the video does, is the right intuition and a low count — a single modern step can be billions of fused multiply-adds.
A desktop CPU with 8 or 16 cores (many chips now have more) is built for a few complex instruction streams. An NVIDIA GPU is built for data-parallel work. The GeForce RTX 5090, a Blackwell (GB202) card, officially has 21,760 CUDA cores, as 170 streaming multiprocessors (SMs) with 128 CUDA cores each — not 21,760 little CPUs. Threads run in warps of 32, in the SIMT model the CUDA guide describes: the same instruction is issued across a warp, with masking when threads diverge. Each CUDA core is a simpler arithmetic unit than a CPU core. That is what the video means by “each one is much simpler, but together they do thousands of calculations at the same time.”
Two official nuances the clip has no time for. First, GEMM on a 50-series card often runs on Tensor Cores (5th generation on Blackwell; 680 on the 5090), not only on the CUDA cores on the box. Mixed precision (torch.autocast, TF32, BF16, FP16, FP8) exists to feed those units. Second, “thousands of threads” is the programming model; occupancy, shared memory, and bandwidth usually limit you before you “use all 21,760 cores” in a naive sense.
The one line: model.to("cuda")
The on-screen line is model.to("cuda") (the transcript’s “model.2 CUDA”). nn.Module.to() walks every parameter and buffer and moves it with Tensor.to. You can also write model.cuda() or model.to(device) with device = torch.device("cuda"). After that, the weights live in the GPU’s own memory (GDDR or HBM), not in host RAM.
import torch
import torch.nn as nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = nn.Sequential(nn.Linear(1024, 1024), nn.ReLU(), nn.Linear(1024, 10))
model.to(device) # copies parameters + buffers to GPU memory
x = torch.randn(32, 1024) # still on CPU
x = x.to(device, non_blocking=True) # now the batch is on the GPU too
y = model(x) # kernels run on the GPU
print(y[:2].cpu()) # device-to-host copy; the CPU waits
Official placement rules: a tensor stays on the device where you created it; op results land on the same device as the inputs; mixing devices raises an error unless you to()/copy_(). Moving the module does not move every future tensor. DataLoader batches start on the CPU, so the video’s “later your input data are copied” is a second, explicit step — usually batch.to(device), often with pin_memory=True and non_blocking=True.
That first to("cuda") is not the same as a kernel launch. PyTorch’s pin-memory guide is explicit: Tensor.to() uses cudaMemcpyAsync, but with default non_blocking=False it then calls cudaStreamSynchronize, so the host blocks until the copy finishes. Use non_blocking=True and pinned memory to queue the transfer and keep going. Kernel launches, by contrast, are asynchronous by default — the video’s later point, correct for compute, not for a default weight copy.
Part 1. Kernels: the GPU does not run Python
When you write y = x @ w.T or let a Linear layer run, PyTorch sees two tensors already on CUDA and must multiply them. The GPU cannot interpret Python bytecode. It runs a kernel: a compiled function written in CUDA C++, or generated by Triton, or shipped as part of a library, loaded as PTX or native SASS. You launch a grid of thread blocks; each thread computes a slice of the output. That is the first part of CUDA in the video, and it matches the official programming model (kernels, blocks, grids, warps).
A toy mental picture for a naive GEMM, not what cuBLAS actually ships:
__global__ void matmul(const float* A, const float* B, float* C, int N) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < N && col < N) {
float s = 0.f;
for (int k = 0; k < N; ++k) s += A[row * N + k] * B[k * N + col];
C[row * N + col] = s;
}
}
Production kernels tile into shared memory, vectorize loads, and — on Tensor Cores — issue mma / WMMA instructions on fragments. Autograd’s backward pass is more kernels (weight and input gradients, often fused with bias and activation). You almost never write these yourself for standard layers. That is the next layer.
Part 2. Libraries: cuBLAS is the headline, not the whole stack
The video says you never wrote a kernel, PyTorch did, and libraries like cuBLAS hold ready-made, highly tuned kernels for common math and pick the best one for your matrix sizes. That is right for GEMM. NVIDIA’s cuBLAS (and cuBLASLt) is a BLAS library on the GPU, with heuristics — and, in some paths, autotuning — over variants that depend on shape, layout, dtype, and GPU generation.
PyTorch’s dispatcher does not call cuBLAS for every op. A realistic training step also uses:
- cuDNN for many convolutions, attention building blocks, and normalization paths (or a newer fused kernel that replaced an older cuDNN one).
- cuBLAS / cuBLASLt for a large share of
addmm/ linear layers. - NCCL when you scale across GPUs (
DistributedDataParallel, FSDP). - Vendor or community kernels: FlashAttention, Cutlass, Triton-compiled kernels, and PyTorch’s own ATen CUDA kernels for pointwise ops, softmax, and indexing.
So “cuBLAS picks the best kernel” is the right story for a big matrix multiply, and incomplete as a picture of “the model ran.” A profiler will show a mix of names, not a single cublasSgemm. That is expected.
Part 3. The CUDA runtime launches work and returns
Something has to submit “run this kernel on this data.” In the NVIDIA stack that is the CUDA runtime (cudart, the API behind cudaLaunchKernel, streams, events, and memory). The runtime records the launch on a stream — a FIFO queue of GPU work — and, for a normal kernel launch, returns to the host immediately. PyTorch’s CUDA semantics note says this in so many words: GPU operations are asynchronous by default; they are enqueued on the device and may run later; the effect is usually invisible because the device preserves order in a stream and PyTorch synchronizes when you copy data between CPU and GPU.
# These two lines usually return before the GPU has finished the matmul.
y = model(x)
loss = torch.nn.functional.cross_entropy(y, labels.to(device))
loss.backward()
# The CPU has been enqueueing work. A later .cpu(), .item(), or print() will wait.
That is why “your Python keeps going while the GPU works” is official, and why timing a training step without a synchronization is a lie. Use torch.cuda.Event and torch.cuda.synchronize(), as the PyTorch docs show, or you will measure queueing time, not kernel time. CUDA_LAUNCH_BLOCKING=1 forces synchronous launches and is the supported way to get a useful stack trace when a kernel fails.
Streams let copy and compute overlap if the device has a free copy engine and host memory is pinned. That is why non_blocking=True plus pin_memory exists.
Part 4. The driver, the OS, and the GPU’s command queue
The runtime, as the video says, does not poke the GPU in isolation. User-space CUDA (libcudart and the user-mode driver, libcuda) talks to the NVIDIA kernel driver, which works with the OS to map memory, schedule the device, and place commands in a queue the GPU pulls from. You see the split when the driver is too old for the toolkit, or a container lacks --gpus access: the runtime is present, the queue is not.
The GPU then executes the kernel. The output tensor stays in device memory. Nothing is copied back until host code needs it — print(tensor), tensor.item(), tensor.cpu(), a NumPy conversion, or a save to disk. Those device-to-host copies are the synchronization points PyTorch documents, and they make the CPU wait. That is exactly why “careless prints slow down training”: each print of a CUDA tensor may flush the outstanding stream. The same trap shows up as loss.item() in a tight loop, or as logging .cpu().numpy() every step. Log less, or log asynchronously after an explicit, batched copy.
PyTorch’s caching CUDA allocator keeps blocks around so the next step does not cudaMalloc every time. torch.cuda.empty_cache() returns unused cached blocks to the driver; it does not drop your model. Use torch.cuda.max_memory_allocated() when you chase an OOM, not a print of the tensor.
A minimal training step, with the four layers visible
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
loader = torch.utils.data.DataLoader(dataset, batch_size=32, pin_memory=True)
model.train()
for xb, yb in loader:
xb = xb.to(device, non_blocking=True)
yb = yb.to(device, non_blocking=True)
opt.zero_grad(set_to_none=True)
logits = model(xb) # runtime launches library kernels
loss = torch.nn.functional.cross_entropy(logits, yb)
loss.backward() # more kernels, still on device
opt.step() # parameter updates, still on device
# Do not print(loss) every step; it synchronizes.
Follow one Linear in the forward pass: weights already live on the GPU from model.to(device); xb is copied into device memory; PyTorch picks a cuBLASLt (or similar) GEMM for the shape and dtype; the runtime enqueues the launch on the default stream and returns; the driver queues the work; the SMs run the kernel; the activation stays on the GPU for the next layer. Backward walks the autograd graph and enqueues the corresponding kernels. Until you call loss.item() or move a tensor to CPU, the host has mostly been a work issuer.
Pitfalls
- Forgetting to move the batch. The model is on CUDA, the batch is on CPU, and you get a device-mismatch error — or a silent, slow path if you accidentally left the model on CPU.
print,.item(),.cpu(), and.numpy()in the inner loop. Each one can stall the pipeline the runtime just set up.- Timing without
torch.cuda.synchronize()or CUDA events. You will “speed up” a model that has not finished. - Assuming
to("cuda")is asynchronous. The default is a blocking host copy. Usenon_blocking=Trueand pinned memory when overlap matters. - Assuming every op is cuBLAS. Profile before you rewrite a layer “to beat cuBLAS”; you may already be in a Triton or cuDNN kernel.
CUDA_VISIBLE_DEVICESandtorch.cuda.set_device. The default device is not always the physical GPU you think it is in a shared machine.- CUDA is NVIDIA’s platform. It does not run on AMD (use ROCm /
"cuda"-compatible builds where provided, or the ROCm backend), Apple Silicon (PyTorch MPS), or Google TPUs. “CUDA only runs on NVIDIA GPUs” is officially true. “That is why everyone wants them” is a market comment, not a technical constraint: other backends exist, and they are not CUDA.
How to see the four layers on your own machine
nvidia-smi # driver, GPU, memory
nvcc --version # CUDA toolkit, if installed
python -c "import torch; print(torch.cuda.is_available(), torch.version.cuda, torch.cuda.get_device_name(0))"
from torch.profiler import profile, ProfilerActivity
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
logits = model(xb.to(device))
loss = logits.sum()
loss.backward()
torch.cuda.synchronize()
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=20))
You should see a mix of aten::, cublas, cudnn, or triton names, plus Memcpy when you copy. That table is the video’s four layers with the marketing removed.
Interview-style FAQ
Does Python itself ever run on the GPU? No. The interpreter, autograd graph construction, and most of your training loop stay on the CPU. Compiled kernels run on the device.
Is model.cuda() different from model.to("cuda")? For this purpose, no. to() is the general API (device, dtype, non_blocking); .cuda() is the older shorthand.
Why did print(loss) make my epoch slower? loss is a CUDA tensor. Printing it copies a scalar to the host and synchronizes the stream, so the CPU stops issuing new work until the GPU catches up.
Who writes the kernel for nn.Linear? Usually you don’t. PyTorch dispatches to cuBLAS/cuBLASLt (or another fused kernel) based on shape, layout, and dtype.
What is a CUDA stream? A per-device FIFO of commands. The default stream is enough for correctness. Extra streams exist to overlap copy and compute, with explicit synchronization.
Do I have to call torch.cuda.synchronize() in training? Not for correctness of a normal loop — PyTorch syncs at host-device copies. You need it for accurate timers, some non_blocking copies in the host direction, and some multi-stream setups.
Is an RTX 5090’s 21,760 CUDA cores the same as 21,760 CPU cores? No. They are arithmetic lanes inside 170 SMs, scheduled as warps of 32, plus separate Tensor Cores and RT cores. The official count is real; the programming model is not “one thread per core, like a 21,760-way CPU.”
Can I run this CUDA stack on a non-NVIDIA GPU? Not as CUDA. Use the vendor’s PyTorch backend (MPS, ROCm, XPU) or a cloud TPU stack. The ideas — kernels, libraries, a runtime, a driver queue — rhyme; the APIs do not.
Why does the first batch take longer? Context and cuBLAS handles are created lazily, kernels are loaded, and the allocator warms up. Time from the second or third step, after a synchronize.
Memory, occupancy, and why “all 21,760 cores” is the wrong target
A kernel that is correct can still be slow. Each SM has a limited register file and a limited shared-memory / L1 budget (on Blackwell SMs the architecture whitepaper lists a 256 KB register file and 128 KB of L1/shared memory per SM). Launch enough threads to hide memory latency, but not so many that you spill registers or starve the SM. That tradeoff is occupancy. Official Nsight and the CUDA occupancy calculator exist because you cannot read it from the CUDA-core count on the box.
Device memory is a second wall. The RTX 5090 Founders Edition ships 32 GB of GDDR7 on a 512-bit interface. Activations often dominate weights. torch.cuda.memory_summary() tells you whether you are fragmenting or truly out of memory. Gradient checkpointing (torch.utils.checkpoint) trades compute for a smaller activation footprint. Mixed precision shrinks many activations and feeds Tensor Cores. A safe starting point:
from torch import amp
scaler = amp.GradScaler("cuda")
for xb, yb in loader:
xb, yb = xb.to(device, non_blocking=True), yb.to(device, non_blocking=True)
opt.zero_grad(set_to_none=True)
with amp.autocast("cuda", dtype=torch.bfloat16):
loss = torch.nn.functional.cross_entropy(model(xb), yb)
scaler.scale(loss).backward()
scaler.step(opt)
scaler.update()
BF16 on Ampere and newer often does not need a scaler; FP16 still does, because small gradients underflow. Check the current AMP docs for your device.
torch.compile, CUDA Graphs, and when async gets surprising
torch.compile (TorchInductor) can fuse ops into fewer kernels — sometimes Triton, sometimes the same cuBLAS path. That does not replace CUDA; it feeds it better. CUDA Graphs record a sequence of launches and replay them with less CPU enqueue overhead, which makes “the runtime returns immediately” even more extreme.
Expect a slow first compiled iteration, graphs that dislike data-dependent control flow, and errors from an async kernel reported later unless you set CUDA_LAUNCH_BLOCKING=1. If a traceback points at loss.backward() but the bug was a launch two lines earlier, that is the async model doing what the docs said it would.
Multi-GPU, briefly
One process and one GPU is the video’s scope. When you add devices, NCCL (or Gloo) is another library in the same stack: all-reduce is itself kernels plus a runtime, through the driver to P2P, NVLink, or the NIC. DistributedDataParallel still starts with model.to(device) on each rank. Device-to-device to() / copy_() has its own synchronization rules in the CUDA semantics note.
More FAQ
What is the difference between CUDA cores and Tensor Cores? CUDA cores are the general SIMT arithmetic lanes (the 21,760). Tensor Cores are specialized matrix units used by mixed-precision GEMM and many attention kernels. A training kernel may use both.
Why is my GPU utilization low in nvidia-smi? Often the CPU is the bottleneck (data loading, Python overhead, or a sync on every step), or the kernels are too small to fill the SMs. The profiler will show whether you are wait-bound or launch-bound.
Does torch.cuda.empty_cache() fix my OOM? It returns cached blocks to the driver. It does not shrink live tensors. Delete references, shrink the batch, or checkpoint.
Is pin_memory=True always a win? It helps when you overlap host-to-device copies with compute, at a cost in host memory. It is the official partner of non_blocking=True for input pipelines.
Recap
| Layer | What the video says | Official tightening |
|---|---|---|
| Why GPU | 8–16 CPU cores vs 21,760 CUDA cores on a 5090 | 21,760 is official; they sit in 170 SMs, warps of 32, plus Tensor Cores |
model.to("cuda") | Weights, then data, go to GPU memory | True; default to() is a blocking host copy; batches need their own to() |
| Kernels | GPU can’t run Python; a kernel runs on thousands of threads | Official CUDA model: grids, blocks, warps |
| Libraries | cuBLAS picks a tuned kernel for the shapes | Right for GEMM; training also uses cuDNN, Triton, NCCL, ATen |
| Runtime | Launch returns immediately; Python continues | Official default: GPU ops are asynchronous |
| Driver | OS + NVIDIA driver queue work for the GPU | User-mode CUDA submits; the kernel driver owns the device queue |
| Results | Stay on the GPU until you print; the copy stalls the CPU | Device-to-host copies synchronize; don’t print in the inner loop |
| Portability | CUDA runs only on NVIDIA GPUs | True of CUDA; other vendors have other backends |
Kernels, libraries, runtime, driver: that is still the right four-part answer. The one line of PyTorch is the request to put tensors on the device; CUDA is the stack that turns the next multiply into millions of lanes of hardware arithmetic without your Python ever leaving the CPU. Follow @rankcore.ai, and read more on blog.rankcore.ai.
Want to go deeper?
Our step-by-step video courses turn these ideas into results.
Comments
No comments yet — be the first.