Python RuntimeError:预期所有张量都在同一个设备上,但至少找到两个设备,cuda:0和cpu!恢复训练时,

Python RuntimeError:预期所有张量都在同一个设备上,但至少找到两个设备,cuda:0和cpu!恢复训练时,,python,deep-learning,pytorch,runtime-error,Python,Deep Learning,Pytorch,Runtime Error,我在gpu上训练时保存了一个检查点。 在重新加载检查点并继续训练后,我得到以下错误 Traceback (most recent call last): File "main.py", line 140, in <module> train(model,optimizer,train_loader,val_loader,criteria=args.criterion,epoch=epoch,batch=batch) File "main.

我在gpu上训练时保存了一个检查点。 在重新加载检查点并继续训练后,我得到以下错误

Traceback (most recent call last):
  File "main.py", line 140, in <module>
    train(model,optimizer,train_loader,val_loader,criteria=args.criterion,epoch=epoch,batch=batch)
  File "main.py", line 71, in train
    optimizer.step()
  File "/opt/conda/lib/python3.7/site-packages/torch/autograd/grad_mode.py", line 26, in decorate_context
    return func(*args, **kwargs)
  File "/opt/conda/lib/python3.7/site-packages/torch/optim/sgd.py", line 106, in step
    buf.mul_(momentum).add_(d_p, alpha=1 - dampening)
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
我不明白为什么我会犯这个错误。 args.gpu==True,我将模型、所有数据和损失函数传递给cuda,不知怎么的,cpu上仍然有一个张量,有人能找出什么问题吗

谢谢。

如果设备参数处于打开状态,则可能会出现故障:

如果需要通过
.cuda()
将模型移动到GPU,请在为其构建优化器之前执行此操作。
.cuda()
之后的模型参数将与调用之前的参数是不同的对象。
通常,在构造和使用优化器时,应该确保优化参数位于一致的位置


问题似乎来自
标准(pred,target)
。你能检查一下预定时间和目标时间吗?
def train(model,optimizer,train_loader,val_loader,criteria,epoch=0,batch=0):
    batch_count = batch
    if criteria == 'l1':
        criterion = L1_imp_Loss()
    elif criteria == 'l2':
        criterion = L2_imp_Loss()
    if args.gpu and torch.cuda.is_available():
        model.cuda()
        criterion = criterion.cuda()

    print(f'{datetime.datetime.now().time().replace(microsecond=0)} Starting to train..')
    
    while epoch <= args.epochs-1:
        print(f'********{datetime.datetime.now().time().replace(microsecond=0)} Epoch#: {epoch+1} / {args.epochs}')
        model.train()
        interval_loss, total_loss= 0,0
        for i , (input,target) in enumerate(train_loader):
            batch_count += 1
            if args.gpu and torch.cuda.is_available():
                input, target = input.cuda(), target.cuda()
            input, target = input.float(), target.float()
            pred = model(input)
            loss = criterion(pred,target)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            ....
torch.save({'epoch': epoch,'batch':batch_count,'model_state_dict': model.state_dict(),'optimizer_state_dict':
                    optimizer.state_dict(),'loss': total_loss/len(train_loader),'train_set':args.train_set,'val_set':args.val_set,'args':args}, f'{args.weights_dir}/FastDepth_Final.pth')