草庐IT

python - tensorflow 服务器 : I don't want to initialize global variables for every session

coder 2023-08-13 原文

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

我将调查内存泄漏,如果它消失了,请关闭此问题。

编辑:添加了问题的简单可重现示例:

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


背景:我正在运行 Tensorflow 服务器,并从“ fork ”进程连接到它。动态创建(和销毁)进程对我来说很重要——我把高负载的部分代码移到了那里,因为 weird memory leak ,对 Python 分析器不可见(线程不能解决问题)。因此,我希望进程能够快速初始化并立即开始工作。只有当进程被销毁时,内存才会被释放。

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

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

因此,我认为修改模型会使 Python 对子进程进行大量 pickle('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)]]

提前致谢!

最佳答案

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

通常您希望缓存 session ,我相信这是 TF 服务使用的策略。这将是迄今为止将 TF 模型部署到数据中心的最佳体验。

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

但如果您真的想创建和销毁 session ,您可以用常量 ("freeze" it) 替换图中的变量。在这种情况下,我还会考虑禁用图优化,因为使用一组新的提要和提取的第一个 session.run 调用默认会花一些时间优化图(通过 配置GraphOptions 原型(prototype)中的 RewriterConfig

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

关于python - tensorflow 服务器 : I don't want to initialize global variables for every session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52700621/

有关python - tensorflow 服务器 : I don't want to initialize global variables for every session的更多相关文章

随机推荐