When running PyTorch code, there is one line we all type out of sheer muscle memory:

.to('cuda')

Immediately, the fans in your desktop case spin up like a jet engine preparing for takeoff. (Though if you’re training on a cloud instance, you probably won’t hear a thing.)

But have you ever paused to ask yourself:

“How does Python — a language famous for being slow — control a GPU that operates at such breakneck speeds?”

Today, we’re going to look at how a few lines of Python manage to command a GPU to perform complex calculations, and exactly what happens between your keyboard and the hardware.


1. Python: The Driver, Not the Engine

Let’s get the most important concept out of the way first.

The Python code you write in PyTorch does not run on the GPU.

To be precise, Python only issues the commands; C++ and CUDA are the ones doing the heavy lifting. Think of Python as the Foreman.

The Foreman (Python) shouts, “Hey, multiply these two matrices!” The actual workers (C++/CUDA) then hop into their heavy machinery (the GPU) to get the job done.

Thanks to this clever architecture, we get to write code in easy, readable Python while achieving C++-level performance.

What you see is Python, but what’s running underneath is pure C++ and CUDA.


2. The Dispatcher: PyTorch’s Central Control

Let’s say you call torch.add(a, b) in Python.

Once the call leaves the Python layer, it enters a central control room written in C++ called the Dispatcher.

The Dispatcher is an internal component of PyTorch. Its job is to decide exactly which piece of code should run when a function like torch.add is called.

It’s not as simple as asking “CPU or GPU?” The Dispatcher acts as a magical traffic controller that ensures all of PyTorch’s features — Auto Differentiation (Autograd), Quantization, XLA, etc. — work together without getting tangled up.

2–1. The Tensor ID: Dispatch Key Set

Every Tensor carries a “Dispatch Key Set” — essentially a detailed ID card.

This ID card tells the system everything about the Tensor’s identity:

  • Backend Info: Is this a CUDA tensor, a CPU tensor, or an MPS tensor?
  • Layout Info: Is this a standard dense (strided) tensor or a sparse tensor?
  • DType Info: Is it a float or an integer?
  • Autograd Info: Does it have requires_grad=True? Do we need to track gradients?

2–2. The Workflow: Routing the Call

When torch.add(a, b) is called, the Dispatcher looks at the ID cards (Key Sets) of the tensors and opens a massive manual known as the Dispatch Table.

Scenario 1: A Simple Addition

“Okay, both tensors only have the CPU key. No gradients needed. Great, send this straight to the cpu_add_kernel function in the ATen library!"

(ATen library is a part of PyTorch implementation)

The C++ operation runs immediately.

Scenario 2: A Complex GPU Training Step

“Hold on. Checking the ID card… I see a CUDA key, but I also see an Autograd key."

Dispatch Keys are sorted by priority. The system handles the highest priority key first. In this case, Autograd outranks CUDA.

The Dispatcher passes the ball to the Autograd handler first. The handler says, “Got it. I’ve recorded this addition operation so we can use it for backpropagation later,” and builds a node in the Computational Graph.

For a deeper dive into how this works, check out my previous post on PyTorch Autograd.

The Autograd handler then passes the ball back to the Dispatcher.

Now the Dispatcher says, “Okay, next up is the CUDA key. Send this to the CUDA implementation!" and the GPU finally performs the calculation.

This entire sequence happens in microseconds at the C++ level. Thanks to the Dispatcher, a single function like torch.add automatically handles gradient tracking, GPU acceleration, and error checking without you having to write a single line of boilerplate.

You don’t need to write: if gpu: ... else if autograd: .... PyTorch handles it for you.


3. Entering the World of CUDA

Once the Dispatcher decides, “You, go to CUDA,” we leave the CPU world and enter the realm of the GPU.

The language here is neither Python nor C++, but CUDA (Compute Unified Device Architecture).

3–1. Division of Labor: Host vs. Device

We need to define our terms:

  • Host: The CPU and system memory (RAM). This is where your Python script and PyTorch’s C++ backend run.
  • Device: The GPU and its dedicated memory (VRAM). This is the construction site where the hard labor happens.

When you write Python code, you are effectively piloting a C++ program on the Host. This program picks up a “phone” called the CUDA Runtime API to call the Device and give it orders.

3–2. The Kernel: Work Orders for the GPU

Here comes another term: Kernel.

A Kernel is a small function designed to run specifically on the GPU. When Python issues a command, PyTorch effectively shouts:

“Hey GPU! I’m going to Launch an add_kernel. Use the data at address #1 and #2, and write the result to address #3."

This is called a Kernel Launch.

If you’ve used PyTorch for years but never wrote a Kernel, don’t worry. That’s normal. PyTorch comes pre-packaged with thousands of highly optimized Kernels deep inside its library.

3–3. The PCIe Bus: The Narrow Bridge

This is where we hit a major hardware bottleneck: the PCIe Bus.

Modern GPUs have insane internal memory bandwidth.

For example, NVIDIA’s H100 GPU uses HBM3 memory to achieve a memory bandwidth of over 3 TB/s. The newer H200s are even faster.

However, the bridge connecting the CPU to the GPU — the PCIe interface — is comparatively tiny.

A typical PCIe Gen 4 x16 link offers about 28~32 GB/s in one direction (approx. 64 GB/s bidirectional).

Compare 3,000 GB/s (internal GPU speed) to 30 GB/s (connection speed). The bridge is 100x slower than the city it connects to.

This is why you shouldn’t abuse .to('cuda'). Every time you run that command, you are forcing data across this slow PCIe bridge.

Experienced engineers know: move your data to the GPU once, keep it there, do all your math, and only bring the final result back. Moving data back and forth is the quickest way to kill performance.


4. Inside the Hardware: The Rule of 32

The Kernel has arrived at the GPU. What happens inside the silicon?

Warps and SIMT

While the smallest unit of execution on a GPU is a Thread, the hardware actually groups them into bundles called Warps. A Warp consists of 32 threads.

All 32 threads in a Warp must execute the exact same instruction at the same time. This architecture is called SIMT (Single Instruction, Multiple Threads). If the command is “Step forward,” all 32 step forward. If it’s “Add,” all 32 add.

What happens if you have an if-else statement where 16 threads want to do Option A and 16 want to do Option B?

The GPU suffers from Warp Divergence. The hardware literally has to pause half the group, let the first half finish, then pause the first half while the second half runs. Performance gets cut in half. Fortunately, PyTorch Kernels are highly optimized to avoid this.

To Recap:

  1. Host (CPU) pushes data to the Device (GPU). (This is the slowest part).
  2. PyTorch Launches a C++ CUDA Kernel.
  3. Thousands of GPU cores, grouped into Warps (32 threads), execute the math in lockstep.
  4. The result stays in GPU memory; Python only holds a pointer (address) to that result.

5. Asynchronous Execution: The CPU Doesn’t Wait

When you run output = model(input) in Python and the code moves to the next line, has the GPU finished the calculation?

No.

The Coffee Shop Analogy

Imagine ordering a coffee at a busy cafe (the CPU). You hand over your order, and it gets sent to the barista station (the GPU).

Do you stand frozen at the register until the coffee is ready? No. You step aside, check your phone, talk to a friend, or look at the pastry case.

PyTorch works the same way.

When you call a GPU function, the operation is placed in a Queue. The CPU says, “Here’s the order,” and immediately moves on to the next line of Python code without waiting for the result. This is Asynchronous Execution.

This allows the CPU to prepare the next batch of data or do other work while the GPU is crunching numbers.

But you might ask:

“Wait, if I use output in the very next line, won't it crash because the data isn't ready?"

Don’t worry. If you try to use the data, PyTorch handles the timing.

If you write print(output) (which requires moving data to CPU to display it), PyTorch recognizes that you need the actual value now. It forces a Synchronization, effectively saying, "Hey GPU, are you done? I'll wait right here until you are."

The Benchmarking Trap

Because of this asynchronous nature, measuring speed naively can be misleading.

If you use time.time() around a GPU operation without synchronization, you might think your model is running at light speed. In reality, you only measured how long it took to launch the kernel, not how long it took to execute it.

For accurate benchmarking, you must force the CPU to wait:

# Correct way to benchmark
torch.cuda.synchronize() # Wait for previous tasks
start = time.time()

model(input)

torch.cuda.synchronize() # Wait for model to actually finish
end = time.time()

6. Wrapping Up: Python Skin, C++ Muscle

It’s been a deep dive. Let’s summarize the journey:

  1. Python Code: The Foreman issues orders.
  2. Dispatcher: Checks the ID (Dispatch Key), handles Autograd, and routes traffic.
  3. PCIe Bus: Data crosses the “slow bridge” to the GPU (optimize this by minimizing transfers!).
  4. CUDA Kernel: The work order is launched.
  5. GPU Hardware: Warps of 32 threads execute instructions in parallel lockstep.
  6. Async Execution: The CPU fires and forgets, only waiting when absolutely necessary.

Behind every simple line of PyTorch code lies a sophisticated collaboration between software and hardware.

While you don’t need to know this to build a model, understanding these mechanics helps you debug strange issues and write code that truly utilizes the full power of your hardware.