TensorFlow总是(预先)分配我的显卡上的所有空闲内存(VRAM),这是可以的,因为我希望我的模拟在我的工作站上尽可能快地运行。
但是,我想记录一下TensorFlow实际使用了多少内存。此外,如果我还可以记录单张量使用了多少内存,那就太好了。
此信息对于测量和比较不同ML/AI架构所需的内存大小非常重要。
有什么建议吗?
发布于 2016-10-23 05:11:03
Update,可以使用TensorFlow操作查询分配器:
# maximum across all sessions and .run calls so far
sess.run(tf.contrib.memory_stats.MaxBytesInUse())
# current usage
sess.run(tf.contrib.memory_stats.BytesInUse())此外,您还可以通过查看RunMetadata获取有关session.run调用的详细信息,包括在run调用期间分配的所有内存。类似这样的东西
run_metadata = tf.RunMetadata()
sess.run(c, options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE, output_partition_graphs=True), run_metadata=run_metadata)这是一个端到端的例子--取列向量和行向量,然后将它们相加,得到一个加法矩阵:
import tensorflow as tf
no_opt = tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0,
do_common_subexpression_elimination=False,
do_function_inlining=False,
do_constant_folding=False)
config = tf.ConfigProto(graph_options=tf.GraphOptions(optimizer_options=no_opt),
log_device_placement=True, allow_soft_placement=False,
device_count={"CPU": 3},
inter_op_parallelism_threads=3,
intra_op_parallelism_threads=1)
sess = tf.Session(config=config)
with tf.device("cpu:0"):
a = tf.ones((13, 1))
with tf.device("cpu:1"):
b = tf.ones((1, 13))
with tf.device("cpu:2"):
c = a+b
sess = tf.Session(config=config)
run_metadata = tf.RunMetadata()
sess.run(c, options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE, output_partition_graphs=True), run_metadata=run_metadata)
with open("/tmp/run2.txt", "w") as out:
out.write(str(run_metadata))如果你打开run.txt,你会看到这样的消息:
node_name: "ones"
allocation_description {
requested_bytes: 52
allocator_name: "cpu"
ptr: 4322108320
}
....
node_name: "ones_1"
allocation_description {
requested_bytes: 52
allocator_name: "cpu"
ptr: 4322092992
}
...
node_name: "add"
allocation_description {
requested_bytes: 676
allocator_name: "cpu"
ptr: 4492163840因此,在这里可以看到,a和b分别分配了52字节(13*4),结果分配了676字节。
发布于 2020-12-23 20:33:41
雅罗斯拉夫·布拉托夫的答案是TF1的最佳解决方案。
但是,对于TF2,contrib包并不存在。最好的方法是使用tf的分析器-- https://www.tensorflow.org/guide/profiler#memory_profile_tool
它将绘制一个内存利用率图,如下所示。

https://stackoverflow.com/questions/40190510
复制相似问题