Issue in printing model summary due to AttributeError: 'tuple' object has no attribute 'size'

username: hs99
cooked: <p>I HAVE the model code as:<br>
class RNN(nn.Module):<br>
“”“RNN module(cell type lstm or gru)”“”<br>
def <strong>init</strong>(<br>
self,<br>
input_size,<br>
hid_size,<br>
num_rnn_layers=1,<br>
dropout_p = 0.2,<br>
bidirectional = False,<br>
rnn_type = ‘lstm’,<br>
):<br>
super().<strong>init</strong>()</p>
<pre><code>    if rnn_type == 'lstm':
        self.rnn_layer = nn.LSTM(
            input_size=input_size,
            hidden_size=hid_size,
            num_layers=num_rnn_layers,
            dropout=dropout_p if num_rnn_layers&gt;1 else 0,
            bidirectional=bidirectional,
            batch_first=True,
        )
        
    else:
        self.rnn_layer = nn.GRU(
            input_size=input_size,
            hidden_size=hid_size,
            num_layers=num_rnn_layers,
            dropout=dropout_p if num_rnn_layers&gt;1 else 0,
            bidirectional=bidirectional,
            batch_first=True,
        )
def forward(self, input):
    outputs, hidden_states = self.rnn_layer(input)
    return outputs, hidden_states
</code></pre>
<hr>
<p>class RNNModel(nn.Module):<br>
def <strong>init</strong>(<br>
self,<br>
input_size,<br>
hid_size,<br>
rnn_type,<br>
bidirectional,<br>
n_classes=5,<br>
kernel_size=5,<br>
):<br>
super().<strong>init</strong>()</p>
<pre><code>    self.rnn_layer = RNN(
        input_size=46,#hid_size * 2 if bidirectional else hid_size,
        hid_size=hid_size,
        rnn_type=rnn_type,
        bidirectional=bidirectional
    )
    self.conv1 = ConvNormPool(
        input_size=input_size,
        hidden_size=hid_size,
        kernel_size=kernel_size,
    )
    self.conv2 = ConvNormPool(
        input_size=hid_size,
        hidden_size=hid_size,
        kernel_size=kernel_size,
    )
    self.avgpool = nn.AdaptiveAvgPool1d((1))
    self.fc = nn.Linear(in_features=hid_size, out_features=n_classes)

def forward(self, input):
    print("shape")
    print(input.shape) # **shape isshape torch.Size([32, 1, 187])**
    x = self.conv1(input)
    x = self.conv2(x)
    x, _ = self.rnn_layer(x)
    x = self.avgpool(x)
    x = x.view(-1, x.size(1) * x.size(2))
    x = F.softmax(self.fc(x), dim=1)#.squeeze(1)
    return x
</code></pre>
<hr>
<p>when I create <img src="https://discuss.pytorch.org/images/emoji/apple/sweat_smile.png?v=12" title=":sweat_smile:" class="emoji" alt=":sweat_smile:" loading="lazy" width="20" height="20"><br>
m1=RNNModel(1, 64, ‘lstm’, True).to(device)</p>
<p>and run</p>
<p><span class="hashtag-raw">#from</span> torchsummary import summary<br>
summary(m1,(1,187),32)</p>
<p>The following error raises:</p>
<hr>
<p>AttributeError                            Traceback (most recent call last)<br>
 in <br>
1 <span class="hashtag-raw">#from</span> torchsummary import summary<br>
----&gt; 2 summary(m1,(1,187),32)</p>
<p>/opt/conda/lib/python3.7/site-packages/torchsummary/torchsummary.py in summary(model, input_size, batch_size, device)<br>
70     # make a forward pass<br>
71     # print(x.shape)<br>
—&gt; 72     model(*x)<br>
73<br>
74     # remove these hooks</p>
<p>/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)<br>
725             result = self._slow_forward(*input, **kwargs)<br>
726         else:<br>
 → 727             result = self.forward(*input, **kwargs)<br>
728         for hook in itertools.chain(<br>
729                 _global_forward_hooks.values(),</p>
<p> in forward(self, input)<br>
35         x = self.conv1(input)<br>
36         x = self.conv2(x)<br>
—&gt; 37         x, _ = self.rnn_layer(x)<br>
38         x = self.avgpool(x)<br>
39         x = x.view(-1, x.size(1) * x.size(2))</p>
<p>/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)<br>
725             result = self._slow_forward(*input, **kwargs)<br>
726         else:<br>
 → 727             result = self.forward(*input, **kwargs)<br>
728         for hook in itertools.chain(<br>
729                 _global_forward_hooks.values(),</p>
<p> in forward(self, input)<br>
32             )<br>
33     def forward(self, input):<br>
—&gt; 34         outputs, hidden_states = self.rnn_layer(input)<br>
35         return outputs, hidden_states</p>
<p>/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)<br>
729                 _global_forward_hooks.values(),<br>
730                 self._forward_hooks.values()):<br>
 → 731             hook_result = hook(self, input, result)<br>
732             if hook_result is not None:<br>
733                 result = hook_result</p>
<p>/opt/conda/lib/python3.7/site-packages/torchsummary/torchsummary.py in hook(module, input, output)<br>
21             if isinstance(output, (list, tuple)):<br>
22                 summary[m_key][“output_shape”] = [<br>
—&gt; 23                     [-1] + list(o.size())[1:] for o in output<br>
24                 ]<br>
25             else:</p>
<p>/opt/conda/lib/python3.7/site-packages/torchsummary/torchsummary.py in (.0)<br>
21             if isinstance(output, (list, tuple)):<br>
22                 summary[m_key][“output_shape”] = [<br>
—&gt; 23                     [-1] + list(o.size())[1:] for o in output<br>
24                 ]<br>
25             else:</p>
<p>AttributeError: ‘tuple’ object has no attribute ‘size’</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/4/3/43f31e56291a725de6d36e36a886ba00818973e7.png" data-download-href="https://discuss.pytorch.org/uploads/default/43f31e56291a725de6d36e36a886ba00818973e7" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/4/3/43f31e56291a725de6d36e36a886ba00818973e7.png" alt="image" data-base62-sha1="9H6RUoi6ev9FX48n5fEwTcUbSaX" width="690" height="498" data-dominant-color="272D32"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">693×501 52.2 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>in frwd layer i have commented i/p shape also shape isshape torch.Size([32, 1, 187])**<br>
Batch size is 32<br>
Why is this so??Pls help</p>

username: ptrblck
cooked: <p>This seems to be a known <a href="https://github.com/sksq96/pytorch-summary/issues/33">issue</a> of <code>pytorch-summary</code>, which was fixed <a href="https://github.com/TylerYep/torchinfo">in a fork</a>.</p>

username: hs99
cooked: <p><a class="mention" href="/u/ptrblck">@ptrblck</a> can u pls tell me the actual fix…I am unable to find the exact solution in the fork?</p>

username: ptrblck
cooked: <p>I think the “fix” is to use the package from the forked repository:</p>
<pre><code class="lang-auto">pip install torchinfo
</code></pre>
<pre><code class="lang-python">from torchinfo import summary

model = ConvNet()
batch_size = 16
summary(model, input_size=(batch_size, 1, 28, 28))
</code></pre>

username: hs99
cooked: <p><a class="mention" href="/u/ptrblck">@ptrblck</a> i got another issue!!</p>
<pre><code class="lang-auto">
from torchinfo import summary
batch_size = 32
summary(m1, input_size=(32, 1, 187))
</code></pre>
<p>I am getting</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/opt/conda/lib/python3.7/site-packages/torchinfo/torchinfo.py in summary(model, input_size, input_data, batch_dim, col_names, col_width, depth, device, dtypes, verbose, **kwargs)
    159                 if isinstance(x, (list, tuple)):
--&gt; 160                     _ = model.to(device)(*x, **kwargs)
    161                 elif isinstance(x, dict):

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
    726         else:
--&gt; 727             result = self.forward(*input, **kwargs)
    728         for hook in itertools.chain(

&lt;ipython-input-49-26860265b2db&gt; in forward(self, input)
     36         x = self.conv2(x)
---&gt; 37         x, _ = self.rnn_layer(x)
     38         x = self.avgpool(x)

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
    726         else:
--&gt; 727             result = self.forward(*input, **kwargs)
    728         for hook in itertools.chain(

&lt;ipython-input-48-c383aa5a9c6e&gt; in forward(self, input)
     33     def forward(self, input):
---&gt; 34         outputs, hidden_states = self.rnn_layer(input)
     35         return outputs, hidden_states

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
    730                 self._forward_hooks.values()):
--&gt; 731             hook_result = hook(self, input, result)
    732             if hook_result is not None:

/opt/conda/lib/python3.7/site-packages/torchsummary/torchsummary.py in hook(module, input, output)
     22                 summary[m_key]["output_shape"] = [
---&gt; 23                     [-1] + list(o.size())[1:] for o in output
     24                 ]

/opt/conda/lib/python3.7/site-packages/torchsummary/torchsummary.py in &lt;listcomp&gt;(.0)
     22                 summary[m_key]["output_shape"] = [
---&gt; 23                     [-1] + list(o.size())[1:] for o in output
     24                 ]

AttributeError: 'tuple' object has no attribute 'size'

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
&lt;ipython-input-101-d16bdb924f0b&gt; in &lt;module&gt;
      1 from torchinfo import summary
      2 batch_size = 32
----&gt; 3 summary(m1, input_size=(32, 1, 187))

/opt/conda/lib/python3.7/site-packages/torchinfo/torchinfo.py in summary(model, input_size, input_data, batch_dim, col_names, col_width, depth, device, dtypes, verbose, **kwargs)
    170                 "Failed to run torchinfo. See above stack traces for more details. "
    171                 f"Executed layers up to: {executed_layers}"
--&gt; 172             ) from e
    173         finally:
    174             if hooks is not None:

RuntimeError: Failed to run torchinfo. See above stack traces for more details. Executed layers up to: [ConvNormPool: 1-1, Conv1d: 2-1, BatchNorm1d: 2-2, Swish: 2-3, Conv1d: 2-4, BatchNorm1d: 2-5, Swish: 2-6, Conv1d: 2-7, BatchNorm1d: 2-8, Swish: 2-9, MaxPool1d: 2-10, ConvNormPool: 1-2, Conv1d: 2-11, BatchNorm1d: 2-12, Swish: 2-13, Conv1d: 2-14, BatchNorm1d: 2-15, Swish: 2-16, Conv1d: 2-17, BatchNorm1d: 2-18, Swish: 2-19, MaxPool1d: 2-20]

</code></pre>
<p>Pls help me resolve this issue!!Its important!</p>