【问题标题】:How to reset initialization in TensorFlow 2如何在 TensorFlow 2 中重置初始化
【发布时间】:2020-01-06 17:27:43
【问题描述】:

如果我在初始化 tf.Variable 后尝试更改 TensorFlow 2 中的并行度,

import tensorflow as tf
_ = tf.Variable([1])
tf.config.threading.set_inter_op_parallelism_threads(1)

我收到一个错误

RuntimeError:初始化后无法修改 Inter op 并行度。

我理解为什么会这样,但它(以及可能的其他因素)导致我的测试相互干扰。例如

def test_model():  # this test
   v = tf.Variable([1])
   ...

def test_threading():  # is breaking this test
   tf.config.threading.set_inter_op_parallelism_threads(1)
   ...

如何重置 TensorFlow 状态以便设置线程?

【问题讨论】:

    标签: python tensorflow pytest tensorflow2.0


    【解决方案1】:

    这是可以通过“hacky”方式实现的。但我建议以正确的方式执行此操作(即在开始时设置配置)。

    import tensorflow as tf
    from tensorflow.python.eager import context
    
    _ = tf.Variable([1])
    
    context._context = None
    context._create_context()
    
    tf.config.threading.set_inter_op_parallelism_threads(1)
    

    编辑:开头设置config是什么意思,

    import tensorflow as tf
    from tensorflow.python.eager import context
    
    tf.config.threading.set_inter_op_parallelism_threads(1)
    _ = tf.Variable([1])
    
    

    但在某些情况下,您不能总是这样做。仅指出在tf 中设置配置的常规方式。因此,如果您的情况不允许您在开始时修复 tf.config,您必须重置您的 tf.eager.context,如上面的解决方案所示。

    【讨论】:

    • 您能否详细说明一开始的配置?
    • 我是说,首先设置所有必要的tf.config 属性,然后继续进行计算。在您的示例中,它将首先是 tf.config.threading....tf.Variable(...)。但我知道,根据您的情况,这可能是不可能的。只是建议尽可能坚持这种格式。
    • 我不明白您的建议是否(以及如何)可以清除上下文。你能在你的回答中解释一下吗?例如,我认为无法为tf.config.threadingtf.Variable 提供上下文
    • 请记住,我无法控制 tf config.threading...tf.Variable 的执行顺序:每个调用都在单独的测试中,顺序由测试运行者确定
    • 是的,正如我所说,那么我的第一点不适用于您。但我是说首先有tf.config,然后是你的tf Graph 相关组件和操作。但是我发布的解决方案应该适合你。
    猜你喜欢
    • 2017-09-15
    • 2018-11-09
    • 2016-12-21
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 2017-05-22
    • 2017-03-12
    • 2016-02-11
    相关资源
    最近更新 更多