File size: 8,524 Bytes
801501a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
307
308
309
"""
Implementation of time conditioned Transformer.
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F


class PositionalEncoding(nn.Module):
    def __init__(self, d_hid, n_position=200):
        super(PositionalEncoding, self).__init__()

        # Not a parameter
        self.register_buffer(
            "pos_table", self._get_sinusoid_encoding_table(n_position, d_hid)
        )

    def _get_sinusoid_encoding_table(self, n_position, d_hid):
        """Sinusoid position encoding table"""
        # TODO: make it with torch instead of numpy

        def get_position_angle_vec(position):
            return [
                position / np.power(10000, 2 * (hid_j // 2) / d_hid)
                for hid_j in range(d_hid)
            ]

        sinusoid_table = np.array(
            [get_position_angle_vec(pos_i) for pos_i in range(n_position)]
        )
        sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2])  # dim 2i
        sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2])  # dim 2i+1

        return torch.FloatTensor(sinusoid_table).unsqueeze(0)

    def forward(self, x):
        """
        Input:
            x: [B,N,D]
        """
        return x + self.pos_table[:, : x.size(1)].clone().detach()


class ConcatSquashLinear(nn.Module):
    def __init__(self, dim_in, dim_out, dim_ctx):
        super(ConcatSquashLinear, self).__init__()
        self._layer = nn.Linear(dim_in, dim_out)
        self._hyper_bias = nn.Linear(dim_ctx, dim_out, bias=False)
        self._hyper_gate = nn.Linear(dim_ctx, dim_out)

    def forward(self, ctx, x):
        assert ctx.dim() == x.dim()
        gate = torch.sigmoid(self._hyper_gate(ctx))
        bias = self._hyper_bias(ctx)
        ret = self._layer(x) * gate + bias
        return ret


class TimeMLP(nn.Module):
    def __init__(
        self,
        dim_in,
        dim_h,
        dim_out,
        dim_ctx=None,
        act=F.relu,
        dropout=0.0,
        use_time=False,
    ):
        super().__init__()
        self.act = act
        self.use_time = use_time

        dim_h = int(dim_h)
        if use_time:
            self.fc1 = ConcatSquashLinear(dim_in, dim_h, dim_ctx)
            self.fc2 = ConcatSquashLinear(dim_h, dim_out, dim_ctx)
        else:
            self.fc1 = nn.Linear(dim_in, dim_h)
            self.fc2 = nn.Linear(dim_h, dim_out)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x, ctx=None):
        if self.use_time:
            x = self.fc1(x=x, ctx=ctx)
        else:
            x = self.fc1(x)

        x = self.act(x)
        x = self.dropout(x)
        if self.use_time:
            x = self.fc2(x=x, ctx=ctx)
        else:
            x = self.fc2(x)

        x = self.dropout(x)
        return x


class MultiHeadAttention(nn.Module):
    def __init__(self, dim_self, dim_ref, num_heads, dropout=0.0):
        super().__init__()
        self.num_heads = num_heads
        head_dim = dim_self // num_heads
        self.scale = head_dim**-0.5
        self.to_queries = nn.Linear(dim_self, dim_self)
        self.to_keys_values = nn.Linear(dim_ref, dim_self * 2)
        self.project = nn.Linear(dim_self, dim_self)
        self.dropout = nn.Dropout(dropout)

    def forward(
        self,
        x,
        y=None,
        mask=None,
        alpha=None,
    ):
        y = y if y is not None else x
        b_a, n, c = x.shape
        b, m, d = y.shape
        # b n h dh
        queries = self.to_queries(x).reshape(
            b_a, n, self.num_heads, c // self.num_heads
        )
        # b m 2 h dh
        keys_values = self.to_keys_values(y).reshape(
            b, m, 2, self.num_heads, c // self.num_heads
        )
        keys, values = keys_values[:, :, 0], keys_values[:, :, 1]
        if alpha is not None:
            out, attention = self.forward_interpolation(
                queries, keys, values, alpha, mask
            )
        else:
            attention = torch.einsum("bnhd,bmhd->bnmh", queries, keys) * self.scale
            if mask is not None:
                if mask.dim() == 2:
                    mask = mask.unsqueeze(1)
                attention = attention.masked_fill(mask.unsqueeze(3), float("-inf"))
            attention = attention.softmax(dim=2)
            attention = self.dropout(attention)
            out = torch.einsum("bnmh,bmhd->bnhd", attention, values).reshape(b, n, c)
        out = self.project(out)
        return out, attention


class TimeTransformerEncoderLayer(nn.Module):
    def __init__(
        self,
        dim_self,
        dim_ctx=None,
        num_heads=1,
        mlp_ratio=2.0,
        act=F.leaky_relu,
        dropout=0.0,
        use_time=True,
    ):
        super().__init__()
        self.use_time = use_time
        self.act = act
        self.attn = MultiHeadAttention(dim_self, dim_self, num_heads, dropout)
        self.attn_norm = nn.LayerNorm(dim_self)

        mlp_ratio = int(mlp_ratio)
        self.mlp = TimeMLP(
            dim_self, dim_self * mlp_ratio, dim_self, dim_ctx, use_time=use_time
        )
        self.norm = nn.LayerNorm(dim_self)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x, ctx=None):
        res = x
        x, attn = self.attn(x)
        x = self.attn_norm(x + res)

        res = x
        x = self.mlp(x, ctx=ctx)
        x = self.norm(x + res)

        return x, attn


class TimeTransformerDecoderLayer(TimeTransformerEncoderLayer):
    def __init__(
        self,
        dim_self,
        dim_ref,
        dim_ctx=None,
        num_heads=1,
        mlp_ratio=2,
        act=F.leaky_relu,
        dropout=0.0,
        use_time=True,
    ):
        super().__init__(
            dim_self=dim_self,
            dim_ctx=dim_ctx,
            num_heads=num_heads,
            mlp_ratio=mlp_ratio,
            act=act,
            dropout=dropout,
            use_time=use_time,
        )
        self.cross_attn = MultiHeadAttention(dim_self, dim_ref, num_heads, dropout)
        self.cross_attn_norm = nn.LayerNorm(dim_self)

    def forward(self, x, y, ctx=None):
        res = x
        x, attn = self.attn(x)
        x = self.attn_norm(x + res)

        res = x
        x, attn = self.cross_attn(x, y)
        x = self.cross_attn_norm(x + res)

        res = x
        x = self.mlp(x, ctx=ctx)
        x = self.norm(x + res)

        return x, attn


class TimeTransformerEncoder(nn.Module):
    def __init__(
        self,
        dim_self,
        dim_ctx=None,
        num_heads=1,
        mlp_ratio=2.0,
        act=F.leaky_relu,
        dropout=0.0,
        use_time=True,
        num_layers=3,
        last_fc=False,
        last_fc_dim_out=None,
    ):
        super().__init__()
        self.last_fc = last_fc
        if last_fc:
            self.fc = nn.Linear(dim_self, last_fc_dim_out)
        self.layers = nn.ModuleList(
            [
                TimeTransformerEncoderLayer(
                    dim_self,
                    dim_ctx=dim_ctx,
                    num_heads=num_heads,
                    mlp_ratio=mlp_ratio,
                    act=act,
                    dropout=dropout,
                    use_time=use_time,
                )
                for _ in range(num_layers)
            ]
        )

    def forward(self, x, ctx=None):
        for i, layer in enumerate(self.layers):
            x, attn = layer(x, ctx=ctx)

        if self.last_fc:
            x = self.fc(x)
        return x


class TimeTransformerDecoder(nn.Module):
    def __init__(
        self,
        dim_self,
        dim_ref,
        dim_ctx=None,
        num_heads=1,
        mlp_ratio=2.0,
        act=F.leaky_relu,
        dropout=0.0,
        use_time=True,
        num_layers=3,
        last_fc=True,
        last_fc_dim_out=None,
    ):
        super().__init__()
        self.last_fc = last_fc
        if last_fc:
            self.fc = nn.Linear(dim_self, last_fc_dim_out)

        self.layers = nn.ModuleList(
            [
                TimeTransformerDecoderLayer(
                    dim_self,
                    dim_ref,
                    dim_ctx,
                    num_heads,
                    mlp_ratio,
                    act,
                    dropout,
                    use_time,
                )
                for _ in range(num_layers)
            ]
        )

    def forward(self, x, y, ctx=None):
        for i, layer in enumerate(self.layers):
            x, attn = layer(x, y=y, ctx=ctx)
        if self.last_fc:
            x = self.fc(x)

        return x