一、传入cuda方式(torch)
1.1 .to(device)
可以指定CPU 或者GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 单GPU或者CPU
model.to(device)
#如果是多GPU
if torch.cuda.device_count() > 1:
model = nn.DataParallel(model,device_ids=[0,1,2])
model.to(device)
1.2 .cuda()
.cuda() 只能指定GPU
#指定某个GPU
os.environ['CUDA_VISIBLE_DEVICE']='1'
model.cuda()
#如果是多GPU
os.environment['CUDA_VISIBLE_DEVICES'] = '0,1,2,3'
device_ids = [0,1,2,3]
net = torch.nn.Dataparallel(net, device_ids =device_ids)
net = torch.nn.Dataparallel(net) # 默认使用所有的device_ids
net = net.cuda()
二、列表传入cuda
由于列表list没有cuda属性,要转为tensor
target = np.array(target)# list转numpy.array
target = torch.from_numpy(target) # array2tensor
三、CUDA的一些使用(torch)
1.DEVICE名
本人笔记本所带的GPU是GTX 1650
import torch
print(torch.cuda.get_device_name())
#GeForce GTX 1650
2.可用的GPU数量.
-Returns the number of GPUs available
import torch
print(torch.cuda.device_count())
3.目前GPU的序号
Returns the index of a currently selected device
import torch
print(torch.cuda.current_device())
4.某个tensor所在的DEVICE
import torch
x = torch.tensor([[1,2,3],[4,5,6]])
print(x.device)
#cpu
5.把tensor放进GPU中
5.1法一 在进行tensor变量命名的时候定义好DEVICE即可
import torch
x = torch.tensor([[1,2,3],[4,5,6]],device = torch.device('cuda'))
print(x.device)
#cuda:0
5.2法二 提前在外部定义好cuda,然后每次定义tensor的时候直接引用变量
import torch
cuda0 = torch.device('cuda:0')
x = torch.tensor([[1,2,3],[4,5,6]],device = cuda0)
print(x.device)
cuda:0
6.把CPU中的tensor转移到GPU中
应用tensor.to(device) 其中device应该是torch.device的对象
import torch
device0 = torch.device('cuda:0')
x = torch.rand((2,3))
print(x.device) #cpu
y = x.to(device0)
print(y.device) #cuda:0
7.神经网络中CUDA的使用
在网络计算中,参与计算的主要是两个部分,一个是模型的参数,一个是实际输入的训练数据。将这两部分的数据都移动到GPU中进行计算才能将网络搬移到GPU中
7.1 module.to(device)的用法
这句话的本质是将某一个模型的参数以tensor的形式输入到device中,这样参数的计算就是在GPU里面了
import torch
device = torch.device('cuda:0')
M = torch.nn.Linear(10,10)
M = M.to(device)
Linear(in_features=10, out_features=10, bias=True)
7.2将训练数据输入到GPU中
for batch_idx, (inputs, targets) in enumerate(trainloader):
inputs, targets = inputs.to(device), targets.to(device)






网友评论