본문 바로가기
인공신경망(DL)

GPU로 학습

by kiimy 2023. 3. 22.
728x90

<CUDA, cudnn, 환경 변수 설정>

= Anaconda를 활용하자!

conda install -c anaconda cudatoolkit==[버전]
ex) conda install -c anaconda cudatoolkit==10.1..

# CUDA 먼저 설치하면 어느 정도 상호호환되는 cudnn 자동 설치
# 원하는 버전이 있을시 ==[버전]
conda install -c anaconda cudnn

https://doitgrow.com/28

 

[환경 설정] 텐서플로우(Tensorflow) 2.x GPU 설정 및 사용하는 법 (윈도우10 기준)

게임할 때에는 컴퓨터가 자동으로 그래픽 카드를 인식하여 작동시키지만, 우리가 데이터 분석을 할 때에는 여러가지 설정을 해주어야 합니다. 오늘은 딥러닝의 가장 유명한 프레임워크인 텐서

doitgrow.com

import tensorflow as tf

# GPU 사용 가능한지 확인
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

# 모든 GPU 메모리 사용 허용
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
    try:
        tf.config.experimental.set_virtual_device_configuration(
            gpus[0],
            [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024 * 4)]
        )
    except RuntimeError as e:
        print(e)

# GPU를 사용하여 모델 학습
with tf.device('/device:GPU:0'):
    # 모델 구성 및 컴파일
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    # 모델 학습
    model.fit(x_train, y_train, batch_size=32, epochs=10, validation_data=(x_test, y_test))
    
    ...
    with문을 사용하면 특정 컨텍스트를 묶어 해당 부분만을 특정 GPU로 실행
    '''
y_test_pred = model.predict(X_test)
# print(sys.version)
print(device_lib.list_local_devices())

# GPU 사용 가능한지 확인
print("Num GPUs Available: ", tf.config.experimental.list_physical_devices('GPU'))

# Cuda 및 GPU 동작 확인
print(tf.test.is_built_with_cuda())
print(tf.test.is_built_with_gpu_support())
print(tf.test.gpu_device_name())

출력 결과

[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 2094470795125646661
xla_global_id: -1
, name: "/device:GPU:0"
device_type: "GPU"
memory_limit: 4169138176
locality {
  bus_id: 1
  links {
  }
}
incarnation: 3012637775583558840
physical_device_desc: "device: 0, name: NVIDIA GeForce GTX 1660 SUPER, pci bus id: 0000:01:00.0, compute capability: 7.5"
xla_global_id: 416903419
]
...
Num GPUs Available:  [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
True
True
/device:GPU:0
728x90

댓글