├── LICENSE ├── README.md └── transact_code ├── test_run_transact.py ├── transact.py └── transact_config.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TransAct 2 | ## Transformer-based Realtime User Action Model for Recommendation at Pinterest 3 | 4 | TransAct is a PyTorch module for modeling user sequences using the Transformer architecture. It is designed to handle user behavior data with sequential interactions, such as recommendation systems or user activity prediction. 5 | 6 | # Paper 7 | Xue Xia, Chantat Eksombatchai, Nikil Pancha, Dhruvil Deven Badani, Po- 8 | Wei Wang, Neng Gu, Saurabh Vishwas Joshi, Nazanin Farahpour, Zhiyuan 9 | Zhang, Andrew Zhai. 2023. TransAct: Transformer-based Realtime User 10 | Action Model for Recommendation at Pinterest. 11 | 12 | ## Prerequisites 13 | 14 | - Python 3.9.7 or higher: You can download and install Python from the official Python website at [https://www.python.org/downloads/](https://www.python.org/downloads/) or by using a package manager like conda or pip. 15 | 16 | - torch 1.12: You can install torch 1.12 using pip with the following command: 17 | 18 | ``` 19 | pip install torch==1.12 20 | ``` 21 | 22 | Alternatively, if you are using conda, you can install torch 1.12 with the following command: 23 | 24 | ``` 25 | conda install -c pytorch torch==1.12 26 | 27 | # Usage 28 | ``` 29 | python transact_code/test_run_transact.py 30 | ``` 31 | -------------------------------------------------------------------------------- /transact_code/test_run_transact.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from transact import TransAct 3 | from transact_config import TransActConfig 4 | 5 | 6 | def test_run_transact(): 7 | action_vocab = list(range(0, 20)) 8 | full_seq_len = 100 9 | test_batch_size = 8 10 | action_emb_dim = 32 11 | item_emb_dim = 32 12 | time_window_ms = 1000 * 60 * 60 * 1 # 1 hr 13 | latest_n_emb = 10 14 | 15 | action_type_seq = torch.randint(0, 20, (test_batch_size, full_seq_len)) 16 | item_embedding_seq = torch.rand(test_batch_size, full_seq_len, item_emb_dim) 17 | action_time_seq = torch.randint(0, 20, (test_batch_size, full_seq_len)) 18 | request_time = torch.randint(500, 1000, (test_batch_size,)) 19 | item_embedding = torch.rand(test_batch_size, item_emb_dim) 20 | input_features = ( 21 | action_type_seq, 22 | item_embedding_seq, 23 | action_time_seq, 24 | request_time, 25 | item_embedding, 26 | ) 27 | 28 | print("Initializing TransAct...") 29 | transact_config = TransActConfig( 30 | action_vocab=action_vocab, 31 | seq_len=full_seq_len, 32 | action_emb_dim=action_emb_dim, 33 | item_emb_dim=item_emb_dim, 34 | time_window_ms=time_window_ms, 35 | latest_n_emb=latest_n_emb, 36 | ) 37 | 38 | transact_module = TransAct(transact_config) 39 | 40 | print("Test forward pass") 41 | output = transact_module(*input_features) 42 | print(output) 43 | print("Test succeeded") 44 | 45 | 46 | test_run_transact() 47 | -------------------------------------------------------------------------------- /transact_code/transact.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import logging 4 | from typing import Dict, List, Final 5 | import random 6 | from transact_config import TransActConfig 7 | 8 | 9 | class TransAct(nn.Module): 10 | """ 11 | TransAct: Transformer-based Realtime User Action Model for Recommendation at Pinterest 12 | """ 13 | 14 | def __init__( 15 | self, 16 | transact_config: TransActConfig, 17 | ): 18 | """ 19 | Module Initialization 20 | """ 21 | super().__init__() 22 | self.transact_config = transact_config 23 | self.action_emb_dim: Final[int] = self.transact_config.action_emb_dim 24 | self.item_emb_dim: Final[int] = self.transact_config.item_emb_dim 25 | self.concat_candidate_emb: Final[ 26 | bool 27 | ] = self.transact_config.concat_candidate_emb 28 | self.time_window_ms: Final[int] = self.transact_config.time_window_ms 29 | self.seq_len: Final[int] = self.transact_config.seq_len 30 | self.latest_n_emb: Final[int] = self.transact_config.latest_n_emb 31 | self.action_vocab: Final[list] = self.transact_config.action_vocab 32 | if self.concat_candidate_emb: 33 | transformer_in_dim = self.action_emb_dim + self.item_emb_dim * 2 34 | else: 35 | transformer_in_dim = self.action_emb_dim + self.item_emb_dim 36 | 37 | self.register_buffer("action_type_lookup", self.convert_vocab_to_idx()) 38 | self.action_emb_module = nn.Embedding( 39 | len(self.action_vocab), self.action_emb_dim, padding_idx=0 40 | ) 41 | encoder_layer = nn.TransformerEncoderLayer( 42 | d_model=transformer_in_dim, 43 | nhead=self.transact_config.nhead, 44 | dim_feedforward=self.transact_config.dim_feedforward, 45 | batch_first=True, 46 | ) 47 | self.transformer_encoder = nn.TransformerEncoder( 48 | encoder_layer, num_layers=self.transact_config.num_layer 49 | ) 50 | if self.transact_config.concat_max_pool: 51 | self.out_linear = nn.Linear(transformer_in_dim, transformer_in_dim) 52 | 53 | def convert_vocab_to_idx(self) -> torch.Tensor: 54 | logging.info(f"Action used: {self.action_vocab}") 55 | t = torch.zeros(100, dtype=torch.long) 56 | i = 0 57 | for id in sorted(self.action_vocab): 58 | t[id + 1] = i 59 | i += 1 60 | return t 61 | 62 | def forward( 63 | self, 64 | action_type_seq: torch.Tensor, 65 | item_embedding_seq: torch.Tensor, 66 | action_time_seq: torch.Tensor, 67 | request_time: torch.Tensor, 68 | item_embedding: torch.Tensor, 69 | ) -> torch.Tensor: 70 | """ 71 | :param action_type_seq: Tensor of shape (batch_size, seq_len) representing the sequence of action types 72 | :param item_embedding_seq: Tensor of shape (batch_size, seq_len, item_emb_dim) representing the sequence of item embeddings 73 | :param action_time_seq: Tensor of shape (batch_size, seq_len) representing the sequence of action times 74 | :param request_time: Tensor of shape (batch_size, 1) representing the request time 75 | :param item_embedding: Tensor of shape (batch_size, item_emb_dim) representing the current item embedding 76 | :return: Tensor of shape (batch_size, latest_n_emb+1) representing the output of the forward pass 77 | """ 78 | # step 1: get the latest N actions from sequence features 79 | action_type_seq = action_type_seq[:, : self.seq_len] 80 | item_embedding_seq = item_embedding_seq[:, : self.seq_len, :] 81 | action_time_seq = action_time_seq[:, : self.seq_len] 82 | 83 | # step 2: get action embedding 84 | action_type_seq = self.action_type_lookup[action_type_seq + 1] 85 | action_emb_tensor = self.action_emb_module(action_type_seq) 86 | 87 | # step 3: create mask that tells transformer which position to be ignored by the attention. 88 | # mask padded positions 89 | key_padding_mask = action_type_seq <= 0 90 | 91 | # mask actions that happened in a time window before the request time 92 | request_time = request_time.unsqueeze(-1).expand(-1, self.seq_len) 93 | 94 | # randomly sample a time window to introduce randomness 95 | rand_time_window_ms = random.randint(0, self.time_window_ms) 96 | short_time_window_idx_trn = ( 97 | request_time - action_time_seq 98 | ) < rand_time_window_ms 99 | # use all the actions during inference 100 | short_time_window_idx_eval = (request_time - action_time_seq) < 0 101 | 102 | # adjust the mask accordingly 103 | if self.training: 104 | key_padding_mask = self._adjust_mask( 105 | key_padding_mask, short_time_window_idx_trn 106 | ) 107 | else: 108 | key_padding_mask = self._adjust_mask( 109 | key_padding_mask, short_time_window_idx_eval 110 | ) 111 | 112 | # step 4: stack seq embedding with action embedding and candidate embedding 113 | action_pin_emb = torch.cat((action_emb_tensor, item_embedding_seq), dim=2) 114 | 115 | if self.concat_candidate_emb: 116 | # Stack the candidate pin embedding with the sequence embedding 117 | item_embedding_expanded = item_embedding.unsqueeze(1).expand( 118 | -1, self.seq_len, -1 119 | ) 120 | action_pin_emb = torch.cat( 121 | (action_pin_emb, item_embedding_expanded), dim=-1 122 | ) 123 | 124 | # step 5: pass the sequence to transformer 125 | tfmr_out = self.transformer_encoder( 126 | src=action_pin_emb, src_key_padding_mask=key_padding_mask 127 | ) 128 | 129 | # step 6: process the transformer output 130 | output_concat = [] 131 | if self.transact_config.concat_max_pool: 132 | # Apply max pooling to the transformer output 133 | pooled_out = self.out_linear(tfmr_out.max(dim=1).values) 134 | output_concat.append(pooled_out) 135 | if self.latest_n_emb > 0: 136 | tfmr_out = tfmr_out[:, : self.latest_n_emb] 137 | output_concat.append(tfmr_out.flatten(1)) 138 | return torch.cat(output_concat, dim=1) 139 | 140 | def _adjust_mask(self, mask: torch.Tensor, short_time_window_idx: torch.Tensor): 141 | # make sure not all actions in the sequence are masked 142 | mask = torch.bitwise_or(mask, short_time_window_idx) 143 | mask[:, 0] = torch.zeros(mask.shape[0], dtype=mask.dtype, device=mask.device) 144 | new_attn_mask = torch.zeros_like(mask, dtype=torch.float, device=mask.device) 145 | new_attn_mask.masked_fill_(mask, float("-inf")) 146 | return new_attn_mask 147 | -------------------------------------------------------------------------------- /transact_code/transact_config.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | 4 | @dataclass 5 | class TransActConfig: 6 | """ 7 | Configuration class to build a TransAct PyTorch module. 8 | 9 | :param seq_len: Length of the input sequence 10 | :param time_window_ms: Time window in milliseconds for random window mask 11 | :param latest_n_emb: Number of latest embeddings to use in output 12 | :param concat_candidate_emb: Whether to concatenate candidate embeddings with user sequence 13 | :param concat_max_pool: Whether to apply max pooling to the output of the transformer encoder and append it to output 14 | :param action_vocab: Vocabulary of user actions 15 | :param action_emb_dim: Dimension of user action embeddings 16 | :param item_emb_dim: Dimension of item embeddings 17 | :param num_layer: Number of TransformerEncoderLayer 18 | :param nhead: Number of heads in the TransformerEncoderLayer 19 | :param dim_feedforward: Feed forward dimension of the TransformerEncoderLayer 20 | """ 21 | 22 | seq_len: int = 100 23 | time_window_ms: int = 1000 * 60 * 60 * 1 24 | latest_n_emb: int = 10 25 | concat_candidate_emb: bool = True 26 | concat_max_pool: bool = True 27 | action_vocab: list = range(0, 20) 28 | action_emb_dim: int = 32 29 | item_emb_dim: int = 32 30 | num_layer: int = 2 31 | nhead: int = 2 32 | dim_feedforward: int = 32 33 | --------------------------------------------------------------------------------