source

현재 사용 가능한 GPU를 텐서플로우에서 얻는 방법

nicesource 2022. 10. 15. 08:36
반응형

현재 사용 가능한 GPU를 텐서플로우에서 얻는 방법

분산 Tensor Flow를 사용할 계획이 있는데, Tensor Flow가 훈련과 테스트에 GPU를 사용할 수 있다는 것을 알게 되었습니다.클러스터 환경에서는 각 머신에 0 또는 1개 이상의 GPU가 있을 수 있으며 가능한 한 많은 머신에서 TensorFlow 그래프를 GPU로 실행하고 싶습니다.

tf.Session()TensorFlow는 GPU를 사용합니다.

I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0 
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:838] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080, pci bus id: 0000:01:00.0)

궁금한 점은 현재 사용 가능한 GPU에 대한 정보를 TensorFlow에서 어떻게 얻을 수 있는가 하는 것입니다.로그에서 GPU 정보를 불러올 수 있지만 좀 더 정교하고 프로그램적인 방법으로 작업을 수행하고 싶습니다.또한 CUDA_VISIBLE_DEVICES 환경변수를 사용하여 GPU를 의도적으로 제한할 수 있으므로 OS 커널에서 GPU 정보를 가져오는 방법은 알고 싶지 않습니다.

간단히 말하면, 저는 다음과 같은 기능을 원합니다.tf.get_available_gpus()['/gpu:0', '/gpu:1']GPU 2입니다.떻게게 구현 ?? ????

로컬 프로세스에서 사용할 수 있는 디바이스를 나열할 수 있는 문서화되어 있지 않은 메서드가 있습니다(N.B. 문서화되어 있지 않은 메서드로서 이것은 하위 호환성이 없는 변경의 대상이 됩니다).이 함수는 프로토콜 버퍼 개체 목록을 반환합니다.다음과 같이 GPU 디바이스의 문자열 디바이스 이름 목록을 추출할 수 있습니다.

from tensorflow.python.client import device_lib

def get_available_gpus():
    local_device_protos = device_lib.list_local_devices()
    return [x.name for x in local_device_protos if x.device_type == 'GPU']

1.('TensorFlow 1.4') 것에 해 주세요.device_lib.list_local_devices()는 기본적으로 모든 디바이스에 모든 GPU 메모리를 할당하는 초기화 코드를 실행합니다(GitHub 문제).이를 방지하려면 먼저 명시적으로 작은 세션으로 세션을 생성하십시오.per_process_gpu_fraction , 「」allow_growth=True모든 메모리가 할당되지 않도록 합니다.자세한 내용은 이 질문을 참조하십시오.

다음 코드를 사용하여 모든 장치 목록을 확인할 수 있습니다.

from tensorflow.python.client import device_lib

device_lib.list_local_devices()

테스트 효용에도 방법이 있습니다.이제 다음 작업만 하면 됩니다.

tf.test.is_gpu_available()

및/또는

tf.test.gpu_device_name()

인수에 대한 Tensorflow 문서를 검색합니다.

2.부터 TensorFlow 2.1을 할 수 .tf.config.list_physical_devices('GPU'):

import tensorflow as tf

gpus = tf.config.list_physical_devices('GPU')
for gpu in gpus:
    print("Name:", gpu.name, "  Type:", gpu.device_type)

GPU가 2개 설치되어 있는 경우 다음과 같이 출력됩니다.

Name: /physical_device:GPU:0   Type: GPU
Name: /physical_device:GPU:1   Type: GPU

2에서는 TF 2.0을 .experimental:

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

참조:

승인된 답변은 GPU의 수를 제공하지만 GPU의 모든 메모리를 할당합니다.이 문제를 회피하려면 device_lib.list_local_devices()를 호출하기 전에 더 낮은 고정 메모리를 가진 세션을 만듭니다.이러한 세션은 어플리케이션에 따라서는 바람직하지 않을 수 있습니다.

결과적으로 메모리를 할당하지 않고 nvidia-smi를 사용하여 GPU의 수를 취득했습니다.

import subprocess

n = str(subprocess.check_output(["nvidia-smi", "-L"])).count('UUID')

Ry의 로, .R.를 했습니다.Ry가 훌륭한 설명을 한 것 말고도, 그가 제안했던 부분은device_lib.list_local_devices()명령줄에서 GPU 관련 정보를 확인하는 방법을 보여 드리겠습니다.

현재 NN 프레임워크에서는 NVIDIA의 gpus만 동작하기 때문에 답변은 NN 프레임워크에만 적용됩니다.Nvidia에는 /proc 파일 시스템 인터페이스를 사용하여 드라이버, 설치된 NVIDIA 그래픽 카드 및 AGP 상태에 대한 런타임 정보를 얻는 방법이 나와 있습니다.

/proc/driver/nvidia/gpus/0..N/information

설치된 각 NVIDIA 그래픽 어댑터(모델명, IRQ, BIOS 버전, 버스 유형)에 대한 정보를 제공합니다.BIOS 버전은 X가 실행 중일 때만 사용할 수 있습니다.

명령줄에서 할 수 .cat /proc/driver/nvidia/gpus/0/information첫 번째 GPU에 대한 정보를 확인할 수 있습니다. python에서 쉽게 실행할 수 있으며 두 번째, 세 번째, 네 번째 GPU에서 장애가 발생할 때까지 확인할 수 있습니다.

확실히 Mrry의 답변은 더 강력하며, 제 답변이 Linux 이외의 머신에서 기능할지 어떨지는 잘 모르겠습니다만, Nvidia의 페이지는 많은 사람들이 모르는 다른 흥미로운 정보를 제공하고 있습니다.

텐서플로우 2에서는 다음과 같이 동작합니다.

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    print("Name:", gpu.name, "  Type:", gpu.device_type)

2부터는 2.1을 드롭할 수 .experimental:

    gpus = tf.config.list_physical_devices('GPU')

https://www.tensorflow.org/api_docs/python/tf/config/list_physical_devices

했습니다.NVIDIA GTX GeForce 1650 Ti내 머신을 타고 있는tensorflow-gpu==2.2.0

다음 두 줄의 코드를 실행합니다.

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

출력:

Num GPUs Available:  1

TensorFlow Core v2.3.0에서는 다음 코드가 동작합니다.

import tensorflow as tf
visible_devices = tf.config.get_visible_devices()
for devices in visible_devices:
  print(devices)

환경에 따라서는, 이 코드에 의해서 플로우 결과가 됩니다.

PhysicalDevice(name=sysical_device):CPU:0', device_type='CPU') PhysicalDevice(name=sysical_device):GPU:0', device_type='GPU')

텐서플로우가 권장하는 최신 버전:

tf.config.list_physical_devices('GPU')

TF-2.1과 torch를 작업하고 있기 때문에 어떤 ML 프레임에서도 이 오토마싯 선택을 특정하고 싶지 않습니다.원래 nvidia-smi와 os.environment를 사용하면 빈 GPU를 얻을 수 있습니다.

def auto_gpu_selection(usage_max=0.01, mem_max=0.05):
"""Auto set CUDA_VISIBLE_DEVICES for gpu

:param mem_max: max percentage of GPU utility
:param usage_max: max percentage of GPU memory
:return:
"""
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
log = str(subprocess.check_output("nvidia-smi", shell=True)).split(r"\n")[6:-1]
gpu = 0

# Maximum of GPUS, 8 is enough for most
for i in range(8):
    idx = i*3 + 2
    if idx > log.__len__()-1:
        break
    inf = log[idx].split("|")
    if inf.__len__() < 3:
        break
    usage = int(inf[3].split("%")[0].strip())
    mem_now = int(str(inf[2].split("/")[0]).strip()[:-3])
    mem_all = int(str(inf[2].split("/")[1]).strip()[:-3])
    # print("GPU-%d : Usage:[%d%%]" % (gpu, usage))
    if usage < 100*usage_max and mem_now < mem_max*mem_all:
        os.environ["CUDA_VISIBLE_EVICES"] = str(gpu)
        print("\nAuto choosing vacant GPU-%d : Memory:[%dMiB/%dMiB] , GPU-Util:[%d%%]\n" %
              (gpu, mem_now, mem_all, usage))
        return
    print("GPU-%d is busy: Memory:[%dMiB/%dMiB] , GPU-Util:[%d%%]" %
          (gpu, mem_now, mem_all, usage))
    gpu += 1
print("\nNo vacant GPU, use CPU instead\n")
os.environ["CUDA_VISIBLE_EVICES"] = "-1"

GPU 를 취득할 수 있는 경우는, CUDA_VISIBLE_EVICES 가 그 GPU 의 BUSID 로 설정됩니다.

GPU-0 is busy: Memory:[5738MiB/11019MiB] , GPU-Util:[60%]
GPU-1 is busy: Memory:[9688MiB/11019MiB] , GPU-Util:[78%]

Auto choosing vacant GPU-2 : Memory:[1MiB/11019MiB] , GPU-Util:[0%]

또는 CPU를 사용하려면 -1로 설정합니다.

GPU-0 is busy: Memory:[8900MiB/11019MiB] , GPU-Util:[95%]
GPU-1 is busy: Memory:[4674MiB/11019MiB] , GPU-Util:[35%]
GPU-2 is busy: Memory:[9784MiB/11016MiB] , GPU-Util:[74%]

No vacant GPU, use CPU instead

주의: GPU가 필요한 ML 프레임을 Import하기 전에 이 기능을 사용하여 GPU를 자동으로 선택할 수 있습니다.또한 여러 작업을 쉽게 설정할 수 있습니다.

이 방법을 사용하여 모든 부품을 확인합니다.

from __future__ import absolute_import, division, print_function, unicode_literals

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds


version = tf.__version__
executing_eagerly = tf.executing_eagerly()
hub_version = hub.__version__
available = tf.config.experimental.list_physical_devices("GPU")

print("Version: ", version)
print("Eager mode: ", executing_eagerly)
print("Hub Version: ", h_version)
print("GPU is", "available" if avai else "NOT AVAILABLE")

GPU 지원 머신에 최신 TensorFlow 2.x GPU가 설치되어 있는지 확인하고 다음 코드를 python으로 실행합니다.

from __future__ import absolute_import, division, print_function, unicode_literals

import tensorflow as tf 

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

출력은 다음과 같습니다.

2020-02-07 10:45:37.587838:I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] SysFS에서 읽은 NUMA 노드가 음수 값(-1)이 있지만 NUMA 노드가 하나 이상 있어야 하므로 NUMA 노드 2020-02-07 10:45:37896을 반환합니다., 6, 7 Num GPU 사용 가능: 8

임의의 셸에서 다음 실행

python -c "import tensorflow as tf; print(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))"

언급URL : https://stackoverflow.com/questions/38559755/how-to-get-current-available-gpus-in-tensorflow

반응형