Pytorch와 miniconda 환경 설정¶
2023-07-17 Python Requirement.txt 활용법¶
[toc]
Anaconda 환경에서 Python의 Requirement.txt 활용법을 Check 한다. 현재 Main PC에서의 NIPS2023_WORK 을 위한 Anaconda 환경 이름은 py3.11.0 이다.
Requirements.txt 만들기¶
다음 세가지 방법이 있다
bc. pip freeze > requirements.txt
pip3 freeze > requirements.txt
conda list -e > requirements.txt
이 중에서 ~~ conda list -e > requirements.txt ~~ 를 사용한다.
Anaconda 환경을 사용하기¶
그런데, 본 환경은 일부 PIP를 사용하여 설치되었기 때문에 이러한 방법으로는 제대로 install이 되지 않을 수 있다. 그러므로 다음과 같이 yaml 파일로 정리된 Environment 환경을 사용할 수 있다.
bc. conda env export > environment.yml
실제 환경 설치¶
실제로는 이렇게 되지 않을 수 있다. 따라서, 다음의 Package를 체크하였다.
<table>
<col width="19%" />
<col width="23%" />
<col width="13%" />
<col width="18%" />
<col width="25%" />
<thead>
<tr class="header">
<th align="left">Packgage Name</th>
<th align="left">conda Package</th>
<th align="left">version</th>
<th align="left">Channel</th>
<th align="left">Additional Info.</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">tensorboard</td>
<td align="left">tensorboard</td>
<td align="left">2.10.0</td>
<td align="left">conda-forge</td>
<td align="left"></td>
</tr>
<tr class="even">
<td align="left">json</td>
<td align="left">json</td>
<td align="left">0.1.1</td>
<td align="left">jmcmurray</td>
<td align="left"></td>
</tr>
<tr class="odd">
<td align="left">yaml</td>
<td align="left">pyyaml</td>
<td align="left">6.0</td>
<td align="left">conda-forge</td>
<td align="left"></td>
</tr>
<tr class="even">
<td align="left">scipy</td>
<td align="left">scipy</td>
<td align="left">1.9.3</td>
<td align="left">conda-forge</td>
<td align="left"></td>
</tr>
<tr class="odd">
<td align="left">scikit-learn</td>
<td align="left">scikit-learn</td>
<td align="left">1.2.0</td>
<td align="left">conda-forge</td>
<td align="left"></td>
</tr>
<tr class="even">
<td align="left">matplotlib</td>
<td align="left">matplotlib</td>
<td align="left">3.6.2</td>
<td align="left">conda-forge</td>
<td align="left"></td>
</tr>
<tr class="odd">
<td align="left">pytorch</td>
<td align="left">pytorch</td>
<td align="left">1.13.1</td>
<td align="left">pytorch</td>
<td align="left"></td>
</tr>
<tr class="even">
<td align="left">pytorch-cuda</td>
<td align="left">pytorch-cuda</td>
<td align="left">11.7</td>
<td align="left">pytorch and nvidia</td>
<td align="left"></td>
</tr>
<tr class="odd">
<td align="left">torchvision</td>
<td align="left">torchvision</td>
<td align="left">0.14.1</td>
<td align="left">pytorch</td>
<td align="left"></td>
</tr>
<tr class="even">
<td align="left">torchaudio</td>
<td align="left">torchaudio</td>
<td align="left">0.13.1</td>
<td align="left">pytorch</td>
<td align="left"></td>
</tr>
</tbody>
</table>
- wget의 경우는 환경을 변화 시킨 후 별도로 pip로 설치해야 한다.
bc. pip3 install wget
따라서 다음과 같이 Requirements를 잡아보자
bc. # Usage : conda install requirements_test.txt -c conda-forge -c pytorch -c nvidia -c jmcmurray- Channel : conda-forge, pytorch, nvidia, jmcmurray
json==0.1.1
pyyaml==6.0
scipy==1.9.3
scikit-learn==1.2.0
matplotlib==3.6.2
tensorboard==2.10.0
pytorch==1.13.1
torchvision==0.14.1
torchaudio==0.13.1
pytorch-cuda=11.7
Installation¶
Anaconda update¶
다음과 같이 Anaconda를 업데이트 한다. ~~ conda update -n base conda conda update - all python -m pip install - upgrade pip ~~
Anaconda Installation¶
Preliminaries¶
설치방법은 ~~ pip install -r requirements.txt ~~
그런데 Anaconda에서 가상환경을 구축하기 위해서는 다음과 같이 해야 한다. ~~ conda create - name <env> - file requirements.txt ~~
하지만 위 방법으로는 잘 되지 않는다. 그 이유는 어떤 Package의 경우 PIP를 사용하여 설치하여서 그렇다. 이를 회피하기 위해서는 다음 방법을 사용한다. ~~ conda env create -n new-env-name -f environment.yml ~~
다음은 환경 이름을 py3.10.0 으로 한 예 이다. ~~ conda env create -n py3.10.0 -f environment.yml ~~
Experiments¶
실제 A100 서버에는 다음과 같이 실행하였다.
- Conda 가상환경을 생성하면서 설치하도록 한다.
bc. conda create --name py3.10 --file requirements_test.txt -c conda-forge -c pytorch -c nvidia -c jmcmurray
- wget의 경우는 pip3로만 설치가 가능하다.
bc. pip3 install wget
- 테스트 코드는 다음을 사용한다.
bc. python torch_nn02.py -m Adam -d CIFAR10 -e 1 -n ResNet -g 1
Windows¶
그런데 Windows에서는 스크립트 파일을 바꾸어서 Bat 파일로 만들었을 떄, 이상하게 동작을 잘 하지 못했다. 이유를 나중에 알아보아야 한다. 또 하나 문제점은 설치 시 너무 오랜 시간이 걸린다는 점이다. 따라서 하나씩, 디버깅을 해본다. - Conda 환경 Create [OK] ~~ conda create - name test_env python=3.10.0 ~~
bc. conda install tensorboard==2.10.0 -c conda-forge #[OK]
conda install json==0.1.1 -c jmcmurray #[OK]
conda install pyyaml=6.0 -c conda-forge #[OK]
conda install scipy=1.9.3 -c conda-forge #[OK]
conda install scikit-learn==1.2.0 -c conda-forge #[OK]
conda install matplotlib==3.6.2 -c conda-forge #[OK]
conda install pytorch==1.13.1 -c pytorch #[OK]
conda install torchvision==0.14.1 -c pytorch
conda install torchaudio==0.13.1 -c pytorch
<ul>
<li>범인은 pytorch-cuda 이다. 현재 11.8 버전이고 현 상태에서 필요한 버전은 11.7이다. windows 버전의 경우 너무 시간이 많이 걸린다. 해결책은 다음과 같다.
<ul>
<li>channel은 pytorch와 nvidia가 모두 지정*되어야 한다. 하나만 지정되어서는 안된다.</li>
<li>pytorch-cuda==11.7 로 지정하지 말고 pytorch-cuda=11.7 로 지정한다.</li>
<li>*pytorch -> torchvision -> torchaudio 가 설치된 후, pytorch-cuda 가 설치되어야 한다.</li>
</ul>
bc. conda install pytorch-cuda=11.7 -c pytorch -c nvidia
</li>
</ul>
Verification¶
bc. python -c "import torch; print(torch.__version__, torch.cuda.is_available())"
Miscellaneous topics¶
- conda 가상환경 삭제
bc. conda deactivate # 현재 가상환경을 빠져나온 다음 가상환경을 지운다.
conda remove --name [가상환경명] --all
실제 Installation Guide¶
다음 내용은 README.md 의 내용과 동일하다.
We strongly recommend Anaconda environment to operate the provided test codes. When you setup Anaconda packages (or previously installed), we recommend the base virtual environment of your Anaconda platform as follows: ~~ (base)yourID@home$ ~~
For Linux¶
Change the mode of the file "installation.sh" as follows: ~~ chmod +x installation.sh ~~ Run the installation.sh such that ~~ source ./installation.sh ~~ Following this, you write the name of the conda virtual environment after the following command : ~~ Input the name of a conda virtual environment for test codes: ~~ If you input the name as "test_env" such that ~~ test_env ~~ , then you can verify the name as follows: ~~ The name of rhe conda virtual environment: test_env ~~ Automatically, the installation scripts setup the required python packages
For Windows¶
Instead of the installation shell files in Linux, we use the following commands directly to install the test codes on Anaconda frame work.
First, we update the anaconda framework using the following commands:
bc. conda update -n base conda
conda update --all
python -m pip install --upgrade pip
Following this, we input the follwoing code to install the test codes. You set the name of an anaconda environment replace conda_env_name with what you want.
bc. conda env create --name conda_env_name -f environment_test.yml
If you set the name of environment as "test_env", the installation code is as follows (It takes some times):
bc. conda env create --name test_env -f environment_test.yml
After installing the required packages, activate the conda environment named with what you depicts.
bc. conda activate conda_env_name
Verification of installation¶
You will see that the conda environment is changed with the "test_env". ~~ (test_env)yourID@home$ ~~
You can verify the conda environment is setup appropriately with the following python test code: ~~ python -c “import torch; print(torch.__version__, torch.cuda.is_available()) >>>1.13.x True # It indicates that the cuda chain for pytorch is setup proper. ~~
To verify the test program works well, type the following command: ~~ python torch_nn02.py -m Adam -d CIFAR10 -e 10 -n ResNet -g 1 ~~ After the downloading of CIFAR10 dataset, you can see the operation of the test codes.
Usage of GPU¶
[Pytorch] GPU 여부 확인, 사용할 GPU 번호 지정, 모델 및 텐서에 GPU 할당 방법
Linux¶
- CUDA_VISIBLE_DEVICES 를 아래와 같이 지정하면 된다.
# 가장 기본적인 예시(GPU 1개, 여러개 예시) $ CUDA_VISIBLE_DEVICES=0 python file_name.py $ CUDA_VISIBLE_DEVICES=0,1,2 python file_name.py # bash for문, input 인자가 있는 복잡한 예시 $ for var in {1..100} do CUDA_VISIBLE_DEVICES=1 python file_name.py \ --argument1 $var done
- 코드 실행 후, 다른 터미널에서 nvidia-smi를 입력하여 GPU가 잘 사용되고 있는지 여부를 확인한다.
Windows¶
- 터미널의 종류가 다르기 때문에 bash 형태가 아닌 OS 라이브러리를 이용해야 한다.
import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="0" # GPU 여러개를 지정하고 싶은 경우는 아래 형태로 사용 os.environ["CUDA_VISIBLE_DEVICES"]="0,1,2"
윈도우에서는 코드 실행 후, 작업 관리자 -> 성능 -> GPU 탭에서 사용 현황을 확인하면 된다.
Tips¶
특정 번호의 GPU 사용 지정¶
- 만일, 특정 번호(들)의 GPU만을 파이토치에서 사용하고 싶은 경우는 os 모듈의 기능을 활용하여 다음 코드처럼 지정한다.
import os # 0, 1, 2번의 GPU를 모두 사용하고 싶은 경우 예시(각각 cuda:0, cuda:1, cuda:2에 지정) os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2" # 2번 GPU만 사용하고 싶은 경우 예시(cuda:0에 지정) os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "2"
- 여러개의 GPU를 연결한 경우, 그래픽 카드가 연결된 순서대로 각각 cuda:0, cuda:1, ...
- 디바이스로 인식되도록 지정된다
연결된 GPU 정보 및 사용 가능 GPU 개수 확인¶
- 아래의 코드로 각 번호에 연결된 그래픽 카드의 이름과 총 GPU의 개수를 확인할 수 있다.
# GPU 이름 체크(cuda:0에 연결된 그래픽 카드 기준) print(torch.cuda.get_device_name(), device = 0) # 'NVIDIA TITAN X (Pascal)' # 사용 가능 GPU 개수 체크 print(torch.cuda.device_count()) # 3
GPU 사용 가능 여부 확인¶
- 아래의 명령어의 결과가 True로 반환되면 GPU가 연결되어 사용 가능하다는 의미
- GPU 사용 가능 -> True, GPU 사용 불가 -> False
print(torch.cuda.is_available())
- 다음과 같이 코드를 작성하면 GPU 여부에 따라서 사용할 디바이스 종류 자동 지정이 가능
bc(python). # GPU 사용 가능 -> 가장 빠른 번호 GPU, GPU 사용 불가 -> CPU 자동 지정 예시
device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
Git Commit/Push/Pull¶
environment.yml 파일이 변경되어 add 해야 한다고 가정하자. add, commit, push, 다음과 같다.
bc. git add environment.yml
git commit -m "modifying environment.yml. The name of anaconda envronment is py3.10.0, and the python version is 3.10.0"
git push --progress "origin" master:master
pull은 다음과 같다.
bc. git pull --progress "origin"
Git commit에 시간이 너무 많이 걸릴떄¶
requirements.txt 파일을 추가하기 위하여 git commit을 해야 하는데, 너무 시간이 오래걸리면 다음과 같이 한다. ~~ git add requirements.txt git commit -m "message" ~~
그리고 git push 하면 쉽게 된다.
Note¶
Atome Editor에서 Markdown Preview¶
Atom Editor의 Markdown Preview Plus의 경우, 현재 Github에 떠 있는 버전은 문제가 있다. Atom Editor에서도 제대로 동작이 되지 않는다. 반면 내가 가지고 있는 버전은 정상적으로 동작한다. 따라서, Atom Editor 관련한 파일을 잘 보관하였다가 사용할 필요성이 있다. 현재, 이음서비스에 Atom Editor 설치판과 Markdown Preview Plus를 압축파일로 보관 중이다.
Markdown Preview Plus 설치¶
이제, Markdown Preview Plus는 APM으로 설치되지 않는다. 따라서, 이음서비스에 있는 Markdown Preview Plus 파일을
- /.atom/packages/ 에 Markdown Preview Plus 폴더를 만들고
- 직접 다음 사이트에 복사해 넣어 주어야 한다.
bc. .../.atom/packages/Markdown Preview Plus
Linux Background 실행 (nohup)¶
- 참고 사이트 [4]
- 다음과 같이 실행한다.
bc. nohup python torch_nn02.py -bt 1 > result_2023_08-01-1104.txt &
- 그러면 출력으로 해당 프로세스의 PID 값이 나온다.
bc. [1] 1514413
- 현재 running 중의 Process를 알고 싶으면 jobs 를 쓴다.
bc. (py3.10.12) sderoen@etri:~/nips2023_work$ jobs
[1]+ Running nohup python torch_nn02.py -bt 1 > result_2023_08-01-1104.txt &
아까 입력한 명령이 현재 동작 중에 있음을 알 수 있다.
- Process 를 죽이는 방법은 먼저, 위에서 알고 있는 PID 를 사용하여
bc. kill -9 1514413
- 그리고 jobs를 통해 얻게된 작업 (작업 번호를 알아야 한다. 여기서는 [1] 이므로 1) 번호로 죽이는 방법이 있다.
bc. kill %1