Programing

파이썬 셸 내부에서 tensorflow가 GPU 가속을 사용하고 있는지 확인하는 방법은 무엇입니까?

lottogame 2020. 4. 16. 08:13
반응형

파이썬 셸 내부에서 tensorflow가 GPU 가속을 사용하고 있는지 확인하는 방법은 무엇입니까?


나는 두 번째 대답을 사용하여 내 우분투 16.04에 tensorflow 설치 여기 우분투 APT CUDA 설치 내장의와 함께.

이제 내 질문은 tensorflow가 실제로 GPU를 사용하는지 어떻게 테스트 할 수 있습니까? 나는 gtx 960m GPU를 가지고 있습니다. 내가 import tensorflow이것이 출력

I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcurand.so locally

이 출력이 tensorflow가 gpu를 사용하고 있는지 확인하기에 충분합니까?


아니요, 그래프의 다른 노드가 다른 장치에있을 수 있기 때문에 "open CUDA 라이브러리"만으로는 충분하지 않다고 생각합니다.

어떤 장치가 사용되는지 확인하려면 다음과 같이 로그 장치 배치를 활성화하십시오.

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

이 유형의 출력에 대해서는 콘솔을 확인하십시오.


sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))공식 TensorFlow 설명서 뿐만 아니라 다른 답변에 요약 된 것을 사용 하는 것 외에도 GPU에 계산을 할당하고 오류가 있는지 확인할 수 있습니다.

import tensorflow as tf
with tf.device('/gpu:0'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
    b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
    c = tf.matmul(a, b)

with tf.Session() as sess:
    print (sess.run(c))

여기

  • "/ cpu : 0": 컴퓨터의 CPU.
  • "/ gpu : 0": 컴퓨터의 GPU (있는 경우).

GPU를 가지고 있고 사용할 수 있다면 결과가 나타납니다. 그렇지 않으면 긴 스택 추적에 오류가 표시됩니다. 결국 당신은 다음과 같은 것을 가질 것입니다 :

'MatMul'노드에 장치를 할당 할 수 없음 :이 프로세스에 해당 사양과 일치하는 장치가 등록되어 있지 않으므로 명시 적 장치 사양 '/ device : GPU : 0'을 충족 할 수 없습니다


최근 몇 가지 유용한 기능이 TF에 나타났습니다.

세션에서 사용 가능한 장치를 확인할 수도 있습니다.

with tf.Session() as sess:
  devices = sess.list_devices()

devices 당신에게 뭔가를 반환합니다

[_DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:CPU:0, CPU, -1, 4670268618893924978),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, 6127825144471676437),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:XLA_GPU:0, XLA_GPU, 17179869184, 16148453971365832732),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:TPU:0, TPU, 17179869184, 10003582050679337480),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:TPU:1, TPU, 17179869184, 5678397037036584928)

다음 코드는 tensorflow에 사용 가능한 모든 장치를 제공합니다.

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

샘플 출력

[name : "/ cpu : 0"device_type : "CPU"memory_limit : 268435456 locality {} 화신 : 4402277519343584096,

이름 : "/ gpu : 0"device_type : "GPU"memory_limit : 6772842168 locality {bus_id : 1} 화신 : 7471795903849088328 physical_device_desc : "장치 : 0, 이름 : GeForce GTX 1070, pci 버스 ID : 0000 : 05 : 00.0"]


나는 이것을 달성하는 더 쉬운 방법이 있다고 생각합니다.

import tensorflow as tf
if tf.test.gpu_device_name():
    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
else:
    print("Please install GPU version of TF")

일반적으로 다음과 같이 인쇄됩니다.

Default GPU Device: /device:GPU:0

자세한 로그보다 나에게 더 쉬운 것처럼 보입니다.


이것은 훈련하는 동안 GPU를 사용하는 tensorflow를 확인합니다.

암호

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

산출

I tensorflow/core/common_runtime/gpu/gpu_device.cc:885] Found device 0 with properties: 
name: GeForce GT 730
major: 3 minor: 5 memoryClockRate (GHz) 0.9015
pciBusID 0000:01:00.0
Total memory: 1.98GiB
Free memory: 1.72GiB
I tensorflow/core/common_runtime/gpu/gpu_device.cc:906] DMA: 0 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:916] 0:   Y 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GT 730, pci bus id: 0000:01:00.0)
Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GT 730, pci bus id: 0000:01:00.0
I tensorflow/core/common_runtime/direct_session.cc:255] Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GT 730, pci bus id: 0000:01:00.0

텐서 플로우 2.0

tensorflow 2.0부터는 세션이 더 이상 사용되지 않습니다. GPU 기능을 테스트하는 여전히 작동하는 방법은 다음과 같습니다.

import tensorflow as tf

assert tf.test.is_gpu_available()
assert tf.test.is_built_with_cuda()

오류가 발생하면 설치를 확인해야합니다.


다른 답변 외에도 다음은 텐서 플로우 버전에 GPU 지원이 포함되어 있는지 확인하는 데 도움이됩니다.

import tensorflow as tf
print(tf.test.is_built_with_cuda())

이것은 Pensor-3.6에서 Tensorflow에 사용 가능한 장치 목록을 제공해야합니다.

tf = tf.Session(config=tf.ConfigProto(log_device_placement=True))
tf.list_devices()
# _DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 268435456)

GPU 사용을 모니터링하기 위해 nvidia-smi를 사용하는 것을 선호합니다. 프로그래밍을 시작할 때 크게 올라가면 tensorflow가 GPU를 사용하고 있다는 강력한 신호입니다.


좋아, 먼저 ipython shell터미널과 importTensorFlow에서

$ ipython --pylab
Python 3.6.5 |Anaconda custom (64-bit)| (default, Apr 29 2018, 16:14:56) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
Using matplotlib backend: Qt5Agg

In [1]: import tensorflow as tf

이제 다음 명령을 사용하여 GPU 메모리 사용량을 수 있습니다 .

# realtime update for every 2s
$ watch -n 2 nvidia-smi

우리는 importTensorFlow 만 사용했지만 아직 GPU를 사용하지 않았으므로 사용 통계는 다음과 같습니다.

tf 비 GPU 사용량

GPU 메모리 사용량이 얼마나 적은지 확인하십시오 (~ 200MB).



이제 코드에 GPU를로드하겠습니다. 에 표시된대로 다음을 tf documentation수행하십시오.

In [2]: sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

이제 watch stats는 다음과 같이 업데이트 된 GPU 사용량 메모리를 표시해야합니다.

tf GPU 시계

ipython 쉘의 Python 프로세스가 7.7GB의 GPU 메모리를 사용하는 방법을 관찰하십시오.


PS 코드가 실행되는 동안 이러한 통계를 계속 보면서 GPU 사용량이 얼마나 큰지 확인할 수 있습니다.


Jupyter에서 다음을 실행하십시오.

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

제대로 환경을 설정 한 경우, 다음과 같은거야 당신이 "jupyter 노트북"을 실행 한 터미널에 출력을 ,

2017-10-05 14:51:46.335323: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Quadro K620, pci bus id: 0000:02:00.0)
Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: Quadro K620, pci bus id: 0000:02:00.0
2017-10-05 14:51:46.337418: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\direct_session.cc:265] Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: Quadro K620, pci bus id: 0000:02:00.0

여기 Nvidia Quodro K620과 함께 TensorFlow를 사용하고 있습니다.


명령 줄에서 GPU를 쿼리하는 것이 가장 쉽다는 것을 알았습니다.

nvidia-smi

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.98                 Driver Version: 384.98                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 980 Ti  Off  | 00000000:02:00.0  On |                  N/A |
| 22%   33C    P8    13W / 250W |   5817MiB /  6075MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1060      G   /usr/lib/xorg/Xorg                            53MiB |
|    0     25177      C   python                                      5751MiB |
+-----------------------------------------------------------------------------+

학습이 백그라운드 프로세스 인 경우 pid from jobs -ppid from 과 일치해야합니다.nvidia-smi


최신 Tensorflow 업데이트를 통해 다음과 같이 확인할 수 있습니다.

tf.test.is_gpu_available( cuda_only=False, min_cuda_compute_capability=None)

TrueGPU가 사용중인 경우 Tensorflow반환하고 False그렇지 않으면 반환 합니다.

장치를 원하면 device_name다음을 입력 할 수 있습니다 tf.test.gpu_device_name().. 여기 에서 자세한 정보를 얻으십시오


다음 코드를 실행하여 현재 GPU를 사용 중인지 확인할 수 있습니다.

import tensorflow as tf
tf.test.gpu_device_name()

출력이 ''이면 사용 중임을 의미합니다 CPU.
출력이 이와 같은 경우 작동 /device:GPU:0한다는 의미 GPU입니다.


다음 코드를 사용하여 사용중인 것을 확인하십시오 GPU.

from tensorflow.python.client import device_lib 
device_lib.list_local_devices()

이것은 tf.sessionbash 에서 직접 사용할 수있는 장치를 나열하는 데 사용하는 회선입니다 .

python -c "import os; os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'; import tensorflow as tf; sess = tf.Session(); [print(x) for x in sess.list_devices()]; print(tf.__version__);"

사용 가능한 장치 및 tensorflow 버전을 인쇄합니다. 예를 들면 다음과 같습니다.

_DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 268435456, 10588614393916958794)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_GPU:0, XLA_GPU, 17179869184, 12320120782636586575)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, 13378821206986992411)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:GPU:0, GPU, 32039954023, 12481654498215526877)
1.14.0

Jupyter 노트북 상단 근처에 두십시오. 필요하지 않은 것을 주석으로 처리하십시오.

# confirm TensorFlow sees the GPU
from tensorflow.python.client import device_lib
assert 'GPU' in str(device_lib.list_local_devices())

# confirm Keras sees the GPU
from keras import backend
assert len(backend.tensorflow_backend._get_available_gpus()) > 0

# confirm PyTorch sees the GPU
from torch import cuda
assert cuda.is_available()
assert cuda.device_count() > 0
print(cuda.get_device_name(cuda.current_device()))

원래 여기에 answerwed .


TensorFlow 설치에서 GPU 가속이 사용되고 있는지 테스트 할 수있는 옵션이 있습니다.

세 가지 다른 플랫폼에서 다음 명령을 입력 할 수 있습니다.

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
  1. Jupyter Notebook-Jupyter Notebook을 실행중인 콘솔을 확인하십시오. 사용중인 GPU를 볼 수 있습니다.
  2. Python Shell-출력을 직접 볼 수 있습니다. (주-두 번째 명령의 출력을 변수 'sess'에 할당하지 마십시오. 도움이되는 경우).
  3. 스파이더-콘솔에 다음 명령을 입력하십시오.

    import tensorflow as tf tf.test.is_gpu_available()


명령 프롬프트 나 Linux 환경에서 간단히 다음 명령을 실행하십시오.

python -c 'import torch; print(torch.cuda.is_available())' 위의 'True'를 인쇄해야합니다

python -c 'import torch; print(torch.rand(2,3).cuda())' 이것은 다음을 인쇄해야합니다

tensor([[0.7997, 0.6170, 0.7042], [0.4174, 0.1494, 0.0516]], device='cuda:0')

참고 URL : https://stackoverflow.com/questions/38009682/how-to-tell-if-tensorflow-is-using-gpu-acceleration-from-inside-python-shell

반응형