总结Pytorch推理过程中的一些细节。
同步
优化手段
- 减少内存操作:尽量避免在循环或频繁调用的函数中创建和释放大量的
torch.Tensor
。 - 重复使用Tensor:在可能的情况下,尽量重复使用已经分配的
torch.Tensor
,而不是频繁地创建新的Tensor。 - 使用in-place操作:尽可能使用in-place操作,如
torch.Tensor.fill_()
或torch.Tensor.copy_()
,以减少内存分配。 - 手动释放内存:在不再需要的
torch.Tensor
上调用.detach()
或.detach_()
方法,手动释放内存。
相关资源
参考
- How to maximize CPU <==> GPU memory transfer speeds? - #7 by ptrblck - PyTorch Forums
- https://pytorch.org/docs/stable/torch_cuda_memory.html
- CUDA semantics — PyTorch 2.2 documentation
- PyTorch 有哪些坑/bug? - 知乎
- https://pytorch.org/tutorials/recipes/recipes/tuning_guide.html
- https://pytorch-dev-podcast.simplecast.com/episodes