Pytorch provides two main ways of doing this:

  • The less recommended way is to save the entire model object as follows:
torch.save(model, PATH_TO_MODEL)

And then, the saved model can be later read as follows:

model = torch.load(PATH_TO_MODEL)

Although this approach looks the most straightforward, this can be problematic in some cases. This is because we are not only saving the model parameters, but also the model classes and directory structure used in our source code. If our class signatures or directory structures change later, loading the model will fail in potentially unfixable ways.

  • The second and more recommended way is to only save the model parameters as follows:
torch.save(model.state_dict(), PATH_TO_MODEL)

Later, when we need to restore the model, first we instantiate an empty model object and then load the model parameters into that model object as follows:

model = Net()
model.load_state_dict(torch.load(PATH_TO_MODEL)

We will use the morte recommended way to save the model as shown in the following code:

PATH_TO_MODEL = "./convnet.pth"
torch.save(model.state_dict(), PATH_TO_MODEL)

The convnet.pth file is essentially a pickle file containing model parameters.

 

※ reference: Mastering Pytorch

'머신러닝 > Pytorch' 카테고리의 다른 글

define colors using random tuples  (0) 2021.01.06
define the optimizer and the learning rate schedule  (0) 2021.01.06
visualize the filters of the first CNN layer  (0) 2021.01.06
store best weights  (0) 2021.01.04
Storing and loading models  (0) 2020.12.31
COLORS = np.random.randint(0, 255, size=(len(classes), 3), dtype="uint8")
# draw loop
	color = [int(c) for c in COLORS[idx]]

※ reference: pytorch computer vision codebook

define an Adam optmizer object with a learning rate of 1e-4:

from torch import optim
opt = optim.Adam(model_resnet18.parameters(), lr=1e-4)

 

we can read the current value of the learning rate using the following function:

def get_lr(opt):
	for param_group in opt.param_groups:
    	return param_group['lr']
        
current_lr = get_lr(opt)
print('current  lr = {}'.format(current_lr)

 

define a learning scheduler using the CosineAnnealingLR method:

from torch.optim.lr_scheduler import CosineAnnealingLR
lr_schedular = CosineAnnealingLR(opt, T_max=2, eta_min=1e-5)

※ reference: pytorch computer vision codebook

let's get the weight of the first layer:

for w in model_resnet18.parameters():
	w = w.data.cpu()
    print(w.shape)
    break

 

then, normalize the weights:

min_w = torch.min(w)
w1 = (-1 / (2 * min_w)) * w + 0.5
print(torch.min(w1).item(), torch.max(w1).item())

 

next, make a grid and display it:

grid_size = len(w1)
x_grid = [w1[i] for i in range(grid_size)]
x_grid = utils.make_grid(x_grid, nrow=8, padding=1)
print(x_grid.shape)

plt.figure(figsize=(10, 10))
show(x_grid)

 

※ reference: pytorch computer vision codebook

'머신러닝 > Pytorch' 카테고리의 다른 글

define colors using random tuples  (0) 2021.01.06
define the optimizer and the learning rate schedule  (0) 2021.01.06
store best weights  (0) 2021.01.04
Storing and loading models  (0) 2020.12.31
model summary  (0) 2020.12.31
# a deep copy of weights for the best performing model
best_model_wts = copy.deepcopy(model.state_dict())

# initialize best loss to a large value
best_loss=float('inf')

# main loop
	.
	.
	.
	# store best model
	if val_loss < best_loss:
		best_loss = val loss
    	best_model_wts = copy.deepcopy(model.state_dict())
    	# store weights into a local file
    	torch.save(model.state_dict(), path2weights)
    	print("Copied best model weights!")

 

Once training is complete, we'll want to store the trained parameters in a file for deployment and future use.

 

There are two ways of doing so.

 

Let's look at the first method:

 

1. First, we will store the model parameters or state_dict in a file:

# define path2weights
path2weights="./models/weights.pt"

# store state_dict to file
torch.save(model.state_dict(), path2weights)

2. To load the model parameters from the file, we will define an object of the Net class:

# define model: weights are randomly inintiated
_model = Net()

3. Then, we will load state_dict from the file:

weights=torch.load(path2weights)

4. Next, we will set state_dict to the model:

_model.load_state_dict(weights)

In the first method, we stored state_dict or model parameters only.

 

Whenever we need the trained model for deployment, we have to create an object of the model, then load the parameters from the file, and then set the parameters to the model.

 

This is the recommended method by PyTorch creators.

 

Let's look at the second method:

 

1. First, we will store the model in a file:

# define a path2model
path2model="./models/model.pt"

# store model and weights into a file
torch.save(model, path2model)

2. To load the model parameters from the file, we will define an object of the Net class:

#define model: weights are randomly initiated
_model = Net()

3. Then, we will load the model from the local file:

_model=torch.load(path2model)

In second method, we stored the model into a file.

 

In other words, we stored both the model and state_dict into one file. 

 

Whenever we need the trained model for depolyment, we need to create an object of the Net class. 

 

Then, we loaded the model from the file. 

 

So, there is no actual benefit of doing this compared to the previous method.

 

※ reference: pytorch computer vision code book

use torchsummary package to get summary of the model to see the output shape and the number of parameters in each layer.

 

1. install the torchsummary package:

pip install torchsummary

2. let's get the model summary using torchsummary:

from torchsummary import summary
summary(model, input_size=(channels, H, W))

 

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1           [-1, 10, 24, 24]             260
            Conv2d-2             [-1, 20, 8, 8]           5,020
         Dropout2d-3             [-1, 20, 8, 8]               0
            Linear-4                   [-1, 50]          16,050
            Linear-5                   [-1, 10]             510
================================================================
Total params: 21,840
Trainable params: 21,840
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.00
Forward/backward pass size (MB): 0.06
Params size (MB): 0.08
Estimated Total Size (MB): 0.15
----------------------------------------------------------------

 

※ reference: github.com/sksq96/pytorch-summary

rtx 30xx번대 ampere 아키텍처 정식 지원 pytorch 1.7.1(stable) 버전이 나왔다.

 

기존 1.7.0 버전에서는 30xx번대에서 jit 오류를 뿜어댔으나

 

나를 포함한 다른 유저들의 열화와 같은 성원에

 

nightly 버전(1.8)부터 해결되더니 드디어 stable(1.7.1) 버전도 나왔다.

 

아마 기존에는 anaconda의 cuda 버전이 낮아서 안되지 않았나 싶다.

 

각설하고, 윈도우 환경에서 pytorch 1.7.1 + cuda 11.0 + cudnn 8.0.5로 기존 코드들 깔끔하게 동작한다.

 

30xx번대 그래픽 카드 사용자들은 pytorch 업데이트 해서 사용해보자.

'머신러닝 > Pytorch' 카테고리의 다른 글

define the optimizer and the learning rate schedule  (0) 2021.01.06
visualize the filters of the first CNN layer  (0) 2021.01.06
store best weights  (0) 2021.01.04
Storing and loading models  (0) 2020.12.31
model summary  (0) 2020.12.31

앞서 ubuntu에 pytorch 환경을 설정했지만 SSH 콘솔을 통해 코딩 및 디버깅을 하기엔 어려움이 따른다.

 

그래서 구글링을 통해 pycharm pro에서 SSH interpreter를 활용하는 방법을 찾았다.

 

그러니까 뭔말이냐면,

 

내 컴퓨터가 너무 구리거나

 

혹은 너무 좋아서 (RTX 3000번대.. 현재 pytorch에서 암페어 아키텍처를 정식 지원 안해서 못쓴다고 보면 된다, github보면 어거지로 컴파일해서 돌리는 친구들 있는데 속도 안나온다, 괜히 고생하지 말자)

 

딥러닝 개발환경이 안된다면,

 

server의 컴퓨팅 자원을 활용해서 학습도 하고 코딩도 하고 싶은데,

 

디버깅이 편하려면 pycharm을 써야되는데,

 

ssh 콘솔 접속을 통해서 pycharm을 어떻게 써야하나 고민중에,

 

이를 해결할 수 있는 방법이란 얘기이다.

 

왜 pycharm pro를 써야하냐면 pro만 SSH interpreter 기능을 제공한다...

 

참고로 학생일 경우 pro가 1년간 무료로 제공된다.

 

물론 졸업했더라도 학교 이메일만 가지고 있으면 된다.

 

학교 이메일을 통해 계정을 activate할 수 있다.

 

(참고로 본인은 학교 메일로 윈도우와 오피스365를 이용하면서 감사함을 느끼고 있다)

 

www.jetbrains.com/ko-kr/community/education/#students

 

Free Educational Licenses - Community Support

Learn or teach how to code with best-of-industry tools from JetBrains. Free Educational Licenses for JetBrains' tools.

www.jetbrains.com

pycham pro를 실행하고 settings -> project interpreter -> add python interpreter -> SSH interpreter

 

host 및 username을 입력하자.

 

warning 창이 뜨지만 yes를 클릭하고 넘어가자.

 

password를 입력하자.

 

interpreter 폴더를 지정해야하는데 본인은 가상환경을 생성해서 진행하기 때문에

 

anaconda3/envs/venv_name/bin/python3

 

위의 경로로 지정했다.

 

그리고 path mappings에서 local 폴더 및 server 폴더를 지정한다.

 

deployment를 통해 파일 동기화를 수행하는 경로를 지정하는 것이다.

 

설정을 잘 맞췄다면 local에 있는 폴더 및 파일이 서버에 업로드되는 것을 확인할 수 있다.

 

pycharm pro에서 terminal 이용도 가능하다.

 

tools -> start SSH session -> 위의 설정한 host 선택

 

이로써 원격으로 코딩하고 디버깅할 수 있는 환경이 마련됐다.

 

하지만 실사용을 해보니 단점이 명확했다.

 

local의 dataset이 server에도 있어야하니 업로드 시간이 필요했고

 

반대로 추론 결과 및 weight 파일이 server에 저장되니 local로 다운로드가 필요했다.

 

역시 뭐든 local에서 돌리는게 가장 좋은 환경인거 같다.

 

pytorch에서 암페어 아키텍처를 지원하면 서버는 안쓸거 같긴하다.

 

서버 성능이 그렇게 좋은것도 아니고 (1080TI)

계속 windows에서만 작업하다가 ubuntu에서 작업할 일이 생겨서

 

부랴부랴 구글의 도움을 받아 세팅을 완료했다.

 

이전에도 ubuntu에서 작업했지만 좀 오래되서 다 까먹음..

 

서버를 제공받은터라 putty를 통해 세팅을 진행했다.

 

또한 cuda 10.1과 cuDNN 7.6.5로 version을 정한 이유는

 

google colab pro 및 pytorch를 사용중인데

 

거기서 사용하는 version이기 때문이다. (구글 형님 믿고 갑니다)

 

ubuntu는 설치되어있다고 가정하에 cuda 설치를 진행한다.

 

cuda 설치시 driver가 설치되기 때문에 따로 graphic driver를 설치하지 않아도 된다.

 

- 기존 driver 및 cuda가 설치되어 있을 시 제거

$sudo apt-get purge nvidia* && sudo apt-get autoremove && sudo apt-get autoclean && sudo rm -rf /usr/local/cuda*

 

- cuda 10.1 update 2 다운로드 및 설치

 

developer.nvidia.com/cuda-10.1-download-archive-update2?target_os=Linux&target_arch=x86_64&target_distro=Ubuntu&target_version=1804&target_type=runfilelocal

 

CUDA Toolkit 10.1 update2 Archive

Select Target Platform Click on the green buttons that describe your target platform. Only supported platforms will be shown. Operating System Architecture Distribution Version Installer Type Do you want to cross-compile? Yes No Select Host Platform Click

developer.nvidia.com

위의 링크로 가면 Installation Instructions에 따라 다운로드 받고 설치할 수 있다.

 

- 설치가 잘 됐는지 version check

 

nvidia-smi or nvcc --version

 

- cuDNN 7.6.5 설치

nvidia 계정을 생성 및 로그인을 통해 cuDNN 7.6.5를 다운받자.

 

linux용으로 확장자가 solitairetheme8 라는 이름으로 되어있다.

 

아래 명령어로 압축을 해제하자.

$tar -xzvf cudnn-10.1-linux-x64-v7.6.5.32.solitairetheme8

그리고 아래의 명령어로 cudnn을 등록?하자.

$sudo cp cuda/include/cudnn.h /usr/local/cuda/include
$sudo cp cuda/lib64/libcudnn* /usr/local/cuda/lib64
$sudo chmod a+r /usr/local/cuda/include/cudnn.h /usr/local/cuda/lib64/libcudnn*

- anaconda 설치

 

www.anaconda.com/products/individual

 

Anaconda | Individual Edition

Anaconda's open-source Individual Edition is the easiest way to perform Python/R data science and machine learning on a single machine.

www.anaconda.com

위의 링크에서 linux용으로 다운로드 받고 bash쉘로 실행시켜서 설치하자.

$bash ./Anaconda3-2020.07-Linux-x86_64.sh

 

- pytorch 설치

 

cuda 10.1용 pytorch를 설치하자.

$conda install pytorch torchvision torchaudio cudatoolkit=10.1 -c pytorch

 

- python을 실행해서 torch에서 cuda 설치가 잘 됐는지 확인하자.

import torch
torch.cuda.is_available()

설치에 이상이 없으면 True 값이 반환될 것이다.

+ Recent posts