Keras 를 사용하게 되면 Tensorflow 혹은 Theano를 Backend로 활용하는 경우가 있다.

이번에는 Ubuntu 16.04에 Theano를 설치하는 과정을 정리해 보았다.


설치 과정은 http://deeplearning.net/software/theano/install_ubuntu.html 에 자세히 설명되어 있으나

GPU를 활용하기 위해서는 약간의 삽질이 동반될 수 있으므로 따로 정리하였다.


Conda로 설치하는 것을 권장하고 있는데 conda 설정의 복잡함과 개인 pc 에서 궂이 라는 생각으로 그냥 설치하기로 진행한다.


1. PIP 를 통해 Theano 설치


간단히 pip 명령어를 사용하여 Theano를 설치한다.

$ sudo pip install Theano


2. libgpuarray 설치


GPU를 지원하기 위해서는 libgpuarray 라는 패키지가 필요하다.

git 명령어로 해당 패키지를 홈 디렉토리에 다운로드한다.

git clone https://github.com/Theano/libgpuarray.git cd libgpuarray

2.1 libgpuarray 설치는 다음과 같이 빌드 후 설치를 진행하면 된다.

cd <dir> mkdir Build cd Build # you can pass -DCMAKE_INSTALL_PREFIX=/path/to/somewhere to install to an alternate location cmake .. -DCMAKE_BUILD_TYPE=Release # or Debug if you are investigating a crash make sudo make install cd ..

2.2 pygpu 설치

# 이 작업은 반드시 위 방법대로 libgpuarray 가 설치된 후에 진행해야 한다. python setup.py build python setup.py install

2.3 Cython 최신버전 설치하기 (pygpu설치 실패하는 경우)

경우에 따라 아래와 같이 Cython 버전이 낮거나 설치되지 않아서 에러가 발생하는 경우가 있다.

python setup.py Traceback (most recent call last): File "setup.py", line 12, in <module> raise Exception('cython is too old or not installed ' Exception: cython is too old or not installed (at least 0.25 required)

sudo apt-get install 명령으로 cython을 설치해 보아도 아직 업데이트가 안된건지 0.23 이상으로 업그레이드가 되지 않으므로 
홈페이지에서 소스에서 빌드하여 설치하도록 한다. 2018년 4월 11일 현재 최신 버전은 0.28.1 이다.
먼저 기존에 설치된 cython을 삭제하기 위해 다음을 수행한다.

$ sudo apt-get remove cython

https://pypi.python.org/pypi/Cython/ 페이지에서 Cython-0.28.1.tar.gz 파일을 다운로드 한다. 

압축 해재 후 폴더로 이동하여 다음을 수행한다.

cd ~/Downloads/Cython-0.28.1/ sudo python setup.py install

이제 다시 2.2 로 돌아가서 pygpu를 설치해본다.


3. Theano 실행 테스트 (GPU)


이제 Theano가 GPU를 잘 활용하는지 확인해보기 위해 간단한 파이썬 스크립트를 실행해보자.

메모장을 열고 아래 코드를 붙여넣기 한 다음 test.py로 저장한다.

 from theano import function, config, shared, tensor

import numpy
import time

vlen = 10 * 30 * 768  # 10 x #cores x # threads per core
iters = 1000

rng = numpy.random.RandomState(22)
x = shared(numpy.asarray(rng.rand(vlen), config.floatX))
f = function([], tensor.exp(x))
print(f.maker.fgraph.toposort())
t0 = time.time()
for i in range(iters):
    r = f()
t1 = time.time()
print("Looping %d times took %f seconds" % (iters, t1 - t0))
print("Result is %s" % (r,))
if numpy.any([isinstance(x.op, tensor.Elemwise) and
              ('Gpu' not in type(x.op).__name__)
              for x in f.maker.fgraph.toposort()]):
    print('Used the cpu')
else:
    print('Used the gpu')

그냥 이 프로그램을 실행하면 cpu 기반으로 동작하고 다음과 같은 결과가 나온다. 대략 29초가 걸리는 작업이다.

$ python testgpu.py [Elemwise{exp,no_inplace}(<TensorType(float64, vector)>)] Looping 1000 times took 29.441501 seconds Result is [ 1.23178032 1.61879341 1.52278065 ..., 2.20771815 2.29967753 1.62323285] Used the cpu

이제 Theano가 gpu를 사용하도록 하기 위해 아래와 같이 환경변수를 등록한다.

$ export THEANO_FLAGS='device=cuda, floatX=float32'

동일한 프로그램을 다시 실행해보면 아래와 같은 결과가 나온다.

$ python testgpu.py Using cuDNN version 7005 on context None Mapped name None to device cuda: GeForce GTX 980M (0000:01:00.0) [GpuElemwise{exp,no_inplace}(<GpuArrayType<None>(float32, vector)>), HostFromGpu(gpuarray)(GpuElemwise{exp,no_inplace}.0)] Looping 1000 times took 0.219304 seconds Result is [ 1.23178029 1.61879349 1.52278066 ..., 2.20771813 2.29967761 1.62323296] Used the gpu

현재 컴퓨터에는 GTX 980M 이 탑재되어 있고 결과는 0.2초 무려 1/100 넘게 단축되었다.



2018/4/11 최초문서 발행

+ Recent posts