PyTorch on your computer
Last updated
PyTorch is the library most deep learning is written in, and from now on the course uses it. It can’t run inside a web page, so this lesson installs it in your ml-course folder, checks it works, and runs your first PyTorch script: lesson 6.8’s network, line for line. Every Stage 7 script is one you run on your own computer, and each lesson shows what it printed when we ran it, so you can compare.
By the end of this lesson you can
- Install PyTorch in a virtual environment, with the right command for your computer
- Run a PyTorch script and compare its output with the lesson’s
- Match each line of a PyTorch training loop with the simplenet line it replaces
- Put a model and its data on the same device, CPU or GPU
Why Stage 7 leaves the page
Until now every notebook ran in this page, in Pyodide: real Python and NumPy, compiled to run inside your browser. PyTorch can't run there. It's a large compiled library that talks to your graphics card directly, and no browser lets a page do that.
So from here on, the code runs on your own computer, in the ml-course folder and virtual environment you made in lesson 0.10. That's also where you'd run it in a job: PyTorch is the library most deep learning research and most production models are written in.
How each Stage 7 lesson works:
- Each script is shown in full, with its file name. Copy it into a file of that name in your
ml-coursefolder, or download them all at once in step 4. - Under it is what the script printed when we ran it, with PyTorch 2.15 on a computer without a GPU. Run it yourself and compare.
- Your numbers can differ slightly in the last digits, on a different system, PyTorch version or GPU, because floating-point sums done in a different order round differently. Words and shapes should match exactly, and numbers should match to two or three decimal places.
Install PyTorch
Open a terminal, go to your ml-course folder, and activate its environment (lesson 0.10, step 2):
cd Documents\ml-course .venv\Scripts\activate (.venv) $ python --version Python 3.14.0
cd ~/Documents/ml-course source .venv/bin/activate (.venv) $ python --version Python 3.14.0
PyTorch 2.15 needs Python 3.11 or later, and works with 3.14. If python --version says something older, install a newer Python first (Simple Python, lesson 2.9) and make a new .venv with it.
Now the install. PyTorch comes in different builds for different graphics cards, so the command depends on your computer. Find yours:
Windows or macOS, or any computer without an NVIDIA graphics card:
(.venv) $ python -m pip install torch torchvision
On Windows that gets the build for the CPU. On a Mac with an Apple chip (M1 or later), the same build also uses the Mac's GPU.
Linux without an NVIDIA graphics card: on Linux the plain command gets the NVIDIA build, a much bigger download. Ask for the CPU build instead:
(.venv) $ python -m pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
Windows with an NVIDIA graphics card: get the build for CUDA, NVIDIA's GPU software. On Linux, the plain command already does this.
(.venv) $ python -m pip install torch torchvision --index-url https://download.pytorch.org/whl/cu132
cu132 means CUDA 13.2. It needs an up-to-date NVIDIA driver, but not a separate CUDA install: the libraries come inside the package. If you're not sure, use the CPU command. Everything in Stage 7 runs on a CPU, just more slowly, and step 5 shows how one script uses whichever you have.
torchvision is PyTorch's companion for images: datasets like Fashion-MNIST, which you'll use in the project. It's big: installed on Windows, the CPU build of PyTorch takes about 550 MB, and the CUDA build more, so give it a few minutes. The commands come from PyTorch's install selector (see the sources); if one stops working in a later year, the selector has the current one.
Check that it works
Save this as check_torch.py in your ml-course folder:
"""Check that PyTorch is installed, and say which device it will use.""" import sys import torch print("Python ", sys.version.split()[0]) print("PyTorch", torch.__version__) x = torch.rand(2, 3) print("a tensor:", tuple(x.shape), x.dtype) if torch.cuda.is_available(): print("GPU: CUDA,", torch.cuda.get_device_name(0)) elif torch.backends.mps.is_available(): print("GPU: Apple MPS") else: print("GPU: none, so PyTorch will use the CPU")
Run it from the terminal, with the environment active:
(.venv) $ python check_torch.py Python 3.13.14 PyTorch 2.15.0+cpu a tensor: (2, 3) torch.float32 GPU: none, so PyTorch will use the CPU
That's ours: the versions, a tensor of shape holding 32-bit floats, and the device line. On your computer, the versions may be newer, and the last line names your GPU if you have one. If instead you see ModuleNotFoundError: No module named 'torch', PyTorch went into a different Python: lesson 0.10's step 5 has the fix. In VS Code or JupyterLab, pick the .venv kernel and this code works in a notebook cell too.
Your first script: simplenet, in PyTorch
You already know every idea in PyTorch's core: you built it in lessons 6.7 and 6.8. Here is lesson 6.8's moons network again, written with PyTorch. Pick each row to see what's the same and what's new:
A PyTorch tensor is data, a grad, and a record of how it was made, as in simplenet. PyTorch uses 32-bit floats by default, half the memory of NumPy’s 64-bit ones and much faster on a GPU, so convert NumPy arrays to float32.
The whole script, moons.py:
"""Lesson 6.8's moons network, in PyTorch instead of simplenet.""" import torch from sklearn.datasets import make_moons from torch import nn torch.manual_seed(0) X, y = make_moons(n_samples=300, noise=0.2, random_state=0) X = torch.tensor(X, dtype=torch.float32) y = torch.tensor(y) model = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 2)) optimizer = torch.optim.SGD(model.parameters(), lr=0.5) loss_fn = nn.CrossEntropyLoss() for step in range(501): loss = loss_fn(model(X), y) # predict, measure optimizer.zero_grad() loss.backward() # find the gradient optimizer.step() # step if step % 100 == 0: with torch.no_grad(): accuracy = (model(X).argmax(dim=1) == y).float().mean().item() print(f"step {step}: loss {loss.item():.3f}, accuracy {accuracy:.3f}")
(.venv) $ python moons.py step 0: loss 0.753, accuracy 0.703 step 100: loss 0.241, accuracy 0.897 step 200: loss 0.158, accuracy 0.947 step 300: loss 0.106, accuracy 0.973 step 400: loss 0.086, accuracy 0.977 step 500: loss 0.076, accuracy 0.980
Lesson 6.8's simplenet run went from a loss of 0.618 to 0.074, and 98.3% right; this one from 0.753 to 0.076, and 98.0%. The step-0 numbers differ because the two libraries draw different random starting weights, but the training is the same algorithm, and it lands in the same place.
To save copying, here's every Stage 7 script, in one folder per lesson. Unzip it inside ml-course, and run each one from its own folder with python and the file name:
ml-local/6-P/final.py35 linesml-local/6-P/load.py22 linesml-local/6-P/simplenet.py338 linesml-local/6-P/train.py35 linesml-local/7-1/check_torch.py17 linesml-local/7-1/device.py15 linesml-local/7-1/mismatch.py7 linesml-local/7-1/moons.py23 linesml-local/7-10/clinic.py61 linesml-local/7-10/one_batch.py25 linesml-local/7-10/shapes.py11 linesml-local/7-10/shuffled.py30 linesml-local/7-11/mismatch.py18 linesml-local/7-11/runs.py59 linesml-local/7-11/save_load.py41 linesml-local/7-11/seeds.py28 linesml-local/7-12/amp.py36 linesml-local/7-12/floats.py27 linesml-local/7-12/flops.py22 linesml-local/7-12/fp16_wrong.py54 linesml-local/7-12/speed.py48 linesml-local/7-2/autograd.py15 linesml-local/7-2/loop.py52 linesml-local/7-2/nozero.py51 linesml-local/7-3/adam_lr1.py30 linesml-local/7-3/adam.py27 linesml-local/7-3/digits.py41 linesml-local/7-3/ravine.py30 linesml-local/7-4/per_batch.py26 linesml-local/7-4/range_test.py40 linesml-local/7-4/schedules.py56 linesml-local/7-5/clipping.py26 linesml-local/7-5/grad_norms.py24 linesml-local/7-5/sigmoid20.py37 linesml-local/7-6/activations.py25 linesml-local/7-6/normal_init.py38 linesml-local/7-7/batch_of_one.py8 linesml-local/7-7/batchnorm.py45 linesml-local/7-7/layernorm.py22 linesml-local/7-8/augment.py16 linesml-local/7-8/dropout_eval.py30 linesml-local/7-8/regularise.py72 linesml-local/7-9/grad_flow.py18 linesml-local/7-9/nets.py62 linesml-local/7-9/residual.py33 linesml-local/7-P/ablation.py45 linesml-local/7-P/fashion.py60 linesml-local/7-P/final.py33 linesml-local/7-P/load.py27 lines
Devices and GPUs
A GPU does thousands of multiply–adds at once, which is what a network's matrix products need (lesson 7.12 has the numbers). But a GPU has its own memory: a tensor lives in one place, its device, and an operation needs all its inputs in the same place. The devices you'll meet:
"cpu": your computer's ordinary memory. Every tensor starts here unless you say otherwise."cuda": an NVIDIA GPU."mps": the GPU of an Apple silicon Mac.
So a script picks a device once, at the top, and puts both the model and the data on it:
"""Pick the fastest device this computer has, and put the model and the data on it.""" import torch from torch import nn if torch.cuda.is_available(): device = "cuda" # an NVIDIA GPU elif torch.backends.mps.is_available(): device = "mps" # an Apple silicon GPU else: device = "cpu" print("using", device) model = nn.Linear(3, 2).to(device) # moves the weights x = torch.ones(4, 3, device=device) # makes the data there print("output is on", model(x).device)
(.venv) $ python device.py using cpu output is on cpu
We ran it without a GPU, so it says cpu; on yours it may say cuda or mps. model.to(device) moves every weight and bias; device=device makes a tensor there to begin with, and x.to(device) moves one that's already made. Results come back on the same device. The same script runs on any computer, which is why Stage 7's scripts are written this way.
requirements.txt
After installing, save the exact versions again, as in lesson 0.10:
(.venv) $ python -m pip freeze > requirements.txt
With the plain install, the file lists torch==2.15.0, and pip install -r requirements.txt works anywhere. But a build from PyTorch's own index has a tag after its version, like +cu132, and that version isn't on the normal index, so the file alone fails on another computer:
(.venv) $ python -m pip install -r requirements.txt ERROR: Could not find a version that satisfies the requirement torch==2.15.0+cu132 (from versions: 2.9.0, 2.9.1, 2.10.0, 2.11.0, 2.12.0, 2.12.1, 2.13.0, 2.14.0, 2.14.1, 2.15.0) ERROR: No matching distribution found for torch==2.15.0+cu132
The fix is to name the index in the file. Add this line at the top of requirements.txt, above the rest:
--extra-index-url https://download.pytorch.org/whl/cu132 torch==2.15.0+cu132 torchvision==0.29.2+cu132 ...
--extra-index-url tells pip to look on PyTorch's index as well as the normal one. With cpu instead of cu132, the same goes for the Linux CPU build, whose versions end in +cpu.
No GPU? Google Colab and Kaggle
Everything in Stage 7 runs on an ordinary laptop's CPU. But if you'd like a GPU, or you can't install PyTorch on the computer you have, two websites run notebooks on their computers, with GPUs, free of charge:
- Google Colab (colab.research.google.com), with a Google account. Notebooks are saved in your Google Drive.
- Kaggle (kaggle.com), with a Kaggle account. Notebooks are saved on Kaggle.
Both run Jupyter notebooks in your browser, normally with PyTorch, scikit-learn and matplotlib already installed. Here's every lesson's scripts as a ready-made notebook:
- Lesson 6.P: final.py, load.py, simplenet.py, train.py
- Lesson 7.1: check_torch.py, device.py, mismatch.py, moons.py
- Lesson 7.2: autograd.py, loop.py, nozero.py
- Lesson 7.3: adam.py, adam_lr1.py, digits.py, ravine.py
- Lesson 7.4: per_batch.py, range_test.py, schedules.py
- Lesson 7.5: clipping.py, grad_norms.py, sigmoid20.py
- Lesson 7.6: activations.py, normal_init.py
- Lesson 7.7: batch_of_one.py, batchnorm.py, layernorm.py
- Lesson 7.8: augment.py, dropout_eval.py, regularise.py
- Lesson 7.9: grad_flow.py, nets.py, residual.py
- Lesson 7.10: clinic.py, one_batch.py, shapes.py, shuffled.py
- Lesson 7.11: mismatch.py, runs.py, save_load.py, seeds.py
- Lesson 7.12: amp.py, floats.py, flops.py, fp16_wrong.py, speed.py
- Lesson 7.P: ablation.py, fashion.py, final.py, load.py
Each notebook's first cell prints the Python and PyTorch versions and whether there's a GPU. Then each script gets two cells: one starting %%writefile moons.py, which saves the cell's text as a file, and one with !"{sys.executable}" moons.py, which runs it. The ! runs a command as if in a terminal, and {sys.executable} is replaced by the path of the Python running the notebook. That's more careful than !python, which runs whichever Python comes first on the computer's path: on your own computer that can be a different one, without PyTorch, as lesson 0.10's wrong way showed. We ran every one of these notebooks from the top, in an empty folder, and each script printed exactly what its lesson shows.
On Colab: choose File → Upload notebook and pick the .ipynb file. For a GPU, choose Edit → Notebook settings and pick a GPU as the hardware accelerator, before you run anything: changing it restarts the notebook. Then run the cells from the top.
On Kaggle: create a new notebook. For a GPU, open the Settings pane and choose Accelerator → GPU; scripts that download data, like 6.P's and the project's, also need Internet switched on in the same pane (new notebooks have it on). Kaggle's documentation doesn't describe importing a notebook file, so the simplest way is to paste each script into a cell of its own and run the cells in order. A script that imports another, like 6.P's final.py, needs that file saved first: put %%writefile train.py as the first line of its cell.
Things to know about both, from their documentation:
- They're shared, so they're limited. Colab's free GPUs aren't guaranteed, its limits change and aren't published, and a session lasts at most 12 hours. Kaggle gives 12 hours per session too, and in busy times you may wait in a queue for a GPU.
- Sessions end when you're idle, and the computer is wiped. On Colab, download any file a script saves, like
mistakes.png, before you leave. On Kaggle, files saved in/kaggle/working, the notebook's own folder, are kept, up to 20 GB. - A missing package installs with
!pip installand its name, in a cell.
With a GPU, step 5's device.py prints using cuda, and the same scripts run faster, without a line changed. Colab's GPUs are NVIDIA ones, so it's cuda there; we haven't been able to run these notebooks on a GPU ourselves, so expect your numbers to differ slightly from ours (step 1 says why).
Wrong way: the model and the data on different devices
Move the model to the GPU and forget the data, and the first forward pass fails. Without a GPU, PyTorch's "meta" device, which holds shapes but no numbers, shows the same mistake:
"""The wrong way: the model on one device, the data on another.""" import torch from torch import nn model = nn.Linear(3, 2).to("meta") # "meta" stands in for "cuda" on a computer without a GPU x = torch.ones(4, 3) # made on the CPU, the default print(model(x))
(.venv) $ python mismatch.py RuntimeError: Tensor on device meta is not on the expected device cpu!
That's the last line of the traceback. With "cuda" in place of "meta", on a computer with an NVIDIA GPU, it's a RuntimeError too, and its message names the two devices it found. The fix is always the same: send the data wherever the model is, with x.to(device), before the forward pass, including the inputs and labels of every batch in the training loop.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- PyTorch: Get Started Locally: the install selector: the command for each system and GPU
- PyTorch: Tensor Attributes, torch.device: what a device is, and the names cpu, cuda and mps
- PyTorch: MPS backend: training on the GPU of an Apple silicon Mac
- Google Colab: Frequently Asked Questions: what Colab is, its limits, and uploading a notebook
- Kaggle: Notebooks documentation: turning on a GPU and the internet, and what’s kept after a session
- IPython: Built-in magic commands: %%writefile, and ! to run a shell command from a cell
- Python Packaging User Guide: Installing packages: requirements files, and installing from another package index