Whether I can build a new network using another network's children modules

I wonder if I can build a new network using another network’s children module like this:

list = [] 
modules = net.children()
for m in modules:
  list.append(m)
new_net = nn.ModuleList(list)

Will the new network be affected by the old network?

model2 = nn.Sequential(*list(model1.children()))

Will model2 and model1 share the same parameters if model2 is builded in this way?

Just try it.

src_net = nn.Sequential(nn.Conv2d(1, 1, 1), nn.Conv2d(1, 1, 1))
dst_net = nn.Sequential(*list(src_net.children()))

print(src_net[0].weight)
print(dst_net[0].weight)
print(id(src_net[0].weight) == id(dst_net[0].weight))  # True

src_net[0].weight.data = torch.rand(*src_net[0].weight.shape)
print(src_net[0].weight)
print(dst_net[0].weight)
1 Like