8

我試圖使用多線程(和tensorflow後端)來訓練多個具有不同參數值的keras模型。我已經看到了在多個線程中使用相同模型的幾個例子,但在這種特殊情況下,我遇到了有關圖形衝突的各種錯誤等。下面是我想要做的一個簡單示例:TensorFlow/Keras多線程模型擬合

from concurrent.futures import ThreadPoolExecutor 
import numpy as np 
import tensorflow as tf 
from keras import backend as K 
from keras.layers import Dense 
from keras.models import Sequential 


sess = tf.Session() 


def example_model(size): 
    model = Sequential() 
    model.add(Dense(size, input_shape=(5,))) 
    model.add(Dense(1)) 
    model.compile(optimizer='sgd', loss='mse') 
    return model 


if __name__ == '__main__': 
    K.set_session(sess) 
    X = np.random.random((10, 5)) 
    y = np.random.random((10, 1)) 
    models = [example_model(i) for i in range(5, 10)] 

    e = ThreadPoolExecutor(4) 
    res_list = [e.submit(model.fit, X, y) for model in models] 

    for res in res_list: 
     print(res.result()) 

由此產生的錯誤是ValueError: Tensor("Variable:0", shape=(5, 5), dtype=float32_ref) must be from the same graph as Tensor("Variable_2/read:0", shape=(), dtype=float32).。我也嘗試在線程內初始化模型,這給出了類似的失敗。

對此有何想法?我完全沒有關注這個確切的結構,但我更喜歡能夠使用多個線程而不是進程,因此所有模型都在相同的GPU內存分配內進行訓練。

回答

4

Tensorflow圖不是線程安全的(請參閱https://www.tensorflow.org/api_docs/python/tf/Graph),當您創建新的Tensorflow會話時,它默認使用默認圖形。

您可以通過在並行化函數中使用新圖形創建新會話並在那裏構建keras模型來解決此問題。

下面是一些代碼,創建並適合於並行每個可用的GPU型號:

import concurrent.futures 
import numpy as np 

import keras.backend as K 
from keras.layers import Dense 
from keras.models import Sequential 

import tensorflow as tf 
from tensorflow.python.client import device_lib 

def get_available_gpus(): 
    local_device_protos = device_lib.list_local_devices() 
    return [x.name for x in local_device_protos if x.device_type == 'GPU'] 

xdata = np.random.randn(100, 8) 
ytrue = np.random.randint(0, 2, 100) 

def fit(gpu): 
    with tf.Session(graph=tf.Graph()) as sess: 
     K.set_session(sess) 
     with tf.device(gpu): 
      model = Sequential() 
      model.add(Dense(12, input_dim=8, activation='relu')) 
      model.add(Dense(8, activation='relu')) 
      model.add(Dense(1, activation='sigmoid')) 

      model.compile(loss='binary_crossentropy', optimizer='adam') 
      model.fit(xdata, ytrue, verbose=0) 

      return model.evaluate(xdata, ytrue, verbose=0) 

gpus = get_available_gpus() 
with concurrent.futures.ThreadPoolExecutor(len(gpus)) as executor: 
    results = [x for x in executor.map(fit, gpus)] 
print('results: ', results) 
+0

這解決了我的問題,我有兩個模型在一個進程中運行,它總是給我ValueError異常:取參數不能被解釋爲張量。 (張量張量(「輸入:0」,shape =(2,2),dtype = float32_ref)不是該圖的元素。) – forqzy