IT이야기

텐서플로우가 python shell 안쪽에서 gpu 가속을 사용하는지 확인하는 방법

cyworld 2022. 3. 22. 21:21
반응형

텐서플로우가 python shell 안쪽에서 gpu 가속을 사용하는지 확인하는 방법

는 여기 두 번째 답을 사용해서 Ubuntu의 빌트인 아파트 쿠다 설치와 함께 나의 Ubuntu 16.04에 텐서플로우를 설치했다.

이제 제 질문은 어떻게 텐서플로우가 정말로 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

이 출력은 텐서플로우가 gpu를 사용하는지 확인할 수 있을 정도로 충분한가?

아니, 나는 "개방형 CUDA 라이브러리"가 충분한지 알 수 없다고 생각한다. 왜냐하면 그래프의 다른 노드가 다른 장치에 있을 수 있기 때문이다.

tensorflow2를 사용할 경우:

print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))

tensorflow1의 경우 사용되는 장치를 확인하려면 다음과 같이 로그 장치 배치를 활성화하십시오.

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))

여기

  • "/flash:0":시스템의 CPU.
  • "/gpu:0":기계의 GPU(GPU)가 있는 경우.

gpu가 있어 사용할 수 있으면 결과가 나온다.그렇지 않으면 긴 스택 트레이스에 오류가 나타날 것이다.결국 당신은 이와 같은 것을 갖게 될 것이다.

장치를 노드 'MatMul'에 할당할 수 없음: 명시적 장치 사양 '/장치: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)

다음의 코드 조각은 당신에게 텐서 흐름이 가능한 모든 장치를 제공할 것이다.

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

샘플 출력

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

이름: "/gpu:0" device_type: "GPU" memory_limit: 6772842168 locality { bus_id: 1 {} 화신: 74717959038488328 물리적_device_desc: "device: 0, name: name:GeForce GTX 1070, pci 버스 ID: 0000:05:00.0" ]

텐서플로 2.0

세션은 더 이상 2.0에서 사용되지 않는다.대신 다음을 사용할 수 있다.

import tensorflow as tf

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

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

나는 이것을 성취하는 더 쉬운 방법이 있다고 생각한다.

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

이것은 장황한 로그보다 내게 더 쉬워 보인다.

편집:- 이 테스트는 TF 1.x 버전에 대해 테스트되었다.TF 2.0 이상에서 할 수 있는 일이 없었으니 명심해.

이렇게 하면 훈련 중에 GPU를 사용하여 텐서 흐름이 확인될 수 있는가?

코드

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

좋아, 먼저 발사해봐ipython shell에서 출발하여import텐서 흐름:

$ 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

우리만 있으니까.import는 다음과 Ed TensorFlow는 Aba직 GPUpu이다.

tf 비 gpu 사용

GPU 메모리 사용량이 매우 적은 경우(~700MB)에 주목하십시오. 때때로 GPU 메모리 사용량은 0MB까지 낮을 수 있다.


자, 이제 우리 코드에 GPU를 넣자.에 표시된 대로 다음을 수행하십시오.

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

이제 시계 통계에는 다음과 같이 업데이트된 GPU 사용 메모리가 표시되어야 한다.

tf gpu-watch

ipython 쉘의 Python 프로세스가 GPU 메모리의 최대 7GB를 어떻게 사용하고 있는지 지금 확인하십시오.


P.S. 코드가 실행 중일 때 이러한 통계를 계속 시청하면 GPU 사용량이 시간이 지남에 따라 얼마나 강도 높은지 알 수 있다.

다른 답변 외에도, 다음은 사용자의 텐서 흐름 버전이 GPU 지원을 포함하는지 확인하는 데 도움이 될 것이다.

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

Tensorflow >= 2.1에 대한 업데이트.

TensorFlow가 GPU를 사용하고 있는지 확인하는 권장 방법은 다음과 같다.

tf.config.list_physical_devices('GPU') 

을 기준으로 TensorFlow 2.1 을 하면tf.test.gpu_device_name()앞서 언급한 것에 찬성하지 않는다.

그러면 터미널에서 사용할 수 있다.nvidia-smi얼마나 많은 GPU 메모리가 할당되었는지 확인하는 동시에watch -n K nvidia-smi예를 들어 매 K초마다 사용 중인 메모리 양을 알려준다(사용할 수 있음).K = 1실시간으로)

GPU가 여러 개 있고 각각 분리된 GPU에 있는 여러 네트워크를 사용하려는 경우 다음을 사용할 수 있다.

 with tf.device('/GPU:0'):
      neural_network_1 = initialize_network_1()
 with tf.device('/GPU:1'):
      neural_network_2 = initialize_network_2()

이는 Tensorflow(Py-3.6 이하)에 사용할 수 있는 장치 목록을 제공해야 한다.

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를 사용하는 것을 선호한다.만약 당신이 프로그램을 시작할 때 그것이 크게 올라간다면, 그것은 당신의 텐서 흐름이 GPU를 사용하고 있다는 강한 신호다.

Tensorflow의 최근 업데이트로 다음과 같이 확인할 수 있다.

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

이것은 돌아올 것이다.TrueGPU를 사용하는 경우Tensorflow, and returnFalse그렇지 않으면

장치를 원할 경우device_name입력 가능:tf.test.gpu_device_name()자세한 내용은 여기를 참조하십시오.

텐서플로 2.0 >=인 경우

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

여기에 이미지 설명을 입력하십시오.

다음 사항을 주피터(Juffyter에서 실행하십시오.

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

여기 보시다시피 나는 엔비디아 쿼드로 K620과 함께 텐서플로우를 사용하고 있다.

명령줄에서 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 |
+-----------------------------------------------------------------------------+

만약 당신의 배움이 배경과정의 과정이라면.jobs -p의 pid와 일치해야 한다.nvidia-smi

다음 코드를 실행하여 현재 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()

이것을 너의 주피터 공책의 맨 위에 놓아라.필요 없는 것을 코멘트해.

# 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 (for TensorFlow 1.X + Keras)
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()))

참고: TensorFlow 2.0이 출시됨에 따라 Keras는 이제 TF API의 일부로 포함되었다.

원래 여기서 대답했다.

>>> import tensorflow as tf 
>>> tf.config.list_physical_devices('GPU')

2020-05-10 14:58:16.243814: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1
2020-05-10 14:58:16.262675: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-05-10 14:58:16.263119: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1555] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1060 6GB computeCapability: 6.1
coreClock: 1.7715GHz coreCount: 10 deviceMemorySize: 5.93GiB deviceMemoryBandwidth: 178.99GiB/s
2020-05-10 14:58:16.263143: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
2020-05-10 14:58:16.263188: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10
2020-05-10 14:58:16.264289: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10
2020-05-10 14:58:16.264495: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10
2020-05-10 14:58:16.265644: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10
2020-05-10 14:58:16.266329: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10
2020-05-10 14:58:16.266357: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7
2020-05-10 14:58:16.266478: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-05-10 14:58:16.266823: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-05-10 14:58:16.267107: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1697] Adding visible gpu devices: 0
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

@AmitaIrron에서 제안한 바와 같이:

이 섹션은 gpu가 발견되었음을 나타낸다.

2020-05-10 14:58:16.263119: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1555] Found device 0 with properties:

pciBusID: 0000:01:00.0 name: GeForce GTX 1060 6GB computeCapability: 6.1
coreClock: 1.7715GHz coreCount: 10 deviceMemorySize: 5.93GiB deviceMemoryBandwidth: 178.99GiB/s

그리고 여기에 사용 가능한 물리적 장치로 추가되었다.

2020-05-10 14:58:16.267107: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1697] Adding visible gpu devices: 0

[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

나는 아래 조각이 gpu를 테스트하는데 매우 편리하다는 것을 발견했다.

Tensorflow 2.0 테스트

import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
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))

텐서 흐름 1 검정

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))

텐서플로 2.0의 경우

import tensorflow as tf

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

여기의 출처

다른 옵션은 다음과 같다.

tf.config.experimental.list_physical_devices('GPU')

다음은 또한 GPU 장치의 이름을 반환할 것이다.

import tensorflow as tf
tf.test.gpu_device_name()

새로운 버전의 TF(>2.1)에서 TF가 GPU를 사용하고 있는지 확인하는 권장 방법은 다음과 같다.

tf.config.list_physical_devices('GPU')

Tensorflow가 GPU를 사용하고 있는지 확인하려면 Juffyter 또는 IDE에서 이 명령을 실행하십시오.tf.config.list_physical_devices('GPU')

텐서플로 2.1

GPU의 메모리 사용에 대해 nvidia-smi로 검증할 수 있는 간단한 계산.

import tensorflow as tf 

c1 = []
n = 10

def matpow(M, n):
    if n < 1: #Abstract cases where n < 1
        return M
    else:
        return tf.matmul(M, matpow(M, n-1))

with tf.device('/gpu:0'):
    a = tf.Variable(tf.random.uniform(shape=(10000, 10000)), name="a")
    b = tf.Variable(tf.random.uniform(shape=(10000, 10000)), name="b")
    c1.append(matpow(a, n))
    c1.append(matpow(b, n))

사용 가능한 장치를 나열하는 데 사용하는 라인입니다.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__);"

사용 가능한 장치와 텐서플로우 버전을 인쇄한다. 예를 들어,

_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

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

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

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
  1. 주피터 노트북 - 주피터 노트북을 실행하는 콘솔을 확인하십시오.여러분은 GPU가 사용되고 있는 것을 볼 수 있을 것이다.
  2. Python Shell - 출력을 직접 볼 수 있다.(참고- 두 번째 명령의 출력을 변수 'sess'에 할당하지 마십시오. 도움이 되는 경우).
  3. 스파이더 - 콘솔에 다음 명령을 입력하십시오.

    import tensorflow as tf tf.test.is_gpu_available()

TF2.4+는 TF가 GPU를 사용하는지 여부를 확인하기 위해 텐서플로 웹사이트의 "공식" 방법으로 열거되었다.

>>> import tensorflow as tf
>>> print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
Num GPUs Available:  2

TensorFlow 2.0을 사용하는 경우 루프를 사용하여 장치를 표시할 수 있다.

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

텐서플로우 2.x를 사용하는 경우 다음을 사용하십시오.

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

나는 가장 간단하고 포괄적인 접근법을 찾았다.방금 세트tf.debugging.set_log_device_placement(True)운영이 실제로 GPU에서 실행되는지 확인해야 한다.Executing op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0

문서에 대한 자세한 내용: https://www.tensorflow.org/guide/gpu#logging_device_placement

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

반응형