为什么`tf.constant()`的值在TensorFlow中多次存储在内存中?

Fra*_*urt 4 python tensorflow

读过(在TensorFlow中):

a的值tf.constant()在内存中多次存储.

为什么tf.constant()在内存中多次存储的值?

Yar*_*tov 8

因为常数张量的数据嵌入到图形定义中.这意味着这些数据既存储在维护图形定义的客户端中,也存储在运行时中,后者为所有张量分配自己的内存.

IE,试试

a = tf.constant([1,2])
tf.get_default_graph().as_graph_def()
Run Code Online (Sandbox Code Playgroud)

你会看到的

    dtype: DT_INT32
    tensor_shape {
      dim {
        size: 2
      }
    }
    tensor_content: "\001\000\000\000\002\000\000\000"
  }
Run Code Online (Sandbox Code Playgroud)

tensor_content字段是原始内容,与之相同np.array([1,2], dtype=np.int32).tobytes().

现在,要查看运行时分配,可以运行export TF_CPP_MIN_LOG_LEVEL=1.

如果你使用它评估任何东西,a你会看到这样的东西

2017-02-24 16:13:58: I tensorflow/core/framework/log_memory.cc:35] __LOG_MEMORY__ MemoryLogTensorOutput { step_id: 1 kernel_name: "Const_1/_1" tensor { dtype: DT_INT32 shape { dim { size: 2 } } allocation_description { requested_bytes: 8 allocated_bytes: 256 allocator_name: "cuda_host_bfc" allocation_id: 1 ptr: 8605532160 } } }
Run Code Online (Sandbox Code Playgroud)

这意味着运行时要求分配8个字节,TF实际分配256个字节.(关于实际分配的数据量的选择目前有些武断--bfc_allocator.cc)

在图中嵌入常量可以更容易地进行一些基于图形的优化,如常量折叠.但这也意味着大常数效率低下.此外,使用大常量是图表大小超过2GB限制的常见原因.