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 – 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 never uses a GPU, so the sections below explain what the code does and fix its problems. They also show how to run the same model on a GPU using PyTorch's CUDA rules: choosing a device, keeping tensors on the same device, asynchronous execution and GPU memory.


What the notebook above actually does

The embedded notebook builds a 15-point dataset with NumPy and turns it into tensors with torch.from_numpy. It then trains the model y = x ยท w1 ยท w2 with two weight tensors that have requires_grad=True. Each pass through the training loop does four things:

  • Forward pass: X_train.mm(w1).mm(w2) computes predictions with matrix multiplication. There is no activation function, so the model is linear.
  • Loss: (y_pred - Y_train).pow(2).sum() is the sum of squared errors. It equals nn.MSELoss(reduction='sum'), not the default nn.MSELoss(), which takes the mean.
  • Backward pass: loss.backward() fills w1.grad and w2.grad.
  • Update: inside torch.no_grad(), each weight moves against its gradient, and the gradients are then reset with .grad.zero_(). This reset is needed because PyTorch adds new gradients to the old ones instead of replacing them.

Every tensor in the notebook is created on the CPU, and nothing is moved to a GPU. To show CUDA behaviour, the code has to choose a device and put the data and the parameters on it. The corrected version below does this.

Problems in the original notebook

  • The loop runs 9 times, not 10. range(1, 10) stops before 10. The comment says "Start at 10".
  • No progress is ever printed. if iter % 50 == 0 is never true when the loop runs fewer than 50 times.
  • The model barely trains. With a learning rate of 1e-6 and 9 iterations, the weights hardly move from their random starting values. The predictions shown (about 0.26 to 1.24) are far from the targets (about 1.6 to 3.5). The note "Our training has produced a rather accurate regression line" is wrong.
  • There is no bias term. x ยท w1 ยท w2 is the same as x ยท w, a line forced through the origin. This data needs an intercept. Stacking two 1ร—1 weights with no activation in between adds nothing over a single weight.
  • iter is used as a variable name. This hides Python's built-in iter() function.
  • The final prediction builds a gradient graph it doesn't need. The output shows grad_fn=<MmBackward>. Run inference inside torch.no_grad(). Newer PyTorch versions print the name as MmBackward0.
  • Typos in the markdown cells: "defualt" should be "default" and "Foward" should be "Forward".

Corrected lab that runs on CPU or GPU

This version keeps the manual-autograd approach of the original. It adds a bias, uses mean squared error, uses a learning rate that actually trains the model, and runs on CUDA when a GPU is available.

import numpy as np
import torch
import matplotlib.pyplot as plt

# 1. Pick a device once and use it everywhere
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device:", device)

x_train = np.array([[4.7], [2.4], [7.5], [7.1], [4.3], [7.816], [8.9], [5.2],
                    [8.59], [2.1], [8], [10], [4.5], [6], [4]], dtype=np.float32)
y_train = np.array([[2.6], [1.6], [3.09], [2.4], [2.4], [3.357], [2.6], [1.96],
                    [3.53], [1.76], [3.2], [3.5], [1.6], [2.5], [2.2]], dtype=np.float32)

# 2. Copy the data to the device (from_numpy is CPU-only; .to() copies to the GPU)
X = torch.from_numpy(x_train).to(device)
Y = torch.from_numpy(y_train).to(device)

# 3. Create parameters directly on the device so they stay leaf tensors
torch.manual_seed(0)
w = torch.rand(1, 1, device=device, requires_grad=True)
b = torch.zeros(1, device=device, requires_grad=True)

learning_rate = 1e-2

for step in range(1, 3001):
    y_pred = X.mm(w) + b
    loss = (y_pred - Y).pow(2).mean()

    loss.backward()

    with torch.no_grad():
        w -= learning_rate * w.grad
        b -= learning_rate * b.grad
        w.grad.zero_()
        b.grad.zero_()

    if step % 500 == 0:
        print(f"step {step:5d}  loss {loss.item():.4f}")

print("w:", w.item(), "b:", b.item())

# 4. Inference without building a graph, then move back to CPU for NumPy
with torch.no_grad():
    predicted = (X.mm(w) + b).cpu().numpy()

order = np.argsort(x_train[:, 0])
plt.figure(figsize=(12, 8))
plt.scatter(x_train, y_train, label="Original data", s=250, c="g")
plt.plot(x_train[order], predicted[order], label="Fitted line")
plt.legend()
plt.show()Code language: PHP (php)

The loss should fall quickly at first and then level off by the later printouts. The fitted line should pass through the middle of the points, not sit below all of them. A learning rate of 1e-2 works because the loss is a mean over this data. Much larger values (above roughly 0.02 here) make the training diverge.

CUDA semantics you need to know

Device selection. torch.device("cuda") means the current GPU, which is normally cuda:0. Use cuda:1 and so on to target a specific card. To limit which GPUs a process can see, set CUDA_VISIBLE_DEVICES before Python starts. The visible GPUs are renumbered from cuda:0.

python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available(), torch.cuda.device_count())"
CUDA_VISIBLE_DEVICES=1 python train.py   # physical GPU 1 appears as cuda:0Code language: PHP (php)

If torch.version.cuda prints None, the installed PyTorch is a CPU-only build. In that case, install a CUDA-enabled build from the selector on pytorch.org.

All tensors in one operation must be on the same device. PyTorch never moves data between devices on its own. Multiplying a cuda:0 tensor by a CPU tensor raises an error. The result of an operation stays on the device of its inputs.

.to(device) on a parameter creates a new, non-leaf tensor. This is the most common autograd mistake with GPUs:

w = torch.rand(1, 1, requires_grad=True).to("cuda")
print(w.is_leaf)   # False -> w.grad stays None after backward()

# Correct options
w = torch.rand(1, 1, device="cuda", requires_grad=True)
w = torch.rand(1, 1).to("cuda").requires_grad_()Code language: PHP (php)

When you use nn.Module, call model.to(device). This moves the parameters in place, so the problem does not occur.

Execution is asynchronous. CUDA kernels are queued, and Python continues before they finish. Some operations make the CPU wait for the GPU to catch up: .item(), .cpu(), .numpy() after .cpu(), and printing a tensor. Calling loss.item() on every step slows training for this reason, which is why the corrected loop only logs every 500 steps. For accurate timing, call torch.cuda.synchronize() before reading the clock:

import time
torch.cuda.synchronize()
start = time.perf_counter()
out = X.mm(w)
torch.cuda.synchronize()
print("elapsed:", time.perf_counter() - start)Code language: JavaScript (javascript)

Memory is cached. PyTorch keeps freed GPU memory in a cache so it can reuse it quickly. Because of this, nvidia-smi shows more memory in use than torch.cuda.memory_allocated() reports. torch.cuda.memory_reserved() shows the cached total. torch.cuda.empty_cache() returns unused cached blocks to the driver, but it cannot free tensors that your code still references.

Faster host-to-device copies. For large batches, page-locked memory lets copies overlap with GPU work:

batch = batch.pin_memory().to(device, non_blocking=True)Code language: PHP (php)

With a DataLoader, passing pin_memory=True does the pinning step for you.

Common errors and fixes

Error messageCauseFix
Expected all tensors to be on the same deviceData on CPU, weights on GPU, or the reverseCall .to(device) on every input, target and parameter
can't convert cuda:0 device type tensor to numpyCalling .numpy() on a GPU tensorUse .detach().cpu().numpy()
Can't call numpy() on Tensor that requires gradThe tensor is still part of the autograd graphCall .detach() first, or compute it inside torch.no_grad()
AttributeError: 'NoneType' object has no attribute 'zero_'.grad is None because the parameter is a non-leaf tensor created by .to()Create it with device= or call .requires_grad_() after moving it
Torch not compiled with CUDA enabledCPU-only PyTorch buildInstall a CUDA build that matches your driver
CUDA out of memoryBatch or model is too large, or tensors are kept alive across stepsUse smaller batches, store loss.item() instead of loss, and delete unused references

Best practices

  • Define device once at the top of the script and pass it everywhere. Avoid hard-coding .cuda(), so the code still runs on machines without a GPU.
  • For real models, use nn.Linear and an optimizer from torch.optim instead of updating weights by hand. optimizer.zero_grad() and optimizer.step() replace the manual block.
  • Set torch.manual_seed for reproducible starting weights. Exact results can still differ slightly between CPU and GPU.
  • Wrap evaluation in torch.no_grad() or torch.inference_mode() to save memory and time.

Note: A model this small trains faster on the CPU, because the cost of launching GPU kernels and copying data is larger than the work itself. The GPU version is for learning the device rules, not for speed.

Frequently asked questions

How do I check if PyTorch can use my GPU?

Run torch.cuda.is_available(). If it returns False, check that torch.version.cuda is not None (a CPU-only build), that the NVIDIA driver is installed, and that nvidia-smi lists the GPU.

Why is w.grad None after I moved my weight to CUDA?

Calling .to('cuda') on a tensor that has requires_grad=True returns a new non-leaf tensor. PyTorch only fills .grad for leaf tensors. Create the tensor with device='cuda', requires_grad=True, or call .requires_grad_() after moving it.

What is the difference between .cuda() and .to(device)?

Both copy a tensor to a GPU. .to(device) also accepts a CPU device, so the same code runs on machines without a GPU, which makes it the safer choice.

Why does nvidia-smi show more memory than my tensors use?

PyTorch's caching allocator keeps freed blocks reserved so it can reuse them. torch.cuda.memory_allocated() shows the memory your tensors actually use, and torch.cuda.memory_reserved() shows the cached total.

Why is my GPU timing measurement wrong?

CUDA operations run asynchronously, so the Python call can return before the GPU has finished. Call torch.cuda.synchronize() before starting and before stopping the timer.

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 – 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…

Read More

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 – 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