使用常量初始化时,Tensorflow使用太多内存

A__A

我最近注意到了一件奇怪的事情,在使用常量初始化变量时,Tensorflow似乎使用了过多的内存。有人可以帮助我理解以下示例吗?

$ python -m memory_profiler test.py 
[0 1 2 3 4 5 6 7 8 9]
Filename: test.py

Line #    Mem usage    Increment   Line Contents
================================================
 4  144.531 MiB    0.000 MiB   @profile
 5                             def go():
 6  907.312 MiB  762.781 MiB    a = np.arange(100000000)
 7  910.980 MiB    3.668 MiB    s = tf.Session()
 8 1674.133 MiB  763.152 MiB    b = tf.Variable(a)
 9 3963.000 MiB 2288.867 MiB    s.run(tf.variables_initializer([b]))
10 3963.145 MiB    0.145 MiB    print(s.run(b)[:10])
雅罗斯拉夫·布拉托夫(Yaroslav Bulatov)
  • 您有900MB存储在numpy数组中。
  • tf.Variable(a)等同于tf.Variable(tf.constant(a))。为了创建此常量,Python客户端在Python运行时中将900MB常量附加到Graph对象
  • Session.run会触发TF_ExtendGraph,它将图转移到TensorFlow C运行时,另外900MB
  • 会话b tf.Variable在TensorFlow运行时中对象分配900MB

这样就分配了3600MB的内存。为了节省内存,您可以执行以下操作

a_holder = tf.placeholder(np.float32)
b = tf.Variable(a_holder)
sess.run(b.initializer, feed_dict={a_holder: np.arange(100000000)})

TLDR;避免创建大常量。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章