File size: 5,714 Bytes
a10ce46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from functools import partial

import torch
import torch.nn as nn

from einops import rearrange
from torch.nn.init import trunc_normal_


def _make_lna_block(input_dim, output_dim, bias, norm_op, activation):
    layers = [nn.Linear(input_dim, output_dim, bias=bias)]
    if norm_op is not None:
        layers.append(norm_op(output_dim))
    if activation is not None:
        layers.append(activation())
    return nn.Sequential(*layers)


def _build_projector(n_layers, in_dim, out_dim, hidden_dim, activation=nn.GELU):
    norm_op = partial(nn.BatchNorm1d, track_running_stats=False)
    if n_layers > 1:
        layers = _make_lna_block(in_dim, hidden_dim, True, norm_op, activation)
        for _ in range(n_layers - 2):
            layers += _make_lna_block(hidden_dim, hidden_dim, True, norm_op, activation)
        layers += nn.Sequential(
            *[nn.Linear(hidden_dim, out_dim, bias=False), norm_op(out_dim)]
        )
        return nn.Sequential(*layers)
    else:
        layers = [nn.Linear(in_dim, out_dim, bias=False), norm_op(out_dim)]
        return nn.Sequential(*layers)


def _build_predictor(n_layers, in_out_dim, bottleneck_dim, activation=nn.GELU):
    norm_op = partial(nn.BatchNorm1d, track_running_stats=False)
    layers = [_make_lna_block(in_out_dim, bottleneck_dim, True, norm_op, activation)]

    for _ in range(n_layers - 1):
        layers += _make_lna_block(
            bottleneck_dim, bottleneck_dim, True, norm_op, activation
        )

    layers += _make_lna_block(bottleneck_dim, in_out_dim, False, None, None)
    return nn.Sequential(*layers)


class CVAHead(nn.Module):
    def __init__(

        self,

        in_dim,

        out_dim=1024,

        projector_layers=3,

        predictor_layers=1,

        hidden_dim=2048,

        bottleneck_dim=256,

        act_op=nn.GELU,

        use_predictor=True,

    ):
        super().__init__()
        projector_layers = max(projector_layers, 1)

        self.projector = _build_projector(
            projector_layers,
            in_dim,
            out_dim,
            hidden_dim=hidden_dim,
            activation=act_op,
        )

        if use_predictor:
            self.predictor = _build_predictor(
                predictor_layers,
                out_dim,
                bottleneck_dim,
                activation=act_op,
            )

        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, nn.Linear):
            trunc_normal_(m.weight, std=0.02)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.constant_(m.bias, 0)

    def project(self, latent):
        if latent.ndim == 2:
            return self.projector(latent)

        if latent.ndim == 4:
            # spatial_latent: (B, C, H, W)
            b, _, h, w = latent.shape
            flattened_latent = rearrange(latent, "b c h w -> (b h w) c").contiguous()

            proj = self.projector(flattened_latent)

            # make it spatial again
            return rearrange(proj, "(b h w) c -> b c h w", b=b, h=h, w=w).contiguous()

        if latent.ndim == 3:
            # (B, N, C)
            b, n, _ = latent.shape

            return self.projector(latent.flatten(0, 1)).unflatten(0, (b, n))

        raise ValueError(f"{latent.ndim=}D latent input is not supported")

    def predict(self, latent):
        if latent.ndim == 2:
            return self.predictor(self.projector(latent))

        if latent.ndim == 4:
            # spatial_latent: (B, C, H, W)
            b, _, h, w = latent.shape
            flattened_latent = rearrange(latent, "b c h w -> (b h w) c").contiguous()

            projection = self.projector(flattened_latent)
            pred = self.predictor(projection)

            # make it spatial again
            return rearrange(pred, "(b h w) c -> b c h w", b=b, h=h, w=w).contiguous()

        if latent.ndim == 3:
            # (B, N, C)
            b, n, _ = latent.shape
            return self.predictor(self.projector(latent.flatten(0, 1))).unflatten(
                0, (b, n)
            )

        raise ValueError(f"{latent.ndim=}D latent input is not supported")

    def project_predict(self, latent):
        projected = self.project(latent)
        predicted = self.predictor(projected)
        return projected, predicted

    def forward(self, latent, project_only=False):
        if project_only:
            return self.project(latent)

        return self.predict(latent)


class IdentityHead(torch.nn.Module):
    def __init__(self):
        super().__init__()

    def project(self, x):
        return x

    def predict(self, x):
        return x

    def project_predict(self, x):
        return x, x

    def forward(self, x, **kwargs):
        return x


class CVAHeadList(torch.nn.Module):
    def __init__(self, num_scales=2, **params):
        super().__init__()
        self.heads = torch.nn.ModuleList([CVAHead(**params) for _ in range(num_scales)])

    def forward(self, x, scale_idx, project_only=False):
        return self.heads[scale_idx](x, project_only=project_only)


if __name__ == "__main__":
    model = CVAHead(
        768,
        512,
        hidden_dim=2048,
        bottleneck_dim=256,
        act_op=nn.GELU,
    )
    print(model)
    x = torch.randn(2, 36, 768)
    out = model(x, project_only=True)

    print("Output shape:", out.shape)  # Expected: (2, 2048, 6, 6)
    out2 = model(x, project_only=False)
    print("Output shape after prediction:", out2.shape)  # Expected: (2, 2048, 6, 6)