Modifying weights causes segmentation errors

I am trying to implement simplistic 2d Convolution but I end up having segmentation errors if I modify the weight of convolution

x = np.random.rand(100,100)
xtorch = torch.from_numpy(np.float32(im))
convfn = torch.nn.Conv2d(1,1,3,bias=False)
xvar = Variable(xtorch,requires_grad=True)
xout = convfn(xvar)

The above code works fine but if I update weight then I have segmentation error

x = np.random.rand(100,100)
xtorch = torch.from_numpy(np.float32(im))
xvar = Variable(xtorch,requires_grad=True)
weight = np.random.rand(3,3)
weighttorch = torch.from_numpy(np.float32(weight))
convfn = torch.nn.Conv2d(1,1,3,bias=False)
convfn.weight.data = weighttorch # this updates the weight properly with a float tensor
xout = convfn(xvar)

This above code throws a segmentation error though. What is the mistake that I am making here. How can I do simple 2d convolution using conv2d by getting an numpy data.

Your weight’s shape is wrong, it should be 4 dimensional (out_channels x in_channels/groups x kH x kW) as described http://pytorch.org/docs/master/nn.html#torch.nn.functional.conv2d. There was a change a while ago that prints clearer error information in such cases :slight_smile: