i am a new user of pytorch. During my study, i found my model work on CPU, but when i try to train it on
GPU, it doest work, and i don
t know why… Can anybody help me?
Following issues:
class Net(nn.Module):
def __init__(self):
super(Net,self).__init__()
self.conv1=nn.Conv2d(3,6,5)
self.conv2=nn.Conv2d(6,16,5)
self.fc1=nn.Linear(16*5*5,120)
self.fc2=nn.Linear(120,84)
self.fc3=nn.Linear(84,10)
def forward(self,x):
x=F.max_pool2d(F.relu(self.conv1(x)),(2,2))
x=F.max_pool2d(F.relu(self.conv2(x)),2)
x=x.view(x.size()[0],-1)
x=F.relu(self.fc1(x))
x=F.relu(self.fc2(x))
x=self.fc3(x)
return x
net=Net()
print(net)
for epoch in range(2):
running_loss=0.0
for i,data in enumerate(trainloader,0):
inputs,labels=data
inputs,labels=Variable(inputs),Variable(labels)
optimizer.zero_grad()
outputs=net(inputs)
loss=criterion(outputs,labels)
loss.backward()
optimizer.step()
running_loss+=loss.item()
if i%2000==1999:
print('[%5d %5d] loss: %.3f'%(epoch+1,i+1,running_loss/2000))
running_loss=0.0
print('Finished Training')
It train work,and results:
[ 1 2000] loss: 2.198
[ 1 4000] loss: 1.879
[ 1 6000] loss: 1.690
[ 1 8000] loss: 1.579
[ 1 10000] loss: 1.514
[ 1 12000] loss: 1.476
[ 2 2000] loss: 1.405
[ 2 4000] loss: 1.384
[ 2 6000] loss: 1.340
[ 2 8000] loss: 1.352
[ 2 10000] loss: 1.296
[ 2 12000] loss: 1.302
Finished Training
but when on GPU:
device=t.device("cuda:0"if t.cuda.is_available() else "cpu")
net=net.to(device)
for epoch in range(2):
running_loss=0.0
for i,data in enumerate(trainloader,0):
inputs,labels=data
inputs, labels= inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs=net(inputs)
loss=criterion(outputs,labels)
loss.backward()
optimizer.step()
running_loss+=loss.item()
if i%2000==1999:
print('[%5d %5d] loss: %.3f'%(epoch+1,i+1,running_loss/2000))
running_loss=0.0
print('Finished Training')
It doesn`t work,and results:
[ 1 2000] loss: 2.304
[ 1 4000] loss: 2.305
[ 1 6000] loss: 2.306
[ 1 8000] loss: 2.304
[ 1 10000] loss: 2.304
[ 1 12000] loss: 2.304
[ 2 2000] loss: 2.305
[ 2 4000] loss: 2.305
[ 2 6000] loss: 2.305
[ 2 8000] loss: 2.305
[ 2 10000] loss: 2.303
[ 2 12000] loss: 2.305
Finished Training
And i don`t know why.