您的问题确实需要很大一部分内存。这是一个演示,我使用了 2 个示例而不是 batch_size = 32 中的所有示例,
# input arrays to work with
In [2]: A = np.random.random_sample([32,1024,128])
In [3]: B = np.random.random_sample([32,1024,1024])
# inspect their memory usage
In [12]: A.nbytes/1000000
Out[12]: 33.554432 # ~ 33.5 Mb
In [13]: B.nbytes/1000000
Out[13]: 268.435456 # ~ 268 Mb
# your desired multiplication
In [14]: res = B[:2, ..., np.newaxis] * A[:2, :, np.newaxis, ...]
# desired shape of the output
In [15]: res.shape
Out[15]: (2, 1024, 1024, 128)
# inspect memory usage
In [16]: res.nbytes/1000000
Out[16]: 2147.483648 # ~ 2.1 GB
我对这些数组使用了float64。如果您负担不起这样的内存要求,降低内存使用量从而避免Out Of Memory 错误的一种方法是向下转换您的数组并使用单精度(即float32)数组。
您可以使用tf.expand_dims,而不是使用tf.tile(实际上通过多次复制原始张量来创建新张量)进行平铺,这在内存方面会更高效。
这是我首先要研究的两行优化。