在不复制内存的情况下重复 pytorch 张量 [英] Repeating a pytorch tensor without copying memory

查看:34
本文介绍了在不复制内存的情况下重复 pytorch 张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pytorch 是否支持重复张量而不分配更多内存?

假设我们有一个张量

t = torch.ones((1,1000,1000))
t10 = t.repeat(10,1,1)

重复 t 10 次将需要 10 倍的内存.有没有办法在不分配更多内存的情况下创建张量 t10?

Repeating t 10 times will require take 10x the memory. Is there a way how I can create a tensor t10 without allocating significantly more memory?

这里是一个相关的问题,但没有答案.

Here is a related question, but without answers.

推荐答案

您可以使用 torch.expand

t = torch.ones((1, 1000, 1000))
t10 = t.expand(10, 1000, 1000)

请记住,t10 只是对 t 的引用.因此,例如,对 t10[0,0,0] 的更改将导致 t[0,0,0] 的每个成员发生相同的更改>t10[:,0,0].

Keep in mind that the t10 is just a reference to t. So for example, a change to t10[0,0,0] will result in the same change in t[0,0,0] and every member of t10[:,0,0].

除了直接访问之外,在 t10 上执行的大多数操作都会导致内存被复制,这将破坏引用并导致使用更多内存.例如:改变设备(.cpu(), .to(device=...), .cuda()),改变数据类型(.float().long().to(dtype=...)),或使用.contiguous().

Other than direct access, most operations performed on t10 will cause memory to be copied which will break the reference and cause more memory to be used. For example: changing the device (.cpu(), .to(device=...), .cuda()), changing the datatype (.float(), .long(), .to(dtype=...)), or using .contiguous().

这篇关于在不复制内存的情况下重复 pytorch 张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆