티스토리 뷰


Caffe는 딥 뉴럴 네트워크를 트레이닝하여 모델을 만들고 해당 모델에 대해 테스트 및 검증을 할 수 있도록 잘 만들어진 딥러닝 프레임워크이다.

버클리 비전 & 러닝 센터(BVLC)에서 제작하여 배포하고 있다.

BVLC : http://caffe.berkeleyvision.org/


Caffe를 설치 및 테스트 해볼 요량으로 잠깐 건들였다가 꽤 많은 시간을 디버깅에 투자하게 되어, 설치하려는 다른 연구자와 미래의 나를 위해 포스팅을 남긴다.

본 포스팅은 Caffe 설치와 해당 예제(LeNet을 이용한 Mnist 이미지 데이터 학습)를 돌려보는 것까지에 대한 이슈를 해결한 것에 대한 문서다.


특별히 configuration이 필요없는 경우 설치는 아래의 링크를 따라하면 충분히 잘 설치될 수 있다.

Caffe Installation : http://caffe.berkeleyvision.org/installation.html



본 포스팅은 Mac OS X(10.11.5 버전이나, 다른 버전도 호환가능성 높음)이고, CPU만을 사용해서 Caffe를 돌려보고자 하는 경우에 도움이 될 것 같다.


CPU만을 사용하고, 실제로 CUDA로 GPU를 사용하지 않는 경우에도, CUDA를 꼭 함께 설치한다.

CUDA install - https://developer.nvidia.com/cuda-downloads


Git : https://github.com/BVLC/caffe/ 

GIt Repository 에서 caffe를 download 혹은 git clone을 통해 받아온다.


$>> git clone https://github.com/BVLC/caffe.git

(git이 없을 경우, $>> sudo apt-get install git)


$>> cd caffe 

$>> cp Makefile.config.example Makefile.config


Makefile.config.example 파일을 Makefile.config 이라는 이름으로 복사해서 현재 디렉터리에 놓는다.

Makefile.config 파일은 caffe 빌드 시 사용되는 configuration 파일이기 때문에 이 파일을 잘 수정해야 한다.


$>> vi Makefile.config


[Makefile.config]

# Refer to http://caffe.berkeleyvision.org/installation.html

# Contributions simplifying and improving our build system are welcome!


# cuDNN acceleration switch (uncomment to build with cuDNN).

# USE_CUDNN := 1


# CPU-only switch (uncomment to build without GPU support).

CPU_ONLY := 1


# uncomment to disable IO dependencies and corresponding data layers

# USE_OPENCV := 0

# USE_LEVELDB := 0

# USE_LMDB := 0


# uncomment to allow MDB_NOLOCK when reading LMDB files (only if necessary)

#       You should not set this flag if you will be reading LMDBs with any

#       possibility of simultaneous read and write

# ALLOW_LMDB_NOLOCK := 1


# Uncomment if you're using OpenCV 3

# OPENCV_VERSION := 3


# To customize your choice of compiler, uncomment and set the following.

# N.B. the default for Linux is g++ and the default for OSX is clang++

# CUSTOM_CXX := g++


# CUDA directory contains bin/ and lib/ directories that we need.

CUDA_DIR := /usr/local/cuda

# On Ubuntu 14.04, if cuda tools are installed via

# "sudo apt-get install nvidia-cuda-toolkit" then use this instead:

# CUDA_DIR := /usr


# CUDA architecture setting: going with all of them.

# For CUDA < 6.0, comment the *_50 lines for compatibility.

CUDA_ARCH := -gencode arch=compute_20,code=sm_20 \

                -gencode arch=compute_20,code=sm_21 \

                -gencode arch=compute_30,code=sm_30 \

                -gencode arch=compute_35,code=sm_35 \

                -gencode arch=compute_50,code=sm_50 \

                -gencode arch=compute_50,code=compute_50


# BLAS choice:

# atlas for ATLAS (default)

# mkl for MKL

# open for OpenBlas

BLAS := atlas

# Custom (MKL/ATLAS/OpenBLAS) include and lib directories.

# Leave commented to accept the defaults for your choice of BLAS

# (which should work)!

# BLAS_INCLUDE := /path/to/your/blas

# BLAS_LIB := /path/to/your/blas


# Homebrew puts openblas in a directory that is not on the standard search path

# BLAS_INCLUDE := $(shell brew --prefix openblas)/include

# BLAS_LIB := $(shell brew --prefix openblas)/lib


# This is required only if you will compile the matlab interface.

# MATLAB directory should contain the mex binary in /bin.

# MATLAB_DIR := /usr/local

# MATLAB_DIR := /Applications/MATLAB_R2012b.app


# NOTE: this is required only if you will compile the python interface.

# We need to be able to find Python.h and numpy/arrayobject.h.

PYTHON_INCLUDE := /usr/include/python2.7 \

                /usr/local/lib/python2.7/site-packages/numpy/core/include/

# Anaconda Python distribution is quite popular. Include path:

# Verify anaconda location, sometimes it's in root.

# ANACONDA_HOME := $(HOME)/anaconda

# PYTHON_INCLUDE := $(ANACONDA_HOME)/include \

                # $(ANACONDA_HOME)/include/python2.7 \

                # $(ANACONDA_HOME)/lib/python2.7/site-packages/numpy/core/include \


# Uncomment to use Python 3 (default is Python 2)

# PYTHON_LIBRARIES := boost_python3 python3.5m

# PYTHON_INCLUDE := /usr/include/python3.5m \

#                 /usr/lib/python3.5/dist-packages/numpy/core/include


# We need to be able to find libpythonX.X.so or .dylib.

PYTHON_LIB := /usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/

# PYTHON_LIB := $(ANACONDA_HOME)/lib


# Homebrew installs numpy in a non standard path (keg only)

# PYTHON_INCLUDE += $(dir $(shell python -c 'import numpy.core; print(numpy.core.__file__)'))/include

# PYTHON_LIB += $(shell brew --prefix numpy)/lib


# Uncomment to support layers written in Python (will link against Python libs)

# WITH_PYTHON_LAYER := 1


# Whatever else you find you need goes here.

INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include

LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib


# If Homebrew is installed at a non standard location (for example your home directory) and you use it for general dependencies

# INCLUDE_DIRS += $(shell brew --prefix)/include

# LIBRARY_DIRS += $(shell brew --prefix)/lib


# Uncomment to use `pkg-config` to specify OpenCV library paths.

# (Usually not necessary -- OpenCV libraries are normally installed in one of the above $LIBRARY_DIRS.)

# USE_PKG_CONFIG := 1


# N.B. both build and distribute dirs are cleared on `make clean`

BUILD_DIR := build

DISTRIBUTE_DIR := distribute


# Uncomment for debugging. Does not work on OSX due to https://github.com/BVLC/caffe/issues/171

# DEBUG := 1


# The ID of the GPU that 'make runtest' will use to run unit tests.

TEST_GPUID := 0


# enable pretty build (comment to see full commands)

Q ?= @ 


Makefile.config에서 #이 해제된 부분을 강조하여 표시하였다.


CPU_ONLY := 1 로 CPU만으로 Caffe를 돌린다!라고 명시한다.

PYTHON 경로 관련하여 버클리 문서에서 강력하게 추천하는 ANACONDA를 사용하는 것도 바람직하지만, 일단 기본적으로 2.7버전이 맥에 내장되어있기에 즉시 사용하였다. (ANACONDA 설치시, 내부 PYTHON 경로를 자동으로 바꿔줌, 물론 위 파일에서 ANACONDA를 사용하는 PYTHON 링크로 수정해주어야 함)

numpy의 경우 디폴트로 지정되어있는 경로와 맥 / 우분투 경로가 달랐기 때문에 실제 설치된 경로를 찾아서 바꿔주었다.

PYTHON_LIB은 본 문서에 적혀져있는대로 정확하게 2.7 버전의 라이브러리가 담긴 폴더를 타겟해주는 것이 좋다는 구글링 결과를 반영하였다.



$>> sudo make clean -j8

-j8은 make 를 빠르게 수행하기 위한 옵션이다. clean은 이전에 빌드한 적이 없다면 하지 않아도 상관없다.


$>> sudo make all -j8

$>> sudo make pycaffe -j8


$>> sudo make test -j8

$>> sudo make runtest -j8


$>> python -c 'import caffe' 

본 명령은 caffe를 python에서 사용하기 위해 import 하는 명령인데 이 명령이 에러없이 잘 처리되면 잘 빌딩되었다고 볼 수 있다.


만약, 경고창이 뜨고, segmentation error 11 또는 단순히 종료되는 경우, CUDA 인스톨과 Makefile.config 의 경로를 잘 확인해보아야 한다.

warning으로 import 하는데 font문제로 시간이 조금 걸린다는 메세지는 무시해도 실행에 지장이 없다. 해당 워닝도 해결할 수 있는 방법이 구글에 나와있다.


이 과정이 잘 끝나면, Mnist 데이터를 LeNet으로 훈련하는 과정을 한 번 돌려볼 수 있다.


Solving in Python with LeNet : http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/01-learning-lenet.ipynb

이 문서는 외부 공개용이지만, 이 문서 자체는 caffe의 examples 안에 01-learning-lenet.ipynb라는 이름으로 존재한다.


ipynb는 ipython notebook의 약자지만, 현재 ipython은 deprecated되었고, Jupyter를 설치해야 한다.

Jupyter Installation : http://jupyter.readthedocs.io/en/latest/install.html


$>> jupyter notebook

위 명령을 치면, 가용한 웹 브라우저가 켜지면서 해당 디렉터리의 상태를 보이고 해당 문서를 클릭해서 진행할 수 있다.

공식적으로 컴파일은 shift + enter 버튼으로 진행하면된다.

가장 위부터 천천히 진행하면되는데 한 가지 이슈가 있다.


CPU버전으로 사용해야하기 때문에, 



caffe.set_device(0) 은 0번째로 지정한 GPU를 사용하겠다는 부분이고, caffe.set_mode_gpu()는 gpu모드이기 때문에

위 두 줄의 코드 대신, caffe.set_mode.cpu() 를 사용한다.


본 ipython 코드 대신 실제 내부에서 돌릴 때에는 auto_solver가 아닌, solver를 사용하기 때문에,

caffe/examples/mnist/lenet_solver.prototxt 가장 하단에 있는 solver_mode를 CPU 로 놓고 트레이닝을 진행해야 한다.



댓글