I got RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x401408 and 32768x7)

username: Hamza_Malik
cooked: <p>I am new to deep learning<br>
I am trying to use this resnet model for my task but i am getting error</p>
<p>The error is<br>
return F.linear(input, self.weight, self.bias)<br>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>
RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x401408 and 32768x7)</p>
<p>The resnet code is below</p>
<pre><code class="lang-auto">class ResNet(nn.Module):

    def __init__(self, block, layers):
        self.inplanes = 64
        super(ResNet, self).__init__()
        # self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
        #                        bias=False)
        self.conv1 = nn.Conv2d(1, 64, kernel_size=3, stride=1, padding=1,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        # self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0], stride=2)
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
        # self.avgpool = nn.AvgPool2d(8, stride=1)
        # self.fc = nn.Linear(512 * block.expansion, num_classes)
        self.fc5 = nn.Linear(512 * 8 * 8, 7)


        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        # x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        # x = nn.AvgPool2d(kernel_size=x.size()[2:])(x)
        # x = self.avgpool(x)
        x = x.view(x.size(0), -1)  # Flatten the tensor, preserving the batch size
        x = self.fc5(x)

        return x
</code></pre>
<p>Can anyone tell me where is the error?</p>

username: ptrblck
cooked: <p>The <code>in_features</code> of <code>self.fc5</code> seem to be wrong and you might need to set them to <code>401408</code> instead.</p>

username: Hamza_Malik
cooked: <p>I resolve that error Now i got new error of the new file which is<br>
cosine = F.linear(F.normalize(input), F.normalize(self.weight))<br>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>
RuntimeError: mat1 and mat2 shapes cannot be multiplied (144x7 and 512x7)</p>
<p>The code is<br>
cosine = F.linear(F.normalize(input), F.normalize(self.weight))<br>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</p>
<pre><code class="lang-auto">class AddMarginProduct(nn.Module):
    r"""Implement of large margin cosine distance: :
    Args:
        in_features: size of each input sample
        out_features: size of each output sample
        s: norm of input feature
        m: margin
        cos(theta) - m
    """

    def __init__(self, in_features, out_features, s=30.0, m=0.40):
        super(AddMarginProduct, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.s = s
        self.m = m
        self.weight = Parameter(torch.FloatTensor(out_features, in_features))
        nn.init.xavier_uniform_(self.weight)
        

    def forward(self, input, label):
        # --------------------------- cos(theta) &amp; phi(theta) ---------------------------
        print('Input size:', input.size()) #input_shape -&gt; ([144,7])    means 144 rows and 7 coulms 
        print('Weight size:', self.weight.size()) #output_shape -&gt; ([512, 7])   means 512 rows and 7 columns
        
        #input contain the batch size and the input feature

        cosine = F.linear(F.normalize(input), F.normalize(self.weight))
        phi = cosine - self.m
        # --------------------------- convert label to one-hot ---------------------------
        one_hot = torch.zeros(cosine.size(), device='cuda')
        # one_hot = one_hot.cuda() if cosine.is_cuda else one_hot
        one_hot.scatter_(1, label.view(-1, 1).long(), 1)
        # -------------torch.where(out_i = {x_i if condition_i else y_i) -------------
        output = (one_hot * phi) + ((1.0 - one_hot) * cosine)  # you can use torch.where if your torch.__version__ is 0.4
        output *= self.s
        # print(output)

        return output
</code></pre>
<p>Can you help me to resolve it?</p>

username: ptrblck
cooked: <p>Your code works given the printed shapes:</p>
<pre><code class="lang-python">input = torch.randn(144, 7)
weight = torch.randn(512, 7)
cosine = F.linear(F.normalize(input), F.normalize(weight))
print(cosine.shape)
# torch.Size([144, 512])
</code></pre>
<p>so I guess your comment for the <code>weight</code> shape is wrong and you are transposing it:</p>
<pre><code class="lang-python">cosine = F.linear(F.normalize(input), F.normalize(weight.T))
# RuntimeError: mat1 and mat2 shapes cannot be multiplied (144x7 and 512x7)
</code></pre>

username: Hamza_Malik
cooked: <p>May be the comment is wrong<br>
But i don’t know why the error occurs and how to resolve it</p>
<p>This is error</p>
<pre><code class="lang-auto">    cosine = F.linear(F.normalize(input), F.normalize(self.weight))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: mat1 and mat2 shapes cannot be multiplied (144x7 and 512x7)
</code></pre>
<p>This is the code</p>
<pre><code class="lang-auto">class ArcMarginProduct(nn.Module):
    r"""Implement of large margin arc distance: :
        Args:
            in_features: size of each input sample
            out_features: size of each output sample
            s: norm of input feature
            m: margin

            cos(theta + m)
        """
    def __init__(self, in_features, out_features, s=30.0, m=0.50, easy_margin=False):
        super(ArcMarginProduct, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.s = s
        self.m = m
        self.weight = Parameter(torch.FloatTensor(out_features, in_features))
        nn.init.xavier_uniform_(self.weight)

        self.easy_margin = easy_margin
        self.cos_m = math.cos(m)
        self.sin_m = math.sin(m)
        self.th = math.cos(math.pi - m)
        self.mm = math.sin(math.pi - m) * m

    def forward(self, input, label):
        # --------------------------- cos(theta) &amp; phi(theta) ---------------------------

        cosine = F.linear(F.normalize(input), F.normalize(self.weight))
        sine = torch.sqrt((1.0 - torch.pow(cosine, 2)).clamp(0, 1))
        phi = cosine * self.cos_m - sine * self.sin_m
        if self.easy_margin:
            phi = torch.where(cosine &gt; 0, phi, cosine)
        else:
            phi = torch.where(cosine &gt; self.th, phi, cosine - self.mm)
        # --------------------------- convert label to one-hot ---------------------------
        # one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda')
        one_hot = torch.zeros(cosine.size(), device='cuda')
        one_hot.scatter_(1, label.view(-1, 1).long(), 1)
        # -------------torch.where(out_i = {x_i if condition_i else y_i) -------------
        output = (one_hot * phi) + ((1.0 - one_hot) * cosine)  # you can use torch.where if your torch.__version__ is 0.4
        output *= self.s
        # print(output)

        return output
</code></pre>
<p>Can you exactly tell where would i need to change the code?</p>

username: ptrblck
cooked: <p>You could transpose the <code>weight</code> as seen in my code snippet or, better, initialize <code>self.weight</code> as <code>Parameter(torch.empty(in_features, out_features))</code>.</p>

username: Hamza_Malik
cooked: <aside class="quote no-group" data-username="ptrblck" data-post="6" data-topic="183556">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>Parameter(torch.empty(in_features, out_features))</p>
</blockquote>
</aside>
<p>Ok thanks it working now</p>