* Theono installation

Windows 10에서 cuda 7.5와 theano 설치 (GPU 사용)

FEB 1, 2016

REF : HTTP://EJKLIKE.GITHUB.IO/2016/02/01/INSTALL-THEANO-IN-WINDOWS10-WITH-GPU.HTML

우분투에 Nvidia GPU 기반 theano 설치를 완료한 뒤, Windows 10에도 도전해보기로 했다. 설치는 https://vanishingcodes.wordpress.com/2015/10/25/installing-cuda-7-5-and-pycuda-on-windows-for-testing-theano-with-gpu/를 참고하여 진행하였다. 사소한 configuration을 제외하면 큰 문제는 없었다. 순서는 다음과 같다.

1. Visual Studio 2013 설치

  • cuda 7.5 toolkit은 아직 VS2015를 지원하지 않으므로 주의
  • 최소한의 설치옵션으로 진행해도 무방

2. Visual Studio 환경변수 설정

  • 환경변수 Path 변수에 아래 내용 추가
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\;C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE

3. Cuda 7.5 toolkit 설치

4. Anaconda 설치

  • python 2.7 기준으로 설치

5. Python dependency 설치

  • 명령 프롬프트에서 conda install mingw libpython 입력

6. Theano 설치

  • anaconda에 등록된 버전 설치: conda install theano
  • (옵션) 만약, 최신 버전을 설치하고자 한다면 theano 공식 github 참고하여 설치

7. Theano 환경설정파일 만들기

  • 아래 내용의 .theanorc.txt 파일을 $HOME 폴더에 만듦
  • 참고로, $Home 폴더는 설정을 건드리지 않았다면 C:\Users\로그인이름일 것임
[global] floatX = float32 device = gpu [nvcc] fastmath = True

원문에는 flagscompiler_bindir 경로를 설정하도록 되어있었지만, 이는 나에게 아래와 같은 오류를 주었다…

ValueError: Theano nvcc.flags support only parameter/value pairs without space b etween them. e.g.: ‘–machine 64’ is not supported, but ‘–machine=64’ is suppor ted. Please add the ‘=’ symbol. nvcc.flags value is ‘‘C:\Anaconda2\lib’’

https://www.kaggle.com/c/datasciencebowl/forums/t/12677/install-theano-on-windows-8-1-with-gpu-enabled-pycuda-installation-problems의 맨 마지막 코멘트를 참고하여 경로설정을 없앴더니 해결되었다(!)

8. Test: theano가 GPU를 사용하는지 확인

  • 아래의 코드를 실행시켜서 Used the gpu가 뜨면 성공!
from theano import function, config, shared, sandbox import theano.tensor as T 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([], T.exp(x)) print(f.maker.fgraph.toposort()) t0 = time.time() for i in xrange(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, T.Elemwise) for x in f.maker.fgraph.toposort()]):     print('Used the cpu') else:     print('Used the gpu')
결과가 아래와 같은 형태로 나오면 성공!!
Using gpu device 0: GeForce GT 630M (CNMeM is disabled) [GpuElemwise{exp,no_inplace}(<CudaNdarrayType(float32, vector)>), HostFromGpu(GpuElemwise{exp,no_inplace}.0)] Looping 1000 times took 1.42199993134 seconds Result is [ 1.23178029  1.61879349  1.52278066 ...,  2.20771813  2.29967761   1.62323296] Used the gpu

CUDA 설치 때문에 지속적으로 에러 뜨고 import theano가 오류나는 경우

설치해서 잘되었는지 테스트 하면서 import theano 했는데

CUDA is installed, but device gpu is not available (error: cuda unavailable) 이런 warning 뜨고

'crtdefs.h': No such file or directory 이런게 뜨고 오류 난다면, 아래 내용을 참고해서 수정해보자.

5. install pycuda 부분을 따라하고 4번의 [nvcc]의 flags 부분을 수정하니 해결되었다.

해결된 .theanorc 는 이렇게 작성 되었다.

[global]

device = gpu

floatX = float32

[nvcc]

flags=-LC:\Anaconda2\libs

cxxflags = -D_hypot=hypot

compiler_bindir=C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin

[gcc]

cxxflags = -D_hypot=hypot

CNMeM is disabled, CuDNN not available

실행을 시켜보니 제목과 같이 CNMeM도 없고 CuDNN도 안된다. 분명 CUDA가 잡히고 VS2013에서 테스할때는 잘되었는데 말이다.

Python에서 실행시키니 Using gpu device 0: GeForce GTX TITAN X 이런 문구가 나오며 설치는 되어있지만 위의 제목과 같이 CNMeM과 CuDNN은 사용을 못한다.

<cuDNN>

이럴경우, https://developer.nvidia.com/cudnn

여기에서 cuDNN을 다운 받는다.(회원가입 필요, 무료임)

받아서 설치하면 폴더안에 bin, include, lib 의 3가지 폴더가 있고 각 폴더 안에 1개씩 파일들이 존재한다.

이 파일들을 복사해서 NVIDIA GPU ComputingToolkit에 복사하면 된다.

bin 파일 -> C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\bin

include 파일 -> C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\include

lib 파일 -> C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64

난 64비트 이므로 x64로 넣는다.

다 넣어 준 후 관련된 3가지 경로들(C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\bin) 모두 시스템 환경변수 path에 넣어준다.

마지막으로 홈(C:\User\Hyunguk)으로 가서 .theanorc.txt 파일을 연 뒤

[lib]

cudnn=1.0

을 넣어주고 저장하면 끝.

<CNMeM>

이거의 경우에는 과정들을 다 끝낸뒤,

.theanorc.txt에

[lib]

cnmem=.81

이 부분만 추가하면 된다. 뒤에 .81은 초기 메모리 사이즈를 81% 잡겠다는 의미

(참고 링크) http://stackoverflow.com/questions/36248056/how-to-setup-cudnn-with-theano-on-windows-7-64-bit

PyCUDA 테스트

Here is a quick test snippet from the PyCUDA web page here

import pycuda.autoinit import pycuda.driver as drv import numpy  from pycuda.compiler import SourceModule mod = SourceModule(""" __global__ void multiply_them(float *dest, float *a, float *b) {   const int i = threadIdx.x;   dest[i] = a[i] * b[i]; } """)  multiply_them = mod.get_function("multiply_them")  a = numpy.random.randn(400).astype(numpy.float32) b = numpy.random.randn(400).astype(numpy.float32)  dest = numpy.zeros_like(a) multiply_them(         drv.Out(dest), drv.In(a), drv.In(b),         block=(400,1,1), grid=(1,1))  print dest-a*b 

Seeing an array of zeros ? Its working fine then.

Hopefully, this should give you a working pythonish CUDA setup using the latest versions of VS, Windows, Python etc.

설치 완료 후 Pycharm과 Anaconda3 evn 셋팅

설치가 완료 되도 import에서 불러오지 못하는 것을 볼 수 있다. 그냥 사용해도 되지만 페키지와 버전 간 충돌을 막기위해서 envs 셋팅이 필요하다.

쉽게 말해서 버전 python 2x를 위해서 설치한 패키지 들이 있고 python 3x를 위한 패키지 들이 있는데, 어떤 부분은 연구용, 어떤 부분은 프로젝트용으로 하다보면 꼬이는 경우가 발생하므로

envs 폴더에 새로운 폴더를 만들어서 각 해당 부분별로 만들어 준다.(vmware에서 여러개 os를 만들어서 필요한 것을 그때 동작 시키는 것과 비슷한 원리.)

우선 cmd를 열어서 다음을 입력한다.

conda create -n 이름 biopython

이미 생성된 env를 부를때는 call activate 이름

현재 env로 activate가 되있나 확인 할때는 conda env list 를 입력해서 별표(*) 가 있으면 해당 부분이 activate임

위 예시에서는 이름을 V1 으로 해서 만들었고 설치된 패키지가 보인다. 그 후 아래와 같이 activate 상태를 할것인지 물어보게 된다.

activate 이름

을 입력하게 되면 아래와 같이 (이름) 경로 > 상태가 된다. 이 상태에서 설이하고자 하는 패키지를 envs에서 만든 폴더(여기서 V1)에 설치해 준다.

설치는 현재 상태의 cmd에서 conda install scipy

라고 입력하면 scipy가 설치되며, 이미 설치한 경우 아래와 같이 이미 설치 됬다고 뜬다.

설치가 끝난 후 어떤 페키지가 설치되었는지 확인하려면

conda list 를 입력하면 된다.

설치가 끝났으면 이제 pycharm으로 들어가서 메뉴에서 File - settings - Project: 이름.py 로 들어간 후

위쪽에 있는 project interpreter를 눌러서 새로운 경로를 넣어준다.

show all에서 새로운 경로를 찾아서넣어준는데 위에서 우리가 만든 envs 내에 있는 폴더 안에 python.exe를 넣어준다.

이제 from import에서 불러서 사용이 가능!!

만약 env에 지정한 환경 변수 폴더에 파일들이 잘 안깔려있을 수도 있다.

그럴땐 그냥 바로바로 설치했던 anaconda3\python.exe를 경로로 주자.