Pytorch GPU Memory Leakage during evaluation (Pytorch CUDA out of memory error during evaluation)

The first thing you can try is wrapping your model with torch.no_grad().

If you have already wrapped your model with torch.no_grad() and are still experiencing the GPU memory leakage issue,

then you can do the garbage collection as well as the memory cache deletion as follows:

import gc

gc.collect()

torch.cuda.empty_cache()

evaluation mode에서 gpu memory leakage를 경험할 경우 모델을 torch.no_grad()로 감쌌는지 확인해본다. 감쌌는데도 여전히 동일한 문제가 발생할 경우,

import gc

gc.collect()

torch.cuda.empty_cache()

를 해주어 garbage collection과 메모리 캐시 삭제를 해주면 된다. 다만 이 경우 코드의 실행 속도가 느려진다.

참고

Conda 가상환경에서 jupyter notebook 사용하기

conda 가상환경에서 jupyter notebook을 열었는데, 지금껏 열심히 설치한 패키지들이 import되지 않는 난감한 상황이 발생할 때가 있다. 가상환경을 활성화시켰고, 가상환경 안에서 jupyter notebook까지 잘 켰는데 왜 import error가 뜨는걸까?

이는 jupyter notebook은 conda 가상환경에 따로 설치해주지 않아도 사용할수 있는 데에서 발생한다. 그냥 jupyter 패키지를 설치해주면 간단하게 해결된다. 다음의 명령어 두개를 쳐보자.

conda install jupyter

jupyter notebook

이제 노트북이 제대로 실행이 되고, 가상환경에 설치한 패키지들도 문제없이 import 될것이다.

 

 

 

 

 

conda로 pytorch와 tensorflow를 같이 설치할때 from torch._C import * ImportError: numpy.core.multiarray failed to import 에러 해결하기

from torch._C import * ImportError: numpy.core.multiarray failed to import 는 conda를 이용하여 pytorch와 tensorflow를 같이 설치할때 흔히 겪을 수 있는 오류이다.

이 오류는 tensorflow 가 python 3.7과 잘 맞지 않음에서 발생한다. (참고: mjahmad님의 답변)

해결방법은 다음과 같다.

  • python 3.6 의 conda 가상환경을 만든다
    • conda create -n 가상환경이름 python=3.6
  • 방금 만든 가상환경을 활성화
    • conda activate 가상환경이름
  • 개발환경에 맞는 pytorch 설치
    • 설치 명령어는 이곳을 참조
  • tensorflow 를 설치
    • conda install tensorflow

이제 제대로 해결되었는지 test 해보자. command line 에 다음의 명령어를 순서대로 쳐보자.

python

import torch

import tensorflow as tf

import numpy as np

 

 

 

Why does visualizing the filter tell you what the filter is looking for?

If you visualize the first convolutional layer of each neural network, you can see that the first layer looks for oriented edges.


Why does visualizing the filter tell you what the filter is looking for?

This intuition comes from ‘Template Matching’ and ‘Inner Product’.

Imagine you have some template vector, and then imagine you compute a scalar output by taking inner product between your template vector some arbitrary piece of data. Then, the input which maximizes that activation under a norm constraint on the input is exactly when those two vectors match up.

So, in that sense, whenever you are taking an inner products, the thing causes an inner product to excite maximally is a copy of the thing you are taking an inner product with. So, that’s why we can actually visualize these weights and why that shows us what this first layer is looking for.

Pytorch Tutorial : Making Simple Convolutional Network

Hi guys.  I am going to explain how to make simple convolutional network using Pytorch.

(Updating … )

# -*- coding: utf-8 -*-
"""
Created on Tue Nov 13 21:29:47 2018

@author: youngjoong
“””

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 5×5 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)

def forward(self, x):
# Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# If the size is a square you can only specify a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(-1, self.num_flat_features(x)) #(x.size()[0],-1) #(x.size())[0] is batch size, (x.size())[1] is feature size
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x

def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features

net = Net()
print(net)

net = Net()
print(net)

for name, param in net.named_parameters():
print(name)

params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1’s .weight

input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)

net.zero_grad()
out.backward(torch.randn(1,10))

Object Detection: R-CNN, Fast R-CNN, Faster R-CNN, Mask R-CNN, YOLO, and SSD

(Updating…)

Hi guys, today I am going to introduce some recent object detection techniques using CNN. This post is written based on CS231n of Stanford University.


1. What is Object Detection?

Object Detection is figuring out whether there exist objects (from some fixed set of categories we are interested in) in the input image, and localizing that objects.

The difference between object detection and classification+localization problem is

  • there might be varying number of outputs for every input image
  • you don’t know ahead of time how many objects you expect to find in each image

2. Evolution of Object Detection Techniques Using CNN

[R-CNN]

  1. Run some Region Proposal Network and get 2k Regions of Interest (ROI). This is not learned network though. Rather, it uses traditional computer vision techniques like Selective Search, which looks for blob regions.
  2. Warp ROIs to fixed size. This is because the rest part of R-CNN pipelines requires fixed size & square input.
  3. Run each ROIs through a convolutional neural network. Classify ROIs with SVMs. Predicts regression. What I mean by “Predicts regression” is that, do some correction (offset) to the bounding box proposed at the region proposal stage. Note that sometimes the final predicted bounding box will be outside the region of interest.

* There is also “background” class so that when there exists no object in the ROI, R-CNN predicts background to say that there was no object here.

 

[Fast R-CNN]

  1. Rather than processing each region of interest separately, instead we’re going to run the entire image through some convolutional layers all at once to give high resolution convolutional feature map corresponding to the entire image.
  2. We still use region proposals from some fixed thing like Selective Search,

 

 

Gradient, Gradient Ascent, Gradient Descent

오늘은 함수의 극대점, 극소점을 찾기 위해 사용되는 기법인 Gradient Ascent법, Gradient Descent법에 대해 설명하고자 한다.  ( 이 포스팅의 일부분은 다크프로그래머님의 Gradient Descent 탐색 방법 포스팅을 참고하였다.)


1.Gradient란?

1)정의: Gradient는 함수 f의 편미분으로 이루어진 벡터이다. (Gradient is a vector composed of partial derivatives of a function.)

gradient

예시)

gradient_ex

2)특징:

  • Gradient는 함수 f의 값이 가장 크게 변화하는 방향을 나타낸다. 또한 Gradient의 크기는 변화의 정도(기울기)를 나타낸다.
  • Gradient는 optimum에 도달했는지를 알려준다. (grad f = 0)

예시) 다음과 같은 함수 f(x,y)가 있다고 해보자.

ex2.png

(1,1)에서 f값이 최대로 변화하는 방향은 (2,2)이고 변화의 크기(기울기)는 ||(2.2)||=sqrt(8)이다.


2.Gradient Ascent 방법

비용함수의 값을 극대화시키는 파라미터 값을 아래와 같이 점진적으로 찾는 방법

ascent

(여기서 lambda_k는 알고리즘의 수렴속도를 조절하는 파라미터로, step size또는 learning rate이라고 부른다.)

아래의 함수 f를 예시로 들어 설명하겠다.

현재 보고있는 x의 값이 x_f라고 가정하자. 우리는 f를 극대화시키는 x_m을 찾는 것이 목표이므로  x_f에서 더 진전해야한다. Gradient Ascent 알고리즘을 사용해보자면, grad_f(x_k)은 양수이므로 (그림의 파란색 기울기를 보자. 기울기가 양수이다.) 이 알고리즘은 새로운 x의 값으로 x_k에서 더 앞으로 나아간 값을 잡는다. 이렇게 grad f값이 양수가 나오는 한 이 알고리즘은 x값을 점점 전진시켜 x_m에 도달하고자 한다.

 

이번에는 현재 보고있는 x의 값이 x_b라고 가정하자. 우리는 f를 극대화시키는 x_m을 찾는 것이 목표이므로  x_b에서 후진해야한다. Gradient Ascent 알고리즘을 사용해보자면, grad_f(x_k)은 음수이므로 (그림의 빨간색 기울기를 보자. 기울기가 음수이다.) 이 알고리즘은 새로운 x의 값으로 x_b의 뒤에 위치해있는 값을 잡는다. 이렇게 grad f값이 음수가 나오는 한 이 알고리즘은 x값을 점점 후진시켜 x_m에 도달하고자 한다.

gradient_ascent


3.Gradient Descent 방법

비용함수의 값을 극소화시키는 파라미터 값을 아래와 같이 점진적으로 찾는 방법

descent

마찬가지로, 아래의 함수 f를 예시로 들어 설명하겠다.

현재 보고있는 x의 값이 x_f라고 가정하자. 우리는 f를 극소화시키는 x_m을 찾는 것이 목표이므로  x_f에서 더 진전해야한다. Gradient Descent 알고리즘을 사용해보자면, grad_f(x_k)은 음수이므로 (그림의 파란색 기울기를 보자. 기울기가 음수이다.) 이 알고리즘은 새로운 x의 값으로 x_k에서 더 앞으로 나아간 값을 잡는다. 이렇게 grad f값이 음수가 나오는 한 이 알고리즘은 x값을 점점 전진시켜 x_m에 도달하고자 한다.

 

이번에는 현재 보고있는 x의 값이 x_b라고 가정하자. 우리는 f를 극소화시키는 x_m을 찾는 것이 목표이므로  x_b에서 후진해야한다. Gradient Descent 알고리즘을 사용해보자면, grad_f(x_k)은 양수이므로 (그림의 빨간색 기울기를 보자. 기울기가 음수이다.) 이 알고리즘은 새로운 x의 값으로 x_b의 뒤에 위치해있는 값을 잡는다. 이렇게 grad f값이 양수가 나오는 한 이 알고리즘은 x값을 점점 후진시켜 x_m에 도달하고자 한다.

descent_graph_modified.png


이상으로 Gradient와 Gradient Ascent, Gradient Descent에 대한 설명을 마친다.