1 查看当前的device
输入情况:
1
2
|
import torch print ( "Default Device : {}" . format (torch.Tensor([ 4 , 5 , 6 ]).device)) |
输出情况:
Default Device : cpu
2 cpu设备可以使用“cpu:0”来指定
输入情况
1
2
|
device = torch.Tensor([ 1 , 2 , 3 ], device = "cpu:0" ).device print ( "Device Type: {}" . format (device)) |
输出情况
Device Type: cpu
3 gpu设备可以使用“cuda:0”来指定
输入情况
1
2
|
gpu = torch.device( "cuda:0" ) print ( "GPU Device:【{}:{}】" . format (gpu. type , gpu.index)) |
输出情况
GPU Device:【cuda:0】
4 查询CPU和GPU设备数量
输入情况
1
2
|
print ( "Total GPU Count :{}" . format (torch.cuda.device_count())) print ( "Total CPU Count :{}" . format (torch.cuda.os.cpu_count())) |
输出情况
Total GPU Count :1
Total CPU Count :8
5 从CPU设备上转换到GPU设备
5.1 torch.Tensor方法默认使用CPU设备
输入情况
1
2
|
data = torch.Tensor([[ 1 , 4 , 7 ], [ 3 , 6 , 9 ], [ 2 , 5 , 8 ]]) print (data.shape) |
输出情况
torch.Size([3, 3])
5.2 使用to方法将cpu的Tensor转换到GPU设备上
输入情况:
1
2
|
data_gpu = data.to(torch.device( "cuda:0" )) print (data_gpu.device) |
输出情况:
cuda:0
5.3 使用.cuda方法将cpu的Tensor转换到GPU设备上
输入情况:
1
2
3
|
data_gpu2 = data.cuda(torch.device( "cuda:0" )) # 如果只有一块gpu的话 直接写成这样:data_gpu2 = data.cuda() print (data_gpu2.device) |
输出情况:
cuda:0
到此这篇关于PyTorch device与cuda.device用法的文章就介绍到这了,更多相关PyTorch device使用内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_42521185/article/details/123913221