RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False

my code see GitHub - weili1457355863/VPS-Net: A vacant parking slot detection method in the around view image based on deep learning.
it runs well on pytorch 1.7 with cuda,or with CPU on a laptop
device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)
device = “cpu”
ps_detect =PsDetect(opt.model_def, opt.weights_path_yolo, opt.img_size, device)
vps_classify = vpsClassify(opt.weights_path_vps, device)
when I used cpu to run this code in pytorch 1.8 on the other laptop
#device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)
device = “cpu”
ps_detect =PsDetect(opt.model_def, opt.weights_path_yolo, opt.img_size, device)
vps_classify = vpsClassify(opt.weights_path_vps, device)

an error happens,

the code attempts to run on GPU:
vpsClassify calls CustomizedAlexNet()
class vpsClassify(object):
def init(self, model_path, device):
self.model_customized = CustomizedAlexNet()
self.model_customized.eval()
self.model_customized.load(model_path)
self.model_customized.to(device)

CustomizedAlexNet() calls BasicModule
class CustomizedAlexNet(BasicModule):
def init(self, num_classes=2):
super(CustomizedAlexNet, self).init()

BasicModule is based on nn Module
class BasicModule(nn.Module):
def init(self):
super(BasicModule,self).init()
def load(self,path):
self.load_state_dict(torch.load(path))

in load function of BasicModule(), device is no specified, until in init of vpsClassify( self.model_customized.to(device))

what is the problem for pytorch1.8? this code runs well on pytorch 1.7

Did you try to add the suggested map_location argument to torch.load as given in the error message?

Yes I do. by adding mp_location to torch.load, the problem is solved. What puzzled me is that if I don’t specify mp_location in torch.load while specifying it in outer class which call torch.load, Pytorch1.7 run well, Pytorch1.8 report the error, it implys that torch.load in Pytorch1.8 attemtps to load to GPU, and Pytorch1.7 not.