PyTorch 2.0 以下版本中設置默認使用 GPU 的方法
在 PyTorch 2.0以下版本中,默認情況下仍然是使用 CPU 進行計算,除非明確指定使用 GPU。在 PyTorch 2.0 以下版本中,雖然沒有 torch.set_default_device
的便捷方法,但可以通過顯式地將張量、模型和操作分配到 GPU 來使用 GPU。
1. 檢查 GPU 可用性
在使用 GPU 之前,首先檢查系統中是否有可用的 GPU。
import torch# 檢查是否有可用的 GPU
print(torch.cuda.is_available()) # 返回 True 或 False# 檢查可用 GPU 的數量
print(torch.cuda.device_count())# 當前 GPU 名稱
if torch.cuda.is_available():print(torch.cuda.get_device_name(0))
2. 將張量移動到 GPU
張量可以通過 .to('cuda')
或 .cuda()
方法顯式地移動到 GPU。
# 創建一個張量并將其移動到 GPU
x = torch.tensor([1.0, 2.0, 3.0])
x_gpu = x.to('cuda') # 或 x.cuda()
print(x_gpu.device) # 輸出:cuda:0# 在 GPU 上進行計算
y = x_gpu * 2
print(y) # 輸出在 GPU 上的結果
3. 將模型移動到 GPU
PyTorch 模型及其參數需要顯式地移動到 GPU。
# 定義一個簡單的模型
model = torch.nn.Linear(10, 1)# 將模型移動到 GPU
model = model.to('cuda') # 或 model.cuda()# 檢查模型參數所在的設備
print(next(model.parameters()).device) # 輸出:cuda:0
4. 確保輸入數據和模型在同一設備上
模型和輸入數據需要在同一個設備上,否則會報錯。
# 創建一個張量并移動到 GPU
input_data = torch.randn(5, 10).to('cuda')# 定義并移動模型到 GPU
model = torch.nn.Linear(10, 1).to('cuda')# 前向傳播
output = model(input_data)
print(output)
5. 使用 torch.device
動態管理設備
可以使用 torch.device
動態管理設備。
# 定義設備
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')# 將張量移動到設備
x = torch.tensor([1.0, 2.0, 3.0]).to(device)# 將模型移動到設備
model = torch.nn.Linear(10, 1).to(device)
6. 優化器和損失函數的設備兼容性
當使用 GPU 時,模型的輸出和目標(target)都需要在同一設備上。
# 創建數據和目標,并移動到 GPU
data = torch.randn(5, 10).to('cuda')
target = torch.randn(5, 1).to('cuda')# 定義模型并移動到 GPU
model = torch.nn.Linear(10, 1).to('cuda')# 定義損失函數
criterion = torch.nn.MSELoss()# 定義優化器
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)# 前向傳播
output = model(data)
loss = criterion(output, target)# 反向傳播
loss.backward()
optimizer.step()
7. 混合設備計算(可選)
在多 GPU 或混合 CPU/GPU 環境中,可以手動管理每個張量或模型的設備。
# 在 CPU 上創建張量
x_cpu = torch.tensor([1.0, 2.0, 3.0])# 在 GPU 上創建張量
x_gpu = x_cpu.to('cuda')# 將結果移動回 CPU
result = x_gpu * 2
result_cpu = result.to('cpu')
print(result_cpu)
總結
在 PyTorch 2.0 以下版本中,使用 GPU 的核心是 顯式地將張量和模型移動到 GPU,并確保所有相關操作在同一設備上完成。以下是核心方法的匯總:
-
檢查 GPU 可用性:
torch.cuda.is_available()
-
移動張量到 GPU:
.to('cuda')
或.cuda()
-
移動模型到 GPU:
.to('cuda')
或.cuda()
-
動態設備管理:
torch.device