【问题标题】:does tensorflow convert_to_tensor do memory copy?tensorflow convert_to_tensor 做内存复制吗?
【发布时间】:2018-05-11 05:09:58
【问题描述】:

我正在创建一个基于 ndarray 列表对象的 tensorflow 常量。我的理解是张量本身不会对底层数据进行内存复制,而是使用相同的底层 ndarray 数据创建一个 python 对象。但是,在运行了一个小测试之后,似乎它确实复制了数据

def mem_test():
  printMemUsed("before r list")
  r = ['Supporter'] * 100000000
  printMemUsed("after r list")
  r_arr = np.array(r)
  printMemUsed("after nd_array")
  tf.convert_to_tensor(r_arr)
  printMemUsed("after tensor conversion")

def printMemUsed(discript):
    print("{}:\t{}".format(discript, psutil.virtual_memory().used))

这是输出:

before r list:  727310336 -> 727 Mb
after r list:   1528782848 -> 1.5 GB
after nd_array: 2430574592 -> 2.4 GB
after tensor conversion:        8925667328 -> 8.9 GB

编辑:r_arr 的 dtype 为“S9”(以空结尾的字符串)。将输入数组元素更改为 'unicode' (U9) 类型后,在 nd_array 之后虚拟内存消耗高达 5 GB

【问题讨论】:

  • r_arrdtypeconvert 的结果是什么? convert_to_tensor 没有提及是否复制;你在哪里读到的?
  • r_arr 的 dtype 是 S9 并且 tensorflow 的 dtype 是恒定的。我读到 tensorflow 不会复制数据,而只是在底层数据周围创建一个包装器/数据结构

标签: python numpy tensorflow


【解决方案1】:

tf.convert_to_tensor 使用 _tensor_conversion_func_registry 是为不同的输入类型注册的转换函数。对于 Python 列表、元组和 numpy nd.arrays,这发生在 constant_op.py 中。 并根据this 回答tf.constant 创建至少两个副本。

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

因为常量张量的数据嵌入到图形定义中。这意味着这些数据同时存储在客户端(维护图形定义)和运行时(为所有张量分配它自己的内存)中:

编辑:

根据this 的回答,一种选择是使用tf.Variable 并使用tf.placeholder 对其进行初始化。

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 1970-01-01
    • 2012-04-17
    • 2011-10-29
    • 2016-12-01
    • 1970-01-01
    • 2017-08-19
    • 2016-10-28
    • 2010-12-12
    相关资源
    最近更新 更多