RuntimeError: Expected object of backend CPU but got backend CUDA for argument #2 'weight''

username: Omar2017
cooked: <p>anyone can guide me how to solve this issue? <img src="https://discuss.pytorch.org/images/emoji/apple/frowning.png?v=9" title=":frowning:" class="emoji" alt=":frowning:"></p>
<pre><code class="lang-auto">
Traceback (most recent call last):

  File "&lt;ipython-input-24-740ff909cca9&gt;", line 1, in &lt;module&gt;
    runfile('C:/Users/Windows10/Downloads/Hala3/main-run-vr.py', wdir='C:/Users/Windows10/Downloads/Hala3')

  File "C:\Users\Windows10\Anaconda3\envs\New\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\Windows10\Anaconda3\envs\New\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Windows10/Downloads/Hala3/main-run-vr.py", line 543, in &lt;module&gt;
    __main__()

  File "C:/Users/Windows10/Downloads/Hala3/main-run-vr.py", line 541, in __main__
    evalInterval, evalMode, numWorkers, outDir,modelUsed,pretrained,train_test_split,datasetDir,crossValidation,nFolds)

  File "C:/Users/Windows10/Downloads/Hala3/main-run-vr.py", line 416, in main_run
    model,accuracy=modelTrain(modelUsed,pretrained,trainDataset,trainLabels,validationDataset,validationLabels,numEpochs,evalInterval,evalMode,outDir,numWorkers,lr, stepSize, decayRate, trainBatchSize, seqLen,True)

  File "C:/Users/Windows10/Downloads/Hala3/main-run-vr.py", line 295, in modelTrain
    features = model(inputVariable1)

  File "C:\Users\Windows10\Anaconda3\envs\New\lib\site-packages\torch\nn\modules\module.py", line 493, in __call__
    result = self.forward(*input, **kwargs)

  File "C:\Users\Windows10\Downloads\Hala3\createModel.py", line 83, in forward
    x1 = self.convNet(x1)

  File "C:\Users\Windows10\Anaconda3\envs\New\lib\site-packages\torch\nn\modules\module.py", line 493, in __call__
    result = self.forward(*input, **kwargs)

  File "C:\Users\Windows10\Anaconda3\envs\New\lib\site-packages\torch\nn\modules\container.py", line 92, in forward
    input = module(input)

  File "C:\Users\Windows10\Anaconda3\envs\New\lib\site-packages\torch\nn\modules\module.py", line 493, in __call__
    result = self.forward(*input, **kwargs)

  File "C:\Users\Windows10\Anaconda3\envs\New\lib\site-packages\torch\nn\modules\container.py", line 92, in forward
    input = module(input)

  File "C:\Users\Windows10\Anaconda3\envs\New\lib\site-packages\torch\nn\modules\module.py", line 493, in __call__
    result = self.forward(*input, **kwargs)

  File "C:\Users\Windows10\Anaconda3\envs\New\lib\site-packages\torch\nn\modules\conv.py", line 338, in forward
    self.padding, self.dilation, self.groups)

RuntimeError: Expected object of backend CPU but got backend CUDA for argument #2 'weight'

</code></pre>
<p>model = ViolenceModel(modelUsed,pretrained)<br>
svclassifier = SVC(kernel=‘linear’)</p>
<pre><code>trainParams = []
for params in model.parameters():
    if params.requires_grad:
        trainParams += [params]
model.train(True)
if(torch.cuda.is_available()):
    model.cuda()

lossFn = nn.CrossEntropyLoss()
optimizerFn = torch.optim.RMSprop(trainParams, lr=lr)
optimizerFn.zero_grad()
optimScheduler = torch.optim.lr_scheduler.StepLR(optimizerFn, stepSize, decayRate)

minAccuracy = 50
train_loss=[]
val_loss=[]
train_acc=[]
val_acc=[]
bestmodel=None

for epoch in range(numEpochs):
    optimScheduler.step()
    epochLoss = 0
    numCorrTrain = 0
    iterPerEpoch = 0
    model.train(True)
    print('Epoch = {}'.format(epoch + 1))
    writer.add_scalar('lr', optimizerFn.param_groups[0]['lr'], epoch+1)
    for i, (inputs, targets) in enumerate(trainLoader):
        iterPerEpoch += 1
        optimizerFn.zero_grad()
        if(torch.cuda.is_available()):
            inputVariable1 = Variable(inputs.permute(1, 0, 2, 3, 4).cuda()).cpu()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
            labelVariable = Variable(targets.cuda()).cpu()
        
        else:
            inputVariable1=Variable(inputs.permute(1,0,2,3,4))
            labelVariable=Variable(targets)
        #outputLabel = model(inputVariable1)
        features = model(inputVariable1)
        svclassifier.fit(features, labelVariable)
        outputLabel= svclassifier.predict(inputVariable1)
        loss = lossFn(outputLabel, labelVariable)
        loss.backward()
        optimizerFn.step()
        #outputProb = torch.nn.Softmax(dim=1)(outputLabel)
        #_, predicted = torch.max(outputProb.data, 1)
        _, predicted= outputLabel
        if(torch.cuda.is_available()):
            numCorrTrain += (predicted == targets.cuda()).sum()
        else:
            numCorrTrain+=(predicted==targets).sum()
        epochLoss += loss.item()
</code></pre>
<pre><code class="lang-auto">class ViolenceModel(nn.Module):
    def __init__(self,modelused,pretrained):
        super(ViolenceModel, self).__init__()
        if modelused=='alexnet':
                self.mod=models.alexnet(pretrained=pretrained)
                self.convNet = nn.Sequential(*(list(self.mod.children()))[:-1])
                self.mem_size=256
                self.conv_lstm = ConvLSTMCell(256, self.mem_size)
        
        if pretrained:
            for param in self.convNet.parameters():
                param.requires_grad = False
  
    
    def forward(self, x):
        state = None
        seqLen = x.size(0) - 1
        for t in range(0, seqLen):
            x1 = x[t] - x[t+1]
            x1 = self.convNet(x1)
            x1=x1.cuda()
            state = self.conv_lstm(x1, state)
        
        x = self.maxpool(state[0])
        x= x.view(x.size(0), -1)
      
       # x = self.classifier(x)
        return x

</code></pre>
<p>thanks in advance <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>

username: ptrblck
cooked: <p>Your model parameters are on the GPU, while the input and target were copied to the GPU and then back to the CPU again:</p>
<pre><code class="lang-python">if(torch.cuda.is_available()):
    inputVariable1 = Variable(inputs.permute(1, 0, 2, 3, 4).cuda()).cpu()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
    labelVariable = Variable(targets.cuda()).cpu()
</code></pre>