How to get a torch summary of a pre trained object detection model in pytorch?

Santhoshnumberone: <p>Checked out</p>
<h2>
<a name="sksq96httpsgithubcomsksq96pytorch-summaryhttpsgithubcomsksq96pytorch-summary-1" class="anchor" href="#sksq96httpsgithubcomsksq96pytorch-summaryhttpsgithubcomsksq96pytorch-summary-1"></a><a href="https://github.com/sksq96" rel="noopener nofollow ugc">sksq96</a>/<strong><a href="https://github.com/sksq96/pytorch-summary" rel="noopener nofollow ugc">pytorch-summary</a></strong>
</h2>
<p>Tried</p>
<pre><code class="lang-auto">import torch
from torchvision import models
from torchsummary import summary

model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
loaded_model = model().to(device)

summary(loaded_model, (3, 224, 224))
</code></pre>
<p>I get his error</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-60-39b645f0f2fc&gt; in &lt;module&gt;()
      5 model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False)
      6 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
----&gt; 7 loaded_model = model().to(device)
      8 
      9 summary(loaded_model, (3, 224, 224))

/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1108         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1109                 or _global_forward_hooks or _global_forward_pre_hooks):
-&gt; 1110             return forward_call(*input, **kwargs)
   1111         # Do not call functions when jit is used
   1112         full_backward_hooks, non_full_backward_hooks = [], []

TypeError: forward() missing 1 required positional argument: 'images'
</code></pre>
<p>What is going wrong? How do I correct it?</p>

Andrei_Cristea: <p>Should be:</p>
<pre><code class="lang-auto">model.to(device)
</code></pre>
<p>Then just run:</p>
<pre><code class="lang-auto">summary(loaded_model)

Output:
=================================================================
Layer (type:depth-idx)                   Param #
=================================================================
├─GeneralizedRCNNTransform: 1-1          --
├─BackboneWithFPN: 1-2                   --
|    └─IntermediateLayerGetter: 2-1      --
|    |    └─Conv2d: 3-1                  (9,408)
|    |    └─FrozenBatchNorm2d: 3-2       --
|    |    └─ReLU: 3-3                    --
|    |    └─MaxPool2d: 3-4               --
|    |    └─Sequential: 3-5              (212,992)
|    |    └─Sequential: 3-6              1,212,416
|    |    └─Sequential: 3-7              7,077,888
|    |    └─Sequential: 3-8              14,942,208
|    └─FeaturePyramidNetwork: 2-2        --
|    |    └─ModuleList: 3-9              984,064
|    |    └─ModuleList: 3-10             2,360,320
|    |    └─LastLevelMaxPool: 3-11       --
├─RegionProposalNetwork: 1-3             --
|    └─AnchorGenerator: 2-3              --
|    └─RPNHead: 2-4                      --
|    |    └─Conv2d: 3-12                 590,080
|    |    └─Conv2d: 3-13                 771
|    |    └─Conv2d: 3-14                 3,084
├─RoIHeads: 1-4                          --
|    └─MultiScaleRoIAlign: 2-5           --
|    └─TwoMLPHead: 2-6                   --
|    |    └─Linear: 3-15                 12,846,080
|    |    └─Linear: 3-16                 1,049,600
|    └─FastRCNNPredictor: 2-7            --
|    |    └─Linear: 3-17                 93,275
|    |    └─Linear: 3-18                 373,100
=================================================================
Total params: 41,755,286
Trainable params: 41,532,886
Non-trainable params: 222,400
=================================================================
</code></pre>

Santhoshnumberone: <aside class="quote no-group" data-username="Andrei_Cristea" data-post="2" data-topic="151089">
<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/andrei_cristea/48/47843_2.png" class="avatar"> Andrei_Cristea:</div>
<blockquote>
<p><code>model.to(device)</code></p>
</blockquote>
</aside>
<pre><code class="lang-auto">import torch
from torchsummary import summary

model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=False)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
loaded_model = model.to(device)

summary(loaded_model)
</code></pre>
<p>error</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-61-dc22bb1d5de8&gt; in &lt;module&gt;()
      6 loaded_model = model.to(device)
      7 
----&gt; 8 summary(loaded_model)

TypeError: summary() missing 1 required positional argument: 'input_size'
</code></pre>

Andrei_Cristea: <p>What version of torchsummary are you using? EDIT: <em>In most conventional setups</em>, you can check it by running, in a terminal: <code>pip list</code> and looking at the number next to <code>torch-summary</code>.</p>

Santhoshnumberone: <p>I did<br>
<code>!pip show torchsummary</code></p>
<p>I got</p>
<pre><code class="lang-auto">Name: torchsummary
Version: 1.5.1
Summary: Model summary in PyTorch similar to `model.summary()` in Keras
Home-page: https://github.com/sksq96/pytorch-summary
Author: Shubham Chandel @sksq96
Author-email: shubham.zeez@gmail.com
License: UNKNOWN
Location: /usr/local/lib/python3.7/dist-packages
Requires: 
Required-by: 
</code></pre>
<p>PS: Using google colab</p>

Andrei_Cristea: <p>Hmm, it looks like you might be using <a href="https://pypi.org/project/torchsummar" rel="noopener nofollow ugc">torchsummary</a> (one word) rather than <a href="https://pypi.org/project/torch-summary" rel="noopener nofollow ugc">torch-summary</a> (two words). The one you’re using looks like it was last updated in 2018, the other one was updated in 2020. Looking at the repo, it looks like they’ve now moved over to <a href="https://github.com/TylerYep/torchinfo" rel="noopener nofollow ugc">torchinfo</a>.</p>
<p>The readme for torchinfo presents this example use:</p>
<pre><code class="lang-auto">from torchinfo import summary

model = ConvNet()
batch_size = 16
summary(model, input_size=(batch_size, 1, 28, 28))
</code></pre>
<p>So perhaps you try installing torchinfo and using it like so:</p>
<pre><code class="lang-auto">from torchinfo import summary
summary(loaded_model, input_size=(1, 3, 224, 224))
</code></pre>

abuzar01440: <p>device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)</p>
<p>model = KthreeDUNet2().to(device)<br>
def count_parameters_and_size(model):<br>
# Count total parameters<br>
total_params = sum(p.numel() for p in model.parameters())</p>
<pre><code># Count trainable parameters
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
non_trainable_params = total_params - trainable_params
# Calculate model size in MB
# Each parameter is typically stored in float32 format (4 bytes)
model_size_bytes = total_params * 4  # 4 bytes per parameter
model_size_mb = model_size_bytes / (1024 * 1024)  # Convert to MB
model_size_gb = model_size_mb / 1024  # Convert to GB

return {
    'total_parameters': total_params,
    'trainable_parameters': trainable_params,
    "non_trainable_parameters" : non_trainable_params,
    'model_size_mb': model_size_mb, "model_size_gb": model_size_gb
}
</code></pre>
<h1><a name="p-466132-get-model-statistics-1" class="anchor" href="#p-466132-get-model-statistics-1"></a>Get model statistics</h1>
<p>stats = count_parameters_and_size(model)</p>
<h1><a name="p-466132-print-detailed-information-2" class="anchor" href="#p-466132-print-detailed-information-2"></a>Print detailed information</h1>
<p>print(f"Total Parameters: {stats[‘total_parameters’]:,}“)<br>
print(f"Trainable Parameters: {stats[‘trainable_parameters’]:,}”)<br>
print(f"Non-Trainable Parameters: {stats[‘non_trainable_parameters’]:,}“)<br>
print(f"Model Size: {stats[‘model_size_mb’]:.2f} MB”)<br>
print(f"Model Size in GB: {stats[‘model_size_gb’]:.2f} GB")</p>
<h1><a name="p-466132-for-more-detailed-parameter-count-by-layer-3" class="anchor" href="#p-466132-for-more-detailed-parameter-count-by-layer-3"></a>For more detailed parameter count by layer</h1>
<p>def print_model_parameters(model):<br>
print(“\nDetailed parameter count by layer:”)<br>
print(“-” * 80)<br>
print(f"{‘Layer’:&lt;40} {‘Parameters’:&gt;12} {‘Size (MB)’:&gt;12}“)<br>
print(”-" * 80)</p>
<pre><code>for name, parameter in model.named_parameters():
    params = parameter.numel()
    size_mb = (params * 4) / (1024 * 1024)  # size in MB
    size_gb = size_mb / 1024  # size in GB
    print(f"{name:&lt;40} {params:&gt;12,} {size_mb:&gt;12.2f} MB {size_gb:&gt;12.2f} GB")

print("-" * 80)
</code></pre>
<h1><a name="p-466132-print-detailed-parameter-count-by-layer-4" class="anchor" href="#p-466132-print-detailed-parameter-count-by-layer-4"></a>Print detailed parameter count by layer</h1>
<p>print_model_parameters(model)</p>