|
| 1 | +import typing as tp |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch import nn |
| 5 | + |
| 6 | +from rectools.models.nn.transformers.net_blocks import TransformerLayersBase |
| 7 | + |
| 8 | +from .net_blocks import init_feed_forward |
| 9 | + |
| 10 | + |
| 11 | +class LiGRLayer(nn.Module): |
| 12 | + """ |
| 13 | + Transformer Layer as described in "From Features to Transformers: |
| 14 | + Redefining Ranking for Scalable Impact" https://arxiv.org/pdf/2502.03417 |
| 15 | +
|
| 16 | + Parameters |
| 17 | + ---------- |
| 18 | + n_factors: int |
| 19 | + Latent embeddings size. |
| 20 | + n_heads: int |
| 21 | + Number of attention heads. |
| 22 | + dropout_rate: float |
| 23 | + Probability of a hidden unit to be zeroed. |
| 24 | + ff_factors_multiplier: int, default 4 |
| 25 | + Feed-forward layers latent embedding size multiplier. |
| 26 | + bias_in_ff: bool, default ``False`` |
| 27 | + Add bias in Linear layers of Feed Forward |
| 28 | + ff_activation: {"swiglu", "relu", "gelu"}, default "swiglu" |
| 29 | + Activation function to use. |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__( |
| 33 | + self, |
| 34 | + n_factors: int, |
| 35 | + n_heads: int, |
| 36 | + dropout_rate: float, |
| 37 | + ff_factors_multiplier: int = 4, |
| 38 | + bias_in_ff: bool = False, |
| 39 | + ff_activation: str = "swiglu", |
| 40 | + ): |
| 41 | + super().__init__() |
| 42 | + self.multi_head_attn = nn.MultiheadAttention(n_factors, n_heads, dropout_rate, batch_first=True) |
| 43 | + self.layer_norm_1 = nn.LayerNorm(n_factors) |
| 44 | + self.dropout_1 = nn.Dropout(dropout_rate) |
| 45 | + self.layer_norm_2 = nn.LayerNorm(n_factors) |
| 46 | + self.feed_forward = init_feed_forward(n_factors, ff_factors_multiplier, dropout_rate, ff_activation, bias_in_ff) |
| 47 | + self.dropout_2 = nn.Dropout(dropout_rate) |
| 48 | + |
| 49 | + self.gating_linear_1 = nn.Linear(n_factors, n_factors) |
| 50 | + self.gating_linear_2 = nn.Linear(n_factors, n_factors) |
| 51 | + |
| 52 | + def forward( |
| 53 | + self, |
| 54 | + seqs: torch.Tensor, |
| 55 | + attn_mask: tp.Optional[torch.Tensor], |
| 56 | + key_padding_mask: tp.Optional[torch.Tensor], |
| 57 | + ) -> torch.Tensor: |
| 58 | + """ |
| 59 | + Forward pass through transformer block. |
| 60 | +
|
| 61 | + Parameters |
| 62 | + ---------- |
| 63 | + seqs: torch.Tensor |
| 64 | + User sequences of item embeddings. |
| 65 | + attn_mask: torch.Tensor, optional |
| 66 | + Optional mask to use in forward pass of multi-head attention as `attn_mask`. |
| 67 | + key_padding_mask: torch.Tensor, optional |
| 68 | + Optional mask to use in forward pass of multi-head attention as `key_padding_mask`. |
| 69 | +
|
| 70 | +
|
| 71 | + Returns |
| 72 | + ------- |
| 73 | + torch.Tensor |
| 74 | + User sequences passed through transformer layers. |
| 75 | + """ |
| 76 | + mha_input = self.layer_norm_1(seqs) |
| 77 | + mha_output, _ = self.multi_head_attn( |
| 78 | + mha_input, |
| 79 | + mha_input, |
| 80 | + mha_input, |
| 81 | + attn_mask=attn_mask, |
| 82 | + key_padding_mask=key_padding_mask, |
| 83 | + need_weights=False, |
| 84 | + ) |
| 85 | + gated_skip = torch.nn.functional.sigmoid(self.gating_linear_1(seqs)) |
| 86 | + seqs = seqs + torch.mul(gated_skip, self.dropout_1(mha_output)) |
| 87 | + |
| 88 | + ff_input = self.layer_norm_2(seqs) |
| 89 | + ff_output = self.feed_forward(ff_input) |
| 90 | + gated_skip = torch.nn.functional.sigmoid(self.gating_linear_2(seqs)) |
| 91 | + seqs = seqs + torch.mul(gated_skip, self.dropout_2(ff_output)) |
| 92 | + return seqs |
| 93 | + |
| 94 | + |
| 95 | +class LiGRLayers(TransformerLayersBase): |
| 96 | + """ |
| 97 | + LiGR Transformer blocks. |
| 98 | +
|
| 99 | + Parameters |
| 100 | + ---------- |
| 101 | + n_blocks: int |
| 102 | + Number of transformer blocks. |
| 103 | + n_factors: int |
| 104 | + Latent embeddings size. |
| 105 | + n_heads: int |
| 106 | + Number of attention heads. |
| 107 | + dropout_rate: float |
| 108 | + Probability of a hidden unit to be zeroed. |
| 109 | + ff_factors_multiplier: int, default 4 |
| 110 | + Feed-forward layers latent embedding size multiplier. Pass in ``transformer_layers_kwargs`` to override. |
| 111 | + ff_activation: {"swiglu", "relu", "gelu"}, default "swiglu" |
| 112 | + Activation function to use. Pass in ``transformer_layers_kwargs`` to override. |
| 113 | + bias_in_ff: bool, default ``False`` |
| 114 | + Add bias in Linear layers of Feed Forward. Pass in ``transformer_layers_kwargs`` to override. |
| 115 | + """ |
| 116 | + |
| 117 | + def __init__( |
| 118 | + self, |
| 119 | + n_blocks: int, |
| 120 | + n_factors: int, |
| 121 | + n_heads: int, |
| 122 | + dropout_rate: float, |
| 123 | + ff_factors_multiplier: int = 4, |
| 124 | + ff_activation: str = "swiglu", |
| 125 | + bias_in_ff: bool = False, |
| 126 | + ): |
| 127 | + super().__init__() |
| 128 | + self.n_blocks = n_blocks |
| 129 | + self.n_factors = n_factors |
| 130 | + self.n_heads = n_heads |
| 131 | + self.dropout_rate = dropout_rate |
| 132 | + self.ff_factors_multiplier = ff_factors_multiplier |
| 133 | + self.ff_activation = ff_activation |
| 134 | + self.bias_in_ff = bias_in_ff |
| 135 | + self.transformer_blocks = nn.ModuleList([self._init_transformer_block() for _ in range(self.n_blocks)]) |
| 136 | + |
| 137 | + def _init_transformer_block(self) -> nn.Module: |
| 138 | + return LiGRLayer( |
| 139 | + self.n_factors, |
| 140 | + self.n_heads, |
| 141 | + self.dropout_rate, |
| 142 | + self.ff_factors_multiplier, |
| 143 | + bias_in_ff=self.bias_in_ff, |
| 144 | + ff_activation=self.ff_activation, |
| 145 | + ) |
| 146 | + |
| 147 | + def forward( |
| 148 | + self, |
| 149 | + seqs: torch.Tensor, |
| 150 | + timeline_mask: torch.Tensor, |
| 151 | + attn_mask: tp.Optional[torch.Tensor], |
| 152 | + key_padding_mask: tp.Optional[torch.Tensor], |
| 153 | + **kwargs: tp.Any, |
| 154 | + ) -> torch.Tensor: |
| 155 | + """ |
| 156 | + Forward pass through transformer blocks. |
| 157 | +
|
| 158 | + Parameters |
| 159 | + ---------- |
| 160 | + seqs: torch.Tensor |
| 161 | + User sequences of item embeddings. |
| 162 | + timeline_mask: torch.Tensor |
| 163 | + Mask indicating padding elements. |
| 164 | + attn_mask: torch.Tensor, optional |
| 165 | + Optional mask to use in forward pass of multi-head attention as `attn_mask`. |
| 166 | + key_padding_mask: torch.Tensor, optional |
| 167 | + Optional mask to use in forward pass of multi-head attention as `key_padding_mask`. |
| 168 | +
|
| 169 | +
|
| 170 | + Returns |
| 171 | + ------- |
| 172 | + torch.Tensor |
| 173 | + User sequences passed through transformer layers. |
| 174 | + """ |
| 175 | + for block_idx in range(self.n_blocks): |
| 176 | + seqs = self.transformer_blocks[block_idx](seqs, attn_mask, key_padding_mask) |
| 177 | + return seqs |
0 commit comments