MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

PyTorch Lab – 9 – Pytorch CUDA Semantics

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_fn is the node that created a tensor. Following next_functions walks the graph backwards to the leaf tensors (AccumulateGrad).
  • The graph is rebuilt on every forward pass, so Python if statements 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. Calling backward() on it again raises an error unless the first call used retain_graph=True.
  • Gradients add up across calls. Training loops call optimizer.zero_grad() (or set .grad to None) before each backward pass.
  • Wrap inference in with torch.no_grad(): (or torch.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, so X.to(device) without reassignment does nothing useful.
  • "cuda" means the current device, which is cuda:0 unless changed. Inside with torch.cuda.device(1):, tensors created with device="cuda" go to GPU 1. An explicit torch.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.py hides every other GPU from the process. The visible GPU is then numbered cuda:0 inside 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-smi shows 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 symptomCauseFix
Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpuThe model is on the GPU but the inputs or targets are still on the CPU, or the other way roundMove the model and every batch tensor to the same device
torch.cuda.is_available() returns FalseA CPU-only PyTorch build is installed (torch.version.cuda is None), or the NVIDIA driver is missingCheck nvidia-smi, then install the CUDA-enabled wheel using the selector on pytorch.org
CUDA out of memoryThe 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 numpyNumPy needs memory on the hostCall .detach().cpu().numpy()
Trying to backward through the graph a second timeThe graph was freed after the first backward()Recompute the forward pass, or pass retain_graph=True only when it is really needed
graphviz.backend.ExecutableNotFoundThe Graphviz system package is not installedInstall graphviz with the OS package manager

Corrections to the example above

  • No graph is recorded. None of the tensors set requires_grad=True, so y = W*x + b and final_value are plain arithmetic with no autograd graph. The corrected version in the autograd section sets it on W and b.
  • Mixed dtypes. b = torch.tensor(3) is an int64 tensor that is added to a float32 tensor. Type promotion makes this work, but use torch.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, W2 and W3 are scalars, which is why final_value is 6*2 + 6*3 + 6*4 + 10 = 64.
  • Missing non-linearity. model1 is two Linear layers with nothing between them, and model2 starts the same way. Two linear layers in a row reduce to one linear function. Put an activation such as nn.ReLU() between them, as the examples above do.
  • Unmaintained visualiser. hiddenlayer does not work with current PyTorch. Use torchviz, torchinfo or 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

PyTorch Lab – 8 – Pytorch Install And Setup Tensorflow Hidden Layer

This lab sets up HiddenLayer, a small Python library that draws neural network graphs and plots training metrics, along with the Graphviz bindings it uses to render…

Read More

PyTorch Lab – 7 – Pytorch CUDA Semantics

This page covers a PyTorch lab notebook that fits a linear regression model with autograd and manual gradient descent. The title mentions CUDA, but the notebook above…

Read More

PyTorch Lab – 6 – Pytorch Autograd With Variables

This lab uses PyTorch autograd to calculate gradients through a single multiplication, result = var * w1, using the older torch.autograd.Variable wrapper. Below you'll find what each…

Read More

PyTorch Lab – 5 – Pytorch AutogradIntro

This lab shows how PyTorch autograd records operations on tensors and computes gradients. It covers requires_grad, grad_fn, .grad, backward(), torch.no_grad() and detach(). The sections below the notebook…

Read More

PyTorch Lab – 3 – Pytorch Conversions Between PyTorch And NumPy

This lab shows how to convert data between PyTorch tensors and NumPy arrays using tensor.numpy(), torch.from_numpy(), torch.as_tensor() and torch.tensor(). The main point is memory: the first three…

Read More

PyTorch Lab -4 – Pytorch CUDA Semantics

This lab covers how PyTorch places tensors on GPUs: device objects, the current device, moving tensors between the CPU and GPUs, and how the CUDA caching allocator…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x