-
Notifications
You must be signed in to change notification settings - Fork 0
/
temporal.py
889 lines (790 loc) · 38.9 KB
/
temporal.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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
"""
The temporal fusion transformer is a powerful predictive model for forecasting timeseries
"""
from copy import copy
from typing import Dict, List, Tuple, Union
from matplotlib import pyplot as plt
import numpy as np
import torch
from torch import nn
from torchmetrics import Metric as LightningMetric
from pytorch_forecasting.data import TimeSeriesDataSet
from pytorch_forecasting.data.encoders import NaNLabelEncoder
from pytorch_forecasting.metrics import MAE, MAPE, MASE, RMSE, SMAPE, MultiHorizonMetric, MultiLoss
from pytorch_forecasting.models.base_model import BaseModelWithCovariates
from pytorch_forecasting.models.nn import LSTM
# from pytorch_forecasting.models.temporal_fusion_transformer.sub_modules import (
# AddNorm,
# GateAddNorm,
# GatedLinearUnit,
# GatedResidualNetwork,
# InterpretableMultiHeadAttention,
# VariableSelectionNetwork,
# )
from pytorch_forecasting.utils import autocorrelation, create_mask, detach, integer_histogram, padded_stack, to_list
# Dev
from quantile_loss import QuantileLoss
from embeddings import MultiEmbedding
from sub_modules import (
AddNorm,
GateAddNorm,
GatedLinearUnit,
GatedResidualNetwork,
InterpretableMultiHeadAttention,
VariableSelectionNetwork,
)
class TemporalFusionTransformer(nn.Module):
def __init__(
self,
batch_size: int,
device = 'cpu',
wrapper = None,
hparams = None,
hidden_size: int = 16,
lstm_layers: int = 1,
dropout: float = 0.1,
output_size: Union[int, List[int]] = 7,
loss: MultiHorizonMetric = None,
attention_head_size: int = 4,
max_encoder_length: int = 10,
static_categoricals: List[str] = [],
static_reals: List[str] = [],
time_varying_categoricals_encoder: List[str] = [],
time_varying_categoricals_decoder: List[str] = [],
categorical_groups: Dict[str, List[str]] = {},
time_varying_reals_encoder: List[str] = [],
time_varying_reals_decoder: List[str] = [],
x_reals: List[str] = [],
x_categoricals: List[str] = [],
hidden_continuous_size: int = 8,
hidden_continuous_sizes: Dict[str, int] = {},
embedding_sizes: Dict[str, Tuple[int, int]] = {},
embedding_paddings: List[str] = [],
embedding_labels: Dict[str, np.ndarray] = {},
learning_rate: float = 1e-3,
log_interval: Union[int, float] = -1,
log_val_interval: Union[int, float] = None,
log_gradient_flow: bool = False,
reduce_on_plateau_patience: int = 1000,
monotone_constaints: Dict[str, int] = {},
share_single_variable_networks: bool = False,
logging_metrics: nn.ModuleList = None,
**kwargs,
):
"""
Temporal Fusion Transformer for forecasting timeseries - use its :py:meth:`~from_dataset` method if possible.
Implementation of the article
`Temporal Fusion Transformers for Interpretable Multi-horizon Time Series
Forecasting <https://arxiv.org/pdf/1912.09363.pdf>`_. The network outperforms DeepAR by Amazon by 36-69%
in benchmarks.
Enhancements compared to the original implementation (apart from capabilities added through base model
such as monotone constraints):
* static variables can be continuous
* multiple categorical variables can be summarized with an EmbeddingBag
* variable encoder and decoder length by sample
* categorical embeddings are not transformed by variable selection network (because it is a redundant operation)
* variable dimension in variable selection network are scaled up via linear interpolation to reduce
number of parameters
* non-linear variable processing in variable selection network can be shared among decoder and encoder
(not shared by default)
Tune its hyperparameters with
:py:func:`~pytorch_forecasting.models.temporal_fusion_transformer.tuning.optimize_hyperparameters`.
Args:
hidden_size: hidden size of network which is its main hyperparameter and can range from 8 to 512
lstm_layers: number of LSTM layers (2 is mostly optimal)
dropout: dropout rate
output_size: number of outputs (e.g. number of quantiles for QuantileLoss and one target or list
of output sizes).
loss: loss function taking prediction and targets
attention_head_size: number of attention heads (4 is a good default)
max_encoder_length: length to encode (can be far longer than the decoder length but does not have to be)
static_categoricals: names of static categorical variables
static_reals: names of static continuous variables
time_varying_categoricals_encoder: names of categorical variables for encoder
time_varying_categoricals_decoder: names of categorical variables for decoder
time_varying_reals_encoder: names of continuous variables for encoder
time_varying_reals_decoder: names of continuous variables for decoder
categorical_groups: dictionary where values
are list of categorical variables that are forming together a new categorical
variable which is the key in the dictionary
x_reals: order of continuous variables in tensor passed to forward function
x_categoricals: order of categorical variables in tensor passed to forward function
hidden_continuous_size: default for hidden size for processing continous variables (similar to categorical
embedding size)
hidden_continuous_sizes: dictionary mapping continuous input indices to sizes for variable selection
(fallback to hidden_continuous_size if index is not in dictionary)
embedding_sizes: dictionary mapping (string) indices to tuple of number of categorical classes and
embedding size
embedding_paddings: list of indices for embeddings which transform the zero's embedding to a zero vector
embedding_labels: dictionary mapping (string) indices to list of categorical labels
learning_rate: learning rate
log_interval: log predictions every x batches, do not log if 0 or less, log interpretation if > 0. If < 1.0
, will log multiple entries per batch. Defaults to -1.
log_val_interval: frequency with which to log validation set metrics, defaults to log_interval
log_gradient_flow: if to log gradient flow, this takes time and should be only done to diagnose training
failures
reduce_on_plateau_patience (int): patience after which learning rate is reduced by a factor of 10
monotone_constaints (Dict[str, int]): dictionary of monotonicity constraints for continuous decoder
variables mapping
position (e.g. ``"0"`` for first position) to constraint (``-1`` for negative and ``+1`` for positive,
larger numbers add more weight to the constraint vs. the loss but are usually not necessary).
This constraint significantly slows down training. Defaults to {}.
share_single_variable_networks (bool): if to share the single variable networks between the encoder and
decoder. Defaults to False.
logging_metrics (nn.ModuleList[LightningMetric]): list of metrics that are logged during training.
Defaults to nn.ModuleList([SMAPE(), MAE(), RMSE(), MAPE()]).
**kwargs: additional arguments to :py:class:`~BaseModel`.
"""
# if logging_metrics is None:
# logging_metrics = nn.ModuleList([SMAPE(), MAE(), RMSE(), MAPE()])
if loss is None:
loss = QuantileLoss()
# self.save_hyperparameters()
# # store loss function separately as it is a module
# assert isinstance(loss, LightningMetric), "Loss has to be a PyTorch Lightning `Metric`"
# super().__init__(loss=loss, logging_metrics=logging_metrics, **kwargs)
super(TemporalFusionTransformer, self).__init__()
self.device = device
# Hparams
# Data parameters
self.time_steps = 257
self.input_size = 8
self.output_size = 1
self.category_counts = [7, 31, 53, 12, 4]
self.n_multiprocessing_workers = 5
# Relevant indices for TFT
self._input_obs_loc = [0]
self._static_input_loc = [7]
self._known_regular_input_idx = [2]
self._known_categorical_input_idx = [0, 1, 2, 3, 4]
self.column_definition = None
# Network params
self.quantiles = [0.1, 0.5, 0.9]
# self.use_cudnn = use_cudnn # Whether to use GPU optimised LSTM
self.hidden_layer_size = 160
self.dropout_rate = 0.3
self.max_gradient_norm = 0.1
self.learning_rate = 0.01
self.minibatch_size = 64
self.num_epochs = 100
self.early_stopping_patience = 2
self.num_encoder_steps = 252
self.num_stacks = 1
self.num_heads = 1
# # Dev params
# self.hidden_continuous_size = 160
# self.embedding_sizes = {'day_of_week': (7, 160), 'day_of_month': (31, 160), 'week_of_year': (53, 160), 'month': (12, 160), 'Region': (4, 160)}
# self.x_reals = ['log_vol', 'open_to_close', 'days_from_start']
# self.x_categoricals = ['day_of_week', 'day_of_month', 'week_of_year', 'month', 'Region']
# self.reals = ['log_vol', 'open_to_close', 'days_from_start']
# self.static_categoricals = ['Region']
# self.static_reals = []
# self.time_varying_categoricals_encoder = ['day_of_week', 'day_of_month', 'week_of_year', 'month']
# self.time_varying_categoricals_decoder = ['day_of_week', 'day_of_month', 'week_of_year', 'month']
# self.time_varying_reals_encoder = ['log_vol', 'open_to_close', 'days_from_start']
# self.time_varying_reals_decoder = ['days_from_start']
# self.lstm_layers = 1
# self.attention_head_size = 1
# self.output_size = 3
# self.n_targets = 1
# self.static_variables = ['Region']
# self.encoder_variables = ['day_of_week', 'day_of_month', 'week_of_year', 'month', 'days_from_start', 'log_vol', 'open_to_close']
# self.decoder_variables = ['day_of_week', 'day_of_month', 'week_of_year', 'month', 'days_from_start']
# Dev - Wrapper
self.hparams = wrapper.hparams
self.fixed_params = wrapper.fixed_params
self.batch_size = batch_size
self.hidden_layer_size = self.hparams['hidden_layer_size']
self.hidden_continuous_size = self.hparams['hidden_continuous_size']
self.embedding_sizes = self.hparams['embedding_sizes']
self.x_reals = self.hparams['x_reals']
self.x_categoricals = self.hparams['x_categoricals']
self.reals = self.hparams['reals']
self.static_categoricals = self.hparams['static_categoricals']
self.static_reals = self.hparams['static_reals']
self.time_varying_categoricals_encoder = self.hparams['time_varying_categoricals_encoder']
self.time_varying_categoricals_decoder = self.hparams['time_varying_categoricals_decoder']
self.time_varying_reals_encoder = self.hparams['time_varying_reals_encoder']
self.time_varying_reals_decoder = self.hparams['time_varying_reals_decoder']
self.lstm_layers = self.hparams['lstm_layers']
self.attention_head_size = self.hparams['attention_head_size']
self.output_size = self.hparams['output_size']
self.n_targets = self.hparams['n_targets']
self.static_variables = self.hparams['static_variables']
self.encoder_variables = self.hparams['encoder_variables']
self.decoder_variables = self.hparams['decoder_variables']
# processing inputs
# embeddings
self.input_embeddings = MultiEmbedding(
embedding_sizes=self.embedding_sizes,
categorical_groups={}, # what is this
embedding_paddings=[],
x_categoricals=self.x_categoricals,
max_embedding_size=self.hidden_layer_size,
)
# continuous variable processing
self.prescalers = nn.ModuleDict(
{
name: nn.Linear(1, self.hidden_layer_size)
for name in self.reals
}
)
# variable selection
# variable selection for static variables
static_input_sizes = {name: self.embedding_sizes[name][1] for name in self.static_categoricals}
static_input_sizes.update(
{
name: self.hidden_continuous_size
for name in self.static_reals
}
)
self.static_variable_selection = VariableSelectionNetwork(
input_sizes=static_input_sizes,
hidden_size=self.hidden_layer_size,
input_embedding_flags={name: True for name in self.static_categoricals},
dropout=self.dropout_rate,
prescalers=self.prescalers,
)
# variable selection for encoder and decoder
encoder_input_sizes = {
name: self.embedding_sizes[name][1] for name in self.time_varying_categoricals_encoder
}
encoder_input_sizes.update(
{
name: self.hidden_continuous_size
for name in self.time_varying_reals_encoder
}
)
decoder_input_sizes = {
name: self.embedding_sizes[name][1] for name in self.time_varying_categoricals_decoder
}
decoder_input_sizes.update(
{
name: self.hidden_continuous_size
for name in self.time_varying_reals_decoder
}
)
# create single variable grns that are shared across decoder and encoder
self.share_single_variable_networks = False
if self.share_single_variable_networks:
self.shared_single_variable_grns = nn.ModuleDict()
for name, input_size in encoder_input_sizes.items():
self.shared_single_variable_grns[name] = GatedResidualNetwork(
input_size,
min(input_size, self.hidden_layer_size),
self.hidden_layer_size,
self.hparams.dropout,
)
for name, input_size in decoder_input_sizes.items():
if name not in self.shared_single_variable_grns:
self.shared_single_variable_grns[name] = GatedResidualNetwork(
input_size,
min(input_size, self.hidden_layer_size),
self.hidden_layer_size,
self.hparams.dropout,
)
self.encoder_variable_selection = VariableSelectionNetwork(
input_sizes=encoder_input_sizes,
hidden_size=self.hidden_layer_size,
input_embedding_flags={name: True for name in self.time_varying_categoricals_encoder},
dropout=self.dropout_rate,
context_size=self.hidden_layer_size,
prescalers=self.prescalers,
single_variable_grns={}
if not self.share_single_variable_networks
else self.shared_single_variable_grns,
)
self.decoder_variable_selection = VariableSelectionNetwork(
input_sizes=decoder_input_sizes,
hidden_size=self.hidden_layer_size,
input_embedding_flags={name: True for name in self.time_varying_categoricals_decoder},
dropout=self.dropout_rate,
context_size=self.hidden_layer_size,
prescalers=self.prescalers,
single_variable_grns={}
if not self.share_single_variable_networks
else self.shared_single_variable_grns,
)
# static encoders
# for variable selection
self.static_context_variable_selection = GatedResidualNetwork(
input_size=self.hidden_layer_size,
hidden_size=self.hidden_layer_size,
output_size=self.hidden_layer_size,
dropout=self.dropout_rate,
)
# for hidden state of the lstm
self.static_context_initial_hidden_lstm = GatedResidualNetwork(
input_size=self.hidden_layer_size,
hidden_size=self.hidden_layer_size,
output_size=self.hidden_layer_size,
dropout=self.dropout_rate,
)
# for cell state of the lstm
self.static_context_initial_cell_lstm = GatedResidualNetwork(
input_size=self.hidden_layer_size,
hidden_size=self.hidden_layer_size,
output_size=self.hidden_layer_size,
dropout=self.dropout_rate,
)
# for post lstm static enrichment
self.static_context_enrichment = GatedResidualNetwork(
self.hidden_layer_size, self.hidden_layer_size, self.hidden_layer_size, self.dropout_rate
)
# lstm encoder (history) and decoder (future) for local processing
self.lstm_encoder = LSTM(
input_size=self.hidden_layer_size,
hidden_size=self.hidden_layer_size,
num_layers=self.lstm_layers,
dropout=self.dropout_rate if self.lstm_layers > 1 else 0,
batch_first=True,
)
self.lstm_decoder = LSTM(
input_size=self.hidden_layer_size,
hidden_size=self.hidden_layer_size,
num_layers=self.lstm_layers,
dropout=self.dropout_rate if self.lstm_layers > 1 else 0,
batch_first=True,
)
# skip connection for lstm
self.post_lstm_gate_encoder = GatedLinearUnit(self.hidden_layer_size, dropout=self.dropout_rate)
self.post_lstm_gate_decoder = self.post_lstm_gate_encoder
# self.post_lstm_gate_decoder = GatedLinearUnit(self.hidden_layer_size, dropout=self.dropout_rate)
self.post_lstm_add_norm_encoder = AddNorm(self.hidden_layer_size, trainable_add=False)
# self.post_lstm_add_norm_decoder = AddNorm(self.hidden_layer_size, trainable_add=True)
self.post_lstm_add_norm_decoder = self.post_lstm_add_norm_encoder
# static enrichment and processing past LSTM
self.static_enrichment = GatedResidualNetwork(
input_size=self.hidden_layer_size,
hidden_size=self.hidden_layer_size,
output_size=self.hidden_layer_size,
dropout=self.dropout_rate,
context_size=self.hidden_layer_size,
)
# attention for long-range processing
self.multihead_attn = InterpretableMultiHeadAttention(
d_model=self.hidden_layer_size, n_head=self.attention_head_size, dropout=self.dropout_rate
)
self.post_attn_gate_norm = GateAddNorm(
self.hidden_layer_size, dropout=self.dropout_rate, trainable_add=False
)
self.pos_wise_ff = GatedResidualNetwork(
self.hidden_layer_size, self.hidden_layer_size, self.hidden_layer_size, dropout=self.dropout_rate
)
# output processing -> no dropout at this late stage
self.pre_output_gate_norm = GateAddNorm(self.hidden_layer_size, dropout=None, trainable_add=False)
if self.n_targets > 1: # if to run with multiple targets
self.output_layer = nn.ModuleList(
[nn.Linear(self.hidden_layer_size, output_size) for output_size in self.output_size]
)
else:
self.output_layer = nn.Linear(self.hidden_layer_size, self.output_size)
def expand_static_context(self, context, timesteps):
"""
add time dimension to static context
"""
return context[:, None].expand(-1, timesteps, -1)
def get_attention_mask(self, encoder_lengths: torch.LongTensor, decoder_length: int):
"""
Returns causal mask to apply for self-attention layer.
Args:
self_attn_inputs: Inputs to self attention layer to determine mask shape
"""
# indices to which is attended
attend_step = torch.arange(decoder_length, device=self.device)
# indices for which is predicted
predict_step = torch.arange(0, decoder_length, device=self.device)[:, None]
# do not attend to steps to self or after prediction
# todo: there is potential value in attending to future forecasts if they are made with knowledge currently
# available
# one possibility is here to use a second attention layer for future attention (assuming different effects
# matter in the future than the past)
# or alternatively using the same layer but allowing forward attention - i.e. only masking out non-available
# data and self
decoder_mask = attend_step >= predict_step
# do not attend to steps where data is padded
encoder_mask = create_mask(encoder_lengths.max(), encoder_lengths)
# combine masks along attended time - first encoder and then decoder
mask = torch.cat(
(
encoder_mask.unsqueeze(1).expand(-1, decoder_length, -1),
decoder_mask.unsqueeze(0).expand(encoder_lengths.size(0), -1, -1),
),
dim=2,
)
return mask
def forward(self, x: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
input dimensions: n_samples x time x variables
"""
# Dev
batch_size = 64
encoder_lengths = torch.ones([self.batch_size]).to(self.device) * self.fixed_params['num_encoder_steps']
decoder_lengths = torch.ones([self.batch_size]).to(self.device) * (self.fixed_params['total_time_steps'] - self.fixed_params['num_encoder_steps'])
test = len(self.x_reals)
x_cat = x[..., test:].long() # [64, 257, 5]
x_cont = x[..., :test] # [64, 257, 3]
timesteps = x_cont.size(1)
max_encoder_length = int(encoder_lengths.max())
input_vectors = self.input_embeddings(x_cat)
input_vectors.update(
{
name: x_cont[..., idx].unsqueeze(-1) # [31, 256, 1]
for idx, name in enumerate(self.x_reals)
if name in self.reals
}
)
# Embedding and variable selection
if len(self.static_variables) > 0:
# static embeddings will be constant over entire batch
static_embedding = {name: input_vectors[name][:, 0] for name in self.static_variables} # [31, 160] ilkini seçtik?
static_embedding, static_variable_selection = self.static_variable_selection(static_embedding)
else:
static_embedding = torch.zeros(
(x_cont.size(0), self.hidden_layer_size), dtype=self.dtype, device=self.device
)
static_variable_selection = torch.zeros((x_cont.size(0), 0), dtype=self.dtype, device=self.device)
static_context_variable_selection = self.expand_static_context( # [31, 1, 160] > [31, 256, 160] expanded static
self.static_context_variable_selection(static_embedding), timesteps
)
# Historical - past inputs
embeddings_varying_encoder = {
name: input_vectors[name][:, :max_encoder_length] for name in self.encoder_variables
}
embeddings_varying_encoder, encoder_sparse_weights = self.encoder_variable_selection(
embeddings_varying_encoder,
static_context_variable_selection[:, :max_encoder_length],
)
# Future inputs
embeddings_varying_decoder = {
name: input_vectors[name][:, max_encoder_length:] for name in self.decoder_variables # select decoder
}
embeddings_varying_decoder, decoder_sparse_weights = self.decoder_variable_selection(
embeddings_varying_decoder,
static_context_variable_selection[:, max_encoder_length:],
)
# LSTM
# calculate initial state
input_hidden = self.static_context_initial_hidden_lstm(static_embedding).expand( # [31, 160] > [1, 31, 160]
self.lstm_layers, -1, -1
)
input_cell = self.static_context_initial_cell_lstm(static_embedding).expand(self.lstm_layers, -1, -1)
# run local encoder
encoder_output, (hidden, cell) = self.lstm_encoder( # [31, 251, 160]
embeddings_varying_encoder, (input_hidden, input_cell), lengths=encoder_lengths, enforce_sorted=False
)
# run local decoder
decoder_output, _ = self.lstm_decoder(
embeddings_varying_decoder,
(hidden, cell),
lengths=decoder_lengths,
enforce_sorted=False,
)
# skip connection over lstm
lstm_output_encoder = self.post_lstm_gate_encoder(encoder_output)
lstm_output_encoder = self.post_lstm_add_norm_encoder(lstm_output_encoder, embeddings_varying_encoder)
lstm_output_decoder = self.post_lstm_gate_decoder(decoder_output)
lstm_output_decoder = self.post_lstm_add_norm_decoder(lstm_output_decoder, embeddings_varying_decoder)
lstm_output = torch.cat([lstm_output_encoder, lstm_output_decoder], dim=1)
# static enrichment
static_context_enrichment = self.static_context_enrichment(static_embedding)
attn_input = self.static_enrichment(
lstm_output, self.expand_static_context(static_context_enrichment, timesteps)
)
# Attention
attn_output, attn_output_weights = self.multihead_attn(
q=attn_input[:, max_encoder_length:], # query only for predictions
k=attn_input,
v=attn_input,
mask=self.get_attention_mask(
encoder_lengths=encoder_lengths, decoder_length=timesteps - max_encoder_length
),
)
# skip connection over attention
attn_output = self.post_attn_gate_norm(attn_output, attn_input[:, max_encoder_length:])
output = self.pos_wise_ff(attn_output)
# skip connection over temporal fusion decoder (not LSTM decoder despite the LSTM output contains
# a skip from the variable selection network)
output = self.pre_output_gate_norm(output, lstm_output[:, max_encoder_length:])
if self.n_targets > 1: # if to use multi-target architecture
output = [output_layer(output) for output_layer in self.output_layer]
else:
output = self.output_layer(output)
# Dev
return output
return self.to_network_output(
prediction=self.transform_output(output, target_scale=x["target_scale"]),
attention=attn_output_weights,
static_variables=static_variable_selection,
encoder_variables=encoder_sparse_weights,
decoder_variables=decoder_sparse_weights,
decoder_lengths=decoder_lengths,
encoder_lengths=encoder_lengths,
)
def on_fit_end(self):
if self.log_interval > 0:
self.log_embeddings()
def create_log(self, x, y, out, batch_idx, **kwargs):
log = super().create_log(x, y, out, batch_idx, **kwargs)
if self.log_interval > 0:
log["interpretation"] = self._log_interpretation(out)
return log
def _log_interpretation(self, out):
# calculate interpretations etc for latter logging
interpretation = self.interpret_output(
detach(out),
reduction="sum",
attention_prediction_horizon=0, # attention only for first prediction horizon
)
return interpretation
def epoch_end(self, outputs):
"""
run at epoch end for training or validation
"""
if self.log_interval > 0:
self.log_interpretation(outputs)
def interpret_output(
self,
out: Dict[str, torch.Tensor],
reduction: str = "none",
attention_prediction_horizon: int = 0,
attention_as_autocorrelation: bool = False,
) -> Dict[str, torch.Tensor]:
"""
interpret output of model
Args:
out: output as produced by ``forward()``
reduction: "none" for no averaging over batches, "sum" for summing attentions, "mean" for
normalizing by encode lengths
attention_prediction_horizon: which prediction horizon to use for attention
attention_as_autocorrelation: if to record attention as autocorrelation - this should be set to true in
case of ``reduction != "none"`` and differing prediction times of the samples. Defaults to False
Returns:
interpretations that can be plotted with ``plot_interpretation()``
"""
# histogram of decode and encode lengths
encoder_length_histogram = integer_histogram(out["encoder_lengths"], min=0, max=self.hparams.max_encoder_length)
decoder_length_histogram = integer_histogram(
out["decoder_lengths"], min=1, max=out["decoder_variables"].size(1)
)
# mask where decoder and encoder where not applied when averaging variable selection weights
encoder_variables = out["encoder_variables"].squeeze(-2)
encode_mask = create_mask(encoder_variables.size(1), out["encoder_lengths"])
encoder_variables = encoder_variables.masked_fill(encode_mask.unsqueeze(-1), 0.0).sum(dim=1)
encoder_variables /= (
out["encoder_lengths"]
.where(out["encoder_lengths"] > 0, torch.ones_like(out["encoder_lengths"]))
.unsqueeze(-1)
)
decoder_variables = out["decoder_variables"].squeeze(-2)
decode_mask = create_mask(decoder_variables.size(1), out["decoder_lengths"])
decoder_variables = decoder_variables.masked_fill(decode_mask.unsqueeze(-1), 0.0).sum(dim=1)
decoder_variables /= out["decoder_lengths"].unsqueeze(-1)
# static variables need no masking
static_variables = out["static_variables"].squeeze(1)
# attention is batch x time x heads x time_to_attend
# average over heads + only keep prediction attention and attention on observed timesteps
attention = out["attention"][
:, attention_prediction_horizon, :, : out["encoder_lengths"].max() + attention_prediction_horizon
].mean(1)
if reduction != "none": # if to average over batches
static_variables = static_variables.sum(dim=0)
encoder_variables = encoder_variables.sum(dim=0)
decoder_variables = decoder_variables.sum(dim=0)
# reorder attention or averaging
for i in range(len(attention)): # very inefficient but does the trick
if 0 < out["encoder_lengths"][i] < attention.size(1) - attention_prediction_horizon - 1:
relevant_attention = attention[
i, : out["encoder_lengths"][i] + attention_prediction_horizon
].clone()
if attention_as_autocorrelation:
relevant_attention = autocorrelation(relevant_attention)
attention[i, -out["encoder_lengths"][i] - attention_prediction_horizon :] = relevant_attention
attention[i, : attention.size(1) - out["encoder_lengths"][i] - attention_prediction_horizon] = 0.0
elif attention_as_autocorrelation:
attention[i] = autocorrelation(attention[i])
attention = attention.sum(dim=0)
if reduction == "mean":
attention = attention / encoder_length_histogram[1:].flip(0).cumsum(0).clamp(1)
attention = attention / attention.sum(-1).unsqueeze(-1) # renormalize
elif reduction == "sum":
pass
else:
raise ValueError(f"Unknown reduction {reduction}")
attention = torch.zeros(
self.hparams.max_encoder_length + attention_prediction_horizon, device=self.device
).scatter(
dim=0,
index=torch.arange(
self.hparams.max_encoder_length + attention_prediction_horizon - attention.size(-1),
self.hparams.max_encoder_length + attention_prediction_horizon,
device=self.device,
),
src=attention,
)
else:
attention = attention / attention.sum(-1).unsqueeze(-1) # renormalize
interpretation = dict(
attention=attention,
static_variables=static_variables,
encoder_variables=encoder_variables,
decoder_variables=decoder_variables,
encoder_length_histogram=encoder_length_histogram,
decoder_length_histogram=decoder_length_histogram,
)
return interpretation
def plot_prediction(
self,
x: Dict[str, torch.Tensor],
out: Dict[str, torch.Tensor],
idx: int,
plot_attention: bool = True,
add_loss_to_title: bool = False,
show_future_observed: bool = True,
ax=None,
**kwargs,
) -> plt.Figure:
"""
Plot actuals vs prediction and attention
Args:
x (Dict[str, torch.Tensor]): network input
out (Dict[str, torch.Tensor]): network output
idx (int): sample index
plot_attention: if to plot attention on secondary axis
add_loss_to_title: if to add loss to title. Default to False.
show_future_observed: if to show actuals for future. Defaults to True.
ax: matplotlib axes to plot on
Returns:
plt.Figure: matplotlib figure
"""
# plot prediction as normal
fig = super().plot_prediction(
x,
out,
idx=idx,
add_loss_to_title=add_loss_to_title,
show_future_observed=show_future_observed,
ax=ax,
**kwargs,
)
# add attention on secondary axis
if plot_attention:
interpretation = self.interpret_output(out)
for f in to_list(fig):
ax = f.axes[0]
ax2 = ax.twinx()
ax2.set_ylabel("Attention")
encoder_length = x["encoder_lengths"][idx]
ax2.plot(
torch.arange(-encoder_length, 0),
interpretation["attention"][idx, :encoder_length].detach().cpu(),
alpha=0.2,
color="k",
)
f.tight_layout()
return fig
def plot_interpretation(self, interpretation: Dict[str, torch.Tensor]) -> Dict[str, plt.Figure]:
"""
Make figures that interpret model.
* Attention
* Variable selection weights / importances
Args:
interpretation: as obtained from ``interpret_output()``
Returns:
dictionary of matplotlib figures
"""
figs = {}
# attention
fig, ax = plt.subplots()
attention = interpretation["attention"].detach().cpu()
attention = attention / attention.sum(-1).unsqueeze(-1)
ax.plot(
np.arange(-self.hparams.max_encoder_length, attention.size(0) - self.hparams.max_encoder_length), attention
)
ax.set_xlabel("Time index")
ax.set_ylabel("Attention")
ax.set_title("Attention")
figs["attention"] = fig
# variable selection
def make_selection_plot(title, values, labels):
fig, ax = plt.subplots(figsize=(7, len(values) * 0.25 + 2))
order = np.argsort(values)
values = values / values.sum(-1).unsqueeze(-1)
ax.barh(np.arange(len(values)), values[order] * 100, tick_label=np.asarray(labels)[order])
ax.set_title(title)
ax.set_xlabel("Importance in %")
plt.tight_layout()
return fig
figs["static_variables"] = make_selection_plot(
"Static variables importance", interpretation["static_variables"].detach().cpu(), self.static_variables
)
figs["encoder_variables"] = make_selection_plot(
"Encoder variables importance", interpretation["encoder_variables"].detach().cpu(), self.encoder_variables
)
figs["decoder_variables"] = make_selection_plot(
"Decoder variables importance", interpretation["decoder_variables"].detach().cpu(), self.decoder_variables
)
return figs
def log_interpretation(self, outputs):
"""
Log interpretation metrics to tensorboard.
"""
# extract interpretations
interpretation = {
# use padded_stack because decoder length histogram can be of different length
name: padded_stack([x["interpretation"][name].detach() for x in outputs], side="right", value=0).sum(0)
for name in outputs[0]["interpretation"].keys()
}
# normalize attention with length histogram squared to account for: 1. zeros in attention and
# 2. higher attention due to less values
attention_occurances = interpretation["encoder_length_histogram"][1:].flip(0).cumsum(0).float()
attention_occurances = attention_occurances / attention_occurances.max()
attention_occurances = torch.cat(
[
attention_occurances,
torch.ones(
interpretation["attention"].size(0) - attention_occurances.size(0),
dtype=attention_occurances.dtype,
device=attention_occurances.device,
),
],
dim=0,
)
interpretation["attention"] = interpretation["attention"] / attention_occurances.pow(2).clamp(1.0)
interpretation["attention"] = interpretation["attention"] / interpretation["attention"].sum()
figs = self.plot_interpretation(interpretation) # make interpretation figures
label = ["val", "train"][self.training]
# log to tensorboard
for name, fig in figs.items():
self.logger.experiment.add_figure(
f"{label.capitalize()} {name} importance", fig, global_step=self.global_step
)
# log lengths of encoder/decoder
for type in ["encoder", "decoder"]:
fig, ax = plt.subplots()
lengths = (
padded_stack([out["interpretation"][f"{type}_length_histogram"] for out in outputs])
.sum(0)
.detach()
.cpu()
)
if type == "decoder":
start = 1
else:
start = 0
ax.plot(torch.arange(start, start + len(lengths)), lengths)
ax.set_xlabel(f"{type.capitalize()} length")
ax.set_ylabel("Number of samples")
ax.set_title(f"{type.capitalize()} length distribution in {label} epoch")
self.logger.experiment.add_figure(
f"{label.capitalize()} {type} length distribution", fig, global_step=self.global_step
)
def log_embeddings(self):
"""
Log embeddings to tensorboard
"""
for name, emb in self.input_embeddings.items():
labels = self.hparams.embedding_labels[name]
self.logger.experiment.add_embedding(
emb.weight.data.detach().cpu(), metadata=labels, tag=name, global_step=self.global_step
)