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 -1 – Install And Setup PyTorch

This lab installs PyTorch and torchvision so they are ready for the rest of the PyTorch lab series. The notebook above runs pip install torch torchvision from Jupyter. This page adds a current setup in a virtual environment, the CPU and GPU install options, a script that checks the install worked, and fixes for the most common errors.


What the notebook above does and what it leaves out

The notebook has one code cell, !pip install torch torchvision. In the saved output, torch 1.0.1 was already installed under Anaconda with Python 3.7, so pip left it alone and only added torchvision 0.2.2. Those versions are many years old. Current PyTorch releases do not support Python 3.7, so running the same command today in a new environment gives you a much newer version.

The notebook also stops right after the install. It never checks that import torch works or that a GPU can be used. The sections below fill in those steps.

Prerequisites

  • A 64-bit Python 3 release supported by current PyTorch. The supported range moves forward over time, so check the install selector on pytorch.org. 32-bit Python is not supported.
  • pip (comes with Python) and the venv module. On Debian or Ubuntu you may need sudo apt install python3-venv.
  • Several GB of free disk space. The Linux CUDA wheels are large because they include the CUDA runtime libraries.
  • For NVIDIA GPU acceleration: a recent NVIDIA driver. nvidia-smi should run without errors. You do not need to install the full CUDA Toolkit, because the PyTorch wheels ship their own CUDA runtime.
  • For Apple Silicon Macs: the standard macOS wheel already supports the mps (Metal) backend.

Install PyTorch in a virtual environment

A dedicated virtual environment keeps PyTorch and its dependencies away from your system Python and from other projects. On Linux or macOS:

python3 -m venv ~/venvs/pytorch-lab
source ~/venvs/pytorch-lab/bin/activate
python -m pip install --upgrade pip

# Default build from PyPI
pip install torch torchvision

# Jupyter support, registered as its own kernel
pip install jupyter ipykernel
python -m ipykernel install --user --name pytorch-lab --display-name "Python (pytorch-lab)"Code language: PHP (php)

On Windows PowerShell, create the environment with py -m venv $HOME\venvs\pytorch-lab and activate it with $HOME\venvs\pytorch-lab\Scripts\Activate.ps1. The remaining commands are the same.

Always install torch and torchvision with the same command. Each torchvision release is built against one specific torch release. If you install or upgrade only one of them, you can get a mismatched pair, and that is what the original output shows: it kept an old torch and added torchvision alongside it.

Choose a CPU or CUDA build

What pip install torch gives you depends on the platform. When you need a specific build, use the official package index with --index-url. The selector on pytorch.org generates the exact command for your operating system, package manager and CUDA version.

TargetCommandNotes
Linux, defaultpip install torch torchvisionThe PyPI wheel includes CUDA support and is a large download
CPU only (any OS)pip install torch torchvision --index-url https://download.pytorch.org/whl/cpuMuch smaller. A good fit for laptops, CI runners and containers without GPUs
Specific CUDA versionpip install torch torchvision --index-url https://download.pytorch.org/whl/cuXXXReplace cuXXX with a CUDA tag that the selector lists for the current release
Windows with NVIDIA GPUUse the CUDA index URL from the selectorThe default Windows wheel on PyPI is CPU only
macOS (Apple Silicon)pip install torch torchvisionUse the mps device for GPU acceleration

Note: PyTorch no longer publishes new releases to its own conda channel, so conda install pytorch -c pytorch gives you old builds. If you use Anaconda or Miniconda, create a conda environment and run the pip commands above inside it.

Verify the installation

Save the following as check_torch.py and run it with python check_torch.py, or paste it into a notebook cell. It prints the versions, reports which accelerator is available and runs a small calculation on that device.

import torch
import torchvision

print("torch:", torch.__version__)
print("torchvision:", torchvision.__version__)
print("CUDA available:", torch.cuda.is_available())
print("MPS available:", torch.backends.mps.is_available())

if torch.cuda.is_available():
    device = torch.device("cuda")
    print("GPU:", torch.cuda.get_device_name(0))
    print("CUDA runtime used by torch:", torch.version.cuda)
elif torch.backends.mps.is_available():
    device = torch.device("mps")
else:
    device = torch.device("cpu")

x = torch.rand(3, 3, device=device)
y = x @ x.T
print("Device:", y.device)
print(y)Code language: PHP (php)

The version strings show which build you have. CPU-only wheels from the PyTorch index end in +cpu, and CUDA wheels from that index end in a tag such as +cuXXX. On a working GPU machine, CUDA available prints True and the final tensor shows device='cuda:0'. On a CPU-only machine, the tensor still prints, which confirms that PyTorch itself works.

Running pip from Jupyter correctly

!pip runs whichever pip is first on the shell's PATH. That may not belong to the Python environment the notebook kernel uses, so the package can install successfully and import torch still fails. The %pip magic always installs into the running kernel's environment:

%pip install torch torchvision

After installing or upgrading in a notebook, restart the kernel before importing. Otherwise the old version may still be loaded in memory. To check which interpreter the kernel uses, run import sys; print(sys.executable).

Common errors and fixes

SymptomLikely causeFix
ModuleNotFoundError: No module named 'torch' in JupyterThe package went into a different environment from the kernelUse %pip, or select the pytorch-lab kernel you registered with ipykernel
No matching distribution found for torchUnsupported Python version, 32-bit Python, or an unsupported platformInstall a supported 64-bit Python and recreate the virtual environment
torch.cuda.is_available() returns False on a GPU machineA CPU-only wheel is installed, or the NVIDIA driver is missing or too oldCheck that nvidia-smi works, then reinstall using a CUDA index URL from the selector
operator torchvision::nms does not exist or similar import errorstorch and torchvision versions do not matchpip install --upgrade torch torchvision together, using the same index URL
Install fails partway with No space left on deviceThe CUDA wheels plus the pip cache need a lot of spaceFree some disk space, or use pip install --no-cache-dir ...

Good practices for lab and team setups

  • Use one virtual environment per project. Do not install PyTorch into the system Python, and do not use sudo pip.
  • Pin exact versions in a requirements.txt file, for example by running pip freeze > requirements.txt, so the next labs and your teammates get the same build.
  • If you pin a CUDA build, record the index URL alongside the pins. pip freeze does not save it.
  • For CI pipelines and containers that have no GPU, use the CPU index. Image sizes and build times drop considerably.
  • Install packages only from PyPI or download.pytorch.org. Avoid similarly named packages from other sources.

Frequently asked questions

Do I need to install the CUDA Toolkit before installing PyTorch?

No. The PyTorch CUDA wheels include the CUDA runtime libraries they need. You only need a compatible NVIDIA driver, and you can check it with nvidia-smi.

How do I check whether PyTorch can use my GPU?

Run import torch; print(torch.cuda.is_available()). It prints True when an NVIDIA GPU is usable. On Apple Silicon, check torch.backends.mps.is_available() instead.

Should I use pip or conda to install PyTorch?

Use pip. PyTorch no longer publishes new releases to its own conda channel. Conda users can still create a conda environment and run pip install torch torchvision inside it.

Why does import torch fail in Jupyter after a successful pip install?

!pip probably installed into a different Python environment from the notebook kernel. Use %pip install torch torchvision, restart the kernel, and check sys.executable to confirm which interpreter the kernel is using.

Is torchvision required?

It is not required to use PyTorch, but this lab series uses it for image datasets, transforms and pretrained models. Install it in the same command as torch so the two versions match.

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