prosource

CPU에서 Tensorflow를 실행하는 방법

probook 2023. 6. 22. 21:58
반응형

CPU에서 Tensorflow를 실행하는 방법

Ubuntu 14.04에 GPU 버전의 텐서플로를 설치했습니다.

나는 텐서플로가 사용 가능한 GPU에 액세스할 수 있는 GPU 서버에 있습니다.

저는 CPU에서 텐서 플로우를 실행하고 싶습니다.

일반적으로 사용할 수 있습니다.env CUDA_VISIBLE_DEVICES=0GPU 0번에서 실행할 수 있습니다.

대신 CPU를 어떻게 선택할 수 있습니까?

나는 코드를 다시 쓰는 것에 관심이 없습니다.with tf.device("/cpu:0"):

환경 변수를 다음과 같이 설정할 수도 있습니다.

CUDA_VISIBLE_DEVICES=""

소스 코드를 수정할 필요가 없습니다.

위의 답변이 효과가 없으면 다음을 시도합니다.

os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

신청할 수 있습니다device_count "parametertf.Session:

config = tf.ConfigProto(
        device_count = {'GPU': 0}
    )
sess = tf.Session(config=config)

구성 파일의 프로토콜 참조:

tensorflow/core/framework/config.proto

Tensorflow 2.3.1을 실행하는 경우 환경 변수 솔루션이 작동하지 않습니다.github 스레드의 코멘트를 통해 아래 솔루션이 >=2.1.0 버전에 대해 작동한다고 가정합니다.

텐서 흐름 github에서:

import tensorflow as tf

# Hide GPU from visible devices
tf.config.set_visible_devices([], 'GPU')

가져오기 직후에 새 텐서플로 인스턴스를 사용하여 이 작업을 수행해야 합니다(주피터 노트북을 실행 중인 경우 커널을 다시 시작하십시오).

CPU에서 실제로 실행되고 있는지 확인하려면 다음을 수행합니다.

# To find out which devices your operations and tensors are assigned to
tf.debugging.set_log_device_placement(True)

# Create some tensors and perform an operation
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)

print(c)

예상 출력:

2.3.1
Executing op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0
tf.Tensor(
[[22. 28.]
 [49. 64.]], shape=(2, 2), dtype=float32)

▁setting만설정▁for▁only직,만 설정합니다.CUDA_VISIBLE_DEVICES 말하면-1편집:편집:

작업:

import os
import tensorflow as tf

os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

if tf.test.gpu_device_name():
    print('GPU found')
else:
    print("No GPU found")

# No GPU found

작동하지 않음:

import os
import tensorflow as tf

os.environ['CUDA_VISIBLE_DEVICES'] = ''    

if tf.test.gpu_device_name():
    print('GPU found')
else:
    print("No GPU found")

# GPU found

Tensorflow GPU 가이드에서 권장하는 대로입니다.

# Place tensors on the CPU
with tf.device('/CPU:0'):
  a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
  b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
  # Any additional tf code placed in this block will be executed on the CPU

아래 코드만 사용하면 됩니다.

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

의 경우 0의 경우, 나의경, 텐로플 2.4.0의, 당이설지않는, 신하치한않작다습을 .tensorflow-cpu

pip install tensorflow-cpu

설치 수준에서 가능한 또 다른 해결책은 CPU 전용 변형을 찾는 것입니다.

저의 경우, 지금 당장은 다음과 같습니다.

pip3 install https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow_cpu-2.2.0-cp38-cp38-win_amd64.whl

버전을 이 경우에는 른버이선하만됩면니다경우기전하택을올바이,▁just▁((▁the경다우됩in니▁version▁correct▁select,cp38 트힌python 3.8또한 Tensorflow 2.2.0이 사용되며, 현재 버전은 Jul 12 '20)입니다.


이 답변에서 설명한 것과 같은 벤브 사용에 대한 보너스 포인트.

파브리치오의 대답은 저에게 효과가 있었습니다.

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="-1"

텐서 플로우를 가져오기 전에 변경해야 했습니다.텐서플로 2.4.0을 사용하고 있습니다.

다른 (하위) 솔루션은 GPU 컴퓨팅에 필요한 cusolver64_10.dll 파일의 이름을 바꾸는 것입니다.텐서플로는 dll을 찾을 수 없기 때문에 자동으로 CPU를 사용합니다.

다음과 같은 위치에 있어야 합니다.C:\프로그램 파일\NVIDIA GPU 컴퓨팅 툴킷\CUDA\v11.2\bin

당신은 할 수 있습니다.사용할 GPU를 설정할 수 있는 한 가지 가능한 기능은 다음과 같습니다.

import tensorflow as tf

def set_gpu(gpu_ids_list):
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        try:
            gpus_used = [gpus[i] for i in gpu_ids_list]
            tf.config.set_visible_devices(gpus_used, 'GPU')
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
        except RuntimeError as e:
            # Visible devices must be set before GPUs have been initialized
            print(e)

가 4개인 가 4개인 시스템을 한다고 가정합니다.id = 0그리고 그와 함께 있는 사람.id = 2라이브러리를 가져온 직후 코드의 첫 번째 명령은 다음과 같습니다.

set_gpu([0, 2])

이 경우 CPU만 사용하려면 다음과 같이목록을 사용하여 함수를 호출할 수 있습니다.

set_gpu([])

완전성을 위해 런타임 초기화에서 장치의 모든 메모리가 할당되지 않도록 하려면 를 사용할 수 있습니다.마지막으로 GPU 메모리를 동적으로 점유하면서 사용할 장치를 관리하는 기능은 다음과 같습니다.

import tensorflow as tf

def set_gpu(gpu_ids_list):
    gpus = tf.config.list_physical_devices('GPU')
    if gpus:
        try:
            gpus_used = [gpus[i] for i in gpu_ids_list]
            tf.config.set_visible_devices(gpus_used, 'GPU')
            for gpu in gpus_used:
                tf.config.experimental.set_memory_growth(gpu, True)
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
        except RuntimeError as e:
            # Visible devices must be set before GPUs have been initialized
            print(e)
# this works on tensorflow 2.8, windows 10, jupyterlab Version 3.3.2
# this is the very FIRST lines of code

import tensorflow as tf

tf.config.set_visible_devices([], 'GPU')

# if tf.test.gpu_device_name(): # this lies and tells you about all devices
if tf.config.experimental.list_logical_devices('GPU'):
    print('GPU found')
else:
    print("No GPU found")

이 문제를 해결하기 위해 너무 많은 시간을 보냈습니다. 대부분의 시도는 프로세스를 CPU에서 부분적으로 실행하고 여전히 GPU 메모리에 로드하는 것으로 남겨두었습니다.이상한...

다른 것이 작동하기 전에 위의 코드를 먼저 실행합니다.

저는 나중에 6k에서 12k로 숨길 수 있었습니다.지금은 CPU만 사용하여 실행 중입니다.각 시대는 GPU보다 약 10배 더 오래 걸립니다.에포크당 약 3분에서 에포크당 35분이 조금 넘습니다.이것은 허용 가능한 절충안입니다.교육 시간 대 모델 크기.

일부 시스템에서는 다음을 지정해야 합니다.

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=""  # or even "-1"

텐서 흐름을 가져오기 전에.

언급URL : https://stackoverflow.com/questions/37660312/how-to-run-tensorflow-on-cpu

반응형