创建一个张量原型,其内容大于2GB

Kae*_*ede 3 python tensorflow

我创建了一个大小为(2 ^ 22,256)的ndarray(W),并尝试使用以下数组作为权重矩阵的初始化:

w = tf.Variable(tf.convert_to_tensor(W))
Run Code Online (Sandbox Code Playgroud)

然后,tensorflow引发了一个错误: ValueError:无法创建内容大于2GB的张量原型。

我该如何解决这个问题?PS。我的权重矩阵必须使用该(2 ^ 22,256)矩阵进行初始化。谢谢 :)

Pat*_*wie 5

Protobuf的硬限制为2GB。2 ^ 22 * 256浮点数为4GB。您的问题是,您将通过以下方式将初始值嵌入到图形原型中:

import tensorflow as tf
import numpy as np

w_init = np.random.randn(2**22, 256).astype(np.float32)
w = tf.Variable(tf.convert_to_tensor(w_init))
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print sess.run(tf.reduce_sum(w))
Run Code Online (Sandbox Code Playgroud)

引起

ValueError: Cannot create a tensor proto whose content is larger than 2GB.
Run Code Online (Sandbox Code Playgroud)

上面的图形定义基本上是这样说的:“图形有一个占用4GB的变量,下面是确切值:...”

相反,您应该写

import tensorflow as tf
import numpy as np

w_init = np.random.randn(2**22, 256).astype(np.float32)
w_plhdr = tf.placeholder(dtype=tf.float32, shape=[2**22, 256])
w = tf.get_variable('w', [2**22, 256])
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run(w.assign(w_plhdr), {w_plhdr: w_init})
    print sess.run(tf.reduce_sum(w))
Run Code Online (Sandbox Code Playgroud)

这样,您的变量具有4GB的值,但是图形仅具有以下知识:“嘿,有一个大小为4 GB的变量。只是不在乎图形定义中的确切值。因为有一个覆盖操作这些值反正以后。”。