在tensorflow InteractiveSession()之后是否需要关闭会话

2024-06-01 20:32:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于Tensorflow中InteractiveSession的问题

我知道tf.InteractiveSession()只是方便的语法 sugar用于保持默认会话打开,其基本工作原理如下:

with tf.Session() as sess:
    # Do something

然而,我在网上看到了一些例子,它们在使用InteractiveSession之后没有在代码末尾调用close()

问题
一。如果不关闭会话之类的会话泄漏,是否会导致任何问题?
2。如果我们不关闭GC,它如何为交互会话工作?


Tags: 代码sessiontftensorflowaswith语法sugar
1条回答
网友
1楼 · 发布于 2024-06-01 20:32:32

是的,tf.InteractiveSession只是保持默认会话打开的方便语法糖。

会话实现有a comment

Calling this method frees all resources associated with the session.

快速测试

#! /usr/bin/env python
# -*- coding: utf-8 -*-


import argparse
import tensorflow as tf
import numpy as np


def open_interactive_session():
    A = tf.Variable(np.random.randn(16, 255, 255, 3).astype(np.float32))
    sess = tf.InteractiveSession()
    sess.run(tf.global_variables_initializer())


def open_and_close_interactive_session():
    A = tf.Variable(np.random.randn(16, 255, 255, 3).astype(np.float32))
    sess = tf.InteractiveSession()
    sess.run(tf.global_variables_initializer())
    sess.close()


def open_and_close_session():
    A = tf.Variable(np.random.randn(16, 255, 255, 3).astype(np.float32))
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--num', help='repeat', type=int, default=5)
    parser.add_argument('type', choices=['interactive', 'interactive_close', 'normal'])
    args = parser.parse_args()

    sess_func = open_and_close_session

    if args.type == 'interactive':
        sess_func = open_interactive_session
    elif args.type == 'interactive_close':
        sess_func = open_and_close_interactive_session

    for _ in range(args.num):
        sess_func()
    with tf.Session() as sess:
        print("bytes used=", sess.run(tf.contrib.memory_stats.BytesInUse()))

给予

"""
python example_session2.py interactive
('bytes used=', 405776640)
python example_session2.py interactive_close
('bytes used=', 7680)
python example_session2.py
('bytes used=', 7680)
"""

这会在未关闭会话时引发会话泄漏。注意,即使在关闭会话时,TensorFlow中当前也存在一个错误,该错误在每个会话中保留1280字节请参见Tensorflow leaks 1280 bytes with each session opened and closed?(现在已修复)。

此外,试图启动GC的^{}中有一些逻辑。

有趣的是,我从来没有看到过警告

An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call InteractiveSession.close() to release resources held by the other session(s)

好像是implemented。它猜测交互会话唯一存在的理由是它在Jupyter notebook文件或非活动shell中与.eval()结合使用。但我建议不要使用eval(参见Official ZeroOut gradient example error: AttributeError: 'list' object has no attribute 'eval'

However, I have seen some examples online, they did't call close() at the end of the code after using InteractiveSession.

我对此并不感到惊讶。猜猜在一些malloc之后没有freedelete的代码片段有多少。祝福操作系统释放内存。

相关问题 更多 >