Sign In

WSL CUDA

Y
Yerim
  1. Setup

WSL2

WSL

•
WSL (Linux용 Windows 하위 시스템)은 별도이 가상 머신 또는 이중 부팅 없이 Windows 컴퓨터에서 Linux 환경을 실행할 수 있는 Windows 기능
•
Linux의 배포판(Ubuntu, Debian, Fedora 등)을 선택하여 설치하고 사용할 수 있다
•
Windows 환경과 Linux 환경을 동시에 사용해야하는 개발자들에게 매우 유용
•
Linux 배포판을 매우 가볍게 사용할 수 있다

컴퓨터 환경 확인

1. Windows 10 1903 이상, 빌드 18362 이상 또는 Windows 11
(Windows 10 Home, Windows 11 Home 버전도 사용가능)
2. Hyper-V 가상화(Hyper-V Virtualization support)를 지원하는 컴퓨터
•
window + R로 실행 창에서 winver.exe를 열어 현재 컴퓨터의 윈도우 버전 확인
•
작업관리자 > 성능에서 가상화 사용이 가능한지 확인한다

WSL 설치

•
제어판 > 프로그램 > Windows 기능 켜기/끄기 → Linux용 Windows 하위 시스템 체크
wsl --install
wsl --status
wsl --list --online
•
위의 명령어를 사용하여 설치가 완료되었는지 확인 가능
•
우분투가 설치되지 않았다면 wsl --install Ubuntu-22.04와 같은 명령어로 우분투 설치

Cuda 설치

NVIDIA Driver

$ nvidia-sim
•
윈도우에 설치된 nvidia driver를 사용하므로 ubuntu 내부에서 nvidia driver를 설치하면 안된다
•
nvidia-sim 명령어로 설치된 dvier의 버전을 확인할 수 있다

build-essential 설치

$ sudo apt update
$ sudo apt install build-essential
•
cmake, gcc, g++ 등의 라이브러리를 제공

CUDA 설정

•
python 3.7 ~ 3.10 + pyTorch 1.12.1에 대응하는 CUDA 11.6 버전
•
python 3.8 ~ 3.11 + pyTorch 2.1.2(최신버전)에 대응하는 CUDA 12.1
ver 12.1
$ wget https://developer.download.nvidia.com/compute/cuda/12.1.0/local_installers/cuda_12.1.0_530.30.02_linux.run
$ sudo sh cuda_12.1.0_530.30.02_linux.run
Failed to verify gcc version. See log at /var/log/cuda-installer. log for details
•
CUDA 12.1과 호환되는 GCC 버전을 설치하는 것이 중요 (GCC 9.X 또는 10.X)
GCC 9 설치
sudo apt update
sudo apt install gcc-9 g++-9
GCC 버전 변경
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 10
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-9 10
GCC 버전 선택
sudo update-alternatives --config gcc
sudo update-alternatives --config g++
There are 2 choices for the alternative gcc (providing /usr/bin/gcc).

  Selection    Path            Priority   Status
------------------------------------------------------------
  0            /usr/bin/gcc-13  100       auto mode
* 1            /usr/bin/gcc-9   90        manual mode

Press enter to keep the current choice[*], or type selection number: 1
•
목록 중 원하는 버전을 선택 (auto로 되어있다면 manual을 선택)
Warning: Incomplete installation
$ sudo sh cuda_12.1.0_530.30.02_linux.run
===========
= Summary =
===========

Driver:   Not Selected
Toolkit:  Installed in /usr/local/cuda-12.1/

Please make sure that
 -   PATH includes /usr/local/cuda-12.1/bin
 -   LD_LIBRARY_PATH includes /usr/local/cuda-12.1/lib64, or, add /usr/local/cuda-12.1/lib64 to /etc/ld.so.conf and run ldconfig as root

To uninstall the CUDA Toolkit, run cuda-uninstaller in /usr/local/cuda-12.1/bin
***WARNING: Incomplete installation! This installation did not install the CUDA Driver. A driver of version at least 530.00 is required for CUDA 12.1 functionality to work.
To install the driver using this installer, run the following command, replacing <CudaInstaller> with the name of this run file:
    sudo <CudaInstaller>.run --silent --driver

Logfile is /var/log/cuda-installer.log
•
nvidia-sim으로 호환되는 Driver (530이상)이 설치 되었다면 무시
•
graphic driver를 같이 설치않아서 뜨는 warning
다시 시도
$ sudo sh cuda_12.1.0_530.30.02_linux.run
Warning: Incomplete installation
$ sudo sh cuda_12.1.0_530.30.02_linux.run
===========
= Summary =
===========

Driver:   Not Selected
Toolkit:  Installed in /usr/local/cuda-12.1/

Please make sure that
 -   PATH includes /usr/local/cuda-12.1/bin
 -   LD_LIBRARY_PATH includes /usr/local/cuda-12.1/lib64, or, add /usr/local/cuda-12.1/lib64 to /etc/ld.so.conf and run ldconfig as root

To uninstall the CUDA Toolkit, run cuda-uninstaller in /usr/local/cuda-12.1/bin
***WARNING: Incomplete installation! This installation did not install the CUDA Driver. A driver of version at least 530.00 is required for CUDA 12.1 functionality to work.
To install the driver using this installer, run the following command, replacing <CudaInstaller> with the name of this run file:
    sudo <CudaInstaller>.run --silent --driver

Logfile is /var/log/cuda-installer.log
•
nvidia-sim으로 호환되는 Driver (530이상)이 설치 되었다면 무시
•
graphic driver를 같이 설치않아서 뜨는 warning
설치 확인
$ ls /usr/local/ | grep cuda
cuda
cuda-12.1
ver 11.6
wget https://developer.download.nvidia.com/compute/cuda/11.6.2/local_installers/cuda_11.6.2_510.47.03_linux.run
$ chmod +x cuda_11.6.2_510.47.03_linux.run
$ sudo ./cuda_11.6.2_510.47.03_linux.run --silent --toolkit

$ ls /usr/local/ | grep cuda
cuda
cuda-11.6
cuda-12.1
•
전체 CUDA를 설치하는 것이 아니라 필요한 버전의 toolkit만 설치하면 되기 때문에 toolkit만 설치하도록 옵션을 주어 직접 실행

cuDNN

다운로드
$ wget https://developer.download.nvidia.com/compute/cudnn/redist/cudnn/linux-x86_64/cudnn-linux-x86_64-9.0.0.312_cuda11-archive.tar.xz
$ wget https://developer.download.nvidia.com/compute/cudnn/redist/cudnn/linux-x86_64/cudnn-linux-x86_64-9.0.0.312_cuda12-archive.tar.xz
압축풀기
tar -xvf cudnn-linux-x86_64-9.0.0.312_cuda11-archive.tar.xz
tar -xvf cudnn-linux-x86_64-9.0.0.312_cuda12-archive.tar.xz
•
압축을 푸는 과정을 보고 싶지 않다면 -v 대신 -xf 옵션 실행
올바른 CUDA 폴더에 넣기
$ cd cudnn-linux-x86_64-9.0.0.312_cuda11-archive
$ ls
LICENSE  include  lib

$ sudo cp include/cudnn*.h /usr/local/cuda-11.6/include
$ sudo cp lib/libcudnn* /usr/local/cuda-11.6/lib64

$ cd ../cudnn-linux-x86_64-9.0.0.312_cuda12-archive
$ ls
LICENSE  include  lib

$ sudo cp include/cudnn*.h /usr/local/cuda-12.1/include
$ sudo cp lib/libcudnn* /usr/local/cuda-12.1/lib64
•
폴더 이름이 lib 또는 lib64인 경우가 있어 ls로 폴더명 확인
PATH 설정
$ nvcc -v
Command 'nvcc' not found, but can be installed with:
sudo apt install nvidia-cuda-toolkit
•
PATH 설정이 이루어지지 않기 때문에 출력되는 오류
$ vi ~/.bashrc
... 기존 .bashrc 내용들

function _switch_cuda {
   v=$1
   export PATH=$PATH:/usr/local/cuda-$v/bin
   export CUDADIR=/usr/local/cuda-$v
   export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-$v/lib64
   nvcc --version
}
•
.bashrc 내용에 _switch_cuda 함수를 추가한 뒤 :wq로 저장
◦
리눅스는 i(insert)를 눌러 내용을 추가할 수 있다
◦
내용을 모두 작성하면 esc 키를 누른 뒤 :wq + enter로 저장
$ source ~/.bashrc
$ _switch_cuda 12.1
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2023 NVIDIA Corporation
Built on Tue_Feb__7_19:32:13_PST_2023
Cuda compilation tools, release 12.1, V12.1.66
Build cuda_12.1.r12.1/compiler.32415258_0
•
nvcc --version 이 정상적으로 작동하는 것을 확인
# ~/.bashrc
# 기본 CUDA 버전 설정 (12.1)
export PATH=$PATH:/usr/local/cuda-12.1/bin
export CUDADIR=/usr/local/cuda-12.1

# 필요 시 cuda-11.6 사용
alias use-cuda-11.6='export PATH=/usr/local/cuda-11.6/bin:$PATH && export CUDADIR=/usr/local/cuda-11.6'
alias use-cuda-12.1='export PATH=/usr/local/cuda-12.1/bin:$PATH && export CUDADIR=/usr/local/cuda-12.1'
•
기본적으로 CUDA 12.1이 활성화
•
use-cuda-11.6 명령으로 CUDA 11.6으로 변환 가능

Anaconda

Anaconda 다운로드
$ wget https://repo.anaconda.com/archive/Anaconda3-2024.10-1-Linux-x86_64.sh
•
Aanconda 사이트에서 가장 최신 버전의 링크를 복사하여 다운로드
설치
$ bash Anaconda3-2024.10-1-Linux-x86_64.sh
PATH 경로 추가
$ source ~/.bashrc
export PATH="/home/username/anaconda3/bin:$PATH"
Anaconda 실행
•
ubuntu를 껐다 켜면 anaconda가 실행되는 것을 확인할 수 있다
conda env list
•
가상환경 리스트
conda create -n [가상환경 이름] python=파이썬버전
conda actiavte [가상환경 이름]
•
가상환경 추가
jupyter notebook
•
jupyter notebook 실행 가능
conda install pytorch==2.5.0 torchvision==0.20.0 torchaudio==2.5.0 pytorch-cuda=12.1 -c pytorch -c nvidia
# cuda: 0 또는 GPU 장치를 나타내면 GPU 사용 중
print(model.device)

VSCode

code
•
window에 vscode가 설치되어 있다면 code를 사용하여 실행 가능
•
WSL를 사용하기 위해 extention을 설치 → vscode를 재실행하면 연결 완료
•
VSCode 좌측 하단의 Open a Remote Window 버튼을 클릭하여 WSL 연결 가능
•
연결을 해제하려면 같은 위치의 WSL:Ubuntu 버튼을 클릭하고 Close Remote Connection를 선택
#cuda 사용 가능 여부
import torch

print(torch.cuda.is_available())

#train.py 실행 시 GPU 사용 여부 체크
import torch

if torch.cuda.is_available():
    device = torch.device("cuda")
    print(f'Training on GPU {torch.cuda.get_device_name(0)}')
else:
    device = torch.device("cpu")
    print('Training on CPU')
•
python 파일을 생성하여 위의 코드를 실행한 뒤 GPU가 제대로 동작하는지 확인
Yerim-DevNote
Subscribe to 'Yerim-DevNote'
Subscribe to my site to be the first to receive notifications and emails about the latest updates, including new posts.
Join Slashpage and subscribe to 'Yerim-DevNote'!
Subscribe
👍