File size: 8,644 Bytes
ec378c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
from torch import nn, Tensor
from einops import rearrange
from typing import Dict

import torch
from config import AutoConfig

from timm.layers.norm import LayerNorm2d
from timm.models.convnext import ConvNeXtBlock
from timm.layers.mlp import Mlp


class SimpleConvBlocks(nn.Module):
    def __init__(
        self,
        in_chs,
        out_chs,
        depth=3,
        kernel_size=5,
        max_dim=1024,
        stride=1,
        padding="same",
        norm_layer=LayerNorm2d,
        act=nn.SiLU,
        groups=1,
        bias=False,
        conv1x1=False,
        reduce_dim=False,
        skip_connection=True,
    ):
        super(SimpleConvBlocks, self).__init__()

        if isinstance(kernel_size, int):
            kernel_size = [kernel_size] * depth

        if reduce_dim:
            ch1 = min(in_chs, out_chs)
        else:
            ch1 = max(in_chs, out_chs)

        # ch1 = min(ch1, max_dim)

        layers = []
        self.reduce_dim = False
        if in_chs > max_dim:
            self.reduce_block = nn.Conv2d(in_chs, max_dim, 1, bias=False)
            in_chs = max_dim
            ch1 = max_dim
            self.reduce_dim = True

        # norm_shape = None
        # if norm_layer == nn.BatchNorm2d:
        #     norm_shape = ch1
        # if norm_layer == nn.LayerNorm:
        #     norm_shape = [ch1, 16, 16]  # not elegant

        for i in range(depth - 1):
            block = nn.Sequential(
                nn.Conv2d(
                    in_chs if i == 0 else ch1,
                    ch1,
                    kernel_size[i],
                    stride,
                    padding,
                    groups,
                    bias=bias,
                ),
                norm_layer(ch1),
                act(inplace=True),
            )
            layers.append(block)
        if not conv1x1:
            block = nn.Sequential(
                nn.Conv2d(
                    ch1, out_chs, kernel_size[-1], stride, padding, groups, bias=bias
                ),
                act(inplace=True),
            )
            layers.append(block)
        if conv1x1:
            block = nn.Sequential(
                nn.Conv2d(
                    ch1, ch1, kernel_size[-1], stride, padding, groups, bias=bias
                ),
                norm_layer(ch1),
                act(inplace=True),
                nn.Conv2d(ch1, out_chs, 1, bias=bias),
                act(inplace=True),
            )
            layers.append(block)

        self.block = nn.Sequential(*layers)

        self.skip_connection = skip_connection
        self.depth = depth

    def forward(self, x):
        if self.reduce_dim:
            x = self.reduce_block(x)

        for i, b in enumerate(self.block):
            x_prev = x
            x_next = b(x)
            if i < self.depth - 1:
                x = x_next + x_prev if self.skip_connection else x_next
            else:
                x = x_next
        return x


class ConvBlocks(nn.Module):
    def __init__(
        self,
        in_chs,
        out_chs,
        max_dim=1024,
        depth=3,
        kernel_size=5,
    ):
        super().__init__()

        dim = min(in_chs, max_dim)

        self.blocks = []
        for i in range(depth):
            _in_chs = in_chs if i == 0 else dim
            norm_layer = None  # defaults to LayerNorm
            # if i == depth - 1 and skip_last_norm:
            # norm_layer = nn.Identity
            self.blocks.append(
                ConvNeXtBlock(_in_chs, dim, kernel_size,
                              norm_layer=norm_layer),
            )
        self.blocks.append(nn.Conv2d(dim, out_chs, 3, padding="same"))
        self.blocks.append(nn.GELU())
        self.blocks = nn.Sequential(*self.blocks)

    def forward(self, x: Tensor):
        return self.blocks(x)


class DictConvBlocks(nn.Module):
    def __init__(
        self,
        layers=[5, 11, 17, 23],
        in_dims=[1024, 1024, 1024, 1024],
        out_dim=256,
        max_dim=1024,
        kernel_sizes=[5, 5, 5, 5],
        depths=[3, 3, 3, 3],
        block=ConvBlocks,
    ):
        super().__init__()

        self.blocks_dict = nn.ModuleDict()
        for i, layer in enumerate(layers):
            self.blocks_dict[str(layer)] = block(
                in_dims[i],
                out_dim,
                max_dim=max_dim,
                depth=depths[i],
                kernel_size=kernel_sizes[i],
            )

    def forward(self, x: Dict[str, Tensor]):
        for layer, block in self.blocks_dict.items():
            x[layer] = block(x[layer])
        return x


def build_conv_blocks(cfg: AutoConfig):
    return DictConvBlocks(
        layers=cfg.MODEL.BACKBONE.LAYERS,
        in_dims=cfg.MODEL.BACKBONE.FEATURE_DIMS,
        out_dim=cfg.MODEL.CONV_HEAD.WIDTH,
        max_dim=cfg.MODEL.CONV_HEAD.MAX_DIM,
        kernel_sizes=cfg.MODEL.CONV_HEAD.KERNEL_SIZES,
        depths=cfg.MODEL.CONV_HEAD.DEPTHS,
        block=SimpleConvBlocks if cfg.MODEL.CONV_HEAD.SIMPLE else ConvBlocks,
    )


class ClassTokenMLPs(nn.Module):
    def __init__(
        self,
        layers=[5, 11, 17, 23],
        in_dims=[1024, 1024, 1024, 1024],
        out_dim=256,
    ):
        super().__init__()

        self.mlp_dict = nn.ModuleDict()
        for i, layer in enumerate(layers):
            self.mlp_dict[str(layer)] = Mlp(
                in_features=in_dims[i], out_features=out_dim
            )

    def forward(self, x: Dict[str, Tensor]):
        for layer, mlp in self.mlp_dict.items():
            x[layer] = mlp(x[layer])
        return x


def build_class_token_mlp(cfg: AutoConfig):
    return ClassTokenMLPs(
        layers=cfg.MODEL.BACKBONE.LAYERS,
        in_dims=cfg.MODEL.BACKBONE.CLS_DIMS,
        out_dim=cfg.MODEL.CONV_HEAD.WIDTH,
    )


def build_class_token_mlp_prev(cfg: AutoConfig):
    return ClassTokenMLPs(
        layers=cfg.MODEL.BACKBONE_SMALL.LAYERS,
        in_dims=cfg.MODEL.BACKBONE_SMALL.CLS_DIMS,
        out_dim=cfg.MODEL.BACKBONE_SMALL.WIDTH,
    )

class PreviousFeatureMLPs(nn.Module):
    def __init__(
        self,
        feat_dim=1024,
        c_dim=256,
        t_dim=128,
        out_dim=256,
    ):
        super().__init__()

        self.mlp = Mlp(
            in_features=feat_dim + c_dim + t_dim,
            out_features=out_dim,
        )
        self.feature_dim = feat_dim
        self.c_dim = c_dim
        self.t_dim = t_dim
        
        
    def forward(self, x: Tensor, t: Tensor, c: Tensor=None):
        bsz, tsz, _ = x.shape
        t = rearrange(t, "(b t) c -> b t c", b=bsz)
        tsz = t.shape[1]
        if c is None:
            c = torch.zeros(bsz, tsz, self.c_dim, device=x.device)
        else:
            c = rearrange(c, "(b t) c -> b t c", b=bsz)
        x = torch.cat([x, c, t], dim=-1)
        return self.mlp(x)

def build_prev_feat_mlp(cfg: AutoConfig):
    return PreviousFeatureMLPs(
        feat_dim=cfg.MODEL.PREV_FEAT.DIM,
        c_dim=cfg.MODEL.COND.DIM,
        t_dim=cfg.MODEL.BACKBONE_SMALL.T_DIM,
        out_dim=cfg.MODEL.BACKBONE_SMALL.WIDTH,
    )

class SubjectPreviousFrameCompress(nn.Module):
    def __init__(
        self,
        num_time_steps,
        in_width,
        merge_width,
        subject_list,
        hidden_ratio=4,
    ):
        super().__init__()
        self.subject_list = subject_list
        self.hidden_dim = int(merge_width * hidden_ratio)
        self.t = num_time_steps

        self.subject_layer = nn.ModuleDict()
        for subject in self.subject_list:
            self.subject_layer[subject] = nn.Sequential(
                nn.Linear(int(in_width * num_time_steps), self.hidden_dim),
                nn.GELU(),
            )
        self.merge_layer = Mlp(self.hidden_dim, out_features=merge_width)

    def forward(
        self,
        x: Tensor,  # [(B T), C]
        subject: str,
    ):
        x = rearrange(x, "b t c -> b (t c)", t=self.t)
        x = self.subject_layer[subject](x)
        x = self.merge_layer(x)
        return x


def build_prev_compress(cfg: AutoConfig):
    return SubjectPreviousFrameCompress(
        num_time_steps=cfg.DATASET.N_PREV_FRAMES-1,
        in_width=cfg.MODEL.BACKBONE_SMALL.WIDTH,
        merge_width=cfg.MODEL.BACKBONE_SMALL.MERGE_WIDTH,
        subject_list=cfg.DATASET.SUBJECT_LIST,
        hidden_ratio=4,
    )

def build_ftr_compress(cfg: AutoConfig):
    return SubjectPreviousFrameCompress(
        num_time_steps=cfg.DATASET.N_FTR_FRAMES-1,
        in_width=cfg.MODEL.BACKBONE_SMALL.WIDTH,
        merge_width=cfg.MODEL.BACKBONE_SMALL.MERGE_WIDTH,
        subject_list=cfg.DATASET.SUBJECT_LIST,
        hidden_ratio=4,
    )