Error for affine_grid_generator when using 5D tensor

I have a tensor size of 1x2x32x32x32. I want to feed it into spatial transformation network using the tutorial in pytorch. I have change the size of fc based on my input size. The final size before send to the grid = F.affine_grid(theta, x.size()) is

theta: (1,6)
x (1,2,32,32,32)

However, I got the error. How should I fix it? You can run my code in the colab at

ret = torch.affine_grid_generator(theta, size)
RuntimeError: invalid argument 6: wrong matrix size at /opt/conda/conda-bld/pytorch-nightly_1555305720252/work/aten/src/THC/generic/
This is my code

from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import numpy as np

plt.ion()   # interactive mode
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # Spatial transformer localization-network
        self.localization = nn.Sequential(
            nn.Conv3d(2, 8, kernel_size=7),
            nn.MaxPool3d(2, stride=2),
            nn.Conv3d(8, 10, kernel_size=5),
            nn.MaxPool3d(2, stride=2),
        # Regressor for the 3 * 2 affine matrix
        self.fc_loc = nn.Sequential(
            nn.Linear(10 * 4 * 4 * 4, 32),
            nn.Linear(32, 3 * 2)

        # Initialize the weights/bias with identity transformation
        self.fc_loc[2][1, 0, 0, 0, 1, 0], dtype=torch.float))

    # Spatial transformer network forward function
    def stn(self, x):
        xs = self.localization(x)
        print (xs.size())
        xs = xs.view(-1, 10 * 4 * 4 * 4)        
        theta = self.fc_loc(xs)
        theta = theta.view(-1, 2, 3)
        grid = F.affine_grid(theta, x.size())
        x = F.grid_sample(x, grid)
        return x

    def forward(self, x):
        # transform the input
        x = self.stn(x)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = Net().to(device)
x =  torch.rand(1,2,32,32,32).to(device)
print('Input shape', x.shape)
x_stn = model(x)

Ok. I fixed it. It should be theta = theta.view(-1, 3, 4)

Do you have an explanation for this ? it works for me too but i’m not able to understand it