PyTorch Environment Installation
System Requirements
Operating System Support
- Windows: Windows 10/11 (64-bit)
- macOS: macOS 10.15+
- Linux: Mainstream distributions (Ubuntu 18.04+, CentOS 7+)
Python Version
- Python 3.8 - 3.11 (recommended 3.9 or 3.10)
Hardware Requirements
- CPU: Modern processor supporting AVX instruction set
- Memory: At least 8GB RAM (recommended 16GB+)
- GPU: NVIDIA GPU (optional, for CUDA acceleration)
Installation Method Selection
1. Official Recommended: pip Installation
The simplest and most direct installation method, suitable for most users.
2. Conda Installation
Suitable for users who need to manage multiple Python environments.
3. Source Compilation
Suitable for advanced users who need custom configuration or the latest development version.
Detailed Installation Steps
Method 1: Using pip Installation
1. Check Python Environment
python --version
pip --version2. Create Virtual Environment (Recommended)
# Create virtual environment
python -m venv pytorch_env
# Activate virtual environment
# Windows
pytorch_env\Scripts\activate
# macOS/Linux
source pytorch_env/bin/activate3. Install PyTorch
CPU Version (Suitable for learning and small-scale experiments):
pip install torch torchvision torchaudioGPU Version (Requires NVIDIA GPU and CUDA):
# CUDA 11.8 version
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
# CUDA 12.1 version
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121Method 2: Using Conda Installation
1. Install Anaconda or Miniconda
Download and install from: https://www.anaconda.com/
2. Create Conda Environment
conda create -n pytorch_env python=3.10
conda activate pytorch_env3. Install PyTorch
# CPU version
conda install pytorch torchvision torchaudio cpuonly -c pytorch
# GPU version
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidiaCUDA Environment Configuration
1. Check GPU Support
import torch
print(f"CUDA available: {torch.cuda.is_available()}")
print(f"CUDA version: {torch.version.cuda}")
print(f"GPU count: {torch.cuda.device_count()}")
if torch.cuda.is_available():
print(f"GPU name: {torch.cuda.get_device_name(0)}")2. Install CUDA Toolkit (if needed)
Visit NVIDIA website to download corresponding version of CUDA Toolkit: https://developer.nvidia.com/cuda-toolkit
3. Verify CUDA Installation
nvcc --version
nvidia-smiVerify Installation
Create test script test_pytorch.py:
import torch
import torchvision
import numpy as np
def test_pytorch_installation():
print("=== PyTorch Installation Verification ===")
# Basic info
print(f"PyTorch version: {torch.__version__}")
print(f"TorchVision version: {torchvision.__version__}")
# CUDA support
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"CUDA version: {torch.version.cuda}")
print(f"cuDNN version: {torch.backends.cudnn.version()}")
print(f"GPU count: {torch.cuda.device_count()}")
for i in range(torch.cuda.device_count()):
print(f"GPU {i}: {torch.cuda.get_device_name(i)}")
# Basic tensor operation test
print("\n=== Basic Functionality Test ===")
# CPU tensor
x = torch.randn(3, 4)
y = torch.randn(4, 5)
z = torch.mm(x, y)
print(f"CPU matrix multiplication result shape: {z.shape}")
# GPU tensor (if available)
if torch.cuda.is_available():
x_gpu = x.cuda()
y_gpu = y.cuda()
z_gpu = torch.mm(x_gpu, y_gpu)
print(f"GPU matrix multiplication result shape: {z_gpu.shape}")
print(f"GPU tensor device: {z_gpu.device}")
# Automatic differentiation test
x = torch.randn(2, 2, requires_grad=True)
y = x.pow(2).sum()
y.backward()
print(f"Automatic differentiation gradient shape: {x.grad.shape}")
# Neural network module test
import torch.nn as nn
model = nn.Linear(10, 1)
input_tensor = torch.randn(5, 10)
output = model(input_tensor)
print(f"Neural network output shape: {output.shape}")
print("\n✅ PyTorch installation verification successful!")
if __name__ == "__main__":
test_pytorch_installation()Run test:
python test_pytorch.pyCommon Problem Solutions
1. Import Error
# Error: ImportError: No module named 'torch'
# Solution: Ensure correct virtual environment, reinstall PyTorch2. CUDA Version Mismatch
# Error: RuntimeError: CUDA runtime version mismatch
# Solution: Install PyTorch matching system CUDA version3. Memory Insufficient
# Error: RuntimeError: CUDA out of memory
# Solution: Reduce batch size or use CPU training4. Windows Long Path Issue
# Enable long path support on Windows
git config --system core.longpaths trueRecommended Development Environment
1. IDE Selection
- PyCharm: Powerful Python IDE
- VS Code: Lightweight with rich plugins
- Jupyter Notebook: Suitable for experiments and learning
2. Essential Plugins/Extensions
- Python syntax highlighting
- Code autocompletion
- Git integration
- Debugger support
3. Useful Python Packages
pip install jupyter matplotlib seaborn pandas scikit-learn tqdmPerformance Optimization Suggestions
1. Use Appropriate Data Type
# Using float32 instead of float64 saves memory
x = torch.randn(1000, 1000, dtype=torch.float32)2. Enable cuDNN Benchmark
import torch.backends.cudnn as cudnn
cudnn.benchmark = True # Suitable for fixed input sizes3. Set Thread Count
torch.set_num_threads(4) # Adjust based on CPU core countUpdate PyTorch
pip Update
pip install --upgrade torch torchvision torchaudioconda Update
conda update pytorch torchvision torchaudio -c pytorchSummary
Correctly installing and configuring PyTorch environment is the first step to success in deep learning projects. Suggestions:
- Prioritize using virtual environments to isolate project dependencies
- Choose CPU or GPU version based on hardware conditions
- Regularly update to latest stable version
- Keep development environment clean and consistent
After installation, you can start exploring the powerful features of PyTorch!