[python] CPU에서 Tensorflow를 실행하는 방법

Ubuntu 14.04에 GPU 버전의 tensorflow를 설치했습니다.

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

CPU에서 tensorflow를 실행하고 싶습니다.

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

대신 CPU 중에서 선택하는 방법은 무엇입니까?

내 코드를 다시 작성하는 데 관심이 없습니다. with tf.device("/cpu:0"):



답변

device_count별로 매개 변수 를 적용 할 수 있습니다 tf.Session.

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

protobuf 구성 파일도 참조하십시오.

tensorflow/core/framework/config.proto


답변

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

CUDA_VISIBLE_DEVICES=""

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


답변

위의 답변이 작동하지 않으면 다음을 시도하십시오.

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


답변

나를 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


답변

아래 코드를 사용하십시오.

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


답변

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

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

tensorflow를 가져 오기 전에.


답변

사용할 수 있습니다 tf.config.set_visible_devices. 사용할 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 개의 GPU가있는 시스템에 있고 두 개의 GPU, 즉를 사용하는 GPU와를 사용하는 GPU 만 사용하려는 경우 라이브러리를 가져온 직후 코드의 첫 번째 명령은 다음 id = 0id = 2같습니다.

set_gpu([0, 2])

귀하의 경우 CPU 만 사용하려면 빈 목록으로 함수를 호출 할 수 있습니다 .

set_gpu([])

완전성을 위해 런타임 초기화가 장치의 모든 메모리를 할당하지 않도록하려면 tf.config.experimental.set_memory_growth. 마지막으로 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)