Tensorflow服务器:我不想为每个会话初始化全局变量

时间:2018-10-08 10:47:51

标签: python tensorflow

EDIT2:下面的Github链接包含从进程调用TF模型的问题的可能解决方案。它们包括渴望执行和专用服务器进程,通过http请求提供TF模型预测。与每次初始化全局变量并调用tf.train.Server相比,我想知道是否使用自定义服务器和请求都能赢得胜利,但这似乎是一种更优雅的方式。

我将调查内存泄漏,如果不存在,请关闭此问题。

编辑:添加了该问题的简单可复制示例:

https://github.com/hcl14/Tensorflow-server-launched-from-child-process


背景:我正在运行Tensorflow服务器,并通过“分支”进程连接到它。动态创建(销毁)进程对我来说至关重要-由于weird memory leak,Python探查器不可见(线程无法解决问题),因此将代码的高负载部分移到了那里。因此,我希望快速初始化进程并立即开始工作。仅当进程被破坏时才释放内存。

做实验时,我找到了一个解决方案,将加载的模型和图形保存到全局变量中,然后由子进程(默认情况下使用“ fork”模式)采用,然后调用服务器。

问题:对我来说,奇怪的是,在加载keras模型后,我无法锁定不希望修改的图,并且每次我都需要运行tf.global_variables_initializer()在子进程中打开新会话。但是,在没有任何会话创建的情况下在主流程中运行虚拟运行就可以了。我知道在这种情况下,tensorflow使用默认会话,但是图上的所有变量都应在模型运行后初始化,因此我希望新的会话可以与先前定义的图一起使用。

因此,我认为修改模型使Python会对子进程(“ fork”模式)产生很多不满,这会增加计算和内存开销。

请原谅我很多代码。我使用的模型对我来说是旧的黑匣子,所以我的问题可能与此有关。 Tensorflow版本为1.2 (我无法升级,模型不兼容), Python 3.6.5

此外,也许我的解决方案效率低下,并且有更好的解决方案,对于您的建议我将不胜感激。

我的设置如下:

1.Tensorflow服务器在主进程中启动:

初始化服务器:

def start_tf_server():
    import tensorflow as tf
    cluster = tf.train.ClusterSpec({"local": [tf_server_address]})
    server = tf.train.Server(cluster, job_name="local", task_index=0)    
    server.join() # block process from exiting

在主要过程中:

p = multiprocessing.Process(target=start_tf_server)
p.daemon=True
p.start() # this process never ends, unless tf server crashes

# WARNING! Graph initialization must be made only after Tf server start!
# Otherwise everything will hang
# I suppose this is because of another session will be 
# created before the server one

# init model graph before branching processes
# share graph in the current process scope
interests = init_interests_for_process()
global_vars.multiprocess_globals["interests"] = interests

2。init_interests_for_process()是模型初始化程序,它加载我的旧模型并在全局变量中共享它。我进行了一次虚拟模型传递,以在图形上初始化所有内容,然后想要锁定图形。但这不起作用:

def init_interests_for_process():
    # Prevent errors on my GPU and disable tensorflow 
    # complaining about CPU instructions
    import os
    os.environ["CUDA_VISIBLE_DEVICES"]= ""
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

    import tensorflow as tf

    from tensorflow.contrib.keras import models

    # create tensorflow graph
    graph = tf.get_default_graph()

    with graph.as_default():

        TOKENIZER = joblib.load(TOKENIZER_FILE)

        NN1_MODEL = models.load_model(NN1_MODEL_FILE)

        with open(NN1_CATEGORY_NAMES_FILE, 'r') as f:
            NN1_CATEGORY_NAMES = f.read().splitlines()

        NN2_MODEL = models.load_model(NN2_MODEL_FILE)

        with open(NN2_CATEGORY_NAMES_FILE, 'r') as f:
            NN2_CATEGORY_NAMES = f.read().splitlines()
        # global variable with all the data to be shared
        interests = {}

        interests["TOKENIZER"] = TOKENIZER
        interests["NN1_MODEL"] = NN1_MODEL
        interests["NN1_CATEGORY_NAMES"] = NN1_CATEGORY_NAMES
        interests["NN2_MODEL"] = NN2_MODEL
        interests["NN2_CATEGORY_NAMES"] = NN2_CATEGORY_NAMES
        interests['all_category_names'] = NN1_CATEGORY_NAMES + \
                                          NN2_CATEGORY_NAMES
        # Reconstruct a Python object from a file persisted with joblib.dump.
        interests["INTEREST_SETTINGS"] = joblib.load(INTEREST_SETTINGS_FILE)

        # dummy run to create graph
        x = tf.contrib.keras.preprocessing.sequence.pad_sequences(
                         TOKENIZER.texts_to_sequences("Dummy srting"),
                         maxlen=interests["INTEREST_SETTINGS"]["INPUT_LENGTH"]
                         )
        y1 = NN1_MODEL.predict(x)
        y2 = NN2_MODEL.predict(x)

        # PROBLEM: I want, but cannot lock graph, as child process 
        # wants to run its own tf.global_variables_initializer()
        # graph.finalize()

        interests["GRAPH"] = graph

        return interests

3。现在我生成该进程(实际上,该进程是从另一个进程生成的-层次结构很复杂):

def foo(q):
     result = call_function_which_uses_interests_model(some_data) 
     q.put(result)
     return # I've read it is essential for destroying local variables
q = Queue()
p = Process(target=foo,args=(q,))
p.start()
p.join()
result = q.get() # retrieve data

4。在此过程中,我将模型称为:

# retrieve model from global variable
interests = global_vars.multiprocess_globals["interests"]

tokenizer = interests["TOKENIZER"]
nn1_model = interests["NN1_MODEL"]
nn1_category_names = interests["NN1_CATEGORY_NAMES"]
nn2_model = interests["NN2_MODEL"]
nn2_category_names = interests["NN2_CATEGORY_NAMES"]
input_length = interests["INTEREST_SETTINGS"]["INPUT_LENGTH"]

# retrieve graph
graph = interests["GRAPH"]

# open session for server
logger.debug('Trying tf server at ' + 'grpc://'+tf_server_address)
sess = tf.Session('grpc://'+tf_server_address, graph=graph)

# PROBLEM: and I need to run variables initializer:
sess.run(tf.global_variables_initializer())


tf.contrib.keras.backend.set_session(sess)

# finally, make a call to server:
with sess.as_default():        
    x = tf.contrib.keras.preprocessing.sequence.pad_sequences(
                            tokenizer.texts_to_sequences(input_str),
                            maxlen=input_length)
    y1 = nn1_model.predict(x)
    y2 = nn2_model.predict(x)

一切正常,如果每次生成新进程时我都不锁定图形并运行变量初始化器,那么一切正常。 (除了每个调用大约30-90 MB的内存泄漏,对于python内存分析器不可见)。当我想锁定图形时,会出现有关未初始化变量的错误:

FailedPreconditionError (see above for traceback): 
Attempting to use uninitialized value gru_1/bias
       [[Node: gru_1/bias/read = Identity[T=DT_FLOAT, _class=["loc:@gru_1/bias"],
       _device="/job:local/replica:0/task:0/cpu:0"](gru_1/bias)]]

谢谢!

2 个答案:

答案 0 :(得分:1)

您是否考虑过TensorFlow服务? https://www.tensorflow.org/serving/

通常,您需要缓存会话,我认为这是TF Serving使用的策略。到目前为止,这将是将TF模型部署到数据中心的最佳体验。

您也可以选择另一个方向,例如tf.enable_eager_execution(),这消除了会话的需要。变量仍然被初始化,尽管它是在创建Python变量对象后立即发生的。

但是,如果您确实要创建和销毁Session,则可以用常量("freeze" it)替换图形中的变量。在这种情况下,我还会考虑禁用图形优化,因为默认情况下,使用新的提要和获取集进行的第一个session.run调用会默认花费一些时间来优化图形(通过{内的RewriterConfig配置{1}}原型。

(从对问题的评论中展开)

答案 1 :(得分:0)

我不确定这是否能帮到您,但您需要知道在tensorflow中,变量仅针对给定的Session进行初始化。需要在每个使用的Session中初始化一个变量-即使在最简单的情况下也是如此:

import tensorflow as tf

x = tf.Variable(0.)

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    # x is initialized -- no issue here
    x.eval()

with tf.Session() as sess:
    x.eval()
    # Error -- x was never initialized in this session, even though
    # it has been initialized before in another session