文章目錄
- 1. 介紹
- 2. 查詢和使用
1. 介紹
-
CPU設備意味著所有物理CPU和內存, 這意味著PyTorch的計算將嘗試使用所有CPU核心。可以用以下方式表示:
torch.device('cpu')
-
GPU設備只代表一個GPU和相應的顯存。
torch.device('cuda')
如果有多個GPU,我們使用以下方式表示第 i i i塊GPU(從0開始)
torch.device(f'cuda:{i}')
另外,
cuda:0
和cuda
是等價的,都是指第1塊顯卡。 -
深度學習框架要求計算的所有輸入數據都在同一設備上,無論是CPU還是GPU。
-
不經意地移動數據可能會顯著降低性能,框架通常會使用自己的線程來執行GPU計算,如果我們需要頻繁地切換到Python的主線程,那么這就可能會觸發全局解釋器鎖(GIL),導致GPU的計算被阻塞。
2. 查詢和使用
- 查詢可用GPU的數量
torch.cuda.device_count()
- 處理不存在GPU的情況
torch.device('cuda' if torch.cuda.is_available() else 'cpu')
- 查詢GPU列表
devices = [torch.device(f'cuda:{i}') for i in range(torch.cuda.device_count())] devices = if devices else [torch.device('cpu')]
- 查詢張量所在的設備。 默認情況下,張量是在CPU上創建的。
x = torch.tensor([1, 2, 3]) x.device
- 創建張量時指定存儲設備
x = torch.tensor([1, 2, 3], device=torch.device('cuda')) x.device
- 數據復制到其他設備
- CPU到GPU
x = torch.tensor([1, 2, 3]) x.cuda() # x.to(torch.device('cuda'))
- GPU到CPU
x = torch.tensor([1, 2, 3], device=torch.device('cuda')) x.cpu() # x.to(torch.device('cpu'))
- 多GPU的情況:指定要復制到的GPU的序號
x = torch.tensor([1, 2, 3]) x.cuda(i) # x.to(torch.device(f'cuda:{i}'))
- 模型復制到其他設備:與數據復制到其他設備的方法相同。
net = nn.Linear(2, 1) net.cuda() # net.to(torch.device('cuda'))