¿Se puede obligar a Keras con el backend Tensorflow a usar CPU o GPU a voluntad?


Tengo Keras instalado con el motor Tensorflow y CUDA. A veces me gustaría forzar a Keras a usar CPU. ¿Se puede hacer esto sin decir instalar un Tensorflow solo para CPU separado en un entorno virtual? Si es así, ¿cómo? Si el backend fuera Theano, las banderas podrían establecerse, pero no he oído hablar de banderas Tensorflow accesibles a través de Keras.

Author: mikal94305, 2016-11-19

6 answers

Si quieres forzar a Keras a usar CPU

Camino 1

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"   # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = ""

Antes de importar Keras / Tensorflow.

Camino 2

Ejecuta tu script como

$ CUDA_VISIBLE_DEVICES="" ./your_keras_code.py

Véase también

  1. https://github.com/keras-team/keras/issues/152
  2. https://github.com/fchollet/keras/issues/4613
 63
Author: Martin Thoma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-18 17:57:23

Una forma bastante elegante y separable de hacer esto es usar

import tensorflow as tf
from keras import backend as K

num_cores = 4

if GPU:
    num_GPU = 1
    num_CPU = 1
if CPU:
    num_CPU = 1
    num_GPU = 0

config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,\
        inter_op_parallelism_threads=num_cores, allow_soft_placement=True,\
        device_count = {'CPU' : num_CPU, 'GPU' : num_GPU})
session = tf.Session(config=config)
K.set_session(session)

Aquí con booleans GPU y CPU puede especificar si desea usar una GPU o GPU al ejecutar el código. Observe que estoy haciendo esto especificando que hay 0 dispositivos GPU cuando quiero usar la CPU. Como una ventaja adicional, a través de este método se puede especificar cuántas GPU y CPU a utilizar también! Además, a través de num_cores puede establecer el número de núcleos de CPU a utilizar.

Todo esto se ejecuta en el constructor de mi clase, antes de cualquier otra operación, y es completamente separable de cualquier modelo, u otro código que utilice.

Lo único a tener en cuenta es que necesitarás tensorflow-gpu y cuda/cudnn instalado porque siempre está dando la opción de usar una GPU.

 38
Author: RACKGNOME,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-29 20:01:31

Esto funcionó para mí (win10), lugar antes de importar keras:

import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
 26
Author: Neuraleptic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-19 16:21:25

Según el tutorial de keras , simplemente puede usar el mismo ámbito tf.device que en tensorflow regular:

with tf.device('/gpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops in the LSTM layer will live on GPU:0

with tf.device('/cpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops in the LSTM layer will live on CPU:0
 16
Author: sygi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-19 08:20:27

Solo importa tensortflow y usa keras, es así de fácil.

import tensorflow as tf
# your code here
with tf.device('/gpu:0'):
    model.fit(X, y, epochs=20, batch_size=128, callbacks=callbacks_list)
 8
Author: harshlal028,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-30 22:05:49

Acabo de pasar algún tiempo averiguarlo. La respuesta de Thoma no está completa. Digamos que tu programa es test.py, quieres usar gpu0 para ejecutar este programa, y mantener otras gpu libres.

Debes escribir CUDA_VISIBLE_DEVICES=0 python test.py

Observe que es DEVICES no DEVICE

 2
Author: DDz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-19 06:47:37