UV Tutorial Part 3: Installing PyTorch With CUDA

- Part 1: Lightning-Fast Oldstyle Python Project Management with UV
- Part 2: Creating and Managing Python Projects with UV
- Part 3: Installing PyTorch with CUDA
Why Installing Torch with CUDA is Challenging
Installing PyTorch (torch) with CUDA can be quite challenging due to fact that CUDA installation often involves installing system-level dependencies, which can vary depending on the operating system. Managing these dependencies in a virtual environment adds another layer of complexity, especially when different projects require different versions. Even with conda, mamba, poetry this process is slow and challenging.
Even with uv, you might face some challenges. While uv simplifies many aspects of project management, dealing with system-level dependencies like CUDA still requires careful handling.
Creating a New Project with UV
First, let’s create a new project using uv:
|
|
Note: I couldn’t install torch using uv for Python 3.13, so we are using Python 3.10 here.
Entering the Project Directory
Navigate to your project directory:
|
|
Creating and Activating a Virtual Environment
Now, create a virtual environment with uv:
|
|
To activate the virtual environment on Windows:
|
|
Usually, uv doesn’t require you to activate the virtual environment. However, in this case, we need to activate it to ensure proper installation of torch with CUDA.
Installing Torch with CUDA
Visit the PyTorch official website to get the installation command. We’ll slightly modify the command to install torch with CUDA:
For Windows:
|
|
For Linux, you can ignore the --index-url option:
|
|
Adding Packages to pyproject.toml
To add these packages to the pyproject.toml file:
|
|
Verifying the Installation
To check if torch is installed with CUDA, let’s create a new Python file hello.py:
|
|
Run the file to verify:
|
|
If the output is True, then torch is successfully installed with CUDA.
Uninstalling Torch
If you need to uninstall torch, you can do so with:
|
|
To remove it from the pyproject.toml file:
|
|
This concludes the third part of the UV tutorial. You’ve learned how to handle the installation of complex packages like PyTorch with CUDA using uv. Happy coding!—
Related Content
- UV Tutorial Part 1: Lightning-Fast Old-Style Python Project Management With UV
- UV Tutorial Part 2: Creating and Managing Python Projects With UV