Проверка, действительно ли GPU используется в Keras / Tensorflow, а не просто проверено как настоящее - PullRequest
1 голос
/ 29 марта 2020

Я только что построил установку для глубокого обучения (12-ядерный процессор AMD; GeForce RTX 2080 ti; 64 ГБ ОЗУ). Первоначально я хотел установить CUDnn и CUDA на Ubuntu 19.0, но установка была слишком болезненной, и после прочтения немного, я решил переключиться на Windows 10 ...

После нескольких установок tenorflow- gpu, в condas и за его пределами я столкнулся с дополнительными проблемами, которые, как я предполагал, были связаны с совместимостью CUDnn-CUDA-tenorflow, поэтому удалили различные версии CUDA и tf. Мой вывод из nvcc --version:

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2018 NVIDIA Corporation
Built on Sat_Aug_25_21:08:04_Central_Daylight_Time_2018
Cuda compilation tools, release 10.0, V10.0.130

Прилагается также nvidia-smi (который показывает CUDA == 11.0 ?!)

enter image description here

У меня также есть:

 if tf.test.gpu_device_name():
        print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
    else:
        print("Please install GPU version of TF")
    print("keras version: {0} | Backend used: {1}".format(keras.__version__, backend.backend()))
    print("tensorflow version: {0} | Backend used: {1}".format(tf.__version__, backend.backend()))
    print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
    print("CUDA: {0} | CUDnn: {1}".format(tf_build_info.cuda_version_number,  tf_build_info.cudnn_version_number))

с выводом:

My device: [name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 12853915229880452239
, name: "/device:GPU:0"
device_type: "GPU"
memory_limit: 9104897474
lo

    cality {
      bus_id: 1
      links {
      }
    }
    incarnation: 7328135816345461398
    physical_device_desc: "device: 0, name: GeForce RTX 2080 Ti, pci bus id: 0000:42:00.0, compute capability: 7.5"
    ]
    Default GPU Device: /device:GPU:0
    keras version: 2.3.1 | Backend used: tensorflow
    tensorflow version: 2.1.0 | Backend used: tensorflow
    Num GPUs Available:  1
    CUDA: 10.1 | CUDnn: 7

Итак (я надеюсь) моя установка хотя бы частично сработала, я просто до сих пор не знаю, является ли GPU используется для моего обучения, или если он просто распознал как существующий, но процессор все еще используется . Как я могу это дифференцировать?

Я также использую Pycharm. Была рекомендация по установке Visio Studio и дополнительный шаг здесь :

5. Include cudnn.lib in your Visual Studio project.
Open the Visual Studio project and right-click on the project name.
Click Linker > Input > Additional Dependencies.
Add cudnn.lib and click OK.

Я не делал этого шага. Я также прочитал, что мне нужно установить следующее в переменных среды, но мой каталог пуст:

SET PATH=C:\tools\cuda\bin;%PATH%

Может ли кто-нибудь это проверить?

Также одна из моих моделей кера требует поиска гиперпараметров :

grid = GridSearchCV(estimator=model,
                        param_grid=param_grids,
                        n_jobs=-1, # -1 for all cores
                        cv=KFold(),
                        verbose=10)

grid_result = grid.fit(X_standardized, Y)

Это прекрасно работает на моем MBP (при условии, конечно, что n_jobs = -1 занимает все ядра процессора). На моей DL-установке я получаю предупреждения:

ERROR: The process with PID 5156 (child process of PID 1184) could not be terminated.
Reason: Access is denied.
ERROR: The process with PID 1184 (child process of PID 6920) could not be terminated.
Reason: There is no running instance of the task.
2020-03-28 20:29:48.598918: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-03-28 20:29:48.599348: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-03-28 20:29:48.599655: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-03-28 20:29:48.603023: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-03-28 20:29:48.603649: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-03-28 20:29:48.604236: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-03-28 20:29:48.604773: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-03-28 20:29:48.605524: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-03-28 20:29:48.608151: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2020-03-28 20:29:48.608369: W tensorflow/stream_executor/stream.cc:2041] attempting to perform BLAS operation using StreamExecutor without BLAS support
2020-03-28 20:29:48.608559: W tensorflow/core/common_runtime/base_collective_executor.cc:217] BaseCollectiveExecutor::StartAbort Internal: Blas GEMM launch failed : a.shape=(10, 8), b.shape=(8, 4), m=10, n=4, k=8
     [[{{node dense_1/MatMul}}]]
C:\Users\me\PycharmProjects\untitled\venv\lib\site-packages\sklearn\model_selection\_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details: 
tensorflow.python.framework.errors_impl.InternalError:  Blas GEMM launch failed : a.shape=(10, 8), b.shape=(8, 4), m=10, n=4, k=8
     [[node dense_1/MatMul (defined at C:\Users\me\PycharmProjects\untitled\venv\lib\site-packages\keras\backend\tensorflow_backend.py:3009) ]] [Op:__inference_keras_scratch_graph_982]

Могу ли я предположить, что при использовании GridSearchCV используется только процессор, а не графический процессор? Тем не менее, когда я запускаю и синхронизирую другой метод в моем коде, я сравниваю время MBP (около 40 с при Intel Core i7 с частотой 2,8 ГГц) и время рабочего стола (около 43 с при использовании 12-ядерного потокового преобразователя). Даже при сравнении процессоров я бы ожидал гораздо более быстрого времени, чем MBP. Мое предположение неверно?

Ответы [ 2 ]

1 голос
/ 30 марта 2020

Вы можете увидеть следующие детали здесь .
На основании документации:

If a TensorFlow operation has both CPU and GPU implementations, 
by default, the GPU devices will be given priority when the operation is assigned to a device.
For example, tf.matmul has both CPU and GPU kernels. 
On a system with devices CPU:0 and GPU:0, the GPU:0 device will be selected to run tf.matmul unless you explicitly request running it on another device.

Размещение регистрирующего устройства

tf.debugging.set_log_device_placement(True)

# Create some tensors
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)
Example Result
Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0
tf.Tensor(
[[22. 28.]
 [49. 64.]], shape=(2, 2), dtype=float32)

Для размещения устройства вручную

tf.debugging.set_log_device_placement(True)

# Place tensors on the CPU
with tf.device('/GPU: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]])

c = tf.matmul(a, b)
print(c)
Example Result: 
Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0
tf.Tensor(
[[22. 28.]
 [49. 64.]], shape=(2, 2), dtype=float32)
0 голосов
/ 30 марта 2020

Еще один способ проанализировать производительность графического процессора, который я в итоге нашел (для Windows пользователей), состоял в go в «Диспетчере задач» и изменении одного из мониторов на вкладке «Производительность» на CUDA, затем просто запустите сценарий и наблюдайте за ним.

Также добавление этого

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

перед импортом keras для переключения между CPU и GPU также показывает заметную разницу (хотя для моей простой сети, более быстрый CPU можно объяснить здесь ).

...