This guide covers setting up a PyTorch development environment on Ubuntu, including installation and verification steps.
Welcome to this comprehensive guide on configuring a PyTorch development environment. In this tutorial, you’ll learn how to create an isolated Python virtual environment on an Ubuntu machine, install all required dependencies (including PyTorch, TorchVision, and TorchAudio), and verify the installation. This step-by-step approach ensures that your environment is reproducible for collaboration or deployment.Before you start, visit the PyTorch “Get Started” page to choose your operating system, package manager, and CUDA version. The page dynamically generates the installation commands. For instance, for a nightly CPU build you may receive:
Isolating your project in a virtual environment prevents conflicts between package versions. Create a new virtual environment named “venv”:
Copy
Ask AI
root@ubuntu-host:~ ⟶ python3 -m venv venv
Check that the venv directory has been created:
Copy
Ask AI
root@ubuntu-host:~ ⟶ ls -ltotal 4drwxr-xr-x 5 root root 4096 Dec 18 14:12 venv
Inside the venv folder, you will find several subdirectories and files:
Copy
Ask AI
root@ubuntu-host:~ ⟶ ls -l venv/total 16drwxr-xr-x 2 root root 4096 Dec 18 14:12 bindrwxr-xr-x 2 root root 4096 Dec 18 14:12 includedrwxr-xr-x 3 root root 4096 Dec 18 14:12 liblrwxrwxrwx 1 root root 14 Dec 18 14:12 lib64 -> lib-rw-r--r-- 1 root root 149 Dec 18 14:12 pyvenv.cfg
Activate the virtual environment with:
Copy
Ask AI
root@ubuntu-host:~ ⟶ source venv/bin/activate
Your prompt should now indicate that you are working within the virtual environment. You can safely install packages using pip without affecting the global Python installation.
Step 4: Install PyTorch, TorchVision, and TorchAudio
With the virtual environment activated, install PyTorch and its related libraries via pip. This command also pulls in necessary NVIDIA libraries if a GPU is detected:
Once you’ve completed testing, deactivate the virtual environment to return to the global Python state:
Copy
Ask AI
root@ubuntu-host:~ via 🐍 v3.11.4 (venv) ➜ deactivate
Running pip3 list in the global environment will now display only basic packages (e.g., pip, setuptools, wheel) without the additional PyTorch and NVIDIA libraries.To double-check, reactivate your virtual environment and list its installed packages:
Copy
Ask AI
root@ubuntu-host:~ via 🐍 v3.11.4 ➜ source venv/bin/activateroot@ubuntu-host:~ via 🐍 v3.11.4 (venv) ➜ pip3 list
Exit the interpreter and deactivate the environment:
Copy
Ask AI
root@ubuntu-host:~ via 🐍 v3.11.4 (venv2) ➜ deactivate
Generating a requirements.txt file helps ensure your project’s environment can be perfectly replicated on another machine, thereby improving collaboration efficiency.