레이블이 dmdl인 게시물을 표시합니다. 모든 게시물 표시
레이블이 dmdl인 게시물을 표시합니다. 모든 게시물 표시

2017년 6월 7일 수요일

[DM/DL] 텐서플로우의 인셉션으로 사진 구분하는 예제 (5)

- 2 개의 댓글
기존에 인셉션v3 실습은 과연 무엇을 하고 있는지 정확히 알수 없는 결과였다. 
엔지니어라고 해도 프로그래밍을 하는 알고리즘 자체는 다 알순 없어도 결과는 알아보게 나오면 좋을텐데요. 

그래서 다른 예제를 찾았습니다. 
텐서플로우 설명서라는 깃허브로 다양한 코드들이 어느정도의 설명과 함께 작성되어 있습니다. 
만약 텐서플로우의 모델에 대한 학습이 필요하다면, 아래의 2사이트가 초-중급의 학습으로는 큰 도움이 될 것 같다.
1) https://github.com/golbin/TensorFlow-Tutorials
2) https://tensorflowkorea.gitbooks.io/tensorflow-kr/content/g3doc/tutorials/


하지만, 시스템/네트워크 엔지니어가 막상 이걸 딱 본다고 해서 어떻게 쓰는지 알기도 어려울 수 있으니, 실행하는 것에 대해서 따라하기 수준으로 진행하겠습니다.


1. git clone하기 

작성해 놓은 파일들을 그대로 모두 다운로드 합니다.

root@hoonjo-VirtualBox:~# git clone https://github.com/golbin/TensorFlow-Tutorials.git
Cloning into 'TensorFlow-Tutorials'...
remote: Counting objects: 367, done.
remote: Compressing objects: 100% (10/10), done.
remote: Total 367 (delta 1), reused 9 (delta 1), pack-reused 356
Receiving objects: 100% (367/367), 14.06 MiB | 4.04 MiB/s, done.
Resolving deltas: 100% (148/148), done.

Checking connectivity... done.


2. inception 디렉터리로 이동하기 

너무 쉬운건데 제가 설명하고 있지 않나 그런 생각이 드네요.

root@hoonjo-VirtualBox:~# cd TensorFlow-Tutorials/
root@hoonjo-VirtualBox:~/TensorFlow-Tutorials# ls
01 - TensorFlow Basic      04 - MNIST        07 - GAN        10 - DQN
02 - Neural Network Basic  05 - CNN          08 - RNN        README.md
03 - TensorBoard, Saver    06 - Autoencoder  09 - Inception
root@hoonjo-VirtualBox:~/TensorFlow-Tutorials# cd 09\ -\ Inception/
root@hoonjo-VirtualBox:~/TensorFlow-Tutorials/09 - Inception# ls

predict.py  README.md  retrain.py

3. retrain.py 실행하기 

사용법과 실행하기 그리고 옵션이 모두 위의 깃허브 페이지가 자세히 나와 있습니다.
다만 실행 결과가 없을 뿐이죠.

#1번의 링크에 인셉션 항목을 보면 사용에 대해서 상세하게 설명이 되어 있다.
https://github.com/golbin/TensorFlow-Tutorials/tree/master/09%20-%20Inception

학습시켜 볼 샘플 자료 다운로드

curl http://download.tensorflow.org/example_images/flower_photos.tgz | tar xz -C ./workspace
자신이 가진 다른 이미지를 학습시켜보고 싶다면, 학습시킬 사진을 각각의 레이블 이름으로 폴더를 생성하고, 그 안에 폴더 이름에 맞는 사진을 넣어두면 됩니다.

학습 실행

# python retrain.py \
    --bottleneck_dir=./workspace/bottlenecks \
    --model_dir=./workspace/inception \
    --output_graph=./workspace/flowers_graph.pb \
    --output_labels=./workspace/flowers_labels.txt \
    --image_dir ./workspace/flower_photos \
    --how_many_training_steps 1000

retrain.py 주요 옵션

  • --bottleneck_dir : 학습할 사진을 인셉션 용으로 변환해서 저장할 폴더
  • --model_dir : inception 모델을 다운로드 할 경로
  • --image_dir : 원본 이미지 경로
  • --output_graph : 추론에 사용할 학습된 파일(.pb) 경로
  • --output_labels : 추론에 사용할 레이블 파일 경로
  • --how_many_training_steps : 얼만큼 반복 학습시킬 것인지

4. 실행 결과 

저는 실행을 /workspace를 만들고 거기서 실행을 했습니다.
경로를 다른 절대 경로로 바꾸면 predict가 동작을 하지 않네요. 아마도 코드에 입력해 둔거 같습니다...그래서 시키는대로 ./workspace에 다시 만들었습니다.

대략...엔지니어가 봤을때는 ./workspace/bottlenecks이라는 곳은 학습을 목적으로 하는 데이터들이 저장되고, 반복적으로 특정 이미지의 특정 정보를 가지고 추론했을때 그게 맞다면 좀더 가중치를 주고...하는 방법이 아닐까? .....이건 프로그래밍보다 수학인것처럼 느껴지는..

정확하게 자세한 내용은 아래의 링크를 참고하야 할듯 하다.
https://norman3.github.io/papers/docs/google_inception.html

일단 결과는 다음과 같다.
중요한 것은 학습이 진행되는 동안 1에서 1000까지 정확도가 점점 상승하는 것이 눈에 보인다는 것이다.

일단의 위의 실행보다는 이 실행에 time을 넣어서 PoC하거나 고객 데모용으로 쓰는게 더 보기 좋을 것 같다. 어쨌든 무언가 일하는 것 같은 느낌이라?

사진도 고객쪽에서 받아서 직접 넣고 돌린다면 더 좋아할지도...

root@hoonjo-VirtualBox:~# python retrain.py \
>     --bottleneck_dir=./workspace/bottlenecks \
>     --model_dir=./workspace/inception \
>     --output_graph=./workspace/flowers_graph.pb \
>     --output_labels=./workspace/flowers_labels.txt \
>     --image_dir ./workspace/flower_photos \
>     --how_many_training_steps 1000
>> Downloading inception-2015-12-05.tgz 100.0%
<중략>
Looking for images in 'daisy'
Looking for images in 'dandelion'
Looking for images in 'tulips'
Looking for images in 'roses'
Looking for images in 'sunflowers'
Creating bottleneck at /workspace/bottlenecks/daisy/5602738326_97121e007d_n.jpg.txt
<중략>
2017-06-07 19:12:57.690368: Step 0: Train accuracy = 44.0%
2017-06-07 19:12:57.690465: Step 0: Cross entropy = 1.504567
2017-06-07 19:12:57.798181: Step 0: Validation accuracy = 30.0% (N=100)
2017-06-07 19:12:58.809131: Step 10: Train accuracy = 75.0%
2017-06-07 19:12:58.809331: Step 10: Cross entropy = 1.087505
2017-06-07 19:12:58.904638: Step 10: Validation accuracy = 65.0% (N=100)
2017-06-07 19:12:59.884631: Step 20: Train accuracy = 84.0%
2017-06-07 19:12:59.884729: Step 20: Cross entropy = 0.930921
2017-06-07 19:12:59.998434: Step 20: Validation accuracy = 73.0% (N=100)

2017-06-07 19:13:01.013036: Step 30: Train accuracy = 80.0%
<중략>
2017-06-07 19:14:49.076590: Step 999: Train accuracy = 93.0%
2017-06-07 19:14:49.076712: Step 999: Cross entropy = 0.241719
2017-06-07 19:14:49.175123: Step 999: Validation accuracy = 94.0% (N=100)
Final test accuracy = 90.2% (N=346)
Converted 2 variables to const ops.



원본 출력 결과물은 다음 링크에서 다운 받을수 있습니다. 
Link#
Link#2

5. 사진 예측 

그러면 사진을 어떤식으로 예측하는지 그 과정을 눈으로 한번 보자.
물론 내부 코드 설명을 하자는게 아니라..돌아가는걸 그냥 보자는 뜻이다..;;

추론 테스트

# python predict.py ./workspace/flower_photos/roses/20409866779_ac473f55e0_m.jpg
예제에 나와 있는 내용을 일단 그냥 입력해 본다.
아래에 보이는 것처럼 normalization을 해서 가장 높은 가능성을 가지고 있는 장미에 투표한다.


예제만 보면 이건 PoC라고 할수 없으니까...다른 것을 한번 해보겠다.
Daisy? 이게 이름이 가장 짧아서 좋은거 같다.

python predict.py ./workspace/flower_photos/daisy/3900172983_9312fdf39c_n.jpg

실행 결과는 다음과 같다. 데이지라고 적었지만 이게 무언가 싶어서 찾아봤더니..국화 종류중에 하나라고 한다..이게 데이지인가..? 싶긴 한데...어제 친구랑 한 대화가 생각난다.
표본이 중요하다고...그건 아직 사람 손이 많이 간다고..그 얘기를 무슨 소리인지 이제 더 확실하게 알겠다;;


일단은 고객 BMT나 세션을 할때는 이 예제가 고객/파트너가 보기에는 더 무슨 뜻인지 쉽게 알수 있을꺼 같다. 재미있는 예제인거 같다~!

끝!

[Continue reading...]

[DM/DL] 텐서플로우의 인셉션v3 실행하기 (4)

- 0 개의 댓글
우선 실행하게 되면 CPU가 하늘 높은 줄 모르고 열심히 일하는 것을 볼수 있을 것이다.
우잉잉..소리도 나고...예전에 CPU 성능이 부족할때 기분을 한껏 느낄수 있다. 


실행시에 성능에 따라 learning_rate와 batch_size를 조절할수 있고 max_steps을 조정하여 전체 시간을 줄일수 있다. gpu는...일반 환경이니 굳이 늘릴 필요가 없을 것으로 보여지고...

root@hoonjo-VirtualBox:~/inception/models/inception# time bazel-bin/inception/flowers_train --train_dir=$FLOWERS_DIR/train --data_dir=$FLOWERS_DIR/data --pretrained_model_checkpoi 
nt_path=$INCEPTION_DIR/inception-v3/model.ckpt-157585 --fine_tune=True --initial_learning_rate=0.001 -input_queue_memory_factor=1 --max_steps=50 --num_gpus 1 --batch_size=32
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-06-02 08:56:53.061730: Pre-trained model restored from /root/inception/inception-v3/model.ckpt-157585
2017-06-02 08:59:30.940674: step 0, loss = 2.78 (0.4 examples/sec; 74.705 sec/batch)
2017-06-02 09:07:18.404594: step 10, loss = 2.60 (0.9 examples/sec; 35.722 sec/batch)
2017-06-02 09:13:06.446650: step 20, loss = 2.41 (0.9 examples/sec; 34.499 sec/batch)
2017-06-02 09:18:51.787365: step 30, loss = 2.17 (0.9 examples/sec; 34.545 sec/batch)
2017-06-02 09:24:44.551172: step 40, loss = 2.07 (0.9 examples/sec; 34.955 sec/batch)

real 35m29.532s
user 213m28.596s
sys 19m26.928s

한개만 하면 재미가 없으니 다른 것을 실습해 보도록 하자. 
위에 것이 끝나기를 30분이 넘게 기다리고 있다....그래야 다음 것을 할 것이니까..

이 내용만 봐서는 CPU는 많이 쓰는건 알겠는데 뭐하는지 알기가 어렵다..
따라서, 좀더 쓸만한 예제가 필요하다..!!!

To be continue....



[Continue reading...]

[DM/DL] x86+우분투 리눅스 환경에서 인셉션v3 빌드하기 (3)

- 0 개의 댓글

1_9. inception v3 model을 실습(이긴 한데..문제가 있다..)

이제 실습만 하면 되고 이거면 원래 쉽게 끝나야하는데..문제가 있다.
결과부터 얘기하면 텐서플로우 1.1.0이 오류 bazel의 버전과의 문제로 오류가 나는 경우가 있다. 그래서 때로는 텐서플로우 1.0.0으로 다운그레이드를 하고 실습했다.
(pip install tensorflow==1.0.0) 그리고 재미있는 게 conda와 pip버전 모두 tensorflow를 설치되어서 혼동을 준다...하나만 쓰자 ;;

즉 이런 꼴이 날수도 있다는 뜻이다..(이상한 것이 보이지 않는가?)
root@hoonjo-VirtualBox:~/inception/models/inception# conda list | grep tensor
tensorflow                1.1.0               np112py36_0  
tensorflow-gpu            1.0.0                     <pip>

그리고 만날수 있는 대표적인 오류들은 다음과 같다.
이 오류들은 경우의 수가 다양해서 모두 알순 없지만 bazel 그리고 tensorflow의 버전 별의 차이가 유력하다.
1) AttributeError: module 'tensorflow' has no attribute 'app'
2) ImportError: libcuda.so.1: cannot open shared object file: No such file or directory
Failed to load the native TensorFlow runtime.

inception 디렉터리를 만들고 환경 설정을 해준다.
root@hoonjo-VirtualBox:~# mkdir ~/inception
root@hoonjo-VirtualBox:~# cd ~/inception/
root@hoonjo-VirtualBox:~/inception# export INCEPTION_DIR=/root/inception

해당 디렉터리에 inception 모델 파일을 다운로드 하고 압축해제도 해준다.
root@hoonjo-VirtualBox:~/inception# curl -O http://download.tensorflow.org/model 
s/image/imagenet/inception-v3-2016-03-01.tar.gz
<중략>
root@hoonjo-VirtualBox:~/inception# tar -xvf inception-v3-2016-03-01.tar.gz
inception-v3/
inception-v3/checkpoint
inception-v3/README.txt
inception-v3/model.ckpt-157585
root@hoonjo-VirtualBox:~/inception# 
root@hoonjo-VirtualBox:~/inception# git clone https://github.com/tensorflow/mode 
ls.git
The program 'git' is currently not installed. You can install it by typing:
apt install git

우분투 기본 패키지에는 'git'이 없나 보다 'apt'으로 설치한다.
root@hoonjo-VirtualBox:~/inception# apt install git

다시 시작한다.
root@hoonjo-VirtualBox:~/inception# git clone https://github.com/tensorflow/mode 
ls.git
Cloning into 'models'...
remote: Counting objects: 4845, done.
remote: Compressing objects:   9% (1/11) 
<중략>

root@hoonjo-VirtualBox:~/inception# export FLOWERS_DIR=/root/inception/models/inception

root@hoonjo-VirtualBox:~/inception# which bazel
/root/anaconda3/bin/bazel
root@hoonjo-VirtualBox:~/inception# pwd
/root/inception
root@hoonjo-VirtualBox:~/inception# cd models/
root@hoonjo-VirtualBox:~/inception/models# cd inception/



캐시를 설정하고 안 하고에 따라 성능차이가 발생한다.
root@hoonjo-VirtualBox:~/inception/models/inception# bazel build
Extracting Bazel installation...
................
INFO: Found 0 targets...
INFO: Elapsed time: 18.818s, Critical Path: 0.01s

root@hoonjo-VirtualBox:~/inception/models/inception# export TEST_TMPDIR=/root/.cache 

root@hoonjo-VirtualBox:~/inception/models/inception# bazel build
INFO: $TEST_TMPDIR defined: output root default is '/root/.cache'.
...................
INFO: Found 0 targets...
INFO: Elapsed time: 9.395s, Critical Path: 0.02s
root@hoonjo-VirtualBox:~/inception/models/inception# 


여러번 다운로드 했더니 다운로드 하는건 skip해 버린다..;;
root@hoonjo-VirtualBox:~/inception/models/inception#bazel-bin/inception/download_and_preprocess_flowers $FLOWERS_DIR/data
Skipping download of flower data.
Saving results to /root/inception/models/inception/data
Determining list of input files and labels from /root/inception/models/inception/data/raw-data/validation.
Found 500 JPEG files across 5 labels inside /root/inception/models/inception/data/raw-data/validation.
Launching 2 threads for spacings: [[0, 250], [250, 500]]
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-06-02 08:53:31.392194 [thread 1]: Wrote 250 images to /root/inception/models/inception/data/validation-00001-of-00002
2017-06-02 08:53:31.392236 [thread 1]: Wrote 250 images to 250 shards.
2017-06-02 08:53:31.422970 [thread 0]: Wrote 250 images to /root/inception/models/inception/data/validation-00000-of-00002
2017-06-02 08:53:31.423456 [thread 0]: Wrote 250 images to 250 shards.
2017-06-02 08:53:31.602173: Finished writing all 500 images in data set.
Determining list of input files and labels from /root/inception/models/inception/data/raw-data/train.
Found 3170 JPEG files across 5 labels inside /root/inception/models/inception/data/raw-data/train.
Launching 2 threads for spacings: [[0, 1585], [1585, 3170]]
2017-06-02 08:53:38.656836 [thread 0]: Processed 1000 of 1585 images in thread batch.
2017-06-02 08:53:38.734467 [thread 1]: Processed 1000 of 1585 images in thread batch.
2017-06-02 08:53:42.872016 [thread 1]: Wrote 1585 images to /root/inception/models/inception/data/train-00001-of-00002
2017-06-02 08:53:42.872147 [thread 1]: Wrote 1585 images to 1585 shards.
2017-06-02 08:53:42.914258 [thread 0]: Wrote 1585 images to /root/inception/models/inception/data/train-00000-of-00002
2017-06-02 08:53:42.914331 [thread 0]: Wrote 1585 images to 1585 shards.
2017-06-02 08:53:43.752331: Finished writing all 3170 images in data set.

꽃 사진을 분류하는 샘플이라고 한다. 테스트를 위해서 빌드한다.
root@hoonjo-VirtualBox:~/inception/models/inception# du -sm data/raw-data/train/*
29 data/raw-data/train/daisy
43 data/raw-data/train/dandelion
1 data/raw-data/train/LICENSE.txt
33 data/raw-data/train/roses
47 data/raw-data/train/sunflowers
48 data/raw-data/train/tulips

root@hoonjo-VirtualBox:~/inception/models/inception# bazel build inception/flowers_train
INFO: $TEST_TMPDIR defined: output root default is '/root/.cache'.
...........
INFO: Found 1 target...
Target //inception:flowers_train up-to-date:
  bazel-bin/inception/flowers_train
INFO: Elapsed time: 9.900s, Critical Path: 0.04s

준비 끝!!! 그렇다..여기까지가 준비다..

참고자료 : ppc64le에서 테스트한 결과
 - http://hwengineer.blogspot.kr/2017/05/minsky-continuum-anaconda.html

[Continue reading...]

[DM/DL] x86+우분투 리눅스 환경에서 텐서플로우(Tensorflow) 설치하기 (2)

- 0 개의 댓글
1_6. 추가 패키지를 pip를 통해서 설치
여기서 재미있는 사실은 (..재미가 없을 수도..) conda를 통해서도 텐서플로우가 설치가 가능하지만, 텐서플로우에서는 pip를 공식적으로 가이드 한다는 점입니다. conda에서도 아래의 패키지들이 검색이 되고 설치가 되지만, 조금 더 많은 패키지들을 설치하기 때문에 우선 pip로 설치합니다. (conda로 설치해도 됩니다.)

개인적으로는 여기서부터는 pip로 설치하는 것이 더...텐서플로우 실습에 맞지 않을까? 생각이 듭니다. 따라서 추후에 다시 수정될 수 있습니다.

root@hoonjo-VirtualBox:~# pip install keras
Collecting keras==2.0.4
  Downloading Keras-2.0.4.tar.gz (199kB)

root@hoonjo-VirtualBox:~# pip install gensim
Collecting gensim==2.1.0
  Downloading gensim-2.1.0.tar.gz (15.1MB)

root@hoonjo-VirtualBox:~# pip install konlpy
Collecting konlpy
  Downloading konlpy-0.4.4-py2.py3-none-any.whl (22.5MB)

1_7. 설치된 패키지 실행 경로 작성 
실행을 하려면 JAVA 환경 설정 마냥 경로 설정이 필요합니다.
우분투 64비트 라면 그냥 붙이시면 됩니다.
(물론 몇개월이 지나면 파이썬 버전이...3.7이 될수도 있으니...그건 고려하셔야 할 듯 하네요)

root@hoonjo-VirtualBox:~# export PYTHONPATH=/root/anaconda3/lib/python3.6/site-p 
ackages:$PYTHONPATH

1_8. bazel, tensorflow 그리고 tensorflow-gpu 설치 
여기서 pip를 못 쓰는 패키지가 있습니다. bazel이라는 놈인데...얘는 좀 설치가 의외로 까다롭습니다. 파워CPU는 쉽게 되는 것처럼 나와 있는데....1.0이 넘지 못해서 그런가...위치를 지정해 줘야 합니다. 얘가 기분이 나쁜가 여러번 해 봤는데도 같은 결과가 나왔다.

root@hoonjo-VirtualBox:~# conda install bazel
Fetching package metadata .........

PackageNotFoundError: Package missing in current linux-64 channels: 
  - bazel

Close matches found; did you mean one of these?

    bazel: blaze, babel

그래서 아직 등록되지 않은 bazel 패키지를 검색해 그 중에서 왠지 이름이 끌리는 ...Google? 로 진행했다.


root@hoonjo-VirtualBox:~# conda install -c jjh_cio_testing bazel
Fetching package metadata ...........
Solving package specifications: .

Package plan for installation in environment /root/anaconda3:

The following NEW packages will be INSTALLED:

    bazel: 0.4.5-0 jjh_cio_testing


root@hoonjo-VirtualBox:~# conda install tensorflow
Fetching package metadata .........
Solving package specifications: .

Package plan for installation in environment /root/anaconda3:

The following NEW packages will be INSTALLED:

    libprotobuf: 3.2.0-0          
    protobuf:    3.2.0-py36_0     
    tensorflow:  1.1.0-np112py36_0

root@hoonjo-VirtualBox:~# conda install tensorflow-gpu
Fetching package metadata .........
Solving package specifications: .

Package plan for installation in environment /root/anaconda3:

The following NEW packages will be INSTALLED:

    cudatoolkit:    7.5-0            
    cudnn:          5.1-0            
    tensorflow-gpu: 1.1.0-np112py36_0


시대가 어느때인데, cudatoolkit이 7.5이다..8.0이 나온지 좀 되지 않았나 -_-?
여튼..패키지하는 분들도 바쁘니....

참고로 이 쌩뚱맞은 인스톨 옵션은 다음과 같다. 아직 conda 정식에 등록되지 못한 비운의...패키지들을 인스톨 하고자 할때 쓰는 명령어로 보면 될 것 같다.

-c CHANNEL, --channel CHANNEL
Additional channel to search for packages. These are URLs
searched in the order they are given (including file:// for
local directories). Then, the defaults or channels from .condarc
are searched (unless --override-channels is given). You can use
'defaults' to get the default packages for conda, and 'system'
to get the system packages, which also takes .condarc into
account. You can also use any name and the .condarc chan‐
nel_alias value will be prepended. The default channel_alias is
http://conda.anaconda.org/.


설치된 것들을 확인해 보니 잘 되었다.

root@hoonjo-VirtualBox:~# conda list | grep tensor
tensorflow                1.1.0               np112py36_0  
tensorflow-gpu            1.1.0               np112py36_0  

다음에 계속......

참고자료 : ppc64le에서 테스트한 결과
[Continue reading...]

[DM/DL] x86+우분투 리눅스 환경에서 아나콘다(Anaconda) 설치 하기 (1)

- 0 개의 댓글
텐서플로우 테스트를 위해서 x86에 아나콘다 패키지와 텐서플로우 패키지를 설치해 보려고 한다. 일단 기본 OS는 Windows10/64비트인데, 잠깐 테스트만 해 볼꺼라..가상화 환경에서 해보려고 한다.

따라서 다음과 같은 설정으로 진행했다.
Virtualbox : https://www.virtualbox.org/
우분투 16.04.2 LTS : https://www.ubuntu.com/download/desktop

이때 가상화 환경에서 GPU를 사용하고 싶어서...여러가지 방법으로 알아보았으나...
최종적으로는 VT-D가 보드에서 지원하지 않아서, 진행이 어려웠다.

근본적으로 IOMMU(Input/Output Memory Management Unit, 입출력 메모리 관리 장치)가 지원이 되어야 가상화 환경에서 직접적인 GPU하드웨어까지 접근이 가능하다. 쉽게 말해서 가상화 장치에서 GPU장비를 직접 다룰수 있어야 한다는 것이다.

아마..하나도 안 쉽다고 할 것이 눈에 보인다..

이런 때는 그림이 최고다.

https://software.intel.com/en-us/articles/intel-virtualization-technology-for-directed-io-vt-d-enhancing-intel-platforms-for-efficient-virtualization-of-io-devices


위의 그림을 보면 가상머신(Virtual Machine)이 VMM 또는 호스팅 OS를 거쳐서 디바이스들과 통신을 하는 것을 볼수 있다. 하지만 여러가지의 이름을 가지는 IOMMU(인텔은 VT-D)를 지원하게 되면 직접 가상머신에서 디바이스로 접근이 가능해 진다.

어쨌든 중요한 것은 나는 안된다....그래서 그냥 텐서플로우를 CPU로만 동작시키도록 하겠다.
만약 VT-D가 지원이 된다고 하더라도..고려해야 할 부분들이 여러가지가 있는데 아래를 참고 하기 바란다.

There are several additional prerequisites to be met (see Virtual Box Manual for details):
  • Your motherboard has an IOMMU unit.
  • Your CPU supports the IOMMU.
  • The IOMMU is enabled in the BIOS.
  • The VM must run with VT-x/AMD-V and nested paging enabled.
  • Your Linux kernel was compiled with IOMMU support, DMA remapping, and the PCI stub driver.
  • Your Linux kernel recognizes and uses the IOMMU unit.

ESXi에서 설정되는 것이 궁금하다면 아래의 링크를 참고하면 ASROCK 회사에서 만들어둔 pdf를 확인할 수 있다.
http://www.asrock.com/support/note/vt-d.pdf

0. 우분투 16.04.2 LTS
우분투 설치는 특별한 과정을 볼게 없으나..
Virtualbox의 설치 경로를 관련 패키지들의 빠른 설치를 위해서 가능한 SSD에서 작업할 것을 권장하며, 또한 CPU는 최대로 설정 할 것을 권장한다. 본인은 8코어가 한계였다..
나중에 보면 알겠지만 CPU가 죽어난다...동영상 하나를 볼 여유가 없을 정도로 모두다 땡겨서 가지고 간다.




1. 아나콘다 설치 
파이썬은 간단하게 사용할 것이라면 python.org에서 단순히 기본 패키지를 설치해서 사용하면 된다. 하지만 텐서플로우 처럼 수치 역학 연산등 다양한 작업을 할 것이라고 미리 예측이 된다면..수 많은 배포판 중에서 아나콘다가 가장 무난한 대중적인 배포판이라고 할 수 있겠다. 구글에 검색해 봐도 아나콘다만 잔뜩 나와 있다.
최근 유행하는 고민될때는 1등을 선택하라는;;;; (광고를 붙였는데.. 온니 설명을 위한 것이다.)


Python Distributions

Aside from the official CPython distribution available from python.org, other distributions based on CPython include the following:


어쨌든 그래서 1등 아나콘다를 선택해서 설치한다.

1_1. 설치 파일 다운로드 
개인적으로 책을 파이썬 2.x버전으로 작성하다 보니...2.x가 익숙하나 요즘 대세가..3.x다 보니 아나콘다 3.x 버전을 다운로드 하여 진행한다. 요상한게 Power CPU 베이스는 용량이 작다.. 아마도 기본적으로 설치되어 있는 패키지가 있지 않나? 생각이 된다 정확한 것을 패키지를 비교해 봐야 겠지만.... 또는 x86만큼 많은 패키지들이 포팅되어 있지 않아 그 숫자가 작을수도 있다. 정확한 것을 비교해 봐야 겠지만..일단 여기서는 x86을 할 것이니까 크게 신경쓰지 말자.
https://www.continuum.io/downloads



1_2. 다운로드한 파일을 설치 
위에 나온 설명처럼 이미 짜여져 있는 배시 파일을 실행한다. 설치 경로는 다운로드 받을 파일에서 오른쪽을 클릭하면 경로를 알아낼수 있다. 이를 wget으로 받는다. 그리고 여러차례 'enter'와 'yes'를 입력하고 나면 설치가 완료된다.

root@hoonjo-VirtualBox:~# wget https://repo.continuum.io/archive/Anaconda3-4.4.0 
-Linux-x86_64.sh
--2017-06-02 07:05:33--  https://repo.continuum.io/archive/Anaconda3-4.4.0-Linux-x86_64.sh
Resolving repo.continuum.io (repo.continuum.io)... 104.16.18.10, 104.16.19.10, 2400:cb00:2048:1::6810:130a, ...
Connecting to repo.continuum.io (repo.continuum.io)|104.16.18.10|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 523283080 (499M) [application/x-sh]
Saving to: anaconda3-4.4.0-Linux-x86_64.sh??

          Anaconda3   0%[                    ]       0  --.-KB/s               
         Anaconda3-   0%[                    ]   4.57M  22.8MB/s               
        Anaconda3-4   2%[                    ]  12.44M  31.0MB/s               
       Anaconda3-4.   4%[                    ]  20.58M  34.2MB/s               
      Anaconda3-4.4   5%[>                   ]  29.68M  37.0MB/s               
     Anaconda3-4.4.   7%[>                   ]  38.19M  38.1MB/s               
    Anaconda3-4.4.0   9%[>                   ]  46.91M  39.0MB/s               
   Anaconda3-4.4.0-  10%[=>                  ]  54.72M  39.0MB/s               
  Anaconda3-4.4.0-L  12%[=>                  ]  62.76M  39.1MB/s               
 Anaconda3-4.4.0-Li  13%[=>                  ]  69.41M  38.1MB/s               
Anaconda3-4.4.0-Lin  15%[==>                 ]  75.54M  37.4MB/s  
<중략>             
Anaconda3-4.4.0-Lin 100%[===================>] 499.04M  32.8MB/s    in 14s     

2017-06-02 07:05:48 (35.6 MB/s) - anaconda3-4.4.0-Linux-x86_64.sh??saved [523283080/523283080]

root@hoonjo-VirtualBox:~# chmod 744 Anaconda3-4.4.0-Linux-x86_64.sh 
root@hoonjo-VirtualBox:~# ./Anaconda3-4.4.0-Linux-x86_64.sh 

Welcome to Anaconda3 4.4.0 (by Continuum Analytics, Inc.)

In order to continue the installation process, please review the license
agreement.
Please, press ENTER to continue
>>> 
===================================
Anaconda End User License Agreement
===================================

Copyright 2017, Continuum Analytics, Inc.

<중략>

cryptography
A Python library which exposes cryptographic recipes and primitives.

Do you approve the license terms? [yes|no]
>>> yes

Anaconda3 will now be installed into this location:
/root/anaconda3

  - Press ENTER to confirm the location
  - Press CTRL-C to abort the installation
  - Or specify a different location below

[/root/anaconda3] >>> <Enter>
PREFIX=/root/anaconda3
installing: python-3.6.1-2 ...
<중략>
installing: conda-env-2.6.0-0 ...
Python 3.6.1 :: Continuum Analytics, Inc.
creating default environment...
installation finished.
Do you wish the installer to prepend the Anaconda3 install location
to PATH in your /root/.bashrc ? [yes|no]
[no] >>> yes

Prepending PATH=/root/anaconda3/bin to PATH in /root/.bashrc
A backup will be made to: /root/.bashrc-anaconda3.bak


For this change to become active, you have to open a new terminal.

Thank you for installing Anaconda3!

Share your notebooks and packages on Anaconda Cloud!

Sign up for free: https://anaconda.org


1_3. 설치 확인
아나콘다 패키지를 설치 및 관리하려면 보통 'conda'라는 배포관리 명령어를 통해서 하는데, 이는 바로 실행이 되지 않는다. 즉 conda에 대한 패스는 잡혀 있으나, 현재 사용자 계정에 conda에 대한 사용이 등록되지 않았기 때문이다.
export로 하는 방법도 있지만. 가장 짧고 편한 방법은 '. ~/.bashrc'를 입력하여 읽어 들이는 것입니다. 중요하진 않지만 이는 다음과 같이 별칭(alias) 되어 있습니다.

root@hoonjo-VirtualBox:~# which conda
root@hoonjo-VirtualBox:~# . ~/.bashrc
root@hoonjo-VirtualBox:~# which conda
/root/anaconda3/bin/conda

1_4. conda 패키지 모두 설치
사실 이렇게 모두 다 설치할 필요는 없으나..204개 밖에 안되니까 명령어 실습 겸해서 설치 해 보는 것도 나쁘지 않습니다 하하;;;; 여러가지 테스트를 한다면 머리아프게 누군 설치하고 안 할 바에는 그냥 다 하는게 낫다고 보긴 합니다. :)
*주의할 점* 이미 익숙한 분들도 있겠지만 `와 '는 다른 것입니다. 똑같이 보이시겠지만...`는 치환의 개념으로 주로 쓰이고 '는 주로 묶어 준다는 개념으로 쓰입니다. 이렇게 적고 보니 똑같은 말 하고 있는 것 같네요...

root@hoonjo-VirtualBox:~# conda list | wc -l
204
root@hoonjo-VirtualBox:~# for i in `conda list | awk '{print $1}'`  
> do
> conda install -y $i
> done
Fetching package metadata .........
Solving package specifications: .

# All requested packages already installed.
# packages in environment at /root/anaconda3:
#
_license                  1.1                      py36_1  
Fetching package metadata .........
Solving package specifications: .
<중략>
# All requested packages already installed.
# packages in environment at /root/anaconda3:
#

zlib                      1.2.8 

1_5. conda 패키지 검증
잘 설치 되었겠지만 혹시 모르니 설치된 것들에 대해서 검증해 봅니다.
별 붙은게 새로 설치된 pip 패키지입니다.

root@hoonjo-VirtualBox:~# conda search pip
Fetching package metadata .........
pip                          1.1                      py26_1  defaults        
                             1.1                      py27_1  defaults        
<중략>       
                             9.0.1                    py34_0  defaults        
                             9.0.1                    py35_0  defaults        
                             9.0.1                    py27_1  defaults        
                             9.0.1                    py34_1  defaults        
                             9.0.1                    py35_1  defaults        
                          *  9.0.1                    py36_1  defaults        
root@hoonjo-VirtualBox:~# which pip
/root/anaconda3/bin/pip
root@hoonjo-VirtualBox:~# pip --version
pip 9.0.1 from /root/anaconda3/lib/python3.6/site-packages (python 3.6)

다음에 계속......

참고자료 : ppc64le에서 테스트한 결과
[Continue reading...]
 
Copyright © . 쿠버네티스 전문가 블로그 - Posts · Comments
Theme Template by BTDesigner · Powered by Blogger