2017-06-03 193 views
1

我已經搜索了這個問題的答案,但沒有運氣。Tensorflow:使用多線程加載/運行多個模型

在許多應用程序中,我們有多個部署在一個GPU上的經過訓練的NN模型。另外,我們必須使用多線程技術才能獲得GPU的全部計算能力。例如,我的應用程序中有兩種不同的tensorflow CNN模型,我想在兩個不同的線程中運行(即推理/部署)它們。

這裏是我做過什麼:但是

## define my cnn model 
class my_cnn_model: 
    ... 

## initialize two graphs 
g1 = tf.Graph() 
g2 = tf.Graph() 

## define two sessions and bind one cnn model to each session 
sess1 = tf.InteractiveSession(graph=g1, config=cnn1_cfg) 
cnn1 = my_cnn_model(..., sess1) 

sess2 =tf.InteractiveSession(graph=g2, config=cnn2_cfg) 
cnn2 = my_cnn_model(..., sess2) 

## define two function model runs 
def cnn1_model_run(g1, sess1): 
    ... 
    sess1.run(); 

def cnn2_model_run(g2, sess2): 
    ... 
    sess2.run(); 


## put the functions into two separate threads 
thread_0 = threading.Thread(target= cnn1_model_run,args=...) 
thread_1 = threading.Thread(target= cnn2_model_run,args=...) 

## now issue the two threads 
thread_0.start() 
thread_1.start() 

結果表明,兩個CNN模型相互干擾,並給出錯誤輸出。使用上述機制的問題在哪裏? python多線程函數對於多張量流模型部署是不安全的嗎?

回答

0

也許你可以通過在cnn2_model_run功能附加with g1.as_default():

def cnn1_model_run(g1, sess1): 
    with g1.as_default(), sess1.as_default(): 
     ... 
     sess1.run(); 

相同修復解決問題。