forked from PaddlePaddle/Paddle3D
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_resnet.py
88 lines (83 loc) · 3.25 KB
/
custom_resnet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from paddle.vision.models.resnet import BasicBlock, BottleneckBlock
import paddle
from paddle import nn
from paddle3d.apis import manager
from paddle3d.models.layers import param_init, reset_parameters, constant_init
@manager.BACKBONES.add_component
class CustomResNet(nn.Layer):
def __init__(
self,
numC_input,
num_layer=[2, 2, 2],
num_channels=None,
stride=[2, 2, 2],
backbone_output_ids=None,
block_type='Basic',
):
super(CustomResNet, self).__init__()
# build backbone
assert len(num_layer) == len(stride)
num_channels = [numC_input*2**(i+1) for i in range(len(num_layer))] \
if num_channels is None else num_channels
self.backbone_output_ids = range(len(num_layer)) \
if backbone_output_ids is None else backbone_output_ids
layers = []
if block_type == 'BottleNeck':
curr_numC = numC_input
for i in range(len(num_layer)):
layer = [
BottleneckBlock(
curr_numC,
num_channels[i] // 4,
stride=stride[i],
downsample=nn.Conv2D(curr_numC, num_channels[i], 3,
stride[i], 1))
]
curr_numC = num_channels[i]
layer.extend([
BottleneckBlock(curr_numC, curr_numC // 4)
for _ in range(num_layer[i] - 1)
])
layers.append(nn.Sequential(*layer))
elif block_type == 'Basic':
curr_numC = numC_input
for i in range(len(num_layer)):
layer = [
BasicBlock(
curr_numC,
num_channels[i],
stride=stride[i],
downsample=nn.Conv2D(curr_numC, num_channels[i], 3,
stride[i], 1))
]
curr_numC = num_channels[i]
layer.extend([
BasicBlock(curr_numC, curr_numC)
for _ in range(num_layer[i] - 1)
])
layers.append(nn.Sequential(*layer))
else:
assert False
self.layers = nn.Sequential(*layers)
self.layers.apply(param_init.init_weight)
def forward(self, x):
feats = []
x_tmp = x
for lid, layer in enumerate(self.layers):
x_tmp = layer(x_tmp)
if lid in self.backbone_output_ids:
feats.append(x_tmp)
return feats