Virtual environment setup
Why this matters
PyTorch and its dependencies can conflict with other projects on your machine. A virtual environment isolates your dependencies so PyTorch works reliably, and you can have different versions across projects without breaking anything.
Explanation
What it is: A virtual environment is an isolated directory containing a Python interpreter and installed packages. It lets you install PyTorch and its dependencies without touching your system Python or other projects. How it works: Python's venv module creates a self-contained directory with its own pip and site-packages folder. When you activate it, your shell's PATH is modified so that python and pip point to the virtual environment's binaries instead of the system ones. Any packages you install go into that isolated site-packages, not the system-wide one. When to use it: Always use a virtual environment for PyTorch development. Do this before installing PyTorch, CUDA drivers, or any ML dependencies.
Analogy
A virtual environment is like a sandbox. Your system Python is the entire beach. A virtual environment is a bucket of sand where you can build and rebuild without affecting the beach outside the bucket. Multiple buckets can coexist, each with different sandcastle structures (package versions).
Code
#!/usr/bin/env python3
import os
import subprocess
import sys
def setup_pytorch_venv(venv_name="pytorch_env"):
"""
Create and display setup instructions for a PyTorch virtual environment.
This function shows what commands to run — it does NOT run activation
(which requires shell interaction).
"""
print(f"Creating virtual environment: {venv_name}")
print(f"Python executable: {sys.executable}")
print(f"Python version: {sys.version.split()[0]}")
# Create the virtual environment
subprocess.run([sys.executable, "-m", "venv", venv_name], check=True)
print(f"✓ Virtual environment created at: {os.path.abspath(venv_name)}")
# Determine activation command based on OS
if sys.platform == "win32":
activate_cmd = f"{venv_name}\\Scripts\\activate"
pip_path = f"{venv_name}\\Scripts\\pip"
else:
activate_cmd = f"source {venv_name}/bin/activate"
pip_path = f"{venv_name}/bin/pip"
print(f"\nNext steps:")
print(f"1. Activate the environment:")
print(f" {activate_cmd}")
print(f"\n2. Install PyTorch 2.11.x (CPU):")
print(f" pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu")
print(f"\n3. Or install PyTorch 2.11.x (GPU/CUDA 12.1):")
print(f" pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121")
print(f"\n4. Verify installation:")
print(f" python -c \"import torch; print(f'PyTorch {torch.__version__}')\"")
return venv_name
if __name__ == "__main__":
setup_pytorch_venv() Creating virtual environment: pytorch_env
Python executable: /usr/bin/python3
Python version: 3.11.8
✓ Virtual environment created at: /home/user/pytorch_env
Next steps:
1. Activate the environment:
source pytorch_env/bin/activate
2. Install PyTorch 2.11.x (CPU):
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
3. Or install PyTorch 2.11.x (GPU/CUDA 12.1):
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
4. Verify installation:
python -c "import torch; print(f'PyTorch {torch.__version__}')"
What just happened?
The code created a new virtual environment directory named <code>pytorch_env</code> by calling Python's <code>venv</code> module. It then printed activation instructions for your operating system (Linux/Mac uses <code>source</code>, Windows uses a batch file) and the exact pip commands to install PyTorch 2.11.x. After you run those commands in the activated environment, your PyTorch installation will be completely isolated.
Common gotcha
The most common mistake is forgetting to activate the virtual environment after creating it. Many developers create the venv, then immediately run pip install torch without activating, which installs PyTorch into the system Python instead. You'll know you forgot because which python (or where python on Windows) will not point into your venv directory. Always verify: the prompt should show (pytorch_env) after activation, or run which python to confirm the path includes your venv.
Error recovery
ModuleNotFoundError: No module named 'torch'venv: command not foundERROR: Invalid requirement: 'https://download.pytorch.org/whl/cu121'Experienced dev note
Most tutorials tell you to create a venv, but don't explain why you absolutely should. The real reason: PyTorch depends on many C libraries (CUDA runtime, cuDNN, etc.) that pin to specific versions. If you install PyTorch globally and later need a different deep learning framework that conflicts, you'll either break PyTorch or waste hours debugging version conflicts. Virtual environments cost almost nothing (typically 100–300 MB per project) and save enormous debugging time. Also, when you deactivate the venv and delete the directory, every trace of PyTorch vanishes: no system-wide cruft. This makes experimentation and cleanup trivial.
Check your understanding
You create a virtual environment and install PyTorch in it, then a colleague asks why they shouldn't just run pip install torch globally on their machine since they only work on PyTorch projects. What's the technical reason your approach is safer, even if they only ever use PyTorch?
Show answer hint
A correct answer explains that even if PyTorch is the only deep learning library, PyTorch itself has multiple versions with breaking changes (PyTorch 1.x → 2.x had significant API changes). Future projects may need a different PyTorch version than current ones. A global install makes it impossible to maintain multiple projects with different PyTorch versions simultaneously. Also, if PyTorch installation breaks, it breaks everything: a venv keeps the damage isolated.
python --version to check. If you're on Python 3.8 or earlier, upgrade your system Python before creating the venv. This is a hard requirement in PyTorch 2.11.x; earlier versions (2.0–2.6) still supported 3.8.