How to replace layers in a pretrained fasterrcnn_resnet50_fpn

I have developed a customized SpecialConv2d layer that is mostly the same as nn.Conv2d, but does a couple extra things.

I would like to replace all nn.Conv2d layers in a pretrained Faster-RCNN instance with SpecialConv2d, but there doesn’t seem to be a .features property that I can access. How would I go about doing that?

import torchvision
import torch
import specialconv

frcnn = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)

# I'd like to iterate over everything in frcnn
# and replace all torch.nn.Conv2d layers
# with specialconv.SpecialConv2d layers

Thanks so much!

Hi,

A naive way of copying can be done as follows. Assume we have to copy model1 layer l1 to model2 layer l1.

model2.l1.weight = model1.l1.weight
model2.l1.bias = model1.l1.bias

l1 is a layer name. Use your layer names.

There may be better ways of doing. Let’s wait for others to reply.

Thanks
Regards
Pranavan

This is just what I wanted.

An example would be

import torchvision
import torch
import specialconv

frcnn = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
prev_weight = frcnn.backbone.body.conv1.weight
prev_bias = frcnn.backbone.body.conv1.bias
new_layer = SpecialConv2d(...) # make sure args match
new_layer.weight = prev_weight
new_bias = prev_bias
frcnn.backbone.body.conv1 = new_layer
1 Like