PyTorch 随机数生成占用 CPU 过高

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a463560470/article/details/82985905

PyTorch 随机数生成占用 CPU 过高

今天在使用 pytorch 的过程中,发现 CPU 占用率过高。经过检查,发现是因为先在 CPU 中生成了随机数,然后再调用.to(device)传到 GPU,这样导致效率变得很低,并且CPU 和 GPU 都被消耗。

查阅PyTorch文档后发现,torch.randn(shape, out)可以直接在GPU中生成随机数,只要shapetensor.cuda.Tensor类型即可。这样,就可以避免在 CPU 中生成过大的矩阵,而 shape 变量是很小的。因此,下面的代码就可以进行这种操作了。

noise = torch.cuda.FloatTensor(shape) if torch.cuda.is_available() else torch.FloatTensor(shape)
torch.randn(shape, out=noise)

猜你喜欢

转载自blog.csdn.net/a463560470/article/details/82985905