|
| 1 | +# Pytorch Tabular |
| 2 | +# Author: Manu Joseph <manujoseph@gmail.com> |
| 3 | +# For license information, see LICENSE.TXT |
| 4 | +# Inspired by https://github.com/rixwew/pytorch-fm/blob/master/torchfm/model/afi.py |
| 5 | +"""AutomaticFeatureInteraction Model""" |
| 6 | +import logging |
| 7 | +from typing import Dict |
| 8 | + |
| 9 | +import torch |
| 10 | +import torch.nn as nn |
| 11 | +from omegaconf import DictConfig |
| 12 | + |
| 13 | +from pytorch_tabular.utils import _initialize_layers, _linear_dropout_bn |
| 14 | + |
| 15 | +from ..base_model import BaseModel |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class AutoIntBackbone(BaseModel): |
| 21 | + def __init__(self, config: DictConfig, **kwargs): |
| 22 | + self.embedding_cat_dim = sum([y for x, y in config.embedding_dims]) |
| 23 | + super().__init__(config, **kwargs) |
| 24 | + |
| 25 | + def _build_network(self): |
| 26 | + # Category Embedding layers |
| 27 | + self.cat_embedding_layers = nn.ModuleList( |
| 28 | + [ |
| 29 | + nn.Embedding(cardinality, self.hparams.embedding_dim) |
| 30 | + for cardinality in self.hparams.categorical_cardinality |
| 31 | + ] |
| 32 | + ) |
| 33 | + if self.hparams.batch_norm_continuous_input: |
| 34 | + self.normalizing_batch_norm = nn.BatchNorm1d(self.hparams.continuous_dim) |
| 35 | + # Continuous Embedding Layer |
| 36 | + self.cont_embedding_layer = nn.Embedding( |
| 37 | + self.hparams.continuous_dim, self.hparams.embedding_dim |
| 38 | + ) |
| 39 | + if self.hparams.embedding_dropout != 0 and self.embedding_cat_dim != 0: |
| 40 | + self.embed_dropout = nn.Dropout(self.hparams.embedding_dropout) |
| 41 | + # Deep Layers |
| 42 | + _curr_units = self.hparams.embedding_dim |
| 43 | + if self.hparams.deep_layers: |
| 44 | + activation = getattr(nn, self.hparams.activation) |
| 45 | + # Linear Layers |
| 46 | + layers = [] |
| 47 | + for units in self.hparams.layers.split("-"): |
| 48 | + layers.extend( |
| 49 | + _linear_dropout_bn( |
| 50 | + self.hparams, |
| 51 | + _curr_units, |
| 52 | + int(units), |
| 53 | + activation, |
| 54 | + self.hparams.dropout, |
| 55 | + ) |
| 56 | + ) |
| 57 | + _curr_units = int(units) |
| 58 | + self.linear_layers = nn.Sequential(*layers) |
| 59 | + # Projection to Multi-Headed Attention Dims |
| 60 | + self.attn_proj = nn.Linear(_curr_units, self.hparams.attn_embed_dim) |
| 61 | + _initialize_layers(self.hparams, self.attn_proj) |
| 62 | + # Multi-Headed Attention Layers |
| 63 | + self.self_attns = nn.ModuleList( |
| 64 | + [ |
| 65 | + nn.MultiheadAttention( |
| 66 | + self.hparams.attn_embed_dim, |
| 67 | + self.hparams.num_heads, |
| 68 | + dropout=self.hparams.attn_dropouts, |
| 69 | + ) |
| 70 | + for _ in range(self.hparams.num_attn_blocks) |
| 71 | + ] |
| 72 | + ) |
| 73 | + if self.hparams.has_residuals: |
| 74 | + self.V_res_embedding = torch.nn.Linear( |
| 75 | + _curr_units, self.hparams.attn_embed_dim |
| 76 | + ) |
| 77 | + self.output_dim = ( |
| 78 | + self.hparams.continuous_dim + self.hparams.categorical_dim |
| 79 | + ) * self.hparams.attn_embed_dim |
| 80 | + |
| 81 | + def forward(self, x: Dict): |
| 82 | + # (B, N) |
| 83 | + continuous_data, categorical_data = x["continuous"], x["categorical"] |
| 84 | + x = None |
| 85 | + if self.embedding_cat_dim != 0: |
| 86 | + x_cat = [ |
| 87 | + embedding_layer(categorical_data[:, i]).unsqueeze(1) |
| 88 | + for i, embedding_layer in enumerate(self.cat_embedding_layers) |
| 89 | + ] |
| 90 | + # (B, N, E) |
| 91 | + x = torch.cat(x_cat, 1) |
| 92 | + if self.hparams.continuous_dim > 0: |
| 93 | + cont_idx = ( |
| 94 | + torch.arange(self.hparams.continuous_dim) |
| 95 | + .expand(continuous_data.size(0), -1) |
| 96 | + .to(self.device) |
| 97 | + ) |
| 98 | + if self.hparams.batch_norm_continuous_input: |
| 99 | + continuous_data = self.normalizing_batch_norm(continuous_data) |
| 100 | + x_cont = torch.mul( |
| 101 | + continuous_data.unsqueeze(2), |
| 102 | + self.cont_embedding_layer(cont_idx), |
| 103 | + ) |
| 104 | + # (B, N, E) |
| 105 | + x = x_cont if x is None else torch.cat([x, x_cont], 1) |
| 106 | + if self.hparams.embedding_dropout != 0 and self.embedding_cat_dim != 0: |
| 107 | + x = self.embed_dropout(x) |
| 108 | + if self.hparams.deep_layers: |
| 109 | + x = self.linear_layers(x) |
| 110 | + # (N, B, E*) --> E* is the Attn Dimention |
| 111 | + cross_term = self.attn_proj(x).transpose(0, 1) |
| 112 | + for self_attn in self.self_attns: |
| 113 | + cross_term, _ = self_attn(cross_term, cross_term, cross_term) |
| 114 | + # (B, N, E*) |
| 115 | + cross_term = cross_term.transpose(0, 1) |
| 116 | + if self.hparams.has_residuals: |
| 117 | + # (B, N, E*) --> Projecting Embedded input to Attention sub-space |
| 118 | + V_res = self.V_res_embedding(x) |
| 119 | + cross_term = cross_term + V_res |
| 120 | + # (B, NxE*) |
| 121 | + cross_term = nn.ReLU()(cross_term).reshape(-1, self.output_dim) |
| 122 | + return cross_term |
| 123 | + |
| 124 | + |
| 125 | +class AutoIntModel(BaseModel): |
| 126 | + def __init__(self, config: DictConfig, **kwargs): |
| 127 | + # The concatenated output dim of the embedding layer |
| 128 | + self.embedding_cat_dim = sum([y for x, y in config.embedding_dims]) |
| 129 | + super().__init__(config, **kwargs) |
| 130 | + |
| 131 | + def _build_network(self): |
| 132 | + # Backbone |
| 133 | + self.backbone = AutoIntBackbone(self.hparams) |
| 134 | + self.dropout = nn.Dropout(self.hparams.dropout) |
| 135 | + # Adding the last layer |
| 136 | + self.output_layer = nn.Linear( |
| 137 | + self.backbone.output_dim, self.hparams.output_dim |
| 138 | + ) # output_dim auto-calculated from other config |
| 139 | + _initialize_layers(self.hparams, self.output_layer) |
| 140 | + |
| 141 | + def forward(self, x: Dict): |
| 142 | + x = self.backbone(x) |
| 143 | + x = self.dropout(x) |
| 144 | + y_hat = self.output_layer(x) |
| 145 | + if (self.hparams.task == "regression") and ( |
| 146 | + self.hparams.target_range is not None |
| 147 | + ): |
| 148 | + for i in range(self.hparams.output_dim): |
| 149 | + y_min, y_max = self.hparams.target_range[i] |
| 150 | + y_hat[:, i] = y_min + nn.Sigmoid()(y_hat[:, i]) * (y_max - y_min) |
| 151 | + return {"logits": y_hat, "backbone_features": x} |
0 commit comments