PyTorch Tutorial for Deep Learning in Python — Part 1: Install PyTorch and Create Your First Tensors on the GPU
PyTorch is an open-source deep-learning library for Python: you build neural networks with it, and it does their maths on your computer's CPU or GPU. In this first part you install PyTorch 2.15 in a Python 3.15 project, create your first tensors, move them to the GPU and back, and give the project a command that picks the device every later part runs on.
This is Part 1 of a 15-part series.
- Part 1: Install PyTorch and Create Your First Tensors on the GPU (you are here)
- Part 2: Work with Tensors: Shapes, Data Types and Broadcasting (coming soon)
- Part 3: Load Images with Dataset, DataLoader and Transforms (coming soon)
- Part 4: Build a Neural Network with nn.Module (coming soon)
- Part 5: Compute Gradients with Autograd (coming soon)
- Part 6: Write a Training Loop with a Loss Function and an Optimizer (coming soon)
- Part 7: Track Training Runs with TensorBoard (coming soon)
- Part 8: Evaluate a Classifier with a Confusion Matrix (coming soon)
- Part 9: Save, Load and Resume Training with Checkpoints (coming soon)
- Part 10: Build a Convolutional Neural Network (CNN) (coming soon)
- Part 11: Reduce Overfitting with Data Augmentation, Weight Decay and Early Stopping (coming soon)
- Part 12: Fine-Tune a Pretrained Model with Transfer Learning (coming soon)
- Part 13: Speed Up Training on the GPU (coming soon)
- Part 14: Export a Model with torch.export and Run Predictions (coming soon)
- Part 15: Production Checklist and Recap (coming soon)
Every command and output on this page is real, captured while building the project.
What You'll Have at the End of the Series
Each part teaches one PyTorch concept in depth and uses it on a real project. By the end of Part 15 you'll know how to:
- work with tensors, the grids of numbers everything in PyTorch is built on (Parts 1 and 2);
- load images in batches with
Dataset,DataLoaderand transforms (Part 3); - build a neural network and train it:
nn.Module, autograd, a loss function, an optimizer and the training loop (Parts 4 to 6); - watch and measure training with TensorBoard and a confusion matrix (Parts 7 and 8);
- save training and pick it up again with checkpoints (Part 9);
- build better models: a convolutional network, less overfitting, and a pretrained model fine-tuned on your images (Parts 10 to 12);
- train faster on the GPU, export the model with
torch.exportand make predictions with it (Parts 13 and 14); - run it safely in production, with a checklist (Part 15).
Everything runs on your own computer, with free, open-source software. You don't need a GPU: PyTorch runs on the CPU when there isn't one.
What PyTorch Is
Deep learning trains a neural network, a model made of layers of simple maths, on examples. Show a network thousands of labelled satellite images, and it learns to tell farmland from forest in images it has never seen. Two libraries do that work in this series:
| Name | What it is |
|---|---|
| PyTorch | An open-source deep-learning library. Its PyPI page sums it up as "Tensors and Dynamic neural networks in Python with strong GPU acceleration". Its package is called torch, and so is the module you import |
| torchvision | PyTorch's library for images. Its README says it "consists of popular datasets, model architectures, and common image transformations for computer vision" |
Both work on tensors: grids of numbers with a shape. A colour image, for example, is three grids of numbers, one each for red, green and blue, each as tall and wide as the image. PyTorch keeps a tensor on the computer's main processor, the CPU, or on a GPU, the graphics processor, which does many calculations at once:
CUDA is NVIDIA's platform for running calculations on its GPUs. MPS, short for Metal Performance Shaders, is Apple's: PyTorch's notes say the "mps device enables high-performance training on GPU for macOS devices with Metal programming framework". PyTorch's word for a GPU like these is an accelerator, and its torch.accelerator module finds the one your computer has.
The Example: Land Use from Satellite Images
The series is about PyTorch, not about one app, but every part builds on one project behind the scenes: a classifier that looks at a satellite image and says what the land is used for. It learns from EuroSAT, a dataset of 27,000 labelled images made from Sentinel-2 satellite images, which the Copernicus Earth observation programme makes freely available. torchvision's copy is the "RGB version of the EuroSAT Dataset": colour images of 64 × 64 pixels, in 10 classes:
| Class | Images | Class | Images |
|---|---|---|---|
| AnnualCrop | 3,000 | Pasture | 2,000 |
| Forest | 3,000 | PermanentCrop | 2,500 |
| HerbaceousVegetation | 3,000 | Residential | 3,000 |
| Highway | 2,500 | River | 2,500 |
| Industrial | 2,500 | SeaLake | 3,000 |
The dataset's README says: "The dataset is licensed under the MIT license." It asks you to "consider the Copernicus Sentinel Data Terms and Conditions when using Copernicus Sentinel data", and to cite its two papers:
- Patrick Helber, Benjamin Bischke, Andreas Dengel and Damian Borth, "EuroSAT: A Novel Dataset and Deep Learning Benchmark for Land Use and Land Cover Classification", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, 2019.
- Patrick Helber, Benjamin Bischke, Andreas Dengel and Damian Borth, "Introducing EuroSAT: A Novel Dataset and Deep Learning Benchmark for Land Use and Land Cover Classification", IGARSS 2018, IEEE International Geoscience and Remote Sensing Symposium, 2018.
Part 2 downloads the images, a 94 MB archive. This part sets up the project, with a command that shows the device PyTorch will train on.
Versions Used
| Tool | Version |
|---|---|
| Python | 3.15.2 |
| uv | 0.13.10 |
| PyTorch | 2.15.0 |
| torchvision | 0.29.2 |
| NumPy | 2.5.5 |
| Git | 2.56.1 |
The outputs were captured on a Mac with an Apple M1 Pro and 16 GB of memory, on macOS 26.7.4, where PyTorch uses the Mac's GPU through MPS. I didn't run anything on an NVIDIA GPU: where Windows or Linux differ, this page says so and points to the documentation. Every command on this page works the same in PowerShell on Windows.
What This Part Costs
Nothing. PyTorch, torchvision and uv are free, open-source software, and everything runs on your own computer. On this Mac you need about 1.3 GB of disk space: 670 MB for the project's packages, and as much again for uv's cache, which keeps a copy of every download. On Linux, PyTorch also brings NVIDIA's CUDA libraries, so the download is bigger.
Prerequisites
- uv, which creates Python projects and installs packages. It also downloads Python 3.15 if your computer doesn't have it. Check uv:
uv --version
uv 0.13.10 (e3e7c1eac 2026-11-24 aarch64-apple-darwin)
- Git, to commit the project. Check it:
git --version
git version 2.56.1
- A computer PyTorch 2.15.0 has a build for: a Mac with Apple silicon on macOS 14 or later, a Windows PC with an Intel or AMD processor, or a Linux PC. There's no build for Macs with an Intel processor. To use the Mac's GPU, PyTorch needs macOS 15.0 or later (see the FAQ).
- An internet connection, for the packages.
Step 1: Create the Project
uv init --package --name land-use-classifier --python 3.15 dewiride-land-use-classifier
Initialized project `land-use-classifier` at `/Users/you/source/dewiride-land-use-classifier`

| Part | What it does |
|---|---|
--package | Makes an installable project, with its code in a src/ folder and a command of its own |
--name land-use-classifier | The project's name; its Python package becomes land_use_classifier |
--python 3.15 | Uses Python 3.15 and records it in .python-version |
dewiride-land-use-classifier | The folder to create |
How to Create a Python Project with uv explains every uv init option. uv also made the folder a Git repository. Move into it and name its branch main:
cd dewiride-land-use-classifier
git branch -m main
git branch -m main renames the branch Git created, and prints nothing.
Step 2: Add PyTorch and torchvision
uv add torch torchvision
Using CPython 3.15.2 interpreter at: /Library/Frameworks/Python.framework/Versions/3.15/bin/python3.15
Creating virtual environment at: .venv
Resolved 31 packages in 1.64s
Built land-use-classifier @ file:///Users/you/source/dewiride-land-use-classifier
Prepared 14 packages in 14.55s
Installed 14 packages in 232ms
+ filelock==4.3.2
+ fsspec==2026.9.0
+ jinja2==3.1.6
+ land-use-classifier==0.1.0 (from file:///Users/you/source/dewiride-land-use-classifier)
+ markupsafe==3.0.4
+ mpmath==1.3.0
+ networkx==3.7
+ numpy==2.5.5
+ pillow==13.0.0
+ setuptools==84.2.1
+ sympy==1.14.0
+ torch==2.15.0
+ torchvision==0.29.2
+ typing-extensions==4.16.0

uv used the Python 3.15.2 already installed on this Mac, created the project's environment, .venv, and installed 14 packages into it: PyTorch, torchvision, the packages they need, and the project itself. Downloading and unpacking them took 14.55 seconds here. Four of them matter from the start:
| Package | What it is |
|---|---|
torch | PyTorch 2.15.0 |
torchvision | torchvision 0.29.2, with the EuroSAT dataset, ready-made models and image transforms |
numpy | NumPy 2.5.5, a library for arrays of numbers. torchvision needs it, and PyTorch turns tensors into NumPy arrays and back |
pillow | Pillow 13.0.0, a library for image files, which torchvision needs too |
How to Add a Package to a Python Project with uv covers uv add in detail.
Why 31 packages resolved, but only 14 installed. uv writes the project's packages to a lockfile, uv.lock, for every kind of computer the project could run on, not only this one. On this Mac it installed the 14 it needs. The other 17 are only for Linux, and nearly all of them are NVIDIA's CUDA libraries, which PyTorch uses to run on an NVIDIA GPU. So the same command gives each kind of computer a different PyTorch:
| Your computer | What uv add torch torchvision gives it |
|---|---|
| Mac with Apple silicon | PyTorch for the CPU and the Mac's GPU, through MPS: what this page uses |
| Linux | PyTorch for the CPU and NVIDIA GPUs, plus NVIDIA's CUDA libraries |
| Windows | PyTorch for the CPU only. Its version reads 2.15.0+cpu |
| Mac with an Intel processor | Nothing: PyTorch 2.15.0 has no build for it |
The Windows build of PyTorch on PyPI, where uv add gets it, runs on the CPU only. For an NVIDIA GPU, a Windows computer needs PyTorch from PyTorch's own package index instead. How to Install PyTorch with CUDA Using uv sets that up for Windows, and leaves the Mac and Linux on PyPI.
Step 3: Check the Versions
uv run python -c "import torch, torchvision; print(torch.__version__); print(torchvision.__version__)"
2.15.0
0.29.2
uv run runs a command inside the project's environment, and python -c runs the code in quotes. That code imports PyTorch, as torch, and torchvision, and prints their versions: PyTorch 2.15.0 and torchvision 0.29.2. How to Check Which Version of PyTorch Is Installed explains the labels some builds add to the version, such as +cu132 on Linux and +cpu on Windows, and how to check the version without importing PyTorch.
That command took 28 seconds, with nothing on the screen until the versions appeared. Run it again:
uv run python -c "import torch, torchvision; print(torch.__version__); print(torchvision.__version__)"
2.15.0
0.29.2

This time it took 3 seconds. The first import in a new environment is the slow one, so if a command seems stuck the first time, let it finish.
Step 4: Make Your First Tensor
Before the app gets any code, try tensors in a few short practice scripts. Keep them in a folder of their own, scratch, inside the project:
mkdir scratch
They're practice, not part of the app, so keep them out of Git too. A .gitignore file lists what Git leaves out, one pattern per line, and uv's already keeps .venv out. At the end of it, add a blank line and then these two lines:
# Practice scripts from the tutorial, not part of the app
scratch/
The complete file:
# Python-generated files
__pycache__/
*.py[oc]
build/
dist/
wheels/
*.egg-info
# Virtual environments
.venv
# Practice scripts from the tutorial, not part of the app
scratch/
A line that starts with # is a comment. uv's lines leave out Python's compiled files (__pycache__/, *.py[oc]), what building a package leaves behind (build/, dist/, wheels/, *.egg-info) and the virtual environment (.venv). The new scratch/ line leaves out the practice folder, with everything in it. How to Ignore a Folder in Git with .gitignore shows what the slashes in a pattern change.
Now create scratch/first_tensor.py:
import torch
numbers = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(numbers)
print("Shape: ", numbers.shape)
print("Type: ", numbers.dtype)
print("Device:", numbers.device)

import torchloads PyTorch.torch.tensor(...)makes a tensor from Python numbers. A list of two lists of three numbers becomes a grid of 2 rows and 3 columns..shape,.dtypeand.devicedescribe the tensor: its size along each direction, the type of number it holds, and where it's kept.
Run it:
uv run python scratch/first_tensor.py
tensor([[1., 2., 3.],
[4., 5., 6.]])
Shape: torch.Size([2, 3])
Type: torch.float32
Device: cpu
![The terminal after uv run python scratch/first_tensor.py: the tensor with the rows 1 2 3 and 4 5 6, then Shape torch.Size([2, 3]), Type torch.float32 and Device cpu.](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/ai/pytorch/2026/pytorch-p1-05-first-tensor.webp)
- The tensor prints each number with a dot, as in
1., because it holds decimal numbers. torch.Size([2, 3])is its shape: 2 rows of 3 numbers.torch.float32is its data type: 32-bit decimal numbers, PyTorch's type for decimals unless you ask for another.cpuis where it's kept. PyTorch's tensors tutorial says: "By default, tensors are created on the CPU."
Each of these has a guide of its own: How to Create a Tensor in PyTorch with torch.tensor, How to Get the Shape of a Tensor in PyTorch, How to Check the Data Type of a Tensor in PyTorch and How to Check Which Device a Tensor Is On in PyTorch.
Step 5: Fill Tensors with Zeros, Ones and Random Numbers
You'll rarely type a tensor's numbers in yourself: PyTorch can fill a tensor of any shape for you. Create scratch/filled_tensors.py:
import torch
torch.manual_seed(42)
print(torch.zeros(2, 3))
print(torch.ones(2, 3))
print(torch.rand(2, 3))
print(torch.arange(6))
tile = torch.rand(3, 64, 64)
print("Tile shape:", tile.shape)
Run it:
uv run python scratch/filled_tensors.py
tensor([[0., 0., 0.],
[0., 0., 0.]])
tensor([[1., 1., 1.],
[1., 1., 1.]])
tensor([[0.8823, 0.9150, 0.3829],
[0.9593, 0.3904, 0.6009]])
tensor([0, 1, 2, 3, 4, 5])
Tile shape: torch.Size([3, 64, 64])
![The terminal after uv run python scratch/filled_tensors.py: a 2 by 3 tensor of zeros, one of ones, one of random numbers between 0 and 1 starting with 0.8823, 0.9150 and 0.3829, the whole numbers 0 to 5, and Tile shape torch.Size([3, 64, 64]).](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/ai/pytorch/2026/pytorch-p1-06-filled.webp)
| Line | What it does |
|---|---|
torch.manual_seed(42) | Sets where PyTorch's random numbers start, so the script prints the same "random" numbers on every run |
torch.zeros(2, 3) | 2 rows of 3 zeros |
torch.ones(2, 3) | 2 rows of 3 ones |
torch.rand(2, 3) | 2 rows of 3 random numbers from 0 up to, but not including, 1 |
torch.arange(6) | The whole numbers from 0 up to, but not including, 6. They print without dots, because they're whole numbers |
torch.rand(3, 64, 64) | A tensor of 3 × 64 × 64 random numbers: the shape of one EuroSAT image |
The last line is a first look at Part 2. torchvision's transforms documentation says image tensors are "expected to be of shape (C, H, W), where C is the number of channels, and H and W refer to height and width". A EuroSAT image has 3 channels, red, green and blue, and is 64 pixels high and 64 wide, so as a tensor its shape is [3, 64, 64].
With the same seed you may still see different random numbers from these: PyTorch's notes on reproducibility say "Completely reproducible results are not guaranteed across PyTorch releases, individual commits, or different platforms."
The guides for each: How to Create a Tensor of Zeros in PyTorch with torch.zeros, How to Create a Tensor of Ones in PyTorch with torch.ones, How to Create a Tensor of Random Numbers in PyTorch with torch.rand, How to Get the Same Random Numbers Every Run in PyTorch with torch.manual_seed and How to Create a Range of Numbers in PyTorch with torch.arange.
Step 6: Move a Tensor to the GPU
Tensors start on the CPU. To use the GPU, find the one PyTorch can use, and move the tensor there. Create scratch/gpu_tensor.py:
import torch
accelerator = torch.accelerator.current_accelerator(check_available=True)
device = accelerator or torch.device("cpu")
print("Device:", device)
numbers = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
numbers_on_gpu = numbers.to(device)
print(numbers_on_gpu)
product = numbers_on_gpu @ numbers_on_gpu.T
print(product)
print(product.cpu().tolist())
print(product.sum().item())

The two lines after the import find the device:
torch.accelerator.current_accelerator(check_available=True)returns the GPU that PyTorch can use right now, as a device: MPS on a Mac with Apple silicon, CUDA with an NVIDIA GPU. When there isn't one, it returnsNone.accelerator or torch.device("cpu")keeps that GPU, or uses the CPU when there'sNone. Sodeviceis always somewhere PyTorch can run.
How to Check Whether PyTorch Can Use a GPU (CUDA or Apple MPS) shows the other ways to check. The rest of the script uses the device:
numbers.to(device)returns a copy of the tensor on that device. The tensors tutorial says: "We need to explicitly move tensors to the accelerator using .to method (after checking for accelerator availability)."numbersitself stays on the CPU.numbers_on_gpu.Tis the tensor transposed, its rows turned into columns: 3 rows of 2.@multiplies matrices, the same astorch.matmul, soproductis the 2 × 3 grid times its 3 × 2 transpose, worked out on the GPU..cpu()returns a copy on the CPU, and.tolist()turns it into a plain Python list..sum()adds up every value into a tensor holding one number, and.item()gives you that number as a plain Python number.
Run it:
uv run python scratch/gpu_tensor.py
Device: mps
tensor([[1., 2., 3.],
[4., 5., 6.]], device='mps:0')
tensor([[14., 32.],
[32., 77.]], device='mps:0')
[[14.0, 32.0], [32.0, 77.0]]
155.0
![The terminal after uv run python scratch/gpu_tensor.py: Device mps, the tensor on device mps:0, the product 14, 32, 32, 77 on mps:0, the list [[14.0, 32.0], [32.0, 77.0]] and 155.0.](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/ai/pytorch/2026/pytorch-p1-08-gpu.webp)
Device: mps: PyTorch found the Mac's GPU. With an NVIDIA GPU you'd see CUDA's device here instead, and on a computer without a GPU,cpu.device='mps:0': the tensor is on the GPU. The0is the GPU's number, counting from 0: this Mac has one, andtorch.mps.device_count()printed1. A tensor on the CPU prints without adevice=, as in Step 4.- The product is a 2 × 2 grid. Each number in it multiplies one row of
numbersby another, number by number, and adds those up: 1×1 + 2×2 + 3×3 = 14, 1×4 + 2×5 + 3×6 = 32, and 4×4 + 5×5 + 6×6 = 77. [[14.0, 32.0], [32.0, 77.0]]is the same grid as a Python list, back on the CPU.155.0is 14 + 32 + 32 + 77, as a Python number.
The guides for each step: How to Move a Tensor to the GPU in PyTorch, How to Transpose a Matrix in PyTorch with .T, How to Multiply Matrices in PyTorch with torch.matmul, How to Move a Tensor Back to the CPU in PyTorch with .cpu(), How to Turn a PyTorch Tensor into a Python List with tolist(), How to Add Up the Values of a Tensor in PyTorch with sum() and How to Get a Python Number from a PyTorch Tensor with item().
Step 7: See What Happens When Devices Mix
An operation on two tensors needs both of them on the same device. Create scratch/mixed_devices.py, which adds a tensor on the CPU to one on the GPU:
import torch
accelerator = torch.accelerator.current_accelerator(check_available=True)
device = accelerator or torch.device("cpu")
numbers = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
numbers_on_gpu = numbers.to(device)
print(numbers + numbers_on_gpu)
Run it:
uv run python scratch/mixed_devices.py
Traceback (most recent call last):
File "/Users/you/source/dewiride-land-use-classifier/scratch/mixed_devices.py", line 9, in <module>
print(numbers + numbers_on_gpu)
~~~~~~~~^~~~~~~~~~~~~~~~
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, mps:0 and cpu!

numbers is still on the CPU: .to(device) made a copy on the GPU, and left the original where it was. So line 9 asks PyTorch to add a tensor on mps:0 to one on the cpu, and PyTorch stops with a RuntimeError that names both devices. On a computer without a GPU, device is the CPU, both tensors are already on it, and there's no error.
To fix it, move the CPU tensor to the GPU before adding. Change line 9 to:
print(numbers.to(device) + numbers_on_gpu)
Run it again:
uv run python scratch/mixed_devices.py
tensor([[ 2., 4., 6.],
[ 8., 10., 12.]], device='mps:0')

Both tensors are on mps:0 now, and so is their sum. Fixed: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, mps:0 and cpu! walks through this error in detail.
The app avoids it from the start: it chooses one device, and the later parts put the model and every batch of images on it.
Step 8: Choose the Device in the App
Every later part trains or runs a model, and each needs a device: the GPU when PyTorch can use it, otherwise the CPU, or one you name. Put that choice in one place, a new file, src/land_use_classifier/device.py. It starts with a function that describes the computer's accelerator:
"""Choose the device PyTorch runs on: the computer's GPU when PyTorch can use it, otherwise the CPU."""
import torch
def describe_accelerator() -> str:
"""Name the accelerator this PyTorch build supports, and say whether it can be used right now."""
accelerator = torch.accelerator.current_accelerator()
if accelerator is None:
return "none"
state = "available" if torch.accelerator.is_available() else "not available"
return f"{accelerator.type}, {state}"
torch.accelerator.current_accelerator(), withoutcheck_available, only asks what PyTorch was built for. Its documentation says it returns "the device of the accelerator available at compilation time", and "If no accelerator were available at compilation time, returns None." So it names the kind of GPU the build supports, even on a computer where that GPU can't be used.torch.accelerator.is_available()checks whether it can be used now: the documentation says it checks that "it was built, all the required drivers are available and at least one device is visible".- The return value is text such as
mps, available, for the command to show.accelerator.typeis the device's kind,mpshere.
Then the function the app calls whenever it needs a device:
def pick_device(name: str = "auto") -> torch.device:
"""Return the device called name ("cpu", "cuda" or "mps"), or the best one for "auto".
Raises ValueError when PyTorch can't use that device on this computer.
"""
accelerator = torch.accelerator.current_accelerator(check_available=True)
if name == "auto":
return accelerator or torch.device("cpu")
if name == "cpu":
return torch.device("cpu")
if accelerator is None or accelerator.type != name:
raise ValueError(
f"PyTorch can't use {name} on this computer (accelerator: {describe_accelerator()})"
)
return accelerator
check_available=Trueadds the check for right now: the documentation says it "will also do a runtime check to see if the device torch.accelerator.is_available() on top of the compile-time check". Soacceleratoris a GPU PyTorch can use, orNone."auto", the default, makes Step 6's choice: the GPU if there is one, otherwise the CPU."cpu"always works."cuda"or"mps"works only when that's the GPU PyTorch can use. Otherwise the function raises aValueError, with a message that says what the computer has instead.
The complete file:
"""Choose the device PyTorch runs on: the computer's GPU when PyTorch can use it, otherwise the CPU."""
import torch
def describe_accelerator() -> str:
"""Name the accelerator this PyTorch build supports, and say whether it can be used right now."""
accelerator = torch.accelerator.current_accelerator()
if accelerator is None:
return "none"
state = "available" if torch.accelerator.is_available() else "not available"
return f"{accelerator.type}, {state}"
def pick_device(name: str = "auto") -> torch.device:
"""Return the device called name ("cpu", "cuda" or "mps"), or the best one for "auto".
Raises ValueError when PyTorch can't use that device on this computer.
"""
accelerator = torch.accelerator.current_accelerator(check_available=True)
if name == "auto":
return accelerator or torch.device("cpu")
if name == "cpu":
return torch.device("cpu")
if accelerator is None or accelerator.type != name:
raise ValueError(
f"PyTorch can't use {name} on this computer (accelerator: {describe_accelerator()})"
)
return accelerator

Step 9: Add the devices Command
Thanks to --package, the project already has a command, land-use-classifier, which runs a main function that uv wrote in src/land_use_classifier/__init__.py:
def main() -> None:
print("Hello from land-use-classifier!")
The command moves to a file of its own, so replace the whole of __init__.py with a docstring, a sentence that says what the package is for:
"""Classify satellite images by land use with PyTorch."""
Now create src/land_use_classifier/cli.py. First, what the command accepts:
"""The land-use-classifier command."""
import argparse
def main() -> None:
parser = argparse.ArgumentParser(
prog="land-use-classifier",
description="Classify satellite images by land use with PyTorch.",
)
commands = parser.add_subparsers(dest="command", required=True)
devices = commands.add_parser(
"devices", help="show the PyTorch version and the device it runs on"
)
devices.add_argument(
"--device",
choices=["auto", "cpu", "cuda", "mps"],
default="auto",
help="auto uses the GPU when PyTorch can, otherwise the CPU (default: auto)",
)
args = parser.parse_args()
argparse, Python's own command-line parser, reads what you type afterland-use-classifier.add_subparserslets the command have commands of its own, the waygithasgit commit, andrequired=Truemakes naming one compulsory. This part addsdevices; later parts add commands to train, evaluate, export and predict.--deviceis optional.choiceslists the values it accepts, anddefault="auto"is its value when you leave it out.
Then what devices does:
# PyTorch takes a few seconds to import, so import it only once the arguments are valid.
import torch
import torchvision
from land_use_classifier.device import describe_accelerator, pick_device
print(f"PyTorch: {torch.__version__}")
print(f"torchvision: {torchvision.__version__}")
print(f"Accelerator: {describe_accelerator()}")
try:
device = pick_device(args.device)
except ValueError as error:
devices.error(str(error))
print(f"Device: {device}")
- The imports sit inside
main, afterparse_args(). When you type--helpor a value it doesn't accept,parse_args()prints its message and stops the program before them, so it answers without waiting for PyTorch to load. - The
printlines show the versions, the accelerator and the device. The extra spaces line the values up. devices.error(...)reports theValueErrorfrompick_devicethe wayargparsereports a mistake in what you typed. Python's documentation says it "prints a usage message, including the message, to sys.stderr and terminates the program with a status code of 2." Calling it ondevicesmakes the usage line thedevicescommand's own.
The complete file:
"""The land-use-classifier command."""
import argparse
def main() -> None:
parser = argparse.ArgumentParser(
prog="land-use-classifier",
description="Classify satellite images by land use with PyTorch.",
)
commands = parser.add_subparsers(dest="command", required=True)
devices = commands.add_parser(
"devices", help="show the PyTorch version and the device it runs on"
)
devices.add_argument(
"--device",
choices=["auto", "cpu", "cuda", "mps"],
default="auto",
help="auto uses the GPU when PyTorch can, otherwise the CPU (default: auto)",
)
args = parser.parse_args()
# PyTorch takes a few seconds to import, so import it only once the arguments are valid.
import torch
import torchvision
from land_use_classifier.device import describe_accelerator, pick_device
print(f"PyTorch: {torch.__version__}")
print(f"torchvision: {torchvision.__version__}")
print(f"Accelerator: {describe_accelerator()}")
try:
device = pick_device(args.device)
except ValueError as error:
devices.error(str(error))
print(f"Device: {device}")

Now point the command at the new function. In pyproject.toml, [project.scripts] still names land_use_classifier:main, the function you just removed. Change it:
[project.scripts]
land-use-classifier = "land_use_classifier.cli:main"
land_use_classifier.cli:main means the main function in land_use_classifier/cli.py. How to Add a Command to a Python Project with [project.scripts] explains the table. While you're in the file, replace uv's placeholder description, "Add your description here", with one of your own. The complete file:
[project]
name = "land-use-classifier"
version = "0.1.0"
description = "Classify satellite images by land use with PyTorch."
readme = "README.md"
authors = [
{ name = "Your Name", email = "you@example.com" }
]
requires-python = ">=3.15"
dependencies = [
"torch>=2.15.0",
"torchvision>=0.29.2",
]
[project.scripts]
land-use-classifier = "land_use_classifier.cli:main"
[build-system]
requires = ["uv_build>=0.13.10,<0.14.0"]
build-backend = "uv_build"
authors holds your own name and email, which uv takes from your Git settings: the file above shows placeholders.
Step 10: Run the devices Command
uv run land-use-classifier devices
Built land-use-classifier @ file:///Users/you/source/dewiride-land-use-classifier
Uninstalled 1 package in 2ms
Installed 1 package in 3ms
PyTorch: 2.15.0
torchvision: 0.29.2
Accelerator: mps, available
Device: mps

The first three lines come from uv. It rebuilt and reinstalled the project first, because pyproject.toml had changed: uv's settings reference says "By default, uv will rebuild a project whenever the pyproject.toml, setup.py, or setup.cfg files in the project directory are modified". Reinstalling put the new command in place. Then come the command's own four lines:
PyTorch:andtorchvision:show the versions from Step 3.Accelerator: mps, available: this PyTorch was built for Apple's GPU, and it can use it now.Device: mps: with the default,--device auto, the command chose the GPU.
Now name a device. The CPU always works:
uv run land-use-classifier devices --device cpu
PyTorch: 2.15.0
torchvision: 0.29.2
Accelerator: mps, available
Device: cpu
CUDA doesn't, on a Mac:
uv run land-use-classifier devices --device cuda
PyTorch: 2.15.0
torchvision: 0.29.2
Accelerator: mps, available
usage: land-use-classifier devices [-h] [--device {auto,cpu,cuda,mps}]
land-use-classifier devices: error: PyTorch can't use cuda on this computer (accelerator: mps, available)

With --device cpu, the command printed Device: cpu, though the GPU was there. With --device cuda, on a Mac whose GPU is MPS, pick_device raised its ValueError, and the command turned it into an error that says what the computer has instead. Last, the help screens:
uv run land-use-classifier devices --help
usage: land-use-classifier devices [-h] [--device {auto,cpu,cuda,mps}]
options:
-h, --help show this help message and exit
--device {auto,cpu,cuda,mps}
auto uses the GPU when PyTorch can, otherwise the CPU (default: auto)
uv run land-use-classifier --help
usage: land-use-classifier [-h] {devices} ...
Classify satellite images by land use with PyTorch.
positional arguments:
{devices}
devices show the PyTorch version and the device it runs on
options:
-h, --help show this help message and exit

argparse wrote both help screens from the description and help texts in cli.py. Each took about a second, where the devices runs took 2 to 4: --help stops the program inside parse_args(), before PyTorch is imported.
Step 11: Commit the Project
Check what Git would commit:
git status
On branch main
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
.python-version
README.md
pyproject.toml
src/
uv.lock
nothing added to commit but untracked files present (use "git add" to track)
No scratch folder in the list: Git ignores it. Commit the rest:
git add .
git commit -m "Set up PyTorch and choose the device"
[main (root-commit) 1b10794] Set up PyTorch and choose the device
8 files changed, 556 insertions(+)
create mode 100644 .gitignore
create mode 100644 .python-version
create mode 100644 README.md
create mode 100644 pyproject.toml
create mode 100644 src/land_use_classifier/__init__.py
create mode 100644 src/land_use_classifier/cli.py
create mode 100644 src/land_use_classifier/device.py
create mode 100644 uv.lock

How to Create a Git Repository and Make Your First Commit covers git add and git commit.
Your Project Now Looks Like This
dewiride-land-use-classifier/
├── .gitignore
├── .python-version
├── README.md
├── pyproject.toml
├── scratch/
│ ├── filled_tensors.py
│ ├── first_tensor.py
│ ├── gpu_tensor.py
│ └── mixed_devices.py
├── src/
│ └── land_use_classifier/
│ ├── __init__.py
│ ├── cli.py
│ └── device.py
└── uv.lock
The tree leaves out three folders that are there too: .venv, .git, where Git keeps the project's history, and src/land_use_classifier/__pycache__/, where Python keeps a compiled copy of each module it imports, so it loads faster next time. None of them goes into a commit, and neither does scratch/.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Installing pytorch | uv add pytorch stops with You tried to install "pytorch". The package named for PyTorch is "torch" | uv add torch. Fixed: You tried to install "pytorch". The package named for PyTorch is "torch" shows the whole error |
Running a script with python3 instead of uv run python | ModuleNotFoundError: No module named 'torch': that Python is outside the project's environment | Start it with uv run, in the project folder |
Calling .to(device) without keeping the result | prices.to(device) on a line of its own left prices on the CPU, because .to() returns a copy | Keep the copy: prices = prices.to(device) |
Asking for "cuda" on a Mac | torch.tensor([1.0]).to("cuda") stopped with AssertionError: Torch not compiled with CUDA enabled | Use the device pick_device returns, and check what you have with land-use-classifier devices |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
error: Distribution torch==2.15.0+cu132 ... can't be installed because it doesn't have a source distribution or wheel for the current platform | The project gets PyTorch from PyTorch's CUDA index on every computer, and that index has no build for the Mac | Use the CUDA index on Windows only: Fixed: Distribution torch==2.15.0+cu132 can't be installed because it doesn't have a source distribution or wheel for the current platform |
land-use-classifier devices: error: PyTorch can't use cuda on this computer | The computer has no NVIDIA GPU, or its PyTorch is built for the CPU only, like PyPI's for Windows | Leave --device out to use what the computer has. For an NVIDIA GPU on Windows, install PyTorch from PyTorch's CUDA index |
| The first command that imports PyTorch shows nothing for half a minute | The first import in a new environment is slow: 28 seconds here | Let it finish: the next one took 3 seconds |
FAQ
Does PyTorch use the GPU on a Mac?
Yes, on a Mac with Apple silicon, through MPS. On this Mac, land-use-classifier devices reported Accelerator: mps, available, and Step 6's tensors ran on mps:0. PyTorch's MPS notes give two reasons MPS may not be available: "the current macOS version is not 15.0+ and/or you do not have an MPS-enabled device on this machine."
Do I need a GPU for this series?
No. PyTorch runs everything on the CPU too, and with --device auto the app uses the CPU by itself when there's no GPU. Every part that trains a model says how long training took here, on the M1 Pro's GPU.
Why does the device print as mps, but the tensor as mps:0?
mps names a kind of device, and mps:0 one device of that kind: number 0, the first. This Mac has one MPS device, so every tensor on its GPU is on mps:0.
Is PyTorch free to use?
Yes. PyTorch and torchvision are open-source software: PyTorch's package lists the licences Apache-2.0, BSD-2-Clause, BSD-3-Clause, BSL-1.0, ISC, MIT and Zlib, and torchvision's says BSD. The EuroSAT images come with their own terms: the MIT license, and the Copernicus Sentinel data terms.
Clean Up
Nothing runs in the background, so there's nothing to stop. Keep the project: Part 2 starts from it. The scripts in scratch are yours to keep or delete: Git ignores them, and the app doesn't use them.
Conclusion
You created a Python 3.15 project with uv and installed PyTorch 2.15.0 and torchvision 0.29.2. You made your first tensors, filled tensors with zeros, ones and random numbers, moved one to the Mac's GPU and back, and saw the error PyTorch gives when two tensors are on different devices. And the project has a devices command that chooses the GPU when PyTorch can use it and the CPU otherwise, and says so when a device you name isn't there.
In Part 2 you'll work with tensors in depth, their shapes, data types and broadcasting, and turn EuroSAT's images into tensors.
Additional Resources
- Start Locally — PyTorch's install page, with the command for each platform and GPU.
- torch.accelerator — finding and checking the GPU.
- MPS backend — PyTorch on the GPU of a Mac with Apple silicon.
- Tensors — PyTorch's own introduction to tensors.
- Using uv with PyTorch — uv's guide, with PyTorch's CUDA indexes.
- EuroSAT — the dataset's home page, with its papers and license.
Next → Part 2: Work with Tensors: Shapes, Data Types and Broadcasting (coming soon)
