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 -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 reports memory. The notebook above runs these APIs on a two-GPU machine. The sections below explain what each cell shows, update the deprecated calls, and list the errors you are most likely to hit when working with more than one device.


What CUDA semantics means in PyTorch

Every PyTorch tensor belongs to one device, such as cpu, cuda:0 or cuda:1. PyTorch never moves data between devices without being told to. An operation needs all of its tensor inputs on the same device, and the result is created on that device. Data only moves when you call .to(), .cuda() or .cpu(), or when you pass a device= argument when creating a tensor.

PyTorch also keeps track of a current device for each process, which starts as cuda:0. A bare torch.device('cuda') or a call to .cuda() with no index points to the current device. with torch.cuda.device(n): changes the current device only inside that block. That is why a1 in the example above ended up on cuda:1 while a0, which named cuda0 explicitly, stayed on cuda:0.

GPU work is also asynchronous. A CUDA operation is queued on a stream and control returns to Python before the GPU finishes. Copies between devices and calls like .item() or print(tensor) wait for the GPU automatically. Timing code and error reporting have to account for this, as later sections explain.

Prerequisites and environment check

  • An NVIDIA GPU with a working driver. nvidia-smi should list every GPU you expect.
  • A PyTorch build with CUDA support. The default CPU-only wheels always return False from torch.cuda.is_available().
  • Two or more GPUs for the cross-device cells. On a single GPU, every cuda:1 cell fails with invalid device ordinal, the same way the cuda:2 cell does above.
nvidia-smi --query-gpu=index,name,memory.total --format=csv
python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available(), torch.cuda.device_count())"Code language: JavaScript (javascript)

When torch.version.cuda prints None, the installed PyTorch was built without CUDA. Reinstall it using the CUDA-enabled command from the PyTorch install selector for your platform.

The APIs used in the notebook

CallWhat it doesNotes
torch.cuda.is_available()Returns True if PyTorch can see at least one usable GPUCheck this before any CUDA call
torch.cuda.init()Forces CUDA initialisationRarely needed. PyTorch initialises CUDA lazily on first use
torch.cuda.current_device()Index of the current deviceStarts at 0. Changed by torch.cuda.device or torch.cuda.set_device
torch.cuda.device_count()Number of visible GPUsRespects CUDA_VISIBLE_DEVICES
torch.device('cuda:2')Creates a device descriptorDoes not check that the GPU exists. The error appears when you allocate on it
x.cuda() / x.to(device)Copies to a GPUReturns the same tensor, without copying, if it is already on the target device
with torch.cuda.device(1):Temporarily changes the current deviceAffects only calls that do not name a device index
torch.cuda.memory_allocated()Bytes held by live tensors on the current devicePass a device to query another GPU
torch.cuda.memory_reserved()Bytes held by the caching allocatorReplaces the deprecated memory_cached()
x.new_full(), new_zeros(), new_ones(), new_empty(), new_tensor()Create a new tensor with the dtype and device of xtorch.zeros_like(x) and similar functions also keep the device

Note: The cell commented "Transferring a tensor from GPU 1 to GPU 0" works only because the current device is 0 at that point. x1.cuda() copies to the current device. Inside with torch.cuda.device(1): the same call would return x1 unchanged. Write x1.to('cuda:0') when you need a specific GPU.

Corrected and updated version of the lab

The notebook was written for an older PyTorch release. The script below repeats its main steps with current APIs and explicit device indexes. It also skips the multi-GPU steps when only one GPU is present instead of failing.

import torch

if not torch.cuda.is_available():
    raise SystemExit("No CUDA device visible to PyTorch")

print("PyTorch", torch.__version__, "| CUDA runtime", torch.version.cuda)
n = torch.cuda.device_count()
for i in range(n):
    print(f"cuda:{i} -> {torch.cuda.get_device_name(i)}")

dev0 = torch.device("cuda:0")
x = torch.tensor([10., 20.])          # CPU tensor
x0 = x.to(dev0)                       # explicit target device

# memory_cached() is deprecated: use memory_reserved()
print("allocated:", torch.cuda.memory_allocated(dev0))
print("reserved :", torch.cuda.memory_reserved(dev0))

# Mixing devices: move one operand first
print(x.to(x0.device) + x0)          # tensor([20., 40.], device='cuda:0')

if n > 1:
    dev1 = torch.device("cuda:1")
    x1 = x0.to(dev1)
    print(x1 + x0.to(dev1))           # tensor([20., 40.], device='cuda:1')
    print(x1.new_zeros(2, 2).device)  # cuda:1
else:
    print("Only one GPU: skipping cross-GPU steps")Code language: PHP (php)
  • torch.cuda.memory_cached() is replaced with torch.cuda.memory_reserved(). The old name was deprecated after the caching allocator's statistics were renamed.
  • The failing additions a + a0 and a1 + a0 are fixed by moving one operand to the other's device first.
  • In current releases the cross-device error message reads roughly Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0!. The expected type torch.FloatTensor and binary_op() messages in the notebook come from older versions.
  • The device count is checked before cuda:1 is used, so the script runs on one GPU as well as two.

Understanding GPU memory: allocated vs reserved

PyTorch does not return freed GPU memory to the driver straight away. Its caching allocator keeps freed blocks so later allocations can reuse them without calling the driver again. memory_allocated() counts bytes used by live tensors. memory_reserved() counts everything the allocator holds, including cached blocks that are currently empty. nvidia-smi shows a larger figure still, because it also includes the CUDA context and libraries such as cuBLAS and cuDNN.

torch.cuda.empty_cache() releases only cached blocks that no tensor is using. In the notebook the reserved figure stayed at 1048576 after empty_cache() because live tensors such as x0, y and a0 were still stored in that block. The script below shows the full cycle:

import torch
dev = torch.device("cuda:0")
MiB = 2**20

t = torch.empty(256, 1024, 1024, device=dev)   # 1 GiB of float32
print(torch.cuda.memory_allocated(dev) // MiB, "MiB allocated")

del t
print(torch.cuda.memory_allocated(dev) // MiB, "MiB allocated after del")
print(torch.cuda.memory_reserved(dev) // MiB, "MiB still reserved")

torch.cuda.empty_cache()
print(torch.cuda.memory_reserved(dev) // MiB, "MiB reserved after empty_cache")

print(torch.cuda.max_memory_allocated(dev) // MiB, "MiB peak")
print(torch.cuda.memory_summary(dev, abbreviated=True))Code language: PHP (php)

Expected result: about 1024 MiB allocated, 0 MiB allocated after del, about 1024 MiB still reserved, and close to 0 MiB reserved after empty_cache(). If anything else in the process is using that GPU, the numbers will be slightly higher.

Note: The memory functions report only the current device unless you pass a device. Tensors created on cuda:1 in the notebook do not appear in the memory_allocated() figures, which were measured on device 0.

Device-agnostic and multi-GPU patterns

Production code should pick a device once and pass it everywhere, rather than hard-coding .cuda(). That way the same script runs on a laptop CPU and on a GPU server:

import torch

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model = torch.nn.Linear(128, 10).to(device)       # moves parameters in place
batch = torch.randn(32, 128)

# Pinned host memory + non_blocking lets the copy overlap with GPU work
if device.type == "cuda":
    batch = batch.pin_memory().to(device, non_blocking=True)
out = model(batch)
print(out.device)

# Saving and loading across devices
torch.save(model.state_dict(), "model.pt")
state = torch.load("model.pt", map_location=device)Code language: PHP (php)

To control which physical GPUs a process can see, set CUDA_VISIBLE_DEVICES before Python starts. Visible GPUs are numbered again from zero, so the command below runs on physical GPU 1, which the script sees as cuda:0:

CUDA_VISIBLE_DEVICES=1 python train.py
CUDA_VISIBLE_DEVICES=0,2 python train.py   # two GPUs, seen as cuda:0 and cuda:1Code language: PHP (php)

Because CUDA runs asynchronously, wall-clock timers around GPU code measure only how long it took to queue the work. Call torch.cuda.synchronize() before reading the timer, or use torch.cuda.Event(enable_timing=True) pairs, to measure actual GPU time.

Common errors and fixes

ErrorCauseFix
CUDA error: invalid device ordinalThe device index is not less than device_count(), as with cuda:2 on a two-GPU machineCheck torch.cuda.device_count() and CUDA_VISIBLE_DEVICES
Expected all tensors to be on the same deviceAn operation mixes CPU and GPU tensors, or two different GPUsMove one operand with .to(other.device). A 0-dimensional CPU tensor is allowed as a scalar operand
torch.cuda.is_available() returns FalseCPU-only PyTorch build, missing or too old driver, or GPUs hidden by CUDA_VISIBLE_DEVICESCheck torch.version.cuda and nvidia-smi. Reinstall a CUDA build if needed
CUDA out of memoryBatch too large, or references kept alive, for example summing loss instead of loss.item()Reduce the batch size, use torch.no_grad() for inference, and release references. empty_cache() cannot free memory that live tensors are using
Cannot re-initialize CUDA in forked subprocessCUDA was used before multiprocessing forkedUse the spawn start method, or initialise CUDA only in the child processes
Error reported on an unrelated lineAsynchronous kernel execution delays error reportingRerun with CUDA_LAUNCH_BLOCKING=1 to get an accurate traceback

Best practices

  • Choose the device once and pass device= when creating tensors. This avoids creating a tensor on the CPU and then copying it.
  • Prefer explicit .to('cuda:N') over relying on the current device, and keep with torch.cuda.device() blocks short.
  • Use new_* and *_like functions inside library code so new tensors follow the device and dtype of their inputs.
  • Keep host-device copies out of tight loops. Each .item(), .cpu() or print(tensor) makes the CPU wait for the GPU.
  • Monitor max_memory_allocated() during training to size batches, and call torch.cuda.reset_peak_memory_stats() between experiments.
  • For multi-GPU training, use DistributedDataParallel with one process per GPU rather than moving tensors between GPUs by hand.

Frequently asked questions

What replaced torch.cuda.memory_cached()?

torch.cuda.memory_reserved() returns the same figure: the total bytes held by PyTorch's caching allocator. The old name is deprecated, so new code should use memory_reserved().

Why does torch.cuda.empty_cache() not reduce memory usage?

It releases only cached blocks that no live tensor is using. Memory held by existing tensors, the CUDA context and libraries such as cuDNN stays allocated. To free tensor memory, delete the tensors first or let them go out of scope.

How do I run PyTorch on a specific GPU?

Use an explicit device such as torch.device('cuda:1') with .to(), or start the process with CUDA_VISIBLE_DEVICES=1. The second option hides all other GPUs, and the chosen GPU appears as cuda:0.

Does tensor.cuda() copy the tensor every time?

No. If the tensor is already on the target device, .cuda() and .to() return the original tensor without copying. Otherwise they return a new tensor on the target device.

Can I add a CPU tensor to a GPU tensor?

Not in general. PyTorch raises a same-device error unless the CPU tensor is 0-dimensional, which is treated as a scalar. Move one operand with .to(other.device) first.

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 – 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
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x