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

R.y*_*yan 5 python tensorflow

我有一个关于InteractiveSessionTensorflow的问题

我知道tf.InteractiveSession()这只是用于保持默认会话打开的方便语法糖,并且基本上与下面的工作方式相同:

with tf.Session() as sess:
    # Do something
Run Code Online (Sandbox Code Playgroud)

但是,我在网上看到了一些例子,他们close()在使用InteractiveSession.

问题
1. 不关闭会话会导致什么问题,比如会话泄漏?
2. 如果不关闭 InteractiveSession,GC 是如何工作的?

Pat*_*wie 6

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

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()))
Run Code Online (Sandbox Code Playgroud)

"""
python example_session2.py interactive
('bytes used=', 405776640)
python example_session2.py interactive_close
('bytes used=', 7680)
python example_session2.py
('bytes used=', 7680)
"""
Run Code Online (Sandbox Code Playgroud)

当不关闭会话时,这会引起会话泄漏。请注意,即使在关闭会话时,TensorFlow 中当前也存在错误,每个会话保持 1280 字节,是否看到Tensorflow 在每个会话打开和关闭时泄漏 1280 字节?. (现在已修复)。

此外,__del__尝试启动 GC有一些逻辑。

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

交互式会话已处于活动状态。在某些情况下,这可能会导致内存不足错误。您必须明确调用InteractiveSession.close()以释放其他会话持有的资源

这似乎被实施了。它猜测 InteractiveSession 的唯一存在理由是它在 Jupyter Notebookfiles 或不活动的 shell 中与.eval(). 但我建议不要使用 eval (请参阅官方 ZeroOut 渐变示例错误: AttributeError: 'list' object has no attribute 'eval'

但是,我在网上看到了一些例子,他们在使用InteractiveSession后并没有在代码末尾调用close()。

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