-
Notifications
You must be signed in to change notification settings - Fork 0
/
Encoder.py
238 lines (206 loc) · 8.91 KB
/
Encoder.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
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
import torch
from torch import nn
class Encoder(nn.Module):
"""
The encoder receives an input which contains for each series and time step:
* The series value at the time step, masked to zero if part of the values to be forecasted
* The mask
* The embedding for the series
* The embedding for the time step
And has already been through any input encoder.
The decoder returns an output containing an embedding for each series and time step.
"""
def __init__(
self,
attention_layers: int,
attention_heads: int,
attention_dim: int,
attention_feedforward_dim: int,
dropout: float = 0.1,
):
"""
Parameters:
-----------
attention_layers: int
How many successive attention layers this encoder will use.
attention_heads: int
How many independant heads the attention layer will have.
attention_dim: int
The size of the attention layer input and output, for each head.
attention_feedforward_dim: int
The dimension of the hidden layer in the feed forward step.
dropout: float, default to 0.1
Dropout parameter for the attention.
"""
super().__init__()
self.attention_layers = attention_layers
self.attention_heads = attention_heads
self.attention_dim = attention_dim
self.attention_feedforward_dim = attention_feedforward_dim
self.dropout = dropout
self.transformer_encoder = nn.TransformerEncoder(
nn.TransformerEncoderLayer(
self.attention_dim * self.attention_heads,
self.attention_heads,
self.attention_feedforward_dim,
self.dropout,
),
self.attention_layers,
)
@property
def embedding_dim(self) -> int:
"""
Returns:
--------
dim: int
The expected dimensionality of the input embedding, and the dimensionality of the output embedding
"""
return self.attention_dim * self.attention_heads
def forward(self, encoded: torch.Tensor) -> torch.Tensor:
"""
Compute the embedding for each series and time step.
Parameters:
-----------
encoded: Tensor [batch, series, time steps, input embedding dimension]
A tensor containing an embedding for each series and time step.
This embedding is expected to only contain local information, with no interaction between series or time steps.
Returns:
--------
output: torch.Tensor [batch, series, time steps, output embedding dimension]
The transformed embedding for each series and time step.
"""
num_batches = encoded.shape[0]
num_series = encoded.shape[1]
num_timesteps = encoded.shape[2]
# Merge the series and time steps, since the PyTorch attention implementation only accept three-dimensional input,
# and the attention is applied between all tokens, no matter their series or time step.
encoded = encoded.view(num_batches, num_series * num_timesteps, self.embedding_dim)
# The PyTorch implementation wants the following order: [tokens, batch, embedding]
encoded = encoded.transpose(0, 1)
output = self.transformer_encoder(
encoded, mask=torch.zeros(encoded.shape[0], encoded.shape[0], device=encoded.device)
)
# Reset to the original shape
output = output.transpose(0, 1)
output = output.view(num_batches, num_series, num_timesteps, self.embedding_dim)
return output
class TemporalEncoder(nn.Module):
"""
The encoder for TACTiS, based on the Temporal Transformer architecture.
This encoder alternate between doing self-attention between different series of the same time steps,
and doing self-attention between different time steps of the same series.
This greatly reduces the memory footprint compared to TACTiSEncoder.
The encoder receives an input which contains for each variable and time step:
* The series value at the time step, masked to zero if part of the values to be forecasted
* The mask
* The embedding for the series
* The embedding for the time step
And has already been through any input encoder.
The decoder returns an output containing an embedding for each series and time step.
"""
def __init__(
self,
attention_layers: int,
attention_heads: int,
attention_dim: int,
attention_feedforward_dim: int,
dropout: float = 0.1,
):
"""
Parameters:
-----------
attention_layers: int
How many successive attention pairs of layers this will use.
Note that the total number of layers is going to be the double of this number.
Each pair will consist of a layer with attention done over time steps,
followed by a layer with attention done over series.
attention_heads: int
How many independant heads the attention layer will have.
attention_dim: int
The size of the attention layer input and output, for each head.
attention_feedforward_dim: int
The dimension of the hidden layer in the feed forward step.
dropout: float, default to 0.1
Dropout parameter for the attention.
"""
super().__init__()
self.attention_layers = attention_layers
self.attention_heads = attention_heads
self.attention_dim = attention_dim
self.attention_feedforward_dim = attention_feedforward_dim
self.dropout = dropout
self.layer_timesteps = nn.ModuleList(
[
nn.TransformerEncoderLayer(
self.attention_dim * self.attention_heads,
self.attention_heads,
self.attention_feedforward_dim,
self.dropout,
)
for _ in range(self.attention_layers)
]
)
self.layer_series = nn.ModuleList(
[
nn.TransformerEncoderLayer(
self.attention_dim * self.attention_heads,
self.attention_heads,
self.attention_feedforward_dim,
self.dropout,
)
for _ in range(self.attention_layers)
]
)
@property
def embedding_dim(self) -> int:
"""
Returns:
--------
dim: int
The expected dimensionality of the input embedding, and the dimensionality of the output embedding
"""
return self.attention_dim * self.attention_heads
def forward(self, encoded: torch.Tensor) -> torch.Tensor:
"""
Compute the embedding for each series and time step.
Parameters:
-----------
encoded: Tensor [batch, series, time steps, input embedding dimension]
A tensor containing an embedding for each series and time step.
This embedding is expected to only contain local information, with no interaction between series or time steps.
Returns:
--------
output: torch.Tensor [batch, series, time steps, output embedding dimension]
The transformed embedding for each series and time step.
"""
num_batches = encoded.shape[0]
num_series = encoded.shape[1]
num_timesteps = encoded.shape[2]
data = encoded
for i in range(self.attention_layers):
# Treat the various series as a batch dimension
mod_timesteps = self.layer_timesteps[i]
# [batch, series, time steps, embedding]
data = data.flatten(start_dim=0, end_dim=1)
# [batch * series, time steps, embedding]
data = data.transpose(0, 1)
# [time steps, batch * series, embedding] Correct order for PyTorch module
data = mod_timesteps(data)
data = data.transpose(0, 1)
# [batch * series, time steps, embedding]
data = data.unflatten(dim=0, sizes=(num_batches, num_series))
# [batch, series, time steps, embedding]
# Treat the various time steps as a batch dimension
mod_series = self.layer_series[i]
data = data.transpose(0, 1)
# [series, batch, time steps, embedding]
data = data.flatten(start_dim=1, end_dim=2)
# [series, batch * time steps, embedding] Correct order for PyTorch module
data = mod_series(data)
data = data.unflatten(dim=1, sizes=(num_batches, num_timesteps))
# [series, batch, time steps, embedding]
data = data.transpose(0, 1)
# [batch, series, time steps, embedding]
# The resulting tensor may not be contiguous, which can cause problems further down the line.
output = data.contiguous()
return output