Concepts / Tensors and Basic Tensor Operations in PyTorch

Tensors and Basic Tensor Operations in PyTorch

When you start writing PyTorch code that handles tensors, a natural temptation is to switch everything over to a GPU as soon as one is mentioned.

  • Programming

Asking Before Moving Work to a GPU

When you start writing PyTorch code that handles tensors, a natural temptation is to switch everything over to a GPU as soon as one is mentioned. Before changing any code, it helps to ask a simple question first: does the runtime you are working in support GPU computing at all? PyTorch gives you a direct way to find out. This article starts with that check, then uses what it reveals to build an understanding of how PyTorch decides where work happens.

The question has two parts that are easy to confuse. The first is whether the current environment can use a GPU at all. The second is where a particular tensor and its computations actually live. This article treats them as separate questions, and the first half of the article is about the first one.

What a Device Is

Definition

A device is where computations occur and data resides. In PyTorch, the CPU and the GPU are both examples of devices.

Think of a device as a location with two jobs at once. It is the place where PyTorch carries out arithmetic, and it is also the place where the numbers involved in that arithmetic are held. Because both jobs belong to one concept, you cannot talk about where a computation happens without also talking about where its data lives. A device is therefore not just a processor name; it is the combined answer to 'where is the work done' and 'where is the data kept'.

The two devices named in this course are the CPU and the GPU. Both are locations PyTorch can use for computation and for holding tensor data. The rest of the article explains how PyTorch chooses between them and why that choice matters for every operation you perform.

Checking GPU Availability at Runtime

PyTorch provides torch.cuda.is_available() for the availability question. It reports whether GPU computing is available in the current runtime. A short script that asks PyTorch for that answer looks like this:

python
Output (expected)
True or False, depending on the runtime you are using
Notes on the code
  • import torch loads the PyTorch library
  • torch.cuda.is_available() asks PyTorch whether GPU computing is available here
  • print shows the answer so you can read it
Runtorch.cuda.is_available()Returns True?GPU computingavailablein this runtimeRuntime answerrecordedGPU computing notavailablein this runtimeTrueFalse
What path does the program take depending on whether torch.cuda.is_available() returns True or False, and where does the device selection end up?

The flowchart shows that the check itself ends in a single answer: the runtime either supports GPU computing or it does not. Nothing in this step moves a tensor or changes where any operation runs. It only reports a fact about the environment.

Where a Tensor Lives and Where It Computes

The availability check answers whether a GPU can be used. It does not answer where a given tensor sits. For that, the important relationship is this: a PyTorch tensor resides in a device, and its operations are executed on that same device. The tensor and the work it triggers are tied together.

Two consequences follow from this relationship. First, a tensor is never floating in no location; it always sits on some device. Second, when you ask PyTorch to perform an operation on a tensor, that operation runs on the device where the tensor is. You do not pick the compute location separately from the data location.

Tensordata held by PyTorchDeviceCPU or GPUOperationapplied to the tensorresides inexecutes on the same device
Where does each tensor physically reside, and what happens when an operation is applied to it?

The diagram captures the rule in words: the tensor resides in one device, and the operation is executed on that same device. Because of this, the device is decided by where the tensor already lives, not by a separate choice made at the moment of the operation.

Predicting Where an Addition Runs

Now consider a small computation: two tensors that can be added together. Before reading the result, try to predict what the program produces. Focus on the values first; the device question comes next.

What do you think happens?

Two tensors, [1, 2, 3] and [10, 20, 30], are added together. Which values does the result hold, and which device does the addition run on by default?

Reveal answer
Answer:

The result holds [11, 22, 33], and the addition runs on the CPU by default.

Element by element, 1 plus 10 is 11, 2 plus 20 is 22, and 3 plus 30 is 33. Computations in PyTorch are carried out on the CPU by default, so moving this work to a GPU would be a deliberate step.

Worked example

Tracing the Device of a Tensor Addition

Two tensors, a = [1, 2, 3] and b = [10, 20, 30], are added. Determine the values of the result and the device on which the operation executes.

  1. 1
    Identify where the data resides

    Each tensor resides in a device. Without any deliberate move to a GPU, the tensors and their work stay on the CPU, which is the default.

  2. 2
    Identify the operation

    The operation is addition. A tensor's operation executes on the same device where the tensor resides, so the addition executes on the CPU.

  3. 3
    Compute the values

    Adding element by element gives 1 + 10 = 11, 2 + 20 = 22, and 3 + 30 = 33.

  4. 4
    Combine the answers

    The result holds the values 11, 22, 33 and sits on the same device as its operands, which is the CPU.

Result

The result is [11, 22, 33] on the CPU.

CPU and GPU Side by Side

The CPU and the GPU are both devices, so both can be the place where computation occurs and where data resides. They differ in which one PyTorch uses by default and in whether a given runtime can use a GPU at all. The comparison below keeps to those facts.

CPUdefault deviceComputationcarried out here by defaultDataresides on the CPUGPUused deliberatelyComputationwhen moved hereDataresides on the GPUsame devicesame device
How do the CPU and GPU differ as devices in terms of where computation occurs and where data resides?

Mistakes Beginners Make with Devices

  • Common mistake

    Treating the availability check as a statement about where tensors live

    What it looks like

    Seeing True from torch.cuda.is_available() and assuming every tensor is now on the GPU.

    Why it fails

    The check reports whether GPU computing is available in the current runtime. It is a separate question from where a given tensor resides.

    Do this instead

    Read the availability result as a fact about the runtime, and check the device of the tensor separately.

  • Common mistake

    Assuming work moves to the GPU automatically

    What it looks like

    Writing a tensor addition and expecting it to run on a GPU because one is installed.

    Why it fails

    Computations in PyTorch are carried out on the CPU by default, so moving work to a GPU is a deliberate step.

    Do this instead

    Expect CPU execution unless you deliberately move the work to a GPU.

  • Common mistake

    Reading the result without checking the device

    What it looks like

    Printing only the values of an addition and ignoring where the result sits.

    Why it fails

    A tensor always resides in some device, and its operations execute on that device, so the location is part of the computation's meaning.

    Do this instead

    Treat the device as part of the tensor's state, alongside its values.

  • Common mistake

    Confusing the device of one operand with the device of the other when they differ

Practice Predicting the Device

EASY

A runtime reports False from torch.cuda.is_available(). Two tensors are created and added. Without any deliberate move, on which device does the addition run, and what does the False result tell you about that device choice? Explain using the rule that a tensor's operations run on the device where the tensor resides.

Hints
  • Ask first whether the default computation location depends on GPU availability.
  • Recall that a tensor resides in a device and its operations execute on that same device.
  • Separate the answer about the runtime from the answer about where the tensors live.

Key Takeaways

  • A device is where computations occur and data resides, and the CPU and the GPU are both examples of devices in PyTorch.
  • torch.cuda.is_available() reports whether GPU computing is available in the current runtime, which is separate from where a given tensor resides.
  • A PyTorch tensor resides in a device, and its operations execute on that same device.
  • Computations are carried out on the CPU by default, so moving work to a GPU is a deliberate step.

Related concepts

More concepts starting with T