This lab covers how PyTorch builds a computation graph on the fly as tensor operations run, and how that graph behaves when tensors and models are on a CUDA GPU. The notebook above shows the graph side with plain tensors and the hiddenlayer visualiser. The sections below add a working autograd example, current visualisation tools, the CUDA rules for device placement, asynchronous execution and memory, and fixes for the problems readers run into most often.
What the notebook above covers
The post is titled CUDA semantics, but the embedded notebook (demo9-PytorchComputationGraph.ipynb) is about computation graphs. It builds y = W*x + b from tensors, combines several weighted inputs into final_value, and then draws the graphs of three small nn.Sequential models with the hiddenlayer library. Nothing in it runs on a GPU.
The two topics are closely linked. PyTorch records the graph as operations run, which is why it is called define-by-run. The same recording works on CPU or CUDA, as long as every tensor in an operation is on the same device. This page completes both parts: first the graph and autograd, then the CUDA rules.
Dynamic computation graphs and autograd
In the example above, no tensor has requires_grad=True, so PyTorch computes the values but records no graph. Autograd only tracks operations that involve at least one tensor requiring gradients. The version below records the graph, shows the recorded nodes and runs the backward pass.
import torch
W = torch.randn(6, requires_grad=True) # trainable weights
x = torch.full((6,), 10.0) # input, no gradient needed
b = torch.tensor(3.0, requires_grad=True) # float bias, trainable
y = W * x + b
print(y.grad_fn) # <AddBackward0 object at ...>
print(y.grad_fn.next_functions) # ((<MulBackward0 ...>, 0), (<AccumulateGrad ...>, 0))
loss = y.sum()
loss.backward()
print(W.grad) # tensor([10., 10., 10., 10., 10., 10.]) -> d(loss)/dW = x
print(b.grad) # tensor(6.) -> b is added to 6 elementsCode language: PHP (php)
grad_fnis the node that created a tensor. Followingnext_functionswalks the graph backwards to the leaf tensors (AccumulateGrad).- The graph is rebuilt on every forward pass, so Python
ifstatements and loops can change the graph from one run to the next. This is what the notebook's "Working Dynamically" heading refers to. - After
backward(), PyTorch frees the graph by default. Callingbackward()on it again raises an error unless the first call usedretain_graph=True. - Gradients add up across calls. Training loops call
optimizer.zero_grad()(or set.gradtoNone) before each backward pass. - Wrap inference in
with torch.no_grad():(ortorch.inference_mode()) so no graph is recorded and memory is saved.
Visualising model graphs with current tools
The hiddenlayer project used above is no longer maintained. It relies on private PyTorch ONNX internals, so on recent PyTorch releases hl.build_graph usually fails with an AttributeError that names a torch.onnx function such as _optimize_trace. Two maintained alternatives cover the same need: torchviz draws the autograd graph, and torchinfo prints a table of layers, output shapes and parameter counts.
pip install torch torchviz torchinfo
# torchviz needs the Graphviz binaries on the system PATH
sudo apt-get install -y graphviz # Debian/Ubuntu
# brew install graphviz # macOSCode language: PHP (php)
import torch
from torch import nn
from torchviz import make_dot
from torchinfo import summary
inp, hid, out = 1, 100, 1
model2 = nn.Sequential(
nn.Linear(inp, hid),
nn.ReLU(),
nn.Linear(hid, hid),
nn.Sigmoid(),
nn.Linear(hid, out),
)
X = torch.zeros(10, inp)
pred = model2(X)
# Autograd graph -> model2_graph.png
make_dot(pred, params=dict(model2.named_parameters())).render("model2_graph", format="png")
# Layer table
summary(model2, input_size=(10, inp))Code language: PHP (php)
summary should report 10,401 trainable parameters: 200 for Linear(1, 100), 10,100 for Linear(100, 100) and 101 for Linear(100, 1). In a notebook, make_dot(...) on its own displays the graph inline. For larger models, TensorBoard's SummaryWriter.add_graph(model, X) gives an interactive view.
CUDA semantics: devices and tensor placement
Every tensor and every parameter lives on exactly one device. Operations run on the device where their inputs are, and the result is created on that same device. PyTorch does not move data between CPU and GPU automatically. If one operation mixes devices, it fails.
import torch
from torch import nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using:", device)
if device.type == "cuda":
print(torch.cuda.device_count(), "GPU(s):", torch.cuda.get_device_name(0))
model = nn.Sequential(nn.Linear(1, 100), nn.ReLU(), nn.Linear(100, 1)).to(device) # moves parameters in place
X_train = torch.tensor([[1.7], [2.5], [5.5], [7.9], [8.8]])
X = X_train.to(device) # tensors return a NEW tensor; reassign it
with torch.no_grad():
pred = model(X)
print(pred.device) # cuda:0 on a GPU machine
result = pred.cpu().numpy() # NumPy only works with CPU tensorsCode language: PHP (php)
module.to(device)changes the module in place.tensor.to(device)returns a copy, soX.to(device)without reassignment does nothing useful."cuda"means the current device, which iscuda:0unless changed. Insidewith torch.cuda.device(1):, tensors created withdevice="cuda"go to GPU 1. An explicittorch.device("cuda:1")always means GPU 1.- Copying a tensor between GPUs is allowed with
.to("cuda:1"), but a single operation cannot use inputs from two different GPUs. CUDA_VISIBLE_DEVICES=1 python train.pyhides every other GPU from the process. The visible GPU is then numberedcuda:0inside PyTorch.
Asynchronous execution, timing and memory
CUDA operations are queued and run asynchronously. Python returns as soon as the kernel has been queued, not when it has finished. This keeps the GPU busy, but if you time GPU code without synchronizing, you mostly measure how long it took to queue the work. Operations that need the result on the CPU, such as .item(), .cpu() or print(tensor), wait for the GPU automatically.
import time, torch
assert torch.cuda.is_available()
a = torch.randn(4096, 4096, device="cuda")
_ = a @ a # warm-up (kernel selection, context init)
torch.cuda.synchronize()
start = time.perf_counter()
c = a @ a
torch.cuda.synchronize() # wait for the GPU before stopping the clock
print(f"matmul: {(time.perf_counter() - start) * 1000:.2f} ms")
MB = 1024 ** 2
print("allocated:", torch.cuda.memory_allocated() / MB, "MB") # held by live tensors
print("reserved: ", torch.cuda.memory_reserved() / MB, "MB") # held by the caching allocator
del c
torch.cuda.empty_cache() # return unused cached blocks to the driverCode language: PHP (php)
- PyTorch uses a caching allocator, so
nvidia-smishows reserved memory, not what live tensors are using.empty_cache()does not free memory that tensors still reference. - For faster host-to-GPU copies, load batches into pinned memory (
DataLoader(..., pin_memory=True)) and copy with.to(device, non_blocking=True). - On Ampere and newer GPUs,
torch.set_float32_matmul_precision("high")lets float32 matrix multiplications use TF32. This is usually faster, at the cost of slightly lower precision.
Common errors and fixes
| Error or symptom | Cause | Fix |
|---|---|---|
Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu | The model is on the GPU but the inputs or targets are still on the CPU, or the other way round | Move the model and every batch tensor to the same device |
torch.cuda.is_available() returns False | A CPU-only PyTorch build is installed (torch.version.cuda is None), or the NVIDIA driver is missing | Check nvidia-smi, then install the CUDA-enabled wheel using the selector on pytorch.org |
CUDA out of memory | The batch is too large, or the graph is kept alive by storing loss instead of loss.item() | Reduce the batch size, use torch.no_grad() for evaluation, and accumulate loss.item() |
can't convert cuda:0 device type tensor to numpy | NumPy needs memory on the host | Call .detach().cpu().numpy() |
Trying to backward through the graph a second time | The graph was freed after the first backward() | Recompute the forward pass, or pass retain_graph=True only when it is really needed |
graphviz.backend.ExecutableNotFound | The Graphviz system package is not installed | Install graphviz with the OS package manager |
Corrections to the example above
- No graph is recorded. None of the tensors set
requires_grad=True, soy = W*x + bandfinal_valueare plain arithmetic with no autograd graph. The corrected version in the autograd section sets it onWandb. - Mixed dtypes.
b = torch.tensor(3)is an int64 tensor that is added to a float32 tensor. Type promotion makes this work, but usetorch.tensor(3.0)for parameters so they can have gradients. Only floating-point tensors can require gradients. - Scalar versus size.
torch.tensor(6)is a scalar with the value 6.torch.randn(6)is a tensor with 6 elements. In the example,W1,W2andW3are scalars, which is whyfinal_valueis6*2 + 6*3 + 6*4 + 10 = 64. - Missing non-linearity.
model1is twoLinearlayers with nothing between them, andmodel2starts the same way. Two linear layers in a row reduce to one linear function. Put an activation such asnn.ReLU()between them, as the examples above do. - Unmaintained visualiser.
hiddenlayerdoes not work with current PyTorch. Usetorchviz,torchinfoor TensorBoard instead.
Note: The SVG outputs saved in the notebook come from an old run. On a current PyTorch install, expect an error from hl.build_graph, not those diagrams.
Frequently asked questions
What is a dynamic computation graph in PyTorch?
PyTorch records operations into a graph while they run, not ahead of time. A new graph is built on each forward pass, so ordinary Python control flow can change the model's structure between iterations. The graph is used by backward() to compute gradients and is then freed.
How do I move a PyTorch model and data to the GPU?
Create device = torch.device("cuda" if torch.cuda.is_available() else "cpu"), call model.to(device) once, and reassign each batch with X = X.to(device). The model and its inputs must be on the same device.
Why is torch.cuda.is_available() False when I have an NVIDIA GPU?
Usually a CPU-only PyTorch build is installed, or the NVIDIA driver is missing or too old. Check torch.version.cuda and run nvidia-smi, then install the CUDA-enabled PyTorch build.
Why does my GPU code look extremely fast when I time it?
CUDA kernels run asynchronously, so the Python call returns before the GPU has finished the work. Call torch.cuda.synchronize() before starting and before stopping the timer, or use torch.cuda.Event timers.
Does hiddenlayer still work with PyTorch?
Generally not. The project is unmaintained and depends on private torch.onnx functions that newer PyTorch releases have changed. Use torchviz for autograd graphs and torchinfo for layer summaries.
Related tutorials
- More Machine Learning tutorials
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals