Convolutional Transformer

This is an implementation of the code from this paper

This code is based on huggingface, https://github.com/huggingface/pytorch-openai-transformer-lm/blob/master/model_pytorch.py

MIT License

Copyright (c) 2018 OpenAI

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OFS CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

flood_forecast.transformer_xl.transformer_bottleneck.gelu(x)[source]
flood_forecast.transformer_xl.transformer_bottleneck.swish(x)[source]
class flood_forecast.transformer_xl.transformer_bottleneck.Attention(n_head, n_embd, win_len, scale, q_len, sub_len, sparse=None, attn_pdrop=0.1, resid_pdrop=0.1)[source]
__init__(n_head, n_embd, win_len, scale, q_len, sub_len, sparse=None, attn_pdrop=0.1, resid_pdrop=0.1)[source]

Initializes internal Module state, shared by both nn.Module and ScriptModule.

log_mask(win_len, sub_len)[source]
row_mask(index, sub_len, win_len)[source]

Remark: 1 . Currently, dense matrices with sparse multiplication are not supported by Pytorch. Efficient implementation

should deal with CUDA kernel, which we haven’t implemented yet.

2 . Our default setting here use Local attention and Restart attention.

3 . For index-th row, if its past is smaller than the number of cells the last

cell can attend, we can allow current cell to attend all past cells to fully utilize parallel computing in dense matrices with sparse multiplication.

attn(query: torch.Tensor, key, value: torch.Tensor, activation='Softmax')[source]
merge_heads(x)[source]
split_heads(x, k=False)[source]
forward(x)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

training: bool
class flood_forecast.transformer_xl.transformer_bottleneck.Conv1D(out_dim, rf, in_dim)[source]
__init__(out_dim, rf, in_dim)[source]

Initializes internal Module state, shared by both nn.Module and ScriptModule.

forward(x)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

training: bool
class flood_forecast.transformer_xl.transformer_bottleneck.LayerNorm(n_embd, e=1e-05)[source]

Construct a layernorm module in the OpenAI style (epsilon inside the square root).

__init__(n_embd, e=1e-05)[source]

Initializes internal Module state, shared by both nn.Module and ScriptModule.

forward(x)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

training: bool
class flood_forecast.transformer_xl.transformer_bottleneck.MLP(n_state, n_embd, acf='relu')[source]
__init__(n_state, n_embd, acf='relu')[source]

Initializes internal Module state, shared by both nn.Module and ScriptModule.

forward(x)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

training: bool
class flood_forecast.transformer_xl.transformer_bottleneck.Block(n_head, win_len, n_embd, scale, q_len, sub_len, additional_params: Dict)[source]
__init__(n_head, win_len, n_embd, scale, q_len, sub_len, additional_params: Dict)[source]

Initializes internal Module state, shared by both nn.Module and ScriptModule.

forward(x)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

training: bool
class flood_forecast.transformer_xl.transformer_bottleneck.TransformerModel(n_time_series, n_head, sub_len, num_layer, n_embd, forecast_history: int, dropout: float, scale_att, q_len, additional_params: Dict, seq_num=None)[source]

Transformer model

__init__(n_time_series, n_head, sub_len, num_layer, n_embd, forecast_history: int, dropout: float, scale_att, q_len, additional_params: Dict, seq_num=None)[source]

Initializes internal Module state, shared by both nn.Module and ScriptModule.

win_len

For positional encoding in Transformer, we use learnable position embedding. For covariates, following [3], we use all or part of year, month, day-of-the-week, hour-of-the-day, minute-of-the-hour, age and time-series-ID according to the granularities of datasets. age is the distance to the first observation in that time series [3]. Each of them except time series ID has only one dimension and is normalized to have zero mean and unit variance (if applicable).

forward(series_id: int, x: torch.Tensor)[source]

Runs forward pass of the DecoderTransformer model.

Parameters
  • series_id (int) – ID of the time series

  • x (torch.Tensor) – [description]

Returns

[description]

Return type

[type]

training: bool
class flood_forecast.transformer_xl.transformer_bottleneck.DecoderTransformer(n_time_series: int, n_head: int, num_layer: int, n_embd: int, forecast_history: int, dropout: float, q_len: int, additional_params: Dict, activation='Softmax', forecast_length: Optional[int] = None, scale_att: bool = False, seq_num1=None, sub_len=1, mu=None)[source]
__init__(n_time_series: int, n_head: int, num_layer: int, n_embd: int, forecast_history: int, dropout: float, q_len: int, additional_params: Dict, activation='Softmax', forecast_length: Optional[int] = None, scale_att: bool = False, seq_num1=None, sub_len=1, mu=None)[source]
Args:

n_time_series: Number of time series present in input n_head: Number of heads in the MultiHeadAttention mechanism seq_num: The number of targets to forecast sub_len: sub_len of the sparse attention num_layer: The number of transformer blocks in the model. n_embd: The dimention of Position embedding and time series ID embedding forecast_history: The number of historical steps fed into the time series model dropout: The dropout for the embedding of the model. additional_params: Additional parameters used to initalize the attention model. Can inc

training: bool
forward(x: torch.Tensor, series_id: Optional[int] = None)[source]
Args:

x: Tensor of dimension (batch_size, seq_len, number_of_time_series) series_id: Optional id of the series in the dataframe. Currently not supported

Returns:

Case 1: tensor of dimension (batch_size, forecast_length) Case 2: GLoss sigma and mu: tuple of ((batch_size, forecast_history, 1), (batch_size, forecast_history, 1))