├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── config ├── APAN.yml ├── DySAT.yml ├── JODIE.yml ├── TGAT.yml ├── TGN.yml ├── dist │ ├── APAN.yml │ ├── DySAT.yml │ ├── DySAT_MAG.yml │ ├── JODIE.yml │ ├── TGAT.yml │ └── TGN.yml └── readme.yml ├── down.sh ├── extract_node_dist.py ├── gen_graph.py ├── layers.py ├── memorys.py ├── models ├── GDELT_APAN.pkl ├── GDELT_DySAT.pkl ├── GDELT_JODIE.pkl ├── GDELT_TGAT.pkl ├── GDELT_TGN.pkl ├── MAG_DySAT.pkl ├── MAG_JODIE.pkl ├── MAG_TGAT.pkl ├── MAG_TGN.pkl ├── REDDIT_APAN.pkl ├── REDDIT_DySAT.pkl ├── REDDIT_JODIE.pkl ├── REDDIT_TGAT.pkl ├── REDDIT_TGN.pkl ├── WIKI_APAN.pkl ├── WIKI_DySAT.pkl ├── WIKI_JODIE.pkl ├── WIKI_TGAT.pkl └── WIKI_TGN.pkl ├── modules.py ├── mount_shm.sh ├── sampler.py ├── sampler_core.cpp ├── setup.py ├── train.py ├── train_dist.py ├── train_node.py └── utils.py /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TGL: A General Framework for Temporal Graph Training on Billion-Scale Graphs 2 | 3 | ## Overview 4 | 5 | This repo is the open-sourced code for our work *TGL: A General Framework for Temporal Graph Training on Billion-Scale Graphs*. 6 | 7 | ## Requirements 8 | - python >= 3.6.13 9 | - pytorch >= 1.8.1 10 | - pandas >= 1.1.5 11 | - numpy >= 1.19.5 12 | - dgl >= 0.6.1 13 | - pyyaml >= 5.4.1 14 | - tqdm >= 4.61.0 15 | - pybind11 >= 2.6.2 16 | - g++ >= 7.5.0 17 | - openmp >= 201511 18 | 19 | Our temporal sampler is implemented using C++, please compile the sampler first with the following command 20 | > python setup.py build_ext --inplace 21 | 22 | ## Dataset 23 | 24 | [2022/06/29] We noticed that we uploaded the wrong version of the GDELT dataset and have uploaded the correct version. Please re-download all the files in the GDELT folder. Sorry of any inconvenience created. 25 | 26 | The four datasets used in our paper are available to download from AWS S3 bucket using the `down.sh` script. The total download size is around 350GB. 27 | 28 | To use your own dataset, you need to put the following files in the folder `\DATA\\\` 29 | 30 | 1. `edges.csv`: The file that stores temporal edge informations. The csv should have the following columns with the header as `,src,dst,time,ext_roll` where each of the column refers to edge index (start with zero), source node index (start with zero), destination node index, time stamp, extrapolation roll (0 for training edges, 1 for validation edges, 2 for test edges). The CSV should be sorted by time ascendingly. 31 | 2. `ext_full.npz`: The T-CSR representation of the temporal graph. We provide a script to generate this file from `edges.csv`. You can use the following command to use the script 32 | >python gen_graph.py --data \ 33 | 3. `edge_features.pt` (optional): The torch tensor that stores the edge featrues row-wise with shape (num edges, dim edge features). *Note: at least one of `edge_features.pt` or `node_features.pt` should present.* 34 | 4. `node_features.pt` (optional): The torch tensor that stores the node featrues row-wise with shape (num nodes, dim node features). *Note: at least one of `edge_features.pt` or `node_features.pt` should present.* 35 | 5. `labels.csv` (optional): The file contains node labels for dynamic node classification task. The csv should have the following columns with the header as `,node,time,label,ext_roll` where each of the column refers to node label index (start with zero), node index (start with zero), time stamp, node label, extrapolation roll (0 for training node labels, 1 for validation node labels, 2 for test node labels). The CSV should be sorted by time ascendingly. 36 | 37 | ## Configuration Files 38 | 39 | We provide example configuration files for five temporal GNN methods: JODIE, DySAT, TGAT, TGN and TGAT. The configuration files for single GPU training are located at `/config/` while the multiple GPUs training configuration files are located at `/config/dist/`. 40 | 41 | The provided configuration files are all tested to be working. If you want to use your own network architecture, please refer to `/config/readme.yml` for the meaining of each entry in the yaml configuration file. As our framework is still under development, it possible that some combination of the confiruations will lead to bug. 42 | 43 | ## Run 44 | 45 | Currently, our framework only supports extrapolation setting (inference for the future). 46 | 47 | ### Single GPU Link Prediction 48 | >python train.py --data \ --config \ 49 | 50 | ### MultiGPU Link Prediction 51 | >python -m torch.distributed.launch --nproc_per_node=\ train_dist.py --data \ --config \ --num_gpus \ 52 | 53 | ### Dynamic Node Classification 54 | 55 | Currenlty, TGL only supports performing dynamic node classification using the dynamic node embedding generated in link prediction. 56 | 57 | For Single GPU models, directly run 58 | >python train_node.py --data \ --config \ --model \ 59 | 60 | For multi-GPU models, you need to first generate the dynamic node embedding 61 | >python -m torch.distributed.launch --nproc_per_node=\ extract_node_dist.py --data \ --config \ --num_gpus \ --model \ 62 | 63 | After generating the node embeding for multi-GPU models, run 64 | >python train_node.py --data \ --model \ 65 | 66 | ## Security 67 | 68 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 69 | 70 | ## Cite 71 | 72 | If you use TGL in a scientific publication, we would appreciate citations to the following paper: 73 | 74 | ``` 75 | @article{zhou2022tgl, 76 | title={{TGL}: A General Framework for Temporal GNN Training on Billion-Scale Graphs}, 77 | author={Zhou, Hongkuan and Zheng, Da and Nisa, Israt and Ioannidis, Vasileios and Song, Xiang and Karypis, George}, 78 | year = {2022}, 79 | journal = {Proc. VLDB Endow.}, 80 | volume = {15}, 81 | number = {8}, 82 | } 83 | ``` 84 | 85 | ## License 86 | 87 | This project is licensed under the Apache-2.0 License. 88 | -------------------------------------------------------------------------------- /config/APAN.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - layer: 1 3 | neighbor: 4 | - 10 5 | strategy: 'recent' 6 | prop_time: False 7 | history: 1 8 | duration: 0 9 | num_thread: 32 10 | no_neg: True 11 | memory: 12 | - type: 'node' 13 | dim_time: 100 14 | deliver_to: 'neighbors' 15 | mail_combine: 'last' 16 | memory_update: 'transformer' 17 | attention_head: 2 18 | mailbox_size: 10 19 | combine_node_feature: False 20 | dim_out: 100 21 | gnn: 22 | - arch: 'identity' 23 | train: 24 | - epoch: 100 25 | batch_size: 600 26 | lr: 0.0001 27 | dropout: 0.1 28 | att_dropout: 0.1 29 | # all_on_gpu: True -------------------------------------------------------------------------------- /config/DySAT.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - layer: 2 3 | neighbor: 4 | - 10 5 | - 10 6 | strategy: 'uniform' 7 | prop_time: True 8 | history: 3 9 | duration: 10000 10 | num_thread: 32 11 | memory: 12 | - type: 'none' 13 | dim_out: 0 14 | gnn: 15 | - arch: 'transformer_attention' 16 | layer: 2 17 | att_head: 2 18 | dim_time: 0 19 | dim_out: 100 20 | combine: 'rnn' 21 | train: 22 | - epoch: 50 23 | batch_size: 600 24 | lr: 0.0001 25 | dropout: 0.1 26 | att_dropout: 0.1 27 | all_on_gpu: True -------------------------------------------------------------------------------- /config/JODIE.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - no_sample: True 3 | history: 1 4 | memory: 5 | - type: 'node' 6 | dim_time: 100 7 | deliver_to: 'self' 8 | mail_combine: 'last' 9 | memory_update: 'rnn' 10 | mailbox_size: 1 11 | combine_node_feature: True 12 | dim_out: 100 13 | gnn: 14 | - arch: 'identity' 15 | time_transform: 'JODIE' 16 | train: 17 | - epoch: 100 18 | batch_size: 600 19 | lr: 0.0001 20 | dropout: 0.1 21 | all_on_gpu: True -------------------------------------------------------------------------------- /config/TGAT.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - layer: 2 3 | neighbor: 4 | - 10 5 | - 10 6 | strategy: 'uniform' 7 | prop_time: False 8 | history: 1 9 | duration: 0 10 | num_thread: 32 11 | memory: 12 | - type: 'none' 13 | dim_out: 0 14 | gnn: 15 | - arch: 'transformer_attention' 16 | layer: 2 17 | att_head: 2 18 | dim_time: 100 19 | dim_out: 100 20 | train: 21 | - epoch: 100 22 | batch_size: 600 23 | lr: 0.0001 24 | dropout: 0.1 25 | att_dropout: 0.1 26 | all_on_gpu: True -------------------------------------------------------------------------------- /config/TGN.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - layer: 1 3 | neighbor: 4 | - 10 5 | strategy: 'recent' 6 | prop_time: False 7 | history: 1 8 | duration: 0 9 | num_thread: 32 10 | memory: 11 | - type: 'node' 12 | dim_time: 100 13 | deliver_to: 'self' 14 | mail_combine: 'last' 15 | memory_update: 'gru' 16 | mailbox_size: 1 17 | combine_node_feature: True 18 | dim_out: 100 19 | gnn: 20 | - arch: 'transformer_attention' 21 | layer: 1 22 | att_head: 2 23 | dim_time: 100 24 | dim_out: 100 25 | train: 26 | - epoch: 100 27 | batch_size: 600 28 | # reorder: 16 29 | lr: 0.0001 30 | dropout: 0.2 31 | att_dropout: 0.2 32 | all_on_gpu: True -------------------------------------------------------------------------------- /config/dist/APAN.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - layer: 1 3 | neighbor: 4 | - 10 5 | strategy: 'recent' 6 | prop_time: False 7 | history: 1 8 | duration: 0 9 | num_thread: 64 10 | no_neg: True 11 | memory: 12 | - type: 'node' 13 | dim_time: 100 14 | deliver_to: 'neighbors' 15 | mail_combine: 'last' 16 | memory_update: 'transformer' 17 | attention_head: 2 18 | mailbox_size: 10 19 | combine_node_feature: False 20 | dim_out: 100 21 | gnn: 22 | - arch: 'identity' 23 | train: 24 | - epoch: 30 25 | batch_size: 4000 # local batch_size 26 | lr: 0.0001 27 | dropout: 0.1 28 | att_dropout: 0.1 29 | reorder: 8 -------------------------------------------------------------------------------- /config/dist/DySAT.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - layer: 2 3 | neighbor: 4 | - 10 5 | - 10 6 | strategy: 'uniform' 7 | prop_time: True 8 | history: 3 9 | duration: 25 10 | num_thread: 64 11 | memory: 12 | - type: 'none' 13 | dim_out: 0 14 | gnn: 15 | - arch: 'transformer_attention' 16 | layer: 2 17 | att_head: 2 18 | dim_time: 0 19 | dim_out: 100 20 | combine: 'rnn' 21 | train: 22 | - epoch: 10 23 | batch_size: 4000 # local batch_size 24 | lr: 0.0001 25 | dropout: 0.1 26 | att_dropout: 0.1 -------------------------------------------------------------------------------- /config/dist/DySAT_MAG.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - layer: 2 3 | neighbor: 4 | - 10 5 | - 10 6 | strategy: 'uniform' 7 | prop_time: True 8 | history: 3 9 | duration: 5 10 | num_thread: 64 11 | memory: 12 | - type: 'none' 13 | dim_out: 0 14 | gnn: 15 | - arch: 'transformer_attention' 16 | layer: 2 17 | att_head: 2 18 | dim_time: 0 19 | dim_out: 100 20 | combine: 'rnn' 21 | train: 22 | - epoch: 5 23 | batch_size: 4000 # local batch_size 24 | lr: 0.0001 25 | dropout: 0.1 26 | att_dropout: 0.1 -------------------------------------------------------------------------------- /config/dist/JODIE.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - no_sample: True 3 | history: 1 4 | memory: 5 | - type: 'node' 6 | dim_time: 100 7 | deliver_to: 'self' 8 | mail_combine: 'last' 9 | memory_update: 'rnn' 10 | mailbox_size: 1 11 | combine_node_feature: True 12 | dim_out: 100 13 | gnn: 14 | - arch: 'identity' 15 | time_transform: 'JODIE' 16 | train: 17 | - epoch: 10 18 | batch_size: 4000 # local batch_size 19 | lr: 0.0001 20 | dropout: 0.1 21 | reorder: 8 -------------------------------------------------------------------------------- /config/dist/TGAT.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - layer: 2 3 | neighbor: 4 | - 10 5 | - 10 6 | strategy: 'uniform' 7 | prop_time: False 8 | history: 1 9 | duration: 0 10 | num_thread: 64 11 | memory: 12 | - type: 'none' 13 | dim_out: 0 14 | gnn: 15 | - arch: 'transformer_attention' 16 | layer: 2 17 | att_head: 2 18 | dim_time: 100 19 | dim_out: 100 20 | train: 21 | - epoch: 3 22 | batch_size: 4000 # local batch_size 23 | lr: 0.0001 24 | dropout: 0.1 25 | att_dropout: 0.1 -------------------------------------------------------------------------------- /config/dist/TGN.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - layer: 1 3 | neighbor: 4 | - 10 5 | strategy: 'recent' 6 | prop_time: False 7 | history: 1 8 | duration: 0 9 | num_thread: 64 10 | memory: 11 | - type: 'node' 12 | dim_time: 100 13 | deliver_to: 'self' 14 | mail_combine: 'last' 15 | memory_update: 'gru' 16 | mailbox_size: 1 17 | combine_node_feature: True 18 | dim_out: 100 19 | gnn: 20 | - arch: 'transformer_attention' 21 | layer: 1 22 | att_head: 2 23 | dim_time: 100 24 | dim_out: 100 25 | train: 26 | - epoch: 5 27 | batch_size: 4000 # local batch_size 28 | lr: 0.0001 29 | dropout: 0.2 30 | att_dropout: 0.2 31 | reorder: 8 -------------------------------------------------------------------------------- /config/readme.yml: -------------------------------------------------------------------------------- 1 | sampling: 2 | - layer: 3 | neighbor: 4 | strategy: <'recent' that samples most recent neighbors or 'uniform' that uniformly samples neighbors form the past> 5 | prop_time: 6 | history: 7 | duration: 9 | memory: 10 | - type: <'node', we only support node memory now> 11 | dim_time: 12 | deliver_to: <'self' that delivers the mails only to involved nodes or 'neighbors' that deliver the mails to neighbors> 13 | mail_combine: <'last' that use the latest latest mail as the input to the memory updater> 14 | memory_update: <'gru' or 'rnn'> 15 | mailbox_size: 16 | combine_node_feature: 18 | gnn: 19 | - arch: <'transformer_attention' or 'identity' (no GNN)> 20 | layer: 21 | att_head: 22 | dim_time: 23 | dim_out: 24 | train: 25 | - epoch: 26 | batch_size: 27 | reorder: <(optional) an integer that is divisible by batch size the specifies how many chunks per batch used in the random chunk scheduling> 28 | lr: 29 | dropout: 30 | att_dropout: 31 | all_on_gpu: -------------------------------------------------------------------------------- /down.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | wget -P ./DATA/GDELT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/GDELT/int_train.npz 4 | wget -P ./DATA/GDELT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/GDELT/int_full.npz 5 | wget -P ./DATA/GDELT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/GDELT/node_features.pt 6 | wget -P ./DATA/GDELT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/GDELT/labels.csv 7 | wget -P ./DATA/GDELT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/GDELT/ext_full.npz 8 | wget -P ./DATA/GDELT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/GDELT/edges.csv 9 | wget -P ./DATA/GDELT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/GDELT/edge_features.pt 10 | wget -P ./DATA/LASTFM https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/LASTFM/edges.csv 11 | wget -P ./DATA/LASTFM https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/LASTFM/ext_full.npz 12 | wget -P ./DATA/LASTFM https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/LASTFM/int_full.npz 13 | wget -P ./DATA/LASTFM https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/LASTFM/int_train.npz 14 | wget -P ./DATA/MAG https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/MAG/int_train.npz 15 | wget -P ./DATA/MAG https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/MAG/labels.csv 16 | wget -P ./DATA/MAG https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/MAG/int_full.npz .) 17 | wget -P ./DATA/MAG https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/MAG/ext_full.npz 18 | wget -P ./DATA/MAG https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/MAG/edges.csv 19 | wget -P ./DATA/MAG https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/MAG/node_features.pt 20 | wget -P ./DATA/MOOC https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/MOOC/edges.csv 21 | wget -P ./DATA/MOOC https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/MOOC/ext_full.npz 22 | wget -P ./DATA/MOOC https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/MOOC/int_full.npz 23 | wget -P ./DATA/MOOC https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/MOOC/int_train.npz 24 | wget -P ./DATA/REDDIT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/REDDIT/edge_features.pt 25 | wget -P ./DATA/REDDIT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/REDDIT/edges.csv 26 | wget -P ./DATA/REDDIT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/REDDIT/ext_full.npz 27 | wget -P ./DATA/REDDIT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/REDDIT/int_full.npz 28 | wget -P ./DATA/REDDIT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/REDDIT/int_train.npz 29 | wget -P ./DATA/REDDIT https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/REDDIT/labels.csv 30 | wget -P ./DATA/WIKI https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/WIKI/edge_features.pt 31 | wget -P ./DATA/WIKI https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/WIKI/edges.csv 32 | wget -P ./DATA/WIKI https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/WIKI/ext_full.npz 33 | wget -P ./DATA/WIKI https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/WIKI/int_full.npz 34 | wget -P ./DATA/WIKI https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/WIKI/int_train.npz 35 | wget -P ./DATA/WIKI https://s3.us-west-2.amazonaws.com/dgl-data/dataset/tgl/WIKI/labels.csv -------------------------------------------------------------------------------- /extract_node_dist.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | 4 | parser=argparse.ArgumentParser() 5 | parser.add_argument('--data', type=str, help='dataset name') 6 | parser.add_argument('--config', type=str, help='path to config file') 7 | parser.add_argument('--seed', type=int, default=0, help='random seed to use') 8 | parser.add_argument('--num_gpus', type=int, default=4, help='number of gpus to use') 9 | parser.add_argument('--model', type=str, help='path to model file') 10 | parser.add_argument('--batch_size', type=int, default=4000, help='batch size to generate node embeddings') 11 | parser.add_argument('--omp_num_threads', type=int, default=16) 12 | parser.add_argument("--local_rank", type=int, default=-1) 13 | args=parser.parse_args() 14 | 15 | # set which GPU to use 16 | if args.local_rank < args.num_gpus: 17 | os.environ['CUDA_VISIBLE_DEVICES'] = str(args.local_rank) 18 | else: 19 | os.environ['CUDA_VISIBLE_DEVICES'] = '' 20 | os.environ['OMP_NUM_THREADS'] = str(args.omp_num_threads) 21 | os.environ['MKL_NUM_THREADS'] = str(args.omp_num_threads) 22 | 23 | import torch 24 | import dgl 25 | import random 26 | import math 27 | import hashlib 28 | import numpy as np 29 | from tqdm import tqdm 30 | from dgl.utils.shared_mem import create_shared_mem_array, get_shared_mem_array 31 | from sklearn.metrics import average_precision_score, roc_auc_score 32 | from modules import * 33 | from sampler import * 34 | from utils import * 35 | 36 | def set_seed(seed): 37 | random.seed(seed) 38 | np.random.seed(seed) 39 | torch.manual_seed(seed) 40 | torch.cuda.manual_seed_all(seed) 41 | 42 | set_seed(args.seed) 43 | torch.distributed.init_process_group(backend='gloo') 44 | nccl_group = torch.distributed.new_group(ranks=list(range(args.num_gpus)), backend='nccl') 45 | 46 | if args.local_rank == 0: 47 | _node_feats, _edge_feats = load_feat(args.data) 48 | dim_feats = [0, 0, 0, 0, 0, 0] 49 | if args.local_rank == 0: 50 | if _node_feats is not None: 51 | dim_feats[0] = _node_feats.shape[0] 52 | dim_feats[1] = _node_feats.shape[1] 53 | dim_feats[2] = _node_feats.dtype 54 | node_feats = create_shared_mem_array('node_feats', _node_feats.shape, dtype=_node_feats.dtype) 55 | node_feats.copy_(_node_feats) 56 | del _node_feats 57 | else: 58 | node_feats = None 59 | if _edge_feats is not None: 60 | dim_feats[3] = _edge_feats.shape[0] 61 | dim_feats[4] = _edge_feats.shape[1] 62 | dim_feats[5] = _edge_feats.dtype 63 | edge_feats = create_shared_mem_array('edge_feats', _edge_feats.shape, dtype=_edge_feats.dtype) 64 | edge_feats.copy_(_edge_feats) 65 | del _edge_feats 66 | else: 67 | edge_feats = None 68 | torch.distributed.barrier() 69 | torch.distributed.broadcast_object_list(dim_feats, src=0) 70 | if args.local_rank > 0 and args.local_rank < args.num_gpus: 71 | node_feats = None 72 | edge_feats = None 73 | if os.path.exists('DATA/{}/node_features.pt'.format(args.data)): 74 | node_feats = get_shared_mem_array('node_feats', (dim_feats[0], dim_feats[1]), dtype=dim_feats[2]) 75 | if os.path.exists('DATA/{}/edge_features.pt'.format(args.data)): 76 | edge_feats = get_shared_mem_array('edge_feats', (dim_feats[3], dim_feats[4]), dtype=dim_feats[5]) 77 | sample_param, memory_param, gnn_param, train_param = parse_config(args.config) 78 | 79 | path_saver = args.model 80 | 81 | if args.local_rank == args.num_gpus: 82 | g, df = load_graph(args.data) 83 | num_nodes = [g['indptr'].shape[0] - 1] 84 | else: 85 | num_nodes = [None] 86 | torch.distributed.barrier() 87 | torch.distributed.broadcast_object_list(num_nodes, src=args.num_gpus) 88 | num_nodes = num_nodes[0] 89 | 90 | mailbox = None 91 | if memory_param['type'] != 'none': 92 | if args.local_rank == 0: 93 | node_memory = create_shared_mem_array('node_memory', torch.Size([num_nodes, memory_param['dim_out']]), dtype=torch.float32) 94 | node_memory_ts = create_shared_mem_array('node_memory_ts', torch.Size([num_nodes]), dtype=torch.float32) 95 | mails = create_shared_mem_array('mails', torch.Size([num_nodes, memory_param['mailbox_size'], 2 * memory_param['dim_out'] + dim_feats[4]]), dtype=torch.float32) 96 | mail_ts = create_shared_mem_array('mail_ts', torch.Size([num_nodes, memory_param['mailbox_size']]), dtype=torch.float32) 97 | next_mail_pos = create_shared_mem_array('next_mail_pos', torch.Size([num_nodes]), dtype=torch.long) 98 | update_mail_pos = create_shared_mem_array('update_mail_pos', torch.Size([num_nodes]), dtype=torch.int32) 99 | torch.distributed.barrier() 100 | node_memory.zero_() 101 | node_memory_ts.zero_() 102 | mails.zero_() 103 | mail_ts.zero_() 104 | next_mail_pos.zero_() 105 | update_mail_pos.zero_() 106 | else: 107 | torch.distributed.barrier() 108 | node_memory = get_shared_mem_array('node_memory', torch.Size([num_nodes, memory_param['dim_out']]), dtype=torch.float32) 109 | node_memory_ts = get_shared_mem_array('node_memory_ts', torch.Size([num_nodes]), dtype=torch.float32) 110 | mails = get_shared_mem_array('mails', torch.Size([num_nodes, memory_param['mailbox_size'], 2 * memory_param['dim_out'] + dim_feats[4]]), dtype=torch.float32) 111 | mail_ts = get_shared_mem_array('mail_ts', torch.Size([num_nodes, memory_param['mailbox_size']]), dtype=torch.float32) 112 | next_mail_pos = get_shared_mem_array('next_mail_pos', torch.Size([num_nodes]), dtype=torch.long) 113 | update_mail_pos = get_shared_mem_array('update_mail_pos', torch.Size([num_nodes]), dtype=torch.int32) 114 | mailbox = MailBox(memory_param, num_nodes, dim_feats[4], node_memory, node_memory_ts, mails, mail_ts, next_mail_pos, update_mail_pos) 115 | 116 | if args.local_rank < args.num_gpus: 117 | # GPU worker process 118 | model = GeneralModel(dim_feats[1], dim_feats[4], sample_param, memory_param, gnn_param, train_param).cuda() 119 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], process_group=nccl_group, output_device=args.local_rank) 120 | model.load_state_dict(torch.load(path_saver, map_location=torch.device('cuda:0'))) 121 | creterion = torch.nn.BCEWithLogitsLoss() 122 | optimizer = torch.optim.Adam(model.parameters(), lr=train_param['lr']) 123 | while True: 124 | my_model_state = [None] 125 | model_state = [None] * (args.num_gpus + 1) 126 | torch.distributed.scatter_object_list(my_model_state, model_state, src=args.num_gpus) 127 | if my_model_state[0] == -1: 128 | break 129 | elif my_model_state[0] == 4: 130 | continue 131 | elif my_model_state[0] == 2: 132 | torch.save(model.state_dict(), path_saver) 133 | continue 134 | elif my_model_state[0] == 3: 135 | model.load_state_dict(torch.load(path_saver, map_location=torch.device('cuda:0'))) 136 | continue 137 | my_mfgs = [None] 138 | multi_mfgs = [None] * (args.num_gpus + 1) 139 | torch.distributed.scatter_object_list(my_mfgs, multi_mfgs, src=args.num_gpus) 140 | mfgs = mfgs_to_cuda(my_mfgs[0]) 141 | prepare_input(mfgs, node_feats, edge_feats) 142 | if my_model_state[0] == 0: 143 | model.train() 144 | optimizer.zero_grad() 145 | if mailbox is not None: 146 | mailbox.prep_input_mails(mfgs[0]) 147 | pred_pos, pred_neg = model(mfgs) 148 | loss = creterion(pred_pos, torch.ones_like(pred_pos)) 149 | loss += creterion(pred_neg, torch.zeros_like(pred_neg)) 150 | loss.backward() 151 | optimizer.step() 152 | if mailbox is not None: 153 | with torch.no_grad(): 154 | my_root = [None] 155 | multi_root = [None] * (args.num_gpus + 1) 156 | my_ts = [None] 157 | multi_ts = [None] * (args.num_gpus + 1) 158 | my_eid = [None] 159 | multi_eid = [None] * (args.num_gpus + 1) 160 | torch.distributed.scatter_object_list(my_root, multi_root, src=args.num_gpus) 161 | torch.distributed.scatter_object_list(my_ts, multi_ts, src=args.num_gpus) 162 | torch.distributed.scatter_object_list(my_eid, multi_eid, src=args.num_gpus) 163 | eid = my_eid[0] 164 | mem_edge_feats = edge_feats[eid] if edge_feats is not None else None 165 | root_nodes = my_root[0] 166 | ts = my_ts[0] 167 | block = None 168 | if memory_param['deliver_to'] == 'neighbors': 169 | my_block = [None] 170 | multi_block = [None] * (args.num_gpus + 1) 171 | torch.distributed.scatter_object_list(my_block, multi_block, src=args.num_gpus) 172 | block = my_block[0] 173 | mailbox.update_mailbox(model.module.memory_updater.last_updated_nid, model.module.memory_updater.last_updated_memory, root_nodes, ts, mem_edge_feats, block) 174 | mailbox.update_memory(model.module.memory_updater.last_updated_nid, model.module.memory_updater.last_updated_memory, model.module.memory_updater.last_updated_ts) 175 | if memory_param['deliver_to'] == 'neighbors': 176 | torch.distributed.barrier(group=nccl_group) 177 | if args.local_rank == 0: 178 | mailbox.update_next_mail_pos() 179 | torch.distributed.gather_object(float(loss), None, dst=args.num_gpus) 180 | elif my_model_state[0] == 1: 181 | model.eval() 182 | with torch.no_grad(): 183 | if mailbox is not None: 184 | mailbox.prep_input_mails(mfgs[0]) 185 | pred_pos, pred_neg = model(mfgs) 186 | if mailbox is not None: 187 | my_root = [None] 188 | multi_root = [None] * (args.num_gpus + 1) 189 | my_ts = [None] 190 | multi_ts = [None] * (args.num_gpus + 1) 191 | my_eid = [None] 192 | multi_eid = [None] * (args.num_gpus + 1) 193 | torch.distributed.scatter_object_list(my_root, multi_root, src=args.num_gpus) 194 | torch.distributed.scatter_object_list(my_ts, multi_ts, src=args.num_gpus) 195 | torch.distributed.scatter_object_list(my_eid, multi_eid, src=args.num_gpus) 196 | eid = my_eid[0] 197 | mem_edge_feats = edge_feats[eid] if edge_feats is not None else None 198 | root_nodes = my_root[0] 199 | ts = my_ts[0] 200 | block = None 201 | if memory_param['deliver_to'] == 'neighbors': 202 | my_block = [None] 203 | multi_block = [None] * (args.num_gpus + 1) 204 | torch.distributed.scatter_object_list(my_block, multi_block, src=args.num_gpus) 205 | block = my_block[0] 206 | mailbox.update_mailbox(model.module.memory_updater.last_updated_nid, model.module.memory_updater.last_updated_memory, root_nodes, ts, mem_edge_feats, block) 207 | mailbox.update_memory(model.module.memory_updater.last_updated_nid, model.module.memory_updater.last_updated_memory, model.module.memory_updater.last_updated_ts) 208 | if memory_param['deliver_to'] == 'neighbors': 209 | torch.distributed.barrier(group=nccl_group) 210 | if args.local_rank == 0: 211 | mailbox.update_next_mail_pos() 212 | y_pred = torch.cat([pred_pos, pred_neg], dim=0).sigmoid().cpu() 213 | y_true = torch.cat([torch.ones(pred_pos.size(0)), torch.zeros(pred_neg.size(0))], dim=0) 214 | ap = average_precision_score(y_true, y_pred) 215 | auc = roc_auc_score(y_true, y_pred) 216 | torch.distributed.gather_object(float(ap), None, dst=args.num_gpus) 217 | torch.distributed.gather_object(float(auc), None, dst=args.num_gpus) 218 | elif my_model_state[0] == 5: 219 | model.eval() 220 | with torch.no_grad(): 221 | if mailbox is not None: 222 | mailbox.prep_input_mails(mfgs[0]) 223 | emb = model.module.get_emb(mfgs).detach().cpu() 224 | torch.distributed.gather_object(emb, None, dst=args.num_gpus) 225 | else: 226 | # hosting process 227 | train_edge_end = df[df['ext_roll'].gt(0)].index[0] 228 | val_edge_end = df[df['ext_roll'].gt(1)].index[0] 229 | sampler = None 230 | if not ('no_sample' in sample_param and sample_param['no_sample']): 231 | sampler = ParallelSampler(g['indptr'], g['indices'], g['eid'], g['ts'].astype(np.float32), 232 | sample_param['num_thread'], 1, sample_param['layer'], sample_param['neighbor'], 233 | sample_param['strategy']=='recent', sample_param['prop_time'], 234 | sample_param['history'], float(sample_param['duration'])) 235 | neg_link_sampler = NegLinkSampler(g['indptr'].shape[0] - 1) 236 | 237 | ldf = pd.read_csv('DATA/{}/labels.csv'.format(args.data)) 238 | args.batch_size = math.ceil(len(ldf) / (len(ldf) // args.batch_size // args.num_gpus * args.num_gpus)) 239 | train_param['batch_size'] = math.ceil(len(df) / (len(df) // train_param['batch_size'] // args.num_gpus * args.num_gpus)) 240 | 241 | processed_edge_id = 0 242 | def forward_model_to(time): 243 | global processed_edge_id 244 | if processed_edge_id >= len(df): 245 | return 246 | while df.time[processed_edge_id] < time: 247 | # print('curr:',processed_edge_id,df.time[processed_edge_id],'target:',time) 248 | multi_mfgs = list() 249 | multi_root = list() 250 | multi_ts = list() 251 | multi_eid = list() 252 | multi_block = list() 253 | for _ in range(args.num_gpus): 254 | if processed_edge_id >= len(df): 255 | break 256 | rows = df[processed_edge_id:min(len(df), processed_edge_id + train_param['batch_size'])] 257 | root_nodes = np.concatenate([rows.src.values, rows.dst.values, neg_link_sampler.sample(len(rows))]).astype(np.int32) 258 | ts = np.concatenate([rows.time.values, rows.time.values, rows.time.values]).astype(np.float32) 259 | if sampler is not None: 260 | if 'no_neg' in sample_param and sample_param['no_neg']: 261 | pos_root_end = root_nodes.shape[0] * 2 // 3 262 | sampler.sample(root_nodes[:pos_root_end], ts[:pos_root_end]) 263 | else: 264 | sampler.sample(root_nodes, ts) 265 | ret = sampler.get_ret() 266 | if gnn_param['arch'] != 'identity': 267 | mfgs = to_dgl_blocks(ret, sample_param['history'], cuda=False) 268 | else: 269 | mfgs = node_to_dgl_blocks(root_nodes, ts, cuda=False) 270 | multi_mfgs.append(mfgs) 271 | multi_root.append(root_nodes) 272 | multi_ts.append(ts) 273 | multi_eid.append(rows['Unnamed: 0'].values) 274 | if mailbox is not None and memory_param['deliver_to'] == 'neighbors': 275 | multi_block.append(to_dgl_blocks(ret, sample_param['history'], reverse=True, cuda=False)[0][0]) 276 | processed_edge_id += train_param['batch_size'] 277 | if processed_edge_id >= len(df): 278 | return 279 | model_state = [1] * (args.num_gpus + 1) 280 | my_model_state = [None] 281 | torch.distributed.scatter_object_list(my_model_state, model_state, src=args.num_gpus) 282 | multi_mfgs.append(None) 283 | my_mfgs = [None] 284 | torch.distributed.scatter_object_list(my_mfgs, multi_mfgs, src=args.num_gpus) 285 | if mailbox is not None: 286 | multi_root.append(None) 287 | multi_ts.append(None) 288 | multi_eid.append(None) 289 | my_root = [None] 290 | my_ts = [None] 291 | my_eid = [None] 292 | torch.distributed.scatter_object_list(my_root, multi_root, src=args.num_gpus) 293 | torch.distributed.scatter_object_list(my_ts, multi_ts, src=args.num_gpus) 294 | torch.distributed.scatter_object_list(my_eid, multi_eid, src=args.num_gpus) 295 | if memory_param['deliver_to'] == 'neighbors': 296 | multi_block.append(None) 297 | my_block = [None] 298 | torch.distributed.scatter_object_list(my_block, multi_block, src=args.num_gpus) 299 | gathered_ap = [None] * (args.num_gpus + 1) 300 | gathered_auc = [None] * (args.num_gpus + 1) 301 | torch.distributed.gather_object(float(0), gathered_ap, dst=args.num_gpus) 302 | torch.distributed.gather_object(float(0), gathered_auc, dst=args.num_gpus) 303 | if processed_edge_id >= len(df): 304 | break 305 | 306 | embs = list() 307 | multi_mfgs = list() 308 | for _, rows in tqdm(ldf.groupby(ldf.index // args.batch_size)): 309 | root_nodes = rows.node.values.astype(np.int32) 310 | ts = rows.time.values.astype(np.float32) 311 | if args.data == 'MAG': 312 | # allow paper to sample neighbors 313 | ts += 1 314 | if sampler is not None: 315 | sampler.sample(root_nodes, ts) 316 | ret = sampler.get_ret() 317 | if gnn_param['arch'] != 'identity': 318 | mfgs = to_dgl_blocks(ret, sample_param['history'], cuda=False) 319 | else: 320 | mfgs = node_to_dgl_blocks(root_nodes, ts, cuda=False) 321 | multi_mfgs.append(mfgs) 322 | if len(multi_mfgs) == args.num_gpus: 323 | forward_model_to(ts[-1]) 324 | model_state = [5] * (args.num_gpus + 1) 325 | my_model_state = [None] 326 | torch.distributed.scatter_object_list(my_model_state, model_state, src=args.num_gpus) 327 | multi_mfgs.append(None) 328 | my_mfgs = [None] 329 | torch.distributed.scatter_object_list(my_mfgs, multi_mfgs, src=args.num_gpus) 330 | multi_embs = [None] * (args.num_gpus + 1) 331 | torch.distributed.gather_object(None, multi_embs, dst=args.num_gpus) 332 | embs += multi_embs[:-1] 333 | multi_mfgs = list() 334 | 335 | emb_file_name = hashlib.md5(str(torch.load(args.model, map_location=torch.device('cpu'))).encode('utf-8')).hexdigest() + '.pt' 336 | if not os.path.isdir('embs'): 337 | os.mkdir('embs') 338 | embs = torch.cat(embs, dim=0) 339 | print('Embedding shape:', embs.shape) 340 | torch.save(embs, 'embs/' + emb_file_name) 341 | 342 | # let all process exit 343 | model_state = [-1] * (args.num_gpus + 1) 344 | my_model_state = [None] 345 | torch.distributed.scatter_object_list(my_model_state, model_state, src=args.num_gpus) -------------------------------------------------------------------------------- /gen_graph.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import itertools 3 | import pandas as pd 4 | import numpy as np 5 | from tqdm import tqdm 6 | 7 | parser=argparse.ArgumentParser() 8 | parser.add_argument('--data', type=str, help='dataset name') 9 | parser.add_argument('--add_reverse', default=False, action='store_true') 10 | args=parser.parse_args() 11 | 12 | df = pd.read_csv('DATA/{}/edges.csv'.format(args.data)) 13 | num_nodes = max(int(df['src'].max()), int(df['dst'].max())) + 1 14 | print('num_nodes: ', num_nodes) 15 | 16 | int_train_indptr = np.zeros(num_nodes + 1, dtype=np.int) 17 | int_train_indices = [[] for _ in range(num_nodes)] 18 | int_train_ts = [[] for _ in range(num_nodes)] 19 | int_train_eid = [[] for _ in range(num_nodes)] 20 | 21 | int_full_indptr = np.zeros(num_nodes + 1, dtype=np.int) 22 | int_full_indices = [[] for _ in range(num_nodes)] 23 | int_full_ts = [[] for _ in range(num_nodes)] 24 | int_full_eid = [[] for _ in range(num_nodes)] 25 | 26 | ext_full_indptr = np.zeros(num_nodes + 1, dtype=np.int) 27 | ext_full_indices = [[] for _ in range(num_nodes)] 28 | ext_full_ts = [[] for _ in range(num_nodes)] 29 | ext_full_eid = [[] for _ in range(num_nodes)] 30 | 31 | for idx, row in tqdm(df.iterrows(), total=len(df)): 32 | src = int(row['src']) 33 | dst = int(row['dst']) 34 | if row['int_roll'] == 0: 35 | int_train_indices[src].append(dst) 36 | int_train_ts[src].append(row['time']) 37 | int_train_eid[src].append(idx) 38 | if args.add_reverse: 39 | int_train_indices[dst].append(src) 40 | int_train_ts[dst].append(row['time']) 41 | int_train_eid[dst].append(idx) 42 | # int_train_indptr[src + 1:] += 1 43 | if row['int_roll'] != 3: 44 | int_full_indices[src].append(dst) 45 | int_full_ts[src].append(row['time']) 46 | int_full_eid[src].append(idx) 47 | if args.add_reverse: 48 | int_full_indices[dst].append(src) 49 | int_full_ts[dst].append(row['time']) 50 | int_full_eid[dst].append(idx) 51 | # int_full_indptr[src + 1:] += 1 52 | ext_full_indices[src].append(dst) 53 | ext_full_ts[src].append(row['time']) 54 | ext_full_eid[src].append(idx) 55 | if args.add_reverse: 56 | ext_full_indices[dst].append(src) 57 | ext_full_ts[dst].append(row['time']) 58 | ext_full_eid[dst].append(idx) 59 | # ext_full_indptr[src + 1:] += 1 60 | 61 | for i in tqdm(range(num_nodes)): 62 | int_train_indptr[i + 1] = int_train_indptr[i] + len(int_train_indices[i]) 63 | int_full_indptr[i + 1] = int_full_indptr[i] + len(int_full_indices[i]) 64 | ext_full_indptr[i + 1] = ext_full_indptr[i] + len(ext_full_indices[i]) 65 | 66 | int_train_indices = np.array(list(itertools.chain(*int_train_indices))) 67 | int_train_ts = np.array(list(itertools.chain(*int_train_ts))) 68 | int_train_eid = np.array(list(itertools.chain(*int_train_eid))) 69 | 70 | int_full_indices = np.array(list(itertools.chain(*int_full_indices))) 71 | int_full_ts = np.array(list(itertools.chain(*int_full_ts))) 72 | int_full_eid = np.array(list(itertools.chain(*int_full_eid))) 73 | 74 | ext_full_indices = np.array(list(itertools.chain(*ext_full_indices))) 75 | ext_full_ts = np.array(list(itertools.chain(*ext_full_ts))) 76 | ext_full_eid = np.array(list(itertools.chain(*ext_full_eid))) 77 | 78 | print('Sorting...') 79 | def tsort(i, indptr, indices, t, eid): 80 | beg = indptr[i] 81 | end = indptr[i + 1] 82 | sidx = np.argsort(t[beg:end]) 83 | indices[beg:end] = indices[beg:end][sidx] 84 | t[beg:end] = t[beg:end][sidx] 85 | eid[beg:end] = eid[beg:end][sidx] 86 | 87 | for i in tqdm(range(int_train_indptr.shape[0] - 1)): 88 | tsort(i, int_train_indptr, int_train_indices, int_train_ts, int_train_eid) 89 | tsort(i, int_full_indptr, int_full_indices, int_full_ts, int_full_eid) 90 | tsort(i, ext_full_indptr, ext_full_indices, ext_full_ts, ext_full_eid) 91 | 92 | # import pdb; pdb.set_trace() 93 | print('saving...') 94 | np.savez('DATA/{}/int_train.npz'.format(args.data), indptr=int_train_indptr, indices=int_train_indices, ts=int_train_ts, eid=int_train_eid) 95 | np.savez('DATA/{}/int_full.npz'.format(args.data), indptr=int_full_indptr, indices=int_full_indices, ts=int_full_ts, eid=int_full_eid) 96 | np.savez('DATA/{}/ext_full.npz'.format(args.data), indptr=ext_full_indptr, indices=ext_full_indices, ts=ext_full_ts, eid=ext_full_eid) -------------------------------------------------------------------------------- /layers.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import dgl 3 | import math 4 | import numpy as np 5 | 6 | class TimeEncode(torch.nn.Module): 7 | 8 | def __init__(self, dim): 9 | super(TimeEncode, self).__init__() 10 | self.dim = dim 11 | self.w = torch.nn.Linear(1, dim) 12 | self.w.weight = torch.nn.Parameter((torch.from_numpy(1 / 10 ** np.linspace(0, 9, dim, dtype=np.float32))).reshape(dim, -1)) 13 | self.w.bias = torch.nn.Parameter(torch.zeros(dim)) 14 | 15 | def forward(self, t): 16 | output = torch.cos(self.w(t.reshape((-1, 1)))) 17 | return output 18 | 19 | class EdgePredictor(torch.nn.Module): 20 | 21 | def __init__(self, dim_in): 22 | super(EdgePredictor, self).__init__() 23 | self.dim_in = dim_in 24 | self.src_fc = torch.nn.Linear(dim_in, dim_in) 25 | self.dst_fc = torch.nn.Linear(dim_in, dim_in) 26 | self.out_fc = torch.nn.Linear(dim_in, 1) 27 | 28 | def forward(self, h, neg_samples=1): 29 | num_edge = h.shape[0] // (neg_samples + 2) 30 | h_src = self.src_fc(h[:num_edge]) 31 | h_pos_dst = self.dst_fc(h[num_edge:2 * num_edge]) 32 | h_neg_dst = self.dst_fc(h[2 * num_edge:]) 33 | h_pos_edge = torch.nn.functional.relu(h_src + h_pos_dst) 34 | h_neg_edge = torch.nn.functional.relu(h_src.tile(neg_samples, 1) + h_neg_dst) 35 | return self.out_fc(h_pos_edge), self.out_fc(h_neg_edge) 36 | 37 | 38 | class TransfomerAttentionLayer(torch.nn.Module): 39 | 40 | def __init__(self, dim_node_feat, dim_edge_feat, dim_time, num_head, dropout, att_dropout, dim_out, combined=False): 41 | super(TransfomerAttentionLayer, self).__init__() 42 | self.num_head = num_head 43 | self.dim_node_feat = dim_node_feat 44 | self.dim_edge_feat = dim_edge_feat 45 | self.dim_time = dim_time 46 | self.dim_out = dim_out 47 | self.dropout = torch.nn.Dropout(dropout) 48 | self.att_dropout = torch.nn.Dropout(att_dropout) 49 | self.att_act = torch.nn.LeakyReLU(0.2) 50 | self.combined = combined 51 | if dim_time > 0: 52 | self.time_enc = TimeEncode(dim_time) 53 | if combined: 54 | if dim_node_feat > 0: 55 | self.w_q_n = torch.nn.Linear(dim_node_feat, dim_out) 56 | self.w_k_n = torch.nn.Linear(dim_node_feat, dim_out) 57 | self.w_v_n = torch.nn.Linear(dim_node_feat, dim_out) 58 | if dim_edge_feat > 0: 59 | self.w_k_e = torch.nn.Linear(dim_edge_feat, dim_out) 60 | self.w_v_e = torch.nn.Linear(dim_edge_feat, dim_out) 61 | if dim_time > 0: 62 | self.w_q_t = torch.nn.Linear(dim_time, dim_out) 63 | self.w_k_t = torch.nn.Linear(dim_time, dim_out) 64 | self.w_v_t = torch.nn.Linear(dim_time, dim_out) 65 | else: 66 | if dim_node_feat + dim_time > 0: 67 | self.w_q = torch.nn.Linear(dim_node_feat + dim_time, dim_out) 68 | self.w_k = torch.nn.Linear(dim_node_feat + dim_edge_feat + dim_time, dim_out) 69 | self.w_v = torch.nn.Linear(dim_node_feat + dim_edge_feat + dim_time, dim_out) 70 | self.w_out = torch.nn.Linear(dim_node_feat + dim_out, dim_out) 71 | self.layer_norm = torch.nn.LayerNorm(dim_out) 72 | 73 | def forward(self, b): 74 | assert(self.dim_time + self.dim_node_feat + self.dim_edge_feat > 0) 75 | if b.num_edges() == 0: 76 | return torch.zeros((b.num_dst_nodes(), self.dim_out), device=torch.device('cuda:0')) 77 | if self.dim_time > 0: 78 | time_feat = self.time_enc(b.edata['dt']) 79 | zero_time_feat = self.time_enc(torch.zeros(b.num_dst_nodes(), dtype=torch.float32, device=torch.device('cuda:0'))) 80 | if self.combined: 81 | Q = torch.zeros((b.num_edges(), self.dim_out), device=torch.device('cuda:0')) 82 | K = torch.zeros((b.num_edges(), self.dim_out), device=torch.device('cuda:0')) 83 | V = torch.zeros((b.num_edges(), self.dim_out), device=torch.device('cuda:0')) 84 | if self.dim_node_feat > 0: 85 | Q += self.w_q_n(b.srcdata['h'][:b.num_dst_nodes()])[b.edges()[1]] 86 | K += self.w_k_n(b.srcdata['h'][b.num_dst_nodes():])[b.edges()[0] - b.num_dst_nodes()] 87 | V += self.w_v_n(b.srcdata['h'][b.num_dst_nodes():])[b.edges()[0] - b.num_dst_nodes()] 88 | if self.dim_edge_feat > 0: 89 | K += self.w_k_e(b.edata['f']) 90 | V += self.w_v_e(b.edata['f']) 91 | if self.dim_time > 0: 92 | Q += self.w_q_t(zero_time_feat)[b.edges()[1]] 93 | K += self.w_k_t(time_feat) 94 | V += self.w_v_t(time_feat) 95 | Q = torch.reshape(Q, (Q.shape[0], self.num_head, -1)) 96 | K = torch.reshape(K, (K.shape[0], self.num_head, -1)) 97 | V = torch.reshape(V, (V.shape[0], self.num_head, -1)) 98 | att = dgl.ops.edge_softmax(b, self.att_act(torch.sum(Q*K, dim=2))) 99 | att = self.att_dropout(att) 100 | V = torch.reshape(V*att[:, :, None], (V.shape[0], -1)) 101 | b.edata['v'] = V 102 | b.update_all(dgl.function.copy_edge('v', 'm'), dgl.function.sum('m', 'h')) 103 | else: 104 | if self.dim_time == 0 and self.dim_node_feat == 0: 105 | Q = torch.ones((b.num_edges(), self.dim_out), device=torch.device('cuda:0')) 106 | K = self.w_k(b.edata['f']) 107 | V = self.w_v(b.edata['f']) 108 | elif self.dim_time == 0 and self.dim_edge_feat == 0: 109 | Q = self.w_q(b.srcdata['h'][:b.num_dst_nodes()])[b.edges()[1]] 110 | K = self.w_k(b.srcdata['h'][b.num_dst_nodes():]) 111 | V = self.w_v(b.srcdata['h'][b.num_dst_nodes():]) 112 | elif self.dim_time == 0: 113 | Q = self.w_q(b.srcdata['h'][:b.num_dst_nodes()])[b.edges()[1]] 114 | K = self.w_k(torch.cat([b.srcdata['h'][b.num_dst_nodes():], b.edata['f']], dim=1)) 115 | V = self.w_v(torch.cat([b.srcdata['h'][b.num_dst_nodes():], b.edata['f']], dim=1)) 116 | elif self.dim_node_feat == 0: 117 | Q = self.w_q(zero_time_feat)[b.edges()[1]] 118 | K = self.w_k(torch.cat([b.edata['f'], time_feat], dim=1)) 119 | V = self.w_v(torch.cat([b.edata['f'], time_feat], dim=1)) 120 | elif self.dim_edge_feat == 0: 121 | Q = self.w_q(torch.cat([b.srcdata['h'][:b.num_dst_nodes()], zero_time_feat], dim=1))[b.edges()[1]] 122 | K = self.w_k(torch.cat([b.srcdata['h'][b.num_dst_nodes():], time_feat], dim=1)) 123 | V = self.w_v(torch.cat([b.srcdata['h'][b.num_dst_nodes():], time_feat], dim=1)) 124 | else: 125 | Q = self.w_q(torch.cat([b.srcdata['h'][:b.num_dst_nodes()], zero_time_feat], dim=1))[b.edges()[1]] 126 | K = self.w_k(torch.cat([b.srcdata['h'][b.num_dst_nodes():], b.edata['f'], time_feat], dim=1)) 127 | V = self.w_v(torch.cat([b.srcdata['h'][b.num_dst_nodes():], b.edata['f'], time_feat], dim=1)) 128 | Q = torch.reshape(Q, (Q.shape[0], self.num_head, -1)) 129 | K = torch.reshape(K, (K.shape[0], self.num_head, -1)) 130 | V = torch.reshape(V, (V.shape[0], self.num_head, -1)) 131 | att = dgl.ops.edge_softmax(b, self.att_act(torch.sum(Q*K, dim=2))) 132 | att = self.att_dropout(att) 133 | V = torch.reshape(V*att[:, :, None], (V.shape[0], -1)) 134 | b.srcdata['v'] = torch.cat([torch.zeros((b.num_dst_nodes(), V.shape[1]), device=torch.device('cuda:0')), V], dim=0) 135 | b.update_all(dgl.function.copy_src('v', 'm'), dgl.function.sum('m', 'h')) 136 | if self.dim_node_feat != 0: 137 | rst = torch.cat([b.dstdata['h'], b.srcdata['h'][:b.num_dst_nodes()]], dim=1) 138 | else: 139 | rst = b.dstdata['h'] 140 | rst = self.w_out(rst) 141 | rst = torch.nn.functional.relu(self.dropout(rst)) 142 | return self.layer_norm(rst) 143 | 144 | class IdentityNormLayer(torch.nn.Module): 145 | 146 | def __init__(self, dim_out): 147 | super(IdentityNormLayer, self).__init__() 148 | self.norm = torch.nn.LayerNorm(dim_out) 149 | 150 | def forward(self, b): 151 | return self.norm(b.srcdata['h']) 152 | 153 | class JODIETimeEmbedding(torch.nn.Module): 154 | 155 | def __init__(self, dim_out): 156 | super(JODIETimeEmbedding, self).__init__() 157 | self.dim_out = dim_out 158 | 159 | class NormalLinear(torch.nn.Linear): 160 | # From Jodie code 161 | def reset_parameters(self): 162 | stdv = 1. / math.sqrt(self.weight.size(1)) 163 | self.weight.data.normal_(0, stdv) 164 | if self.bias is not None: 165 | self.bias.data.normal_(0, stdv) 166 | 167 | self.time_emb = NormalLinear(1, dim_out) 168 | 169 | def forward(self, h, mem_ts, ts): 170 | time_diff = (ts - mem_ts) / (ts + 1) 171 | rst = h * (1 + self.time_emb(time_diff.unsqueeze(1))) 172 | return rst 173 | -------------------------------------------------------------------------------- /memorys.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import dgl 3 | from layers import TimeEncode 4 | from torch_scatter import scatter 5 | 6 | class MailBox(): 7 | 8 | def __init__(self, memory_param, num_nodes, dim_edge_feat, _node_memory=None, _node_memory_ts=None,_mailbox=None, _mailbox_ts=None, _next_mail_pos=None, _update_mail_pos=None): 9 | self.memory_param = memory_param 10 | self.dim_edge_feat = dim_edge_feat 11 | if memory_param['type'] != 'node': 12 | raise NotImplementedError 13 | self.node_memory = torch.zeros((num_nodes, memory_param['dim_out']), dtype=torch.float32) if _node_memory is None else _node_memory 14 | self.node_memory_ts = torch.zeros(num_nodes, dtype=torch.float32) if _node_memory_ts is None else _node_memory_ts 15 | self.mailbox = torch.zeros((num_nodes, memory_param['mailbox_size'], 2 * memory_param['dim_out'] + dim_edge_feat), dtype=torch.float32) if _mailbox is None else _mailbox 16 | self.mailbox_ts = torch.zeros((num_nodes, memory_param['mailbox_size']), dtype=torch.float32) if _mailbox_ts is None else _mailbox_ts 17 | self.next_mail_pos = torch.zeros((num_nodes), dtype=torch.long) if _next_mail_pos is None else _next_mail_pos 18 | self.update_mail_pos = _update_mail_pos 19 | self.device = torch.device('cpu') 20 | 21 | def reset(self): 22 | self.node_memory.fill_(0) 23 | self.node_memory_ts.fill_(0) 24 | self.mailbox.fill_(0) 25 | self.mailbox_ts.fill_(0) 26 | self.next_mail_pos.fill_(0) 27 | 28 | def move_to_gpu(self): 29 | self.node_memory = self.node_memory.cuda() 30 | self.node_memory_ts = self.node_memory_ts.cuda() 31 | self.mailbox = self.mailbox.cuda() 32 | self.mailbox_ts = self.mailbox_ts.cuda() 33 | self.next_mail_pos = self.next_mail_pos.cuda() 34 | self.device = torch.device('cuda:0') 35 | 36 | def allocate_pinned_memory_buffers(self, sample_param, batch_size): 37 | limit = int(batch_size * 3.3) 38 | if 'neighbor' in sample_param: 39 | for i in sample_param['neighbor']: 40 | limit *= i + 1 41 | self.pinned_node_memory_buffs = list() 42 | self.pinned_node_memory_ts_buffs = list() 43 | self.pinned_mailbox_buffs = list() 44 | self.pinned_mailbox_ts_buffs = list() 45 | for _ in range(sample_param['history']): 46 | self.pinned_node_memory_buffs.append(torch.zeros((limit, self.node_memory.shape[1]), pin_memory=True)) 47 | self.pinned_node_memory_ts_buffs.append(torch.zeros((limit,), pin_memory=True)) 48 | self.pinned_mailbox_buffs.append(torch.zeros((limit, self.mailbox.shape[1], self.mailbox.shape[2]), pin_memory=True)) 49 | self.pinned_mailbox_ts_buffs.append(torch.zeros((limit, self.mailbox_ts.shape[1]), pin_memory=True)) 50 | 51 | def prep_input_mails(self, mfg, use_pinned_buffers=False): 52 | for i, b in enumerate(mfg): 53 | if use_pinned_buffers: 54 | idx = b.srcdata['ID'].cpu().long() 55 | torch.index_select(self.node_memory, 0, idx, out=self.pinned_node_memory_buffs[i][:idx.shape[0]]) 56 | b.srcdata['mem'] = self.pinned_node_memory_buffs[i][:idx.shape[0]].cuda(non_blocking=True) 57 | torch.index_select(self.node_memory_ts,0, idx, out=self.pinned_node_memory_ts_buffs[i][:idx.shape[0]]) 58 | b.srcdata['mem_ts'] = self.pinned_node_memory_ts_buffs[i][:idx.shape[0]].cuda(non_blocking=True) 59 | torch.index_select(self.mailbox, 0, idx, out=self.pinned_mailbox_buffs[i][:idx.shape[0]]) 60 | b.srcdata['mem_input'] = self.pinned_mailbox_buffs[i][:idx.shape[0]].reshape(b.srcdata['ID'].shape[0], -1).cuda(non_blocking=True) 61 | torch.index_select(self.mailbox_ts, 0, idx, out=self.pinned_mailbox_ts_buffs[i][:idx.shape[0]]) 62 | b.srcdata['mail_ts'] = self.pinned_mailbox_ts_buffs[i][:idx.shape[0]].cuda(non_blocking=True) 63 | else: 64 | b.srcdata['mem'] = self.node_memory[b.srcdata['ID'].long()].cuda() 65 | b.srcdata['mem_ts'] = self.node_memory_ts[b.srcdata['ID'].long()].cuda() 66 | b.srcdata['mem_input'] = self.mailbox[b.srcdata['ID'].long()].cuda().reshape(b.srcdata['ID'].shape[0], -1) 67 | b.srcdata['mail_ts'] = self.mailbox_ts[b.srcdata['ID'].long()].cuda() 68 | 69 | def update_memory(self, nid, memory, root_nodes, ts, neg_samples=1): 70 | if nid is None: 71 | return 72 | num_true_src_dst = root_nodes.shape[0] // (neg_samples + 2) * 2 73 | with torch.no_grad(): 74 | nid = nid[:num_true_src_dst].to(self.device) 75 | memory = memory[:num_true_src_dst].to(self.device) 76 | ts = ts[:num_true_src_dst].to(self.device) 77 | self.node_memory[nid.long()] = memory 78 | self.node_memory_ts[nid.long()] = ts 79 | 80 | def update_mailbox(self, nid, memory, root_nodes, ts, edge_feats, block, neg_samples=1): 81 | with torch.no_grad(): 82 | num_true_edges = root_nodes.shape[0] // (neg_samples + 2) 83 | memory = memory.to(self.device) 84 | if edge_feats is not None: 85 | edge_feats = edge_feats.to(self.device) 86 | if block is not None: 87 | block = block.to(self.device) 88 | # TGN/JODIE 89 | if self.memory_param['deliver_to'] == 'self': 90 | src = torch.from_numpy(root_nodes[:num_true_edges]).to(self.device) 91 | dst = torch.from_numpy(root_nodes[num_true_edges:num_true_edges * 2]).to(self.device) 92 | mem_src = memory[:num_true_edges] 93 | mem_dst = memory[num_true_edges:num_true_edges * 2] 94 | if self.dim_edge_feat > 0: 95 | src_mail = torch.cat([mem_src, mem_dst, edge_feats], dim=1) 96 | dst_mail = torch.cat([mem_dst, mem_src, edge_feats], dim=1) 97 | else: 98 | src_mail = torch.cat([mem_src, mem_dst], dim=1) 99 | dst_mail = torch.cat([mem_dst, mem_src], dim=1) 100 | mail = torch.cat([src_mail, dst_mail], dim=1).reshape(-1, src_mail.shape[1]) 101 | nid = torch.cat([src.unsqueeze(1), dst.unsqueeze(1)], dim=1).reshape(-1) 102 | mail_ts = torch.from_numpy(ts[:num_true_edges * 2]).to(self.device) 103 | if mail_ts.dtype == torch.float64: 104 | import pdb; pdb.set_trace() 105 | # find unique nid to update mailbox 106 | uni, inv = torch.unique(nid, return_inverse=True) 107 | perm = torch.arange(inv.size(0), dtype=inv.dtype, device=inv.device) 108 | perm = inv.new_empty(uni.size(0)).scatter_(0, inv, perm) 109 | nid = nid[perm] 110 | mail = mail[perm] 111 | mail_ts = mail_ts[perm] 112 | if self.memory_param['mail_combine'] == 'last': 113 | self.mailbox[nid.long(), self.next_mail_pos[nid.long()]] = mail 114 | self.mailbox_ts[nid.long(), self.next_mail_pos[nid.long()]] = mail_ts 115 | if self.memory_param['mailbox_size'] > 1: 116 | self.next_mail_pos[nid.long()] = torch.remainder(self.next_mail_pos[nid.long()] + 1, self.memory_param['mailbox_size']) 117 | # APAN 118 | elif self.memory_param['deliver_to'] == 'neighbors': 119 | mem_src = memory[:num_true_edges] 120 | mem_dst = memory[num_true_edges:num_true_edges * 2] 121 | if self.dim_edge_feat > 0: 122 | src_mail = torch.cat([mem_src, mem_dst, edge_feats], dim=1) 123 | dst_mail = torch.cat([mem_dst, mem_src, edge_feats], dim=1) 124 | else: 125 | src_mail = torch.cat([mem_src, mem_dst], dim=1) 126 | dst_mail = torch.cat([mem_dst, mem_src], dim=1) 127 | mail = torch.cat([src_mail, dst_mail], dim=0) 128 | mail = torch.cat([mail, mail[block.edges()[0].long()]], dim=0) 129 | mail_ts = torch.from_numpy(ts[:num_true_edges * 2]).to(self.device) 130 | mail_ts = torch.cat([mail_ts, mail_ts[block.edges()[0].long()]], dim=0) 131 | if self.memory_param['mail_combine'] == 'mean': 132 | (nid, idx) = torch.unique(block.dstdata['ID'], return_inverse=True) 133 | mail = scatter(mail, idx, reduce='mean', dim=0) 134 | mail_ts = scatter(mail_ts, idx, reduce='mean') 135 | self.mailbox[nid.long(), self.next_mail_pos[nid.long()]] = mail 136 | self.mailbox_ts[nid.long(), self.next_mail_pos[nid.long()]] = mail_ts 137 | elif self.memory_param['mail_combine'] == 'last': 138 | nid = block.dstdata['ID'] 139 | # find unique nid to update mailbox 140 | uni, inv = torch.unique(nid, return_inverse=True) 141 | perm = torch.arange(inv.size(0), dtype=inv.dtype, device=inv.device) 142 | perm = inv.new_empty(uni.size(0)).scatter_(0, inv, perm) 143 | nid = nid[perm] 144 | mail = mail[perm] 145 | mail_ts = mail_ts[perm] 146 | self.mailbox[nid.long(), self.next_mail_pos[nid.long()]] = mail 147 | self.mailbox_ts[nid.long(), self.next_mail_pos[nid.long()]] = mail_ts 148 | else: 149 | raise NotImplementedError 150 | if self.memory_param['mailbox_size'] > 1: 151 | if self.update_mail_pos is None: 152 | self.next_mail_pos[nid.long()] = torch.remainder(self.next_mail_pos[nid.long()] + 1, self.memory_param['mailbox_size']) 153 | else: 154 | self.update_mail_pos[nid.long()] = 1 155 | else: 156 | raise NotImplementedError 157 | 158 | def update_next_mail_pos(self): 159 | if self.update_mail_pos is not None: 160 | nid = torch.where(self.update_mail_pos == 1)[0] 161 | self.next_mail_pos[nid] = torch.remainder(self.next_mail_pos[nid] + 1, self.memory_param['mailbox_size']) 162 | self.update_mail_pos.fill_(0) 163 | 164 | class GRUMemeoryUpdater(torch.nn.Module): 165 | 166 | def __init__(self, memory_param, dim_in, dim_hid, dim_time, dim_node_feat): 167 | super(GRUMemeoryUpdater, self).__init__() 168 | self.dim_hid = dim_hid 169 | self.dim_node_feat = dim_node_feat 170 | self.memory_param = memory_param 171 | self.dim_time = dim_time 172 | self.updater = torch.nn.GRUCell(dim_in + dim_time, dim_hid) 173 | self.last_updated_memory = None 174 | self.last_updated_ts = None 175 | self.last_updated_nid = None 176 | if dim_time > 0: 177 | self.time_enc = TimeEncode(dim_time) 178 | if memory_param['combine_node_feature']: 179 | if dim_node_feat > 0 and dim_node_feat != dim_hid: 180 | self.node_feat_map = torch.nn.Linear(dim_node_feat, dim_hid) 181 | 182 | def forward(self, mfg): 183 | for b in mfg: 184 | if self.dim_time > 0: 185 | time_feat = self.time_enc(b.srcdata['ts'] - b.srcdata['mem_ts']) 186 | b.srcdata['mem_input'] = torch.cat([b.srcdata['mem_input'], time_feat], dim=1) 187 | updated_memory = self.updater(b.srcdata['mem_input'], b.srcdata['mem']) 188 | self.last_updated_ts = b.srcdata['ts'].detach().clone() 189 | self.last_updated_memory = updated_memory.detach().clone() 190 | self.last_updated_nid = b.srcdata['ID'].detach().clone() 191 | if self.memory_param['combine_node_feature']: 192 | if self.dim_node_feat > 0: 193 | if self.dim_node_feat == self.dim_hid: 194 | b.srcdata['h'] += updated_memory 195 | else: 196 | b.srcdata['h'] = updated_memory + self.node_feat_map(b.srcdata['h']) 197 | else: 198 | b.srcdata['h'] = updated_memory 199 | 200 | class RNNMemeoryUpdater(torch.nn.Module): 201 | 202 | def __init__(self, memory_param, dim_in, dim_hid, dim_time, dim_node_feat): 203 | super(RNNMemeoryUpdater, self).__init__() 204 | self.dim_hid = dim_hid 205 | self.dim_node_feat = dim_node_feat 206 | self.memory_param = memory_param 207 | self.dim_time = dim_time 208 | self.updater = torch.nn.RNNCell(dim_in + dim_time, dim_hid) 209 | self.last_updated_memory = None 210 | self.last_updated_ts = None 211 | self.last_updated_nid = None 212 | if dim_time > 0: 213 | self.time_enc = TimeEncode(dim_time) 214 | if memory_param['combine_node_feature']: 215 | if dim_node_feat > 0 and dim_node_feat != dim_hid: 216 | self.node_feat_map = torch.nn.Linear(dim_node_feat, dim_hid) 217 | 218 | def forward(self, mfg): 219 | for b in mfg: 220 | if self.dim_time > 0: 221 | time_feat = self.time_enc(b.srcdata['ts'] - b.srcdata['mem_ts']) 222 | b.srcdata['mem_input'] = torch.cat([b.srcdata['mem_input'], time_feat], dim=1) 223 | updated_memory = self.updater(b.srcdata['mem_input'], b.srcdata['mem']) 224 | self.last_updated_ts = b.srcdata['ts'].detach().clone() 225 | self.last_updated_memory = updated_memory.detach().clone() 226 | self.last_updated_nid = b.srcdata['ID'].detach().clone() 227 | if self.memory_param['combine_node_feature']: 228 | if self.dim_node_feat > 0: 229 | if self.dim_node_feat == self.dim_hid: 230 | b.srcdata['h'] += updated_memory 231 | else: 232 | b.srcdata['h'] = updated_memory + self.node_feat_map(b.srcdata['h']) 233 | else: 234 | b.srcdata['h'] = updated_memory 235 | 236 | class TransformerMemoryUpdater(torch.nn.Module): 237 | 238 | def __init__(self, memory_param, dim_in, dim_out, dim_time, train_param): 239 | super(TransformerMemoryUpdater, self).__init__() 240 | self.memory_param = memory_param 241 | self.dim_time = dim_time 242 | self.att_h = memory_param['attention_head'] 243 | if dim_time > 0: 244 | self.time_enc = TimeEncode(dim_time) 245 | self.w_q = torch.nn.Linear(dim_out, dim_out) 246 | self.w_k = torch.nn.Linear(dim_in + dim_time, dim_out) 247 | self.w_v = torch.nn.Linear(dim_in + dim_time, dim_out) 248 | self.att_act = torch.nn.LeakyReLU(0.2) 249 | self.layer_norm = torch.nn.LayerNorm(dim_out) 250 | self.mlp = torch.nn.Linear(dim_out, dim_out) 251 | self.dropout = torch.nn.Dropout(train_param['dropout']) 252 | self.att_dropout = torch.nn.Dropout(train_param['att_dropout']) 253 | self.last_updated_memory = None 254 | self.last_updated_ts = None 255 | self.last_updated_nid = None 256 | 257 | def forward(self, mfg): 258 | for b in mfg: 259 | Q = self.w_q(b.srcdata['mem']).reshape((b.num_src_nodes(), self.att_h, -1)) 260 | mails = b.srcdata['mem_input'].reshape((b.num_src_nodes(), self.memory_param['mailbox_size'], -1)) 261 | if self.dim_time > 0: 262 | time_feat = self.time_enc(b.srcdata['ts'][:, None] - b.srcdata['mail_ts']).reshape((b.num_src_nodes(), self.memory_param['mailbox_size'], -1)) 263 | mails = torch.cat([mails, time_feat], dim=2) 264 | K = self.w_k(mails).reshape((b.num_src_nodes(), self.memory_param['mailbox_size'], self.att_h, -1)) 265 | V = self.w_v(mails).reshape((b.num_src_nodes(), self.memory_param['mailbox_size'], self.att_h, -1)) 266 | att = self.att_act((Q[:,None,:,:]*K).sum(dim=3)) 267 | att = torch.nn.functional.softmax(att, dim=1) 268 | att = self.att_dropout(att) 269 | rst = (att[:,:,:,None]*V).sum(dim=1) 270 | rst = rst.reshape((rst.shape[0], -1)) 271 | rst += b.srcdata['mem'] 272 | rst = self.layer_norm(rst) 273 | rst = self.mlp(rst) 274 | rst = self.dropout(rst) 275 | rst = torch.nn.functional.relu(rst) 276 | b.srcdata['h'] = rst 277 | self.last_updated_memory = rst.detach().clone() 278 | self.last_updated_nid = b.srcdata['ID'].detach().clone() 279 | self.last_updated_ts = b.srcdata['ts'].detach().clone() 280 | 281 | -------------------------------------------------------------------------------- /models/GDELT_APAN.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/GDELT_APAN.pkl -------------------------------------------------------------------------------- /models/GDELT_DySAT.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/GDELT_DySAT.pkl -------------------------------------------------------------------------------- /models/GDELT_JODIE.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/GDELT_JODIE.pkl -------------------------------------------------------------------------------- /models/GDELT_TGAT.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/GDELT_TGAT.pkl -------------------------------------------------------------------------------- /models/GDELT_TGN.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/GDELT_TGN.pkl -------------------------------------------------------------------------------- /models/MAG_DySAT.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/MAG_DySAT.pkl -------------------------------------------------------------------------------- /models/MAG_JODIE.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/MAG_JODIE.pkl -------------------------------------------------------------------------------- /models/MAG_TGAT.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/MAG_TGAT.pkl -------------------------------------------------------------------------------- /models/MAG_TGN.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/MAG_TGN.pkl -------------------------------------------------------------------------------- /models/REDDIT_APAN.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/REDDIT_APAN.pkl -------------------------------------------------------------------------------- /models/REDDIT_DySAT.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/REDDIT_DySAT.pkl -------------------------------------------------------------------------------- /models/REDDIT_JODIE.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/REDDIT_JODIE.pkl -------------------------------------------------------------------------------- /models/REDDIT_TGAT.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/REDDIT_TGAT.pkl -------------------------------------------------------------------------------- /models/REDDIT_TGN.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/REDDIT_TGN.pkl -------------------------------------------------------------------------------- /models/WIKI_APAN.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/WIKI_APAN.pkl -------------------------------------------------------------------------------- /models/WIKI_DySAT.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/WIKI_DySAT.pkl -------------------------------------------------------------------------------- /models/WIKI_JODIE.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/WIKI_JODIE.pkl -------------------------------------------------------------------------------- /models/WIKI_TGAT.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/WIKI_TGAT.pkl -------------------------------------------------------------------------------- /models/WIKI_TGN.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/tgl/241b336b7e54186f71273d8f2e0d0f08ca52389e/models/WIKI_TGN.pkl -------------------------------------------------------------------------------- /modules.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import dgl 3 | from memorys import * 4 | from layers import * 5 | 6 | class GeneralModel(torch.nn.Module): 7 | 8 | def __init__(self, dim_node, dim_edge, sample_param, memory_param, gnn_param, train_param, combined=False): 9 | super(GeneralModel, self).__init__() 10 | self.dim_node = dim_node 11 | self.dim_node_input = dim_node 12 | self.dim_edge = dim_edge 13 | self.sample_param = sample_param 14 | self.memory_param = memory_param 15 | if not 'dim_out' in gnn_param: 16 | gnn_param['dim_out'] = memory_param['dim_out'] 17 | self.gnn_param = gnn_param 18 | self.train_param = train_param 19 | if memory_param['type'] == 'node': 20 | if memory_param['memory_update'] == 'gru': 21 | self.memory_updater = GRUMemeoryUpdater(memory_param, 2 * memory_param['dim_out'] + dim_edge, memory_param['dim_out'], memory_param['dim_time'], dim_node) 22 | elif memory_param['memory_update'] == 'rnn': 23 | self.memory_updater = RNNMemeoryUpdater(memory_param, 2 * memory_param['dim_out'] + dim_edge, memory_param['dim_out'], memory_param['dim_time'], dim_node) 24 | elif memory_param['memory_update'] == 'transformer': 25 | self.memory_updater = TransformerMemoryUpdater(memory_param, 2 * memory_param['dim_out'] + dim_edge, memory_param['dim_out'], memory_param['dim_time'], train_param) 26 | else: 27 | raise NotImplementedError 28 | self.dim_node_input = memory_param['dim_out'] 29 | self.layers = torch.nn.ModuleDict() 30 | if gnn_param['arch'] == 'transformer_attention': 31 | for h in range(sample_param['history']): 32 | self.layers['l0h' + str(h)] = TransfomerAttentionLayer(self.dim_node_input, dim_edge, gnn_param['dim_time'], gnn_param['att_head'], train_param['dropout'], train_param['att_dropout'], gnn_param['dim_out'], combined=combined) 33 | for l in range(1, gnn_param['layer']): 34 | for h in range(sample_param['history']): 35 | self.layers['l' + str(l) + 'h' + str(h)] = TransfomerAttentionLayer(gnn_param['dim_out'], dim_edge, gnn_param['dim_time'], gnn_param['att_head'], train_param['dropout'], train_param['att_dropout'], gnn_param['dim_out'], combined=False) 36 | elif gnn_param['arch'] == 'identity': 37 | self.gnn_param['layer'] = 1 38 | for h in range(sample_param['history']): 39 | self.layers['l0h' + str(h)] = IdentityNormLayer(self.dim_node_input) 40 | if 'time_transform' in gnn_param and gnn_param['time_transform'] == 'JODIE': 41 | self.layers['l0h' + str(h) + 't'] = JODIETimeEmbedding(gnn_param['dim_out']) 42 | else: 43 | raise NotImplementedError 44 | self.edge_predictor = EdgePredictor(gnn_param['dim_out']) 45 | if 'combine' in gnn_param and gnn_param['combine'] == 'rnn': 46 | self.combiner = torch.nn.RNN(gnn_param['dim_out'], gnn_param['dim_out']) 47 | 48 | def forward(self, mfgs, neg_samples=1): 49 | if self.memory_param['type'] == 'node': 50 | self.memory_updater(mfgs[0]) 51 | out = list() 52 | for l in range(self.gnn_param['layer']): 53 | for h in range(self.sample_param['history']): 54 | rst = self.layers['l' + str(l) + 'h' + str(h)](mfgs[l][h]) 55 | if 'time_transform' in self.gnn_param and self.gnn_param['time_transform'] == 'JODIE': 56 | rst = self.layers['l0h' + str(h) + 't'](rst, mfgs[l][h].srcdata['mem_ts'], mfgs[l][h].srcdata['ts']) 57 | if l != self.gnn_param['layer'] - 1: 58 | mfgs[l + 1][h].srcdata['h'] = rst 59 | else: 60 | out.append(rst) 61 | if self.sample_param['history'] == 1: 62 | out = out[0] 63 | else: 64 | out = torch.stack(out, dim=0) 65 | out = self.combiner(out)[0][-1, :, :] 66 | return self.edge_predictor(out, neg_samples=neg_samples) 67 | 68 | def get_emb(self, mfgs): 69 | if self.memory_param['type'] == 'node': 70 | self.memory_updater(mfgs[0]) 71 | out = list() 72 | for l in range(self.gnn_param['layer']): 73 | for h in range(self.sample_param['history']): 74 | rst = self.layers['l' + str(l) + 'h' + str(h)](mfgs[l][h]) 75 | if 'time_transform' in self.gnn_param and self.gnn_param['time_transform'] == 'JODIE': 76 | rst = self.layers['l0h' + str(h) + 't'](rst, mfgs[l][h].srcdata['mem_ts'], mfgs[l][h].srcdata['ts']) 77 | if l != self.gnn_param['layer'] - 1: 78 | mfgs[l + 1][h].srcdata['h'] = rst 79 | else: 80 | out.append(rst) 81 | if self.sample_param['history'] == 1: 82 | out = out[0] 83 | else: 84 | out = torch.stack(out, dim=0) 85 | out = self.combiner(out)[0][-1, :, :] 86 | return out 87 | 88 | class NodeClassificationModel(torch.nn.Module): 89 | 90 | def __init__(self, dim_in, dim_hid, num_class): 91 | super(NodeClassificationModel, self).__init__() 92 | self.fc1 = torch.nn.Linear(dim_in, dim_hid) 93 | self.fc2 = torch.nn.Linear(dim_hid, num_class) 94 | 95 | def forward(self, x): 96 | x = self.fc1(x) 97 | x = torch.nn.functional.relu(x) 98 | x = self.fc2(x) 99 | return x -------------------------------------------------------------------------------- /mount_shm.sh: -------------------------------------------------------------------------------- 1 | sudo mount -o remount,size=600G /dev/shm -------------------------------------------------------------------------------- /sampler.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import yaml 3 | import torch 4 | import time 5 | import numpy as np 6 | import pandas as pd 7 | from tqdm import tqdm 8 | from sampler_core import ParallelSampler, TemporalGraphBlock 9 | 10 | class NegLinkSampler: 11 | 12 | def __init__(self, num_nodes): 13 | self.num_nodes = num_nodes 14 | 15 | def sample(self, n): 16 | return np.random.randint(self.num_nodes, size=n) 17 | 18 | class NegLinkInductiveSampler: 19 | def __init__(self, nodes): 20 | self.nodes = list(nodes) 21 | 22 | def sample(self, n): 23 | return np.random.choice(self.nodes, size=n) 24 | 25 | if __name__ == '__main__': 26 | parser=argparse.ArgumentParser() 27 | parser.add_argument('--data', type=str, help='dataset name') 28 | parser.add_argument('--config', type=str, help='path to config file') 29 | parser.add_argument('--batch_size', type=int, default=600, help='path to config file') 30 | parser.add_argument('--num_thread', type=int, default=64, help='number of thread') 31 | args=parser.parse_args() 32 | 33 | df = pd.read_csv('DATA/{}/edges.csv'.format(args.data)) 34 | g = np.load('DATA/{}/ext_full.npz'.format(args.data)) 35 | sample_config = yaml.safe_load(open(args.config, 'r'))['sampling'][0] 36 | 37 | sampler = ParallelSampler(g['indptr'], g['indices'], g['eid'], g['ts'].astype(np.float32), 38 | args.num_thread, 1, sample_config['layer'], sample_config['neighbor'], 39 | sample_config['strategy']=='recent', sample_config['prop_time'], 40 | sample_config['history'], float(sample_config['duration'])) 41 | 42 | num_nodes = max(int(df['src'].max()), int(df['dst'].max())) 43 | neg_link_sampler = NegLinkSampler(num_nodes) 44 | 45 | tot_time = 0 46 | ptr_time = 0 47 | coo_time = 0 48 | sea_time = 0 49 | sam_time = 0 50 | uni_time = 0 51 | total_nodes = 0 52 | unique_nodes = 0 53 | for _, rows in tqdm(df.groupby(df.index // args.batch_size), total=len(df) // args.batch_size): 54 | root_nodes = np.concatenate([rows.src.values, rows.dst.values, neg_link_sampler.sample(len(rows))]).astype(np.int32) 55 | ts = np.concatenate([rows.time.values, rows.time.values, rows.time.values]).astype(np.float32) 56 | sampler.sample(root_nodes, ts) 57 | ret = sampler.get_ret() 58 | tot_time += ret[0].tot_time() 59 | ptr_time += ret[0].ptr_time() 60 | coo_time += ret[0].coo_time() 61 | sea_time += ret[0].search_time() 62 | sam_time += ret[0].sample_time() 63 | # for i in range(sample_config['history']): 64 | # total_nodes += ret[i].dim_in() - ret[i].dim_out() 65 | # unique_nodes += ret[i].dim_in() - ret[i].dim_out() 66 | # if ret[i].dim_in() > ret[i].dim_out(): 67 | # ts = torch.from_numpy(ret[i].ts()[ret[i].dim_out():]) 68 | # nid = torch.from_numpy(ret[i].nodes()[ret[i].dim_out():]).float() 69 | # nts = torch.stack([ts,nid],dim=1).cuda() 70 | # uni_t_s = time.time() 71 | # unts, idx = torch.unique(nts, dim=0, return_inverse=True) 72 | # uni_time += time.time() - uni_t_s 73 | # total_nodes += idx.shape[0] 74 | # unique_nodes += unts.shape[0] 75 | 76 | print('total time : {:.4f}'.format(tot_time)) 77 | print('pointer time: {:.4f}'.format(ptr_time)) 78 | print('coo time : {:.4f}'.format(coo_time)) 79 | print('search time : {:.4f}'.format(sea_time)) 80 | print('sample time : {:.4f}'.format(sam_time)) 81 | # print('unique time : {:.4f}'.format(uni_time)) 82 | # print('unique per : {:.4f}'.format(unique_nodes / total_nodes)) 83 | 84 | 85 | -------------------------------------------------------------------------------- /sampler_core.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | namespace py = pybind11; 12 | 13 | typedef int NodeIDType; 14 | typedef int EdgeIDType; 15 | typedef float TimeStampType; 16 | 17 | class TemporalGraphBlock 18 | { 19 | public: 20 | std::vector row; 21 | std::vector col; 22 | std::vector eid; 23 | std::vector ts; 24 | std::vector dts; 25 | std::vector nodes; 26 | NodeIDType dim_in, dim_out; 27 | double ptr_time = 0; 28 | double search_time = 0; 29 | double sample_time = 0; 30 | double tot_time = 0; 31 | double coo_time = 0; 32 | 33 | TemporalGraphBlock(){} 34 | 35 | TemporalGraphBlock(std::vector &_row, std::vector &_col, 36 | std::vector &_eid, std::vector &_ts, 37 | std::vector &_dts, std::vector &_nodes, 38 | NodeIDType _dim_in, NodeIDType _dim_out) : 39 | row(_row), col(_col), eid(_eid), ts(_ts), dts(_dts), 40 | nodes(_nodes), dim_in(_dim_in), dim_out(_dim_out) {} 41 | }; 42 | 43 | class ParallelSampler 44 | { 45 | public: 46 | std::vector indptr; 47 | std::vector indices; 48 | std::vector eid; 49 | std::vector ts; 50 | NodeIDType num_nodes; 51 | EdgeIDType num_edges; 52 | int num_thread_per_worker; 53 | int num_workers; 54 | int num_threads; 55 | int num_layers; 56 | std::vector num_neighbors; 57 | bool recent; 58 | bool prop_time; 59 | int num_history; 60 | TimeStampType window_duration; 61 | std::vector::size_type>> ts_ptr; 62 | omp_lock_t *ts_ptr_lock; 63 | std::vector ret; 64 | 65 | ParallelSampler(std::vector &_indptr, std::vector &_indices, 66 | std::vector &_eid, std::vector &_ts, 67 | int _num_thread_per_worker, int _num_workers, int _num_layers, 68 | std::vector &_num_neighbors, bool _recent, bool _prop_time, 69 | int _num_history, TimeStampType _window_duration) : 70 | indptr(_indptr), indices(_indices), eid(_eid), ts(_ts), prop_time(_prop_time), 71 | num_thread_per_worker(_num_thread_per_worker), num_workers(_num_workers), 72 | num_layers(_num_layers), num_neighbors(_num_neighbors), recent(_recent), 73 | num_history(_num_history), window_duration(_window_duration) 74 | { 75 | omp_set_num_threads(num_thread_per_worker * num_workers); 76 | num_threads = num_thread_per_worker * num_workers; 77 | num_nodes = indptr.size() - 1; 78 | num_edges = indices.size(); 79 | ts_ptr_lock = (omp_lock_t *)malloc(num_nodes * sizeof(omp_lock_t)); 80 | for (int i = 0; i < num_nodes; i++) 81 | omp_init_lock(&ts_ptr_lock[i]); 82 | ts_ptr.resize(num_history + 1); 83 | for (auto it = ts_ptr.begin(); it != ts_ptr.end(); it++) 84 | { 85 | it->resize(indptr.size() - 1); 86 | #pragma omp parallel for 87 | for (auto itt = indptr.begin(); itt < indptr.end() - 1; itt++) 88 | (*it)[itt - indptr.begin()] = *itt; 89 | } 90 | } 91 | 92 | void reset() 93 | { 94 | for (auto it = ts_ptr.begin(); it != ts_ptr.end(); it++) 95 | { 96 | it->resize(indptr.size() - 1); 97 | #pragma omp parallel for 98 | for (auto itt = indptr.begin(); itt < indptr.end() - 1; itt++) 99 | (*it)[itt - indptr.begin()] = *itt; 100 | } 101 | } 102 | 103 | void update_ts_ptr(int slc, std::vector &root_nodes, 104 | std::vector &root_ts, float offset) 105 | { 106 | #pragma omp parallel for schedule(static, int(ceil(static_cast(root_nodes.size()) / num_threads))) 107 | for (std::vector::size_type i = 0; i < root_nodes.size(); i++) 108 | { 109 | NodeIDType n = root_nodes[i]; 110 | omp_set_lock(&(ts_ptr_lock[n])); 111 | for (std::vector::size_type j = ts_ptr[slc][n]; j < indptr[n + 1]; j++) 112 | { 113 | // std::cout << "comparing " << ts[j] << " with " << root_ts[i] << std::endl; 114 | if (ts[j] > (root_ts[i] + offset - 1e-7f)) 115 | { 116 | if (j != ts_ptr[slc][n]) 117 | ts_ptr[slc][n] = j - 1; 118 | break; 119 | } 120 | if (j == indptr[n + 1] - 1) 121 | { 122 | ts_ptr[slc][n] = j; 123 | } 124 | } 125 | omp_unset_lock(&(ts_ptr_lock[n])); 126 | } 127 | } 128 | 129 | inline void add_neighbor(std::vector *_row, std::vector *_col, 130 | std::vector *_eid, std::vector *_ts, 131 | std::vector *_dts, std::vector *_nodes, 132 | EdgeIDType &k, TimeStampType &src_ts, int &row_id) 133 | { 134 | _row->push_back(row_id); 135 | _col->push_back(_nodes->size()); 136 | _eid->push_back(eid[k]); 137 | if (prop_time) 138 | _ts->push_back(src_ts); 139 | else 140 | _ts->push_back(ts[k]); 141 | _dts->push_back(src_ts - ts[k]); 142 | _nodes->push_back(indices[k]); 143 | // _row.push_back(0); 144 | // _col.push_back(0); 145 | // _eid.push_back(0); 146 | // if (prop_time) 147 | // _ts.push_back(src_ts); 148 | // else 149 | // _ts.push_back(10000); 150 | // _nodes.push_back(100); 151 | } 152 | 153 | inline void combine_coo(TemporalGraphBlock &_ret, std::vector **_row, 154 | std::vector **_col, 155 | std::vector **_eid, 156 | std::vector **_ts, 157 | std::vector **_dts, 158 | std::vector **_nodes, 159 | std::vector &_out_nodes) 160 | { 161 | std::vector cum_row, cum_col; 162 | cum_row.push_back(0); 163 | cum_col.push_back(0); 164 | for (int tid = 0; tid < num_threads; tid++) 165 | { 166 | // std::cout<size()); 169 | } 170 | int num_root_nodes = _ret.nodes.size(); 171 | _ret.row.resize(cum_col.back()); 172 | _ret.col.resize(cum_col.back()); 173 | _ret.eid.resize(cum_col.back()); 174 | _ret.ts.resize(cum_col.back() + num_root_nodes); 175 | _ret.dts.resize(cum_col.back() + num_root_nodes); 176 | _ret.nodes.resize(cum_col.back() + num_root_nodes); 177 | #pragma omp parallel for schedule(static, 1) 178 | for (int tid = 0; tid < num_threads; tid++) 179 | { 180 | std::transform(_row[tid]->begin(), _row[tid]->end(), _row[tid]->begin(), 181 | [&](auto &v){ return v + cum_row[tid]; }); 182 | std::transform(_col[tid]->begin(), _col[tid]->end(), _col[tid]->begin(), 183 | [&](auto &v){ return v + cum_col[tid] + num_root_nodes; }); 184 | std::copy(_row[tid]->begin(), _row[tid]->end(), _ret.row.begin() + cum_col[tid]); 185 | std::copy(_col[tid]->begin(), _col[tid]->end(), _ret.col.begin() + cum_col[tid]); 186 | std::copy(_eid[tid]->begin(), _eid[tid]->end(), _ret.eid.begin() + cum_col[tid]); 187 | std::copy(_ts[tid]->begin(), _ts[tid]->end(), _ret.ts.begin() + cum_col[tid] + num_root_nodes); 188 | std::copy(_dts[tid]->begin(), _dts[tid]->end(), _ret.dts.begin() + cum_col[tid] + num_root_nodes); 189 | std::copy(_nodes[tid]->begin(), _nodes[tid]->end(), _ret.nodes.begin() + cum_col[tid] + num_root_nodes); 190 | delete _row[tid]; 191 | delete _col[tid]; 192 | delete _eid[tid]; 193 | delete _ts[tid]; 194 | delete _dts[tid]; 195 | delete _nodes[tid]; 196 | } 197 | _ret.dim_in = _ret.nodes.size(); 198 | _ret.dim_out = cum_row.back(); 199 | } 200 | 201 | void sample_layer(std::vector &_root_nodes, std::vector &_root_ts, 202 | int neighs, bool use_ptr, bool from_root) 203 | { 204 | double t_s = omp_get_wtime(); 205 | std::vector *root_nodes; 206 | std::vector *root_ts; 207 | if (from_root) 208 | { 209 | root_nodes = &_root_nodes; 210 | root_ts = &_root_ts; 211 | } 212 | double t_ptr_s = omp_get_wtime(); 213 | if (use_ptr) 214 | update_ts_ptr(num_history, *root_nodes, *root_ts, 0); 215 | ret[0].ptr_time += omp_get_wtime() - t_ptr_s; 216 | for (int i = 0; i < num_history; i++) 217 | { 218 | if (!from_root) 219 | { 220 | root_nodes = &(ret[ret.size() - 1 - i - num_history].nodes); 221 | root_ts = &(ret[ret.size() - 1 - i - num_history].ts); 222 | } 223 | TimeStampType offset = -i * window_duration; 224 | t_ptr_s = omp_get_wtime(); 225 | if ((use_ptr) && (std::abs(window_duration) > 1e-7f)) 226 | update_ts_ptr(num_history - 1 - i, *root_nodes, *root_ts, offset - window_duration); 227 | ret[0].ptr_time += omp_get_wtime() - t_ptr_s; 228 | std::vector *_row[num_threads]; 229 | std::vector *_col[num_threads]; 230 | std::vector *_eid[num_threads]; 231 | std::vector *_ts[num_threads]; 232 | std::vector *_dts[num_threads]; 233 | std::vector *_nodes[num_threads]; 234 | std::vector _out_node(num_threads, 0); 235 | int reserve_capacity = int(ceil((*root_nodes).size() / num_threads)) * neighs; 236 | #pragma omp parallel 237 | { 238 | int tid = omp_get_thread_num(); 239 | unsigned int loc_seed = tid; 240 | _row[tid] = new std::vector; 241 | _col[tid] = new std::vector; 242 | _eid[tid] = new std::vector; 243 | _ts[tid] = new std::vector; 244 | _dts[tid] = new std::vector; 245 | _nodes[tid] = new std::vector; 246 | _row[tid]->reserve(reserve_capacity); 247 | _col[tid]->reserve(reserve_capacity); 248 | _eid[tid]->reserve(reserve_capacity); 249 | _ts[tid]->reserve(reserve_capacity); 250 | _dts[tid]->reserve(reserve_capacity); 251 | _nodes[tid]->reserve(reserve_capacity); 252 | // #pragma omp critical 253 | // std::cout<size()<<" "<((*root_nodes).size()) / num_threads))) 255 | for (std::vector::size_type j = 0; j < (*root_nodes).size(); j++) 256 | { 257 | NodeIDType n = (*root_nodes)[j]; 258 | // if (tid == 16) 259 | // std::cout << _out_node[tid] << " " < std::max(s_search, e_search - neighs); k--) 299 | { 300 | if (ts[k] < nts + offset - 1e-7f) 301 | { 302 | add_neighbor(_row[tid], _col[tid], _eid[tid], _ts[tid], 303 | _dts[tid], _nodes[tid], k, nts, _out_node[tid]); 304 | } 305 | } 306 | } 307 | else 308 | { 309 | // random sampling within ptr 310 | for (int _i = 0; _i < neighs; _i++) 311 | { 312 | EdgeIDType picked = s_search + rand_r(&loc_seed) % (e_search - s_search + 1); 313 | if (ts[picked] < nts + offset - 1e-7f) 314 | { 315 | add_neighbor(_row[tid], _col[tid], _eid[tid], _ts[tid], 316 | _dts[tid], _nodes[tid], picked, nts, _out_node[tid]); 317 | } 318 | } 319 | } 320 | _out_node[tid] += 1; 321 | if (tid == 0) 322 | ret[0].sample_time += omp_get_wtime() - t_sample_s; 323 | } 324 | } 325 | double t_coo_s = omp_get_wtime(); 326 | ret[ret.size() - 1 - i].ts.insert(ret[ret.size() - 1 - i].ts.end(), 327 | root_ts->begin(), root_ts->end()); 328 | ret[ret.size() - 1 - i].nodes.insert(ret[ret.size() - 1 - i].nodes.end(), 329 | root_nodes->begin(), root_nodes->end()); 330 | ret[ret.size() - 1 - i].dts.resize(root_nodes->size()); 331 | combine_coo(ret[ret.size() - 1 - i], _row, _col, _eid, _ts, _dts, _nodes, _out_node); 332 | ret[0].coo_time += omp_get_wtime() - t_coo_s; 333 | } 334 | ret[0].tot_time += omp_get_wtime() - t_s; 335 | } 336 | 337 | void sample(std::vector &root_nodes, std::vector &root_ts) 338 | { 339 | // a weird bug, dgl library seems to modify the total number of threads 340 | omp_set_num_threads(num_threads); 341 | ret.resize(0); 342 | bool first_layer = true; 343 | bool use_ptr = false; 344 | for (int i = 0; i < num_layers; i++) 345 | { 346 | ret.resize(ret.size() + num_history); 347 | if ((first_layer) || ((prop_time) && num_history == 1) || (recent)) 348 | { 349 | first_layer = false; 350 | use_ptr = true; 351 | } 352 | else 353 | use_ptr = false; 354 | if (i==0) 355 | sample_layer(root_nodes, root_ts, num_neighbors[i], use_ptr, true); 356 | else 357 | sample_layer(root_nodes, root_ts, num_neighbors[i], use_ptr, false); 358 | } 359 | } 360 | }; 361 | 362 | template 363 | inline py::array vec2npy(const std::vector &vec) 364 | { 365 | // need to let python garbage collector handle C++ vector memory 366 | // see https://github.com/pybind/pybind11/issues/1042 367 | auto v = new std::vector(vec); 368 | auto capsule = py::capsule(v, [](void *v) 369 | { delete reinterpret_cast *>(v); }); 370 | return py::array(v->size(), v->data(), capsule); 371 | // return py::array(vec.size(), vec.data()); 372 | } 373 | 374 | PYBIND11_MODULE(sampler_core, m) 375 | { 376 | py::class_(m, "TemporalGraphBlock") 377 | .def(py::init &, std::vector &, 378 | std::vector &, std::vector &, 379 | std::vector &, std::vector &, 380 | NodeIDType, NodeIDType>()) 381 | .def("row", [](const TemporalGraphBlock &tgb) { return vec2npy(tgb.row); }) 382 | .def("col", [](const TemporalGraphBlock &tgb) { return vec2npy(tgb.col); }) 383 | .def("eid", [](const TemporalGraphBlock &tgb) { return vec2npy(tgb.eid); }) 384 | .def("ts", [](const TemporalGraphBlock &tgb) { return vec2npy(tgb.ts); }) 385 | .def("dts", [](const TemporalGraphBlock &tgb) { return vec2npy(tgb.dts); }) 386 | .def("nodes", [](const TemporalGraphBlock &tgb) { return vec2npy(tgb.nodes); }) 387 | .def("dim_in", [](const TemporalGraphBlock &tgb) { return tgb.dim_in; }) 388 | .def("dim_out", [](const TemporalGraphBlock &tgb) { return tgb.dim_out; }) 389 | .def("tot_time", [](const TemporalGraphBlock &tgb) { return tgb.tot_time; }) 390 | .def("ptr_time", [](const TemporalGraphBlock &tgb) { return tgb.ptr_time; }) 391 | .def("search_time", [](const TemporalGraphBlock &tgb) { return tgb.search_time; }) 392 | .def("sample_time", [](const TemporalGraphBlock &tgb) { return tgb.sample_time; }) 393 | .def("coo_time", [](const TemporalGraphBlock &tgb) { return tgb.coo_time; }); 394 | py::class_(m, "ParallelSampler") 395 | .def(py::init &, std::vector &, 396 | std::vector &, std::vector &, 397 | int, int, int, std::vector &, bool, bool, 398 | int, TimeStampType>()) 399 | .def("sample", &ParallelSampler::sample) 400 | .def("reset", &ParallelSampler::reset) 401 | .def("get_ret", [](const ParallelSampler &ps) { return ps.ret; }); 402 | } -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from glob import glob 2 | from setuptools import setup 3 | from pybind11.setup_helpers import Pybind11Extension 4 | 5 | ext_modules = [ 6 | Pybind11Extension("sampler_core", 7 | ['sampler_core.cpp'], 8 | extra_compile_args = ['-fopenmp'], 9 | extra_link_args = ['-fopenmp'],), 10 | ] 11 | 12 | setup( 13 | name = "sampler_core", 14 | version = "0.0.1", 15 | author = "Hongkuan Zhou", 16 | author_email = "hongkuaz@usc.edu", 17 | url = "https://tedzhouhk.github.io/about/", 18 | description = "Parallel Sampling for Temporal Graphs", 19 | ext_modules = ext_modules, 20 | ) -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | 4 | parser=argparse.ArgumentParser() 5 | parser.add_argument('--data', type=str, help='dataset name') 6 | parser.add_argument('--config', type=str, help='path to config file') 7 | parser.add_argument('--gpu', type=str, default='0', help='which GPU to use') 8 | parser.add_argument('--model_name', type=str, default='', help='name of stored model') 9 | parser.add_argument('--use_inductive', action='store_true') 10 | parser.add_argument('--rand_edge_features', type=int, default=0, help='use random edge featrues') 11 | parser.add_argument('--rand_node_features', type=int, default=0, help='use random node featrues') 12 | parser.add_argument('--eval_neg_samples', type=int, default=1, help='how many negative samples to use at inference. Note: this will change the metric of test set to AP+AUC to AP+MRR!') 13 | args=parser.parse_args() 14 | 15 | os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu 16 | 17 | import torch 18 | import time 19 | import random 20 | import dgl 21 | import numpy as np 22 | from modules import * 23 | from sampler import * 24 | from utils import * 25 | from sklearn.metrics import average_precision_score, roc_auc_score 26 | 27 | def set_seed(seed): 28 | random.seed(seed) 29 | np.random.seed(seed) 30 | torch.manual_seed(seed) 31 | torch.cuda.manual_seed_all(seed) 32 | 33 | # set_seed(0) 34 | 35 | node_feats, edge_feats = load_feat(args.data, args.rand_edge_features, args.rand_node_features) 36 | g, df = load_graph(args.data) 37 | sample_param, memory_param, gnn_param, train_param = parse_config(args.config) 38 | train_edge_end = df[df['ext_roll'].gt(0)].index[0] 39 | val_edge_end = df[df['ext_roll'].gt(1)].index[0] 40 | 41 | def get_inductive_links(df, train_edge_end, val_edge_end): 42 | train_df = df[:train_edge_end] 43 | test_df = df[val_edge_end:] 44 | 45 | total_node_set = set(np.unique(np.hstack([df['src'].values, df['dst'].values]))) 46 | train_node_set = set(np.unique(np.hstack([train_df['src'].values, train_df['dst'].values]))) 47 | new_node_set = total_node_set - train_node_set 48 | 49 | del total_node_set, train_node_set 50 | 51 | inductive_inds = [] 52 | for index, (_, row) in enumerate(test_df.iterrows()): 53 | if row.src in new_node_set or row.dst in new_node_set: 54 | inductive_inds.append(val_edge_end+index) 55 | 56 | print('Inductive links', len(inductive_inds), len(test_df)) 57 | return [i for i in range(val_edge_end)] + inductive_inds 58 | 59 | if args.use_inductive: 60 | inductive_inds = get_inductive_links(df, train_edge_end, val_edge_end) 61 | df = df.iloc[inductive_inds] 62 | 63 | gnn_dim_node = 0 if node_feats is None else node_feats.shape[1] 64 | gnn_dim_edge = 0 if edge_feats is None else edge_feats.shape[1] 65 | combine_first = False 66 | if 'combine_neighs' in train_param and train_param['combine_neighs']: 67 | combine_first = True 68 | model = GeneralModel(gnn_dim_node, gnn_dim_edge, sample_param, memory_param, gnn_param, train_param, combined=combine_first).cuda() 69 | mailbox = MailBox(memory_param, g['indptr'].shape[0] - 1, gnn_dim_edge) if memory_param['type'] != 'none' else None 70 | creterion = torch.nn.BCEWithLogitsLoss() 71 | optimizer = torch.optim.Adam(model.parameters(), lr=train_param['lr']) 72 | if 'all_on_gpu' in train_param and train_param['all_on_gpu']: 73 | if node_feats is not None: 74 | node_feats = node_feats.cuda() 75 | if edge_feats is not None: 76 | edge_feats = edge_feats.cuda() 77 | if mailbox is not None: 78 | mailbox.move_to_gpu() 79 | 80 | sampler = None 81 | if not ('no_sample' in sample_param and sample_param['no_sample']): 82 | sampler = ParallelSampler(g['indptr'], g['indices'], g['eid'], g['ts'].astype(np.float32), 83 | sample_param['num_thread'], 1, sample_param['layer'], sample_param['neighbor'], 84 | sample_param['strategy']=='recent', sample_param['prop_time'], 85 | sample_param['history'], float(sample_param['duration'])) 86 | 87 | if args.use_inductive: 88 | test_df = df[val_edge_end:] 89 | inductive_nodes = set(test_df.src.values).union(test_df.src.values) 90 | print("inductive nodes", len(inductive_nodes)) 91 | neg_link_sampler = NegLinkInductiveSampler(inductive_nodes) 92 | else: 93 | neg_link_sampler = NegLinkSampler(g['indptr'].shape[0] - 1) 94 | 95 | def eval(mode='val'): 96 | neg_samples = 1 97 | model.eval() 98 | aps = list() 99 | aucs_mrrs = list() 100 | if mode == 'val': 101 | eval_df = df[train_edge_end:val_edge_end] 102 | elif mode == 'test': 103 | eval_df = df[val_edge_end:] 104 | neg_samples = args.eval_neg_samples 105 | elif mode == 'train': 106 | eval_df = df[:train_edge_end] 107 | with torch.no_grad(): 108 | total_loss = 0 109 | for _, rows in eval_df.groupby(eval_df.index // train_param['batch_size']): 110 | root_nodes = np.concatenate([rows.src.values, rows.dst.values, neg_link_sampler.sample(len(rows) * neg_samples)]).astype(np.int32) 111 | ts = np.tile(rows.time.values, neg_samples + 2).astype(np.float32) 112 | if sampler is not None: 113 | if 'no_neg' in sample_param and sample_param['no_neg']: 114 | pos_root_end = len(rows) * 2 115 | sampler.sample(root_nodes[:pos_root_end], ts[:pos_root_end]) 116 | else: 117 | sampler.sample(root_nodes, ts) 118 | ret = sampler.get_ret() 119 | if gnn_param['arch'] != 'identity': 120 | mfgs = to_dgl_blocks(ret, sample_param['history']) 121 | else: 122 | mfgs = node_to_dgl_blocks(root_nodes, ts) 123 | mfgs = prepare_input(mfgs, node_feats, edge_feats, combine_first=combine_first) 124 | if mailbox is not None: 125 | mailbox.prep_input_mails(mfgs[0]) 126 | pred_pos, pred_neg = model(mfgs, neg_samples=neg_samples) 127 | total_loss += creterion(pred_pos, torch.ones_like(pred_pos)) 128 | total_loss += creterion(pred_neg, torch.zeros_like(pred_neg)) 129 | y_pred = torch.cat([pred_pos, pred_neg], dim=0).sigmoid().cpu() 130 | y_true = torch.cat([torch.ones(pred_pos.size(0)), torch.zeros(pred_neg.size(0))], dim=0) 131 | aps.append(average_precision_score(y_true, y_pred)) 132 | if neg_samples > 1: 133 | aucs_mrrs.append(torch.reciprocal(torch.sum(pred_pos.squeeze() < pred_neg.squeeze().reshape(neg_samples, -1), dim=0) + 1).type(torch.float)) 134 | else: 135 | aucs_mrrs.append(roc_auc_score(y_true, y_pred)) 136 | if mailbox is not None: 137 | eid = rows['Unnamed: 0'].values 138 | mem_edge_feats = edge_feats[eid] if edge_feats is not None else None 139 | block = None 140 | if memory_param['deliver_to'] == 'neighbors': 141 | block = to_dgl_blocks(ret, sample_param['history'], reverse=True)[0][0] 142 | mailbox.update_mailbox(model.memory_updater.last_updated_nid, model.memory_updater.last_updated_memory, root_nodes, ts, mem_edge_feats, block, neg_samples=neg_samples) 143 | mailbox.update_memory(model.memory_updater.last_updated_nid, model.memory_updater.last_updated_memory, root_nodes, model.memory_updater.last_updated_ts, neg_samples=neg_samples) 144 | if mode == 'val': 145 | val_losses.append(float(total_loss)) 146 | ap = float(torch.tensor(aps).mean()) 147 | if neg_samples > 1: 148 | auc_mrr = float(torch.cat(aucs_mrrs).mean()) 149 | else: 150 | auc_mrr = float(torch.tensor(aucs_mrrs).mean()) 151 | return ap, auc_mrr 152 | 153 | if not os.path.isdir('models'): 154 | os.mkdir('models') 155 | if args.model_name == '': 156 | path_saver = 'models/{}_{}.pkl'.format(args.data, time.time()) 157 | else: 158 | path_saver = 'models/{}.pkl'.format(args.model_name) 159 | best_ap = 0 160 | best_e = 0 161 | val_losses = list() 162 | group_indexes = list() 163 | group_indexes.append(np.array(df[:train_edge_end].index // train_param['batch_size'])) 164 | if 'reorder' in train_param: 165 | # random chunk shceduling 166 | reorder = train_param['reorder'] 167 | group_idx = list() 168 | for i in range(reorder): 169 | group_idx += list(range(0 - i, reorder - i)) 170 | group_idx = np.repeat(np.array(group_idx), train_param['batch_size'] // reorder) 171 | group_idx = np.tile(group_idx, train_edge_end // train_param['batch_size'] + 1)[:train_edge_end] 172 | group_indexes.append(group_indexes[0] + group_idx) 173 | base_idx = group_indexes[0] 174 | for i in range(1, train_param['reorder']): 175 | additional_idx = np.zeros(train_param['batch_size'] // train_param['reorder'] * i) - 1 176 | group_indexes.append(np.concatenate([additional_idx, base_idx])[:base_idx.shape[0]]) 177 | for e in range(train_param['epoch']): 178 | print('Epoch {:d}:'.format(e)) 179 | time_sample = 0 180 | time_prep = 0 181 | time_tot = 0 182 | total_loss = 0 183 | # training 184 | model.train() 185 | if sampler is not None: 186 | sampler.reset() 187 | if mailbox is not None: 188 | mailbox.reset() 189 | model.memory_updater.last_updated_nid = None 190 | for _, rows in df[:train_edge_end].groupby(group_indexes[random.randint(0, len(group_indexes) - 1)]): 191 | t_tot_s = time.time() 192 | root_nodes = np.concatenate([rows.src.values, rows.dst.values, neg_link_sampler.sample(len(rows))]).astype(np.int32) 193 | ts = np.concatenate([rows.time.values, rows.time.values, rows.time.values]).astype(np.float32) 194 | if sampler is not None: 195 | if 'no_neg' in sample_param and sample_param['no_neg']: 196 | pos_root_end = root_nodes.shape[0] * 2 // 3 197 | sampler.sample(root_nodes[:pos_root_end], ts[:pos_root_end]) 198 | else: 199 | sampler.sample(root_nodes, ts) 200 | ret = sampler.get_ret() 201 | time_sample += ret[0].sample_time() 202 | t_prep_s = time.time() 203 | if gnn_param['arch'] != 'identity': 204 | mfgs = to_dgl_blocks(ret, sample_param['history']) 205 | else: 206 | mfgs = node_to_dgl_blocks(root_nodes, ts) 207 | mfgs = prepare_input(mfgs, node_feats, edge_feats, combine_first=combine_first) 208 | if mailbox is not None: 209 | mailbox.prep_input_mails(mfgs[0]) 210 | time_prep += time.time() - t_prep_s 211 | optimizer.zero_grad() 212 | pred_pos, pred_neg = model(mfgs) 213 | loss = creterion(pred_pos, torch.ones_like(pred_pos)) 214 | loss += creterion(pred_neg, torch.zeros_like(pred_neg)) 215 | total_loss += float(loss) * train_param['batch_size'] 216 | loss.backward() 217 | optimizer.step() 218 | t_prep_s = time.time() 219 | if mailbox is not None: 220 | eid = rows['Unnamed: 0'].values 221 | mem_edge_feats = edge_feats[eid] if edge_feats is not None else None 222 | block = None 223 | if memory_param['deliver_to'] == 'neighbors': 224 | block = to_dgl_blocks(ret, sample_param['history'], reverse=True)[0][0] 225 | mailbox.update_mailbox(model.memory_updater.last_updated_nid, model.memory_updater.last_updated_memory, root_nodes, ts, mem_edge_feats, block) 226 | mailbox.update_memory(model.memory_updater.last_updated_nid, model.memory_updater.last_updated_memory, root_nodes, model.memory_updater.last_updated_ts) 227 | time_prep += time.time() - t_prep_s 228 | time_tot += time.time() - t_tot_s 229 | ap, auc = eval('val') 230 | if e > 2 and ap > best_ap: 231 | best_e = e 232 | best_ap = ap 233 | torch.save(model.state_dict(), path_saver) 234 | print('\ttrain loss:{:.4f} val ap:{:4f} val auc:{:4f}'.format(total_loss, ap, auc)) 235 | print('\ttotal time:{:.2f}s sample time:{:.2f}s prep time:{:.2f}s'.format(time_tot, time_sample, time_prep)) 236 | 237 | print('Loading model at epoch {}...'.format(best_e)) 238 | model.load_state_dict(torch.load(path_saver)) 239 | model.eval() 240 | if sampler is not None: 241 | sampler.reset() 242 | if mailbox is not None: 243 | mailbox.reset() 244 | model.memory_updater.last_updated_nid = None 245 | eval('train') 246 | eval('val') 247 | ap, auc = eval('test') 248 | if args.eval_neg_samples > 1: 249 | print('\ttest AP:{:4f} test MRR:{:4f}'.format(ap, auc)) 250 | else: 251 | print('\ttest AP:{:4f} test AUC:{:4f}'.format(ap, auc)) 252 | -------------------------------------------------------------------------------- /train_dist.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | 4 | parser=argparse.ArgumentParser() 5 | parser.add_argument('--data', type=str, help='dataset name') 6 | parser.add_argument('--config', type=str, help='path to config file') 7 | parser.add_argument('--seed', type=int, default=0, help='random seed to use') 8 | parser.add_argument('--num_gpus', type=int, default=4, help='number of gpus to use') 9 | parser.add_argument('--omp_num_threads', type=int, default=8) 10 | parser.add_argument("--local_rank", type=int, default=-1) 11 | args=parser.parse_args() 12 | 13 | 14 | # set which GPU to use 15 | if args.local_rank < args.num_gpus: 16 | os.environ['CUDA_VISIBLE_DEVICES'] = str(args.local_rank) 17 | else: 18 | os.environ['CUDA_VISIBLE_DEVICES'] = '' 19 | os.environ['OMP_NUM_THREADS'] = str(args.omp_num_threads) 20 | os.environ['MKL_NUM_THREADS'] = str(args.omp_num_threads) 21 | 22 | import torch 23 | import dgl 24 | import datetime 25 | import random 26 | import math 27 | import threading 28 | import numpy as np 29 | from tqdm import tqdm 30 | from dgl.utils.shared_mem import create_shared_mem_array, get_shared_mem_array 31 | from sklearn.metrics import average_precision_score, roc_auc_score 32 | from modules import * 33 | from sampler import * 34 | from utils import * 35 | 36 | def set_seed(seed): 37 | random.seed(seed) 38 | np.random.seed(seed) 39 | torch.manual_seed(seed) 40 | torch.cuda.manual_seed_all(seed) 41 | 42 | set_seed(args.seed) 43 | torch.distributed.init_process_group(backend='gloo', timeout=datetime.timedelta(0, 3600)) 44 | nccl_group = torch.distributed.new_group(ranks=list(range(args.num_gpus)), backend='nccl') 45 | 46 | if args.local_rank == 0: 47 | _node_feats, _edge_feats = load_feat(args.data) 48 | dim_feats = [0, 0, 0, 0, 0, 0] 49 | if args.local_rank == 0: 50 | if _node_feats is not None: 51 | dim_feats[0] = _node_feats.shape[0] 52 | dim_feats[1] = _node_feats.shape[1] 53 | dim_feats[2] = _node_feats.dtype 54 | node_feats = create_shared_mem_array('node_feats', _node_feats.shape, dtype=_node_feats.dtype) 55 | node_feats.copy_(_node_feats) 56 | del _node_feats 57 | else: 58 | node_feats = None 59 | if _edge_feats is not None: 60 | dim_feats[3] = _edge_feats.shape[0] 61 | dim_feats[4] = _edge_feats.shape[1] 62 | dim_feats[5] = _edge_feats.dtype 63 | edge_feats = create_shared_mem_array('edge_feats', _edge_feats.shape, dtype=_edge_feats.dtype) 64 | edge_feats.copy_(_edge_feats) 65 | del _edge_feats 66 | else: 67 | edge_feats = None 68 | torch.distributed.barrier() 69 | torch.distributed.broadcast_object_list(dim_feats, src=0) 70 | if args.local_rank > 0 and args.local_rank < args.num_gpus: 71 | node_feats = None 72 | edge_feats = None 73 | if os.path.exists('DATA/{}/node_features.pt'.format(args.data)): 74 | node_feats = get_shared_mem_array('node_feats', (dim_feats[0], dim_feats[1]), dtype=dim_feats[2]) 75 | if os.path.exists('DATA/{}/edge_features.pt'.format(args.data)): 76 | edge_feats = get_shared_mem_array('edge_feats', (dim_feats[3], dim_feats[4]), dtype=dim_feats[5]) 77 | sample_param, memory_param, gnn_param, train_param = parse_config(args.config) 78 | orig_batch_size = train_param['batch_size'] 79 | if args.local_rank == 0: 80 | if not os.path.isdir('models'): 81 | os.mkdir('models') 82 | path_saver = ['models/{}_{}.pkl'.format(args.data, time.time())] 83 | else: 84 | path_saver = [None] 85 | torch.distributed.broadcast_object_list(path_saver, src=0) 86 | path_saver = path_saver[0] 87 | 88 | if args.local_rank == args.num_gpus: 89 | g, df = load_graph(args.data) 90 | num_nodes = [g['indptr'].shape[0] - 1] 91 | else: 92 | num_nodes = [None] 93 | torch.distributed.barrier() 94 | torch.distributed.broadcast_object_list(num_nodes, src=args.num_gpus) 95 | num_nodes = num_nodes[0] 96 | 97 | mailbox = None 98 | if memory_param['type'] != 'none': 99 | if args.local_rank == 0: 100 | node_memory = create_shared_mem_array('node_memory', torch.Size([num_nodes, memory_param['dim_out']]), dtype=torch.float32) 101 | node_memory_ts = create_shared_mem_array('node_memory_ts', torch.Size([num_nodes]), dtype=torch.float32) 102 | mails = create_shared_mem_array('mails', torch.Size([num_nodes, memory_param['mailbox_size'], 2 * memory_param['dim_out'] + dim_feats[4]]), dtype=torch.float32) 103 | mail_ts = create_shared_mem_array('mail_ts', torch.Size([num_nodes, memory_param['mailbox_size']]), dtype=torch.float32) 104 | next_mail_pos = create_shared_mem_array('next_mail_pos', torch.Size([num_nodes]), dtype=torch.long) 105 | update_mail_pos = create_shared_mem_array('update_mail_pos', torch.Size([num_nodes]), dtype=torch.int32) 106 | torch.distributed.barrier() 107 | node_memory.zero_() 108 | node_memory_ts.zero_() 109 | mails.zero_() 110 | mail_ts.zero_() 111 | next_mail_pos.zero_() 112 | update_mail_pos.zero_() 113 | else: 114 | torch.distributed.barrier() 115 | node_memory = get_shared_mem_array('node_memory', torch.Size([num_nodes, memory_param['dim_out']]), dtype=torch.float32) 116 | node_memory_ts = get_shared_mem_array('node_memory_ts', torch.Size([num_nodes]), dtype=torch.float32) 117 | mails = get_shared_mem_array('mails', torch.Size([num_nodes, memory_param['mailbox_size'], 2 * memory_param['dim_out'] + dim_feats[4]]), dtype=torch.float32) 118 | mail_ts = get_shared_mem_array('mail_ts', torch.Size([num_nodes, memory_param['mailbox_size']]), dtype=torch.float32) 119 | next_mail_pos = get_shared_mem_array('next_mail_pos', torch.Size([num_nodes]), dtype=torch.long) 120 | update_mail_pos = get_shared_mem_array('update_mail_pos', torch.Size([num_nodes]), dtype=torch.int32) 121 | mailbox = MailBox(memory_param, num_nodes, dim_feats[4], node_memory, node_memory_ts, mails, mail_ts, next_mail_pos, update_mail_pos) 122 | 123 | class DataPipelineThread(threading.Thread): 124 | 125 | def __init__(self, my_mfgs, my_root, my_ts, my_eid, my_block, stream): 126 | super(DataPipelineThread, self).__init__() 127 | self.my_mfgs = my_mfgs 128 | self.my_root = my_root 129 | self.my_ts = my_ts 130 | self.my_eid = my_eid 131 | self.my_block = my_block 132 | self.stream = stream 133 | self.mfgs = None 134 | self.root = None 135 | self.ts = None 136 | self.eid = None 137 | self.block = None 138 | 139 | def run(self): 140 | with torch.cuda.stream(self.stream): 141 | # print(args.local_rank, 'start thread') 142 | nids, eids = get_ids(self.my_mfgs[0], node_feats, edge_feats) 143 | mfgs = mfgs_to_cuda(self.my_mfgs[0]) 144 | prepare_input(mfgs, node_feats, edge_feats, pinned=True, nfeat_buffs=pinned_nfeat_buffs, efeat_buffs=pinned_efeat_buffs, nids=nids, eids=eids) 145 | if mailbox is not None: 146 | mailbox.prep_input_mails(mfgs[0], use_pinned_buffers=True) 147 | if memory_param['deliver_to'] == 'neighbors': 148 | self.block = self.my_block[0] 149 | self.mfgs = mfgs 150 | self.root = self.my_root[0] 151 | self.ts = self.my_ts[0] 152 | self.eid = self.my_eid[0] 153 | # print(args.local_rank, 'finished') 154 | 155 | def get_stream(self): 156 | return self.stream 157 | 158 | def get_mfgs(self): 159 | return self.mfgs 160 | 161 | def get_root(self): 162 | return self.root 163 | 164 | def get_ts(self): 165 | return self.ts 166 | 167 | def get_eid(self): 168 | return self.eid 169 | 170 | def get_block(self): 171 | return self.block 172 | 173 | 174 | if args.local_rank < args.num_gpus: 175 | # GPU worker process 176 | model = GeneralModel(dim_feats[1], dim_feats[4], sample_param, memory_param, gnn_param, train_param).cuda() 177 | find_unused_parameters = True if sample_param['history'] > 1 else False 178 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], process_group=nccl_group, output_device=args.local_rank, find_unused_parameters=find_unused_parameters) 179 | creterion = torch.nn.BCEWithLogitsLoss() 180 | optimizer = torch.optim.Adam(model.parameters(), lr=train_param['lr']) 181 | pinned_nfeat_buffs, pinned_efeat_buffs = get_pinned_buffers(sample_param, train_param['batch_size'], node_feats, edge_feats) 182 | if mailbox is not None: 183 | mailbox.allocate_pinned_memory_buffers(sample_param, train_param['batch_size']) 184 | tot_loss = 0 185 | prev_thread = None 186 | while True: 187 | my_model_state = [None] 188 | model_state = [None] * (args.num_gpus + 1) 189 | torch.distributed.scatter_object_list(my_model_state, model_state, src=args.num_gpus) 190 | if my_model_state[0] == -1: 191 | break 192 | elif my_model_state[0] == 4: 193 | continue 194 | elif my_model_state[0] == 2: 195 | torch.save(model.state_dict(), path_saver) 196 | continue 197 | elif my_model_state[0] == 3: 198 | model.load_state_dict(torch.load(path_saver, map_location=torch.device('cuda:0'))) 199 | continue 200 | elif my_model_state[0] == 5: 201 | torch.distributed.gather_object(float(tot_loss), None, dst=args.num_gpus) 202 | tot_loss = 0 203 | continue 204 | elif my_model_state[0] == 0: 205 | if prev_thread is not None: 206 | my_mfgs = [None] 207 | multi_mfgs = [None] * (args.num_gpus + 1) 208 | my_root = [None] 209 | multi_root = [None] * (args.num_gpus + 1) 210 | my_ts = [None] 211 | multi_ts = [None] * (args.num_gpus + 1) 212 | my_eid = [None] 213 | multi_eid = [None] * (args.num_gpus + 1) 214 | my_block = [None] 215 | multi_block = [None] * (args.num_gpus + 1) 216 | torch.distributed.scatter_object_list(my_mfgs, multi_mfgs, src=args.num_gpus) 217 | if mailbox is not None: 218 | torch.distributed.scatter_object_list(my_root, multi_root, src=args.num_gpus) 219 | torch.distributed.scatter_object_list(my_ts, multi_ts, src=args.num_gpus) 220 | torch.distributed.scatter_object_list(my_eid, multi_eid, src=args.num_gpus) 221 | if memory_param['deliver_to'] == 'neighbors': 222 | torch.distributed.scatter_object_list(my_block, multi_block, src=args.num_gpus) 223 | stream = torch.cuda.Stream() 224 | curr_thread = DataPipelineThread(my_mfgs, my_root, my_ts, my_eid, my_block, stream) 225 | curr_thread.start() 226 | prev_thread.join() 227 | # with torch.cuda.stream(prev_thread.get_stream()): 228 | mfgs = prev_thread.get_mfgs() 229 | model.train() 230 | optimizer.zero_grad() 231 | pred_pos, pred_neg = model(mfgs) 232 | loss = creterion(pred_pos, torch.ones_like(pred_pos)) 233 | loss += creterion(pred_neg, torch.zeros_like(pred_neg)) 234 | loss.backward() 235 | optimizer.step() 236 | with torch.no_grad(): 237 | tot_loss += float(loss) 238 | if mailbox is not None: 239 | with torch.no_grad(): 240 | eid = prev_thread.get_eid() 241 | mem_edge_feats = edge_feats[eid] if edge_feats is not None else None 242 | root_nodes = prev_thread.get_root() 243 | ts = prev_thread.get_ts() 244 | block = prev_thread.get_block() 245 | mailbox.update_mailbox(model.module.memory_updater.last_updated_nid, model.module.memory_updater.last_updated_memory, root_nodes, ts, mem_edge_feats, block) 246 | mailbox.update_memory(model.module.memory_updater.last_updated_nid, model.module.memory_updater.last_updated_memory, root_nodes, model.module.memory_updater.last_updated_ts) 247 | if memory_param['deliver_to'] == 'neighbors': 248 | torch.distributed.barrier(group=nccl_group) 249 | if args.local_rank == 0: 250 | mailbox.update_next_mail_pos() 251 | prev_thread = curr_thread 252 | else: 253 | my_mfgs = [None] 254 | multi_mfgs = [None] * (args.num_gpus + 1) 255 | my_root = [None] 256 | multi_root = [None] * (args.num_gpus + 1) 257 | my_ts = [None] 258 | multi_ts = [None] * (args.num_gpus + 1) 259 | my_eid = [None] 260 | multi_eid = [None] * (args.num_gpus + 1) 261 | my_block = [None] 262 | multi_block = [None] * (args.num_gpus + 1) 263 | torch.distributed.scatter_object_list(my_mfgs, multi_mfgs, src=args.num_gpus) 264 | if mailbox is not None: 265 | torch.distributed.scatter_object_list(my_root, multi_root, src=args.num_gpus) 266 | torch.distributed.scatter_object_list(my_ts, multi_ts, src=args.num_gpus) 267 | torch.distributed.scatter_object_list(my_eid, multi_eid, src=args.num_gpus) 268 | if memory_param['deliver_to'] == 'neighbors': 269 | torch.distributed.scatter_object_list(my_block, multi_block, src=args.num_gpus) 270 | stream = torch.cuda.Stream() 271 | prev_thread = DataPipelineThread(my_mfgs, my_root, my_ts, my_eid, my_block, stream) 272 | prev_thread.start() 273 | elif my_model_state[0] == 1: 274 | if prev_thread is not None: 275 | # finish last training mini-batch 276 | prev_thread.join() 277 | mfgs = prev_thread.get_mfgs() 278 | model.train() 279 | optimizer.zero_grad() 280 | pred_pos, pred_neg = model(mfgs) 281 | loss = creterion(pred_pos, torch.ones_like(pred_pos)) 282 | loss += creterion(pred_neg, torch.zeros_like(pred_neg)) 283 | loss.backward() 284 | optimizer.step() 285 | with torch.no_grad(): 286 | tot_loss += float(loss) 287 | if mailbox is not None: 288 | with torch.no_grad(): 289 | eid = prev_thread.get_eid() 290 | mem_edge_feats = edge_feats[eid] if edge_feats is not None else None 291 | root_nodes = prev_thread.get_root() 292 | ts = prev_thread.get_ts() 293 | block = prev_thread.get_block() 294 | mailbox.update_mailbox(model.module.memory_updater.last_updated_nid, model.module.memory_updater.last_updated_memory, root_nodes, ts, mem_edge_feats, block) 295 | mailbox.update_memory(model.module.memory_updater.last_updated_nid, model.module.memory_updater.last_updated_memory, root_nodes, model.module.memory_updater.last_updated_ts) 296 | if memory_param['deliver_to'] == 'neighbors': 297 | torch.distributed.barrier(group=nccl_group) 298 | if args.local_rank == 0: 299 | mailbox.update_next_mail_pos() 300 | prev_thread = None 301 | my_mfgs = [None] 302 | multi_mfgs = [None] * (args.num_gpus + 1) 303 | torch.distributed.scatter_object_list(my_mfgs, multi_mfgs, src=args.num_gpus) 304 | mfgs = mfgs_to_cuda(my_mfgs[0]) 305 | prepare_input(mfgs, node_feats, edge_feats, pinned=True, nfeat_buffs=pinned_nfeat_buffs, efeat_buffs=pinned_efeat_buffs) 306 | model.eval() 307 | with torch.no_grad(): 308 | if mailbox is not None: 309 | mailbox.prep_input_mails(mfgs[0]) 310 | pred_pos, pred_neg = model(mfgs) 311 | if mailbox is not None: 312 | my_root = [None] 313 | multi_root = [None] * (args.num_gpus + 1) 314 | my_ts = [None] 315 | multi_ts = [None] * (args.num_gpus + 1) 316 | my_eid = [None] 317 | multi_eid = [None] * (args.num_gpus + 1) 318 | torch.distributed.scatter_object_list(my_root, multi_root, src=args.num_gpus) 319 | torch.distributed.scatter_object_list(my_ts, multi_ts, src=args.num_gpus) 320 | torch.distributed.scatter_object_list(my_eid, multi_eid, src=args.num_gpus) 321 | eid = my_eid[0] 322 | mem_edge_feats = edge_feats[eid] if edge_feats is not None else None 323 | root_nodes = my_root[0] 324 | ts = my_ts[0] 325 | block = None 326 | if memory_param['deliver_to'] == 'neighbors': 327 | my_block = [None] 328 | multi_block = [None] * (args.num_gpus + 1) 329 | torch.distributed.scatter_object_list(my_block, multi_block, src=args.num_gpus) 330 | block = my_block[0] 331 | mailbox.update_mailbox(model.module.memory_updater.last_updated_nid, model.module.memory_updater.last_updated_memory, root_nodes, ts, mem_edge_feats, block) 332 | mailbox.update_memory(model.module.memory_updater.last_updated_nid, model.module.memory_updater.last_updated_memory, root_nodes, model.module.memory_updater.last_updated_ts) 333 | if memory_param['deliver_to'] == 'neighbors': 334 | torch.distributed.barrier(group=nccl_group) 335 | if args.local_rank == 0: 336 | mailbox.update_next_mail_pos() 337 | y_pred = torch.cat([pred_pos, pred_neg], dim=0).sigmoid().cpu() 338 | y_true = torch.cat([torch.ones(pred_pos.size(0)), torch.zeros(pred_neg.size(0))], dim=0) 339 | ap = average_precision_score(y_true, y_pred) 340 | auc = roc_auc_score(y_true, y_pred) 341 | torch.distributed.gather_object(float(ap), None, dst=args.num_gpus) 342 | torch.distributed.gather_object(float(auc), None, dst=args.num_gpus) 343 | else: 344 | # hosting process 345 | train_edge_end = df[df['ext_roll'].gt(0)].index[0] 346 | val_edge_end = df[df['ext_roll'].gt(1)].index[0] 347 | sampler = None 348 | if not ('no_sample' in sample_param and sample_param['no_sample']): 349 | sampler = ParallelSampler(g['indptr'], g['indices'], g['eid'], g['ts'].astype(np.float32), 350 | sample_param['num_thread'], 1, sample_param['layer'], sample_param['neighbor'], 351 | sample_param['strategy']=='recent', sample_param['prop_time'], 352 | sample_param['history'], float(sample_param['duration'])) 353 | neg_link_sampler = NegLinkSampler(g['indptr'].shape[0] - 1) 354 | 355 | def eval(mode='val'): 356 | if mode == 'val': 357 | eval_df = df[train_edge_end:val_edge_end] 358 | elif mode == 'test': 359 | eval_df = df[val_edge_end:] 360 | elif mode == 'train': 361 | eval_df = df[:train_edge_end] 362 | ap_tot = list() 363 | auc_tot = list() 364 | train_param['batch_size'] = orig_batch_size 365 | itr_tot = max(len(eval_df) // train_param['batch_size'] // args.num_gpus, 1) * args.num_gpus 366 | train_param['batch_size'] = math.ceil(len(eval_df) / itr_tot) 367 | multi_mfgs = list() 368 | multi_root = list() 369 | multi_ts = list() 370 | multi_eid = list() 371 | multi_block = list() 372 | for _, rows in eval_df.groupby(eval_df.index // train_param['batch_size']): 373 | root_nodes = np.concatenate([rows.src.values, rows.dst.values, neg_link_sampler.sample(len(rows))]).astype(np.int32) 374 | ts = np.concatenate([rows.time.values, rows.time.values, rows.time.values]).astype(np.float32) 375 | if sampler is not None: 376 | if 'no_neg' in sample_param and sample_param['no_neg']: 377 | pos_root_end = root_nodes.shape[0] * 2 // 3 378 | sampler.sample(root_nodes[:pos_root_end], ts[:pos_root_end]) 379 | else: 380 | sampler.sample(root_nodes, ts) 381 | ret = sampler.get_ret() 382 | if gnn_param['arch'] != 'identity': 383 | mfgs = to_dgl_blocks(ret, sample_param['history'], cuda=False) 384 | else: 385 | mfgs = node_to_dgl_blocks(root_nodes, ts, cuda=False) 386 | multi_mfgs.append(mfgs) 387 | multi_root.append(root_nodes) 388 | multi_ts.append(ts) 389 | multi_eid.append(rows['Unnamed: 0'].values) 390 | if mailbox is not None and memory_param['deliver_to'] == 'neighbors': 391 | multi_block.append(to_dgl_blocks(ret, sample_param['history'], reverse=True, cuda=False)[0][0]) 392 | if len(multi_mfgs) == args.num_gpus: 393 | model_state = [1] * (args.num_gpus + 1) 394 | my_model_state = [None] 395 | torch.distributed.scatter_object_list(my_model_state, model_state, src=args.num_gpus) 396 | multi_mfgs.append(None) 397 | my_mfgs = [None] 398 | torch.distributed.scatter_object_list(my_mfgs, multi_mfgs, src=args.num_gpus) 399 | if mailbox is not None: 400 | multi_root.append(None) 401 | multi_ts.append(None) 402 | multi_eid.append(None) 403 | my_root = [None] 404 | my_ts = [None] 405 | my_eid = [None] 406 | torch.distributed.scatter_object_list(my_root, multi_root, src=args.num_gpus) 407 | torch.distributed.scatter_object_list(my_ts, multi_ts, src=args.num_gpus) 408 | torch.distributed.scatter_object_list(my_eid, multi_eid, src=args.num_gpus) 409 | if memory_param['deliver_to'] == 'neighbors': 410 | multi_block.append(None) 411 | my_block = [None] 412 | torch.distributed.scatter_object_list(my_block, multi_block, src=args.num_gpus) 413 | gathered_ap = [None] * (args.num_gpus + 1) 414 | gathered_auc = [None] * (args.num_gpus + 1) 415 | torch.distributed.gather_object(float(0), gathered_ap, dst=args.num_gpus) 416 | torch.distributed.gather_object(float(0), gathered_auc, dst=args.num_gpus) 417 | ap_tot += gathered_ap[:-1] 418 | auc_tot += gathered_auc[:-1] 419 | multi_mfgs = list() 420 | multi_root = list() 421 | multi_ts = list() 422 | multi_eid = list() 423 | multi_block = list() 424 | pbar.update(1) 425 | ap = float(torch.tensor(ap_tot).mean()) 426 | auc = float(torch.tensor(auc_tot).mean()) 427 | return ap, auc 428 | 429 | best_ap = 0 430 | best_e = 0 431 | tap = 0 432 | tauc = 0 433 | for e in range(train_param['epoch']): 434 | print('Epoch {:d}:'.format(e)) 435 | time_sample = 0 436 | time_tot = 0 437 | if sampler is not None: 438 | sampler.reset() 439 | if mailbox is not None: 440 | mailbox.reset() 441 | # training 442 | train_param['batch_size'] = orig_batch_size 443 | itr_tot = train_edge_end // train_param['batch_size'] // args.num_gpus * args.num_gpus 444 | train_param['batch_size'] = math.ceil(train_edge_end / itr_tot) 445 | multi_mfgs = list() 446 | multi_root = list() 447 | multi_ts = list() 448 | multi_eid = list() 449 | multi_block = list() 450 | group_indexes = list() 451 | group_indexes.append(np.array(df[:train_edge_end].index // train_param['batch_size'])) 452 | if 'reorder' in train_param: 453 | # random chunk shceduling 454 | reorder = train_param['reorder'] 455 | group_idx = list() 456 | for i in range(reorder): 457 | group_idx += list(range(0 - i, reorder - i)) 458 | group_idx = np.repeat(np.array(group_idx), train_param['batch_size'] // reorder) 459 | group_idx = np.tile(group_idx, train_edge_end // train_param['batch_size'] + 1)[:train_edge_end] 460 | group_indexes.append(group_indexes[0] + group_idx) 461 | base_idx = group_indexes[0] 462 | for i in range(1, train_param['reorder']): 463 | additional_idx = np.zeros(train_param['batch_size'] // train_param['reorder'] * i) - 1 464 | group_indexes.append(np.concatenate([additional_idx, base_idx])[:base_idx.shape[0]]) 465 | with tqdm(total=itr_tot + max((val_edge_end - train_edge_end) // train_param['batch_size'] // args.num_gpus, 1) * args.num_gpus) as pbar: 466 | for _, rows in df[:train_edge_end].groupby(group_indexes[random.randint(0, len(group_indexes) - 1)]): 467 | t_tot_s = time.time() 468 | root_nodes = np.concatenate([rows.src.values, rows.dst.values, neg_link_sampler.sample(len(rows))]).astype(np.int32) 469 | ts = np.concatenate([rows.time.values, rows.time.values, rows.time.values]).astype(np.float32) 470 | if sampler is not None: 471 | if 'no_neg' in sample_param and sample_param['no_neg']: 472 | pos_root_end = root_nodes.shape[0] * 2 // 3 473 | sampler.sample(root_nodes[:pos_root_end], ts[:pos_root_end]) 474 | else: 475 | sampler.sample(root_nodes, ts) 476 | ret = sampler.get_ret() 477 | time_sample += ret[0].sample_time() 478 | if gnn_param['arch'] != 'identity': 479 | mfgs = to_dgl_blocks(ret, sample_param['history'], cuda=False) 480 | else: 481 | mfgs = node_to_dgl_blocks(root_nodes, ts, cuda=False) 482 | multi_mfgs.append(mfgs) 483 | multi_root.append(root_nodes) 484 | multi_ts.append(ts) 485 | multi_eid.append(rows['Unnamed: 0'].values) 486 | if mailbox is not None and memory_param['deliver_to'] == 'neighbors': 487 | multi_block.append(to_dgl_blocks(ret, sample_param['history'], reverse=True, cuda=False)[0][0]) 488 | if len(multi_mfgs) == args.num_gpus: 489 | model_state = [0] * (args.num_gpus + 1) 490 | my_model_state = [None] 491 | torch.distributed.scatter_object_list(my_model_state, model_state, src=args.num_gpus) 492 | multi_mfgs.append(None) 493 | my_mfgs = [None] 494 | torch.distributed.scatter_object_list(my_mfgs, multi_mfgs, src=args.num_gpus) 495 | if mailbox is not None: 496 | multi_root.append(None) 497 | multi_ts.append(None) 498 | multi_eid.append(None) 499 | my_root = [None] 500 | my_ts = [None] 501 | my_eid = [None] 502 | torch.distributed.scatter_object_list(my_root, multi_root, src=args.num_gpus) 503 | torch.distributed.scatter_object_list(my_ts, multi_ts, src=args.num_gpus) 504 | torch.distributed.scatter_object_list(my_eid, multi_eid, src=args.num_gpus) 505 | if memory_param['deliver_to'] == 'neighbors': 506 | multi_block.append(None) 507 | my_block = [None] 508 | torch.distributed.scatter_object_list(my_block, multi_block, src=args.num_gpus) 509 | multi_mfgs = list() 510 | multi_root = list() 511 | multi_ts = list() 512 | multi_eid = list() 513 | multi_block = list() 514 | pbar.update(1) 515 | time_tot += time.time() - t_tot_s 516 | print('Training time:',time_tot) 517 | model_state = [5] * (args.num_gpus + 1) 518 | my_model_state = [None] 519 | torch.distributed.scatter_object_list(my_model_state, model_state, src=args.num_gpus) 520 | gathered_loss = [None] * (args.num_gpus + 1) 521 | torch.distributed.gather_object(float(0), gathered_loss, dst=args.num_gpus) 522 | total_loss = np.sum(np.array(gathered_loss) * train_param['batch_size']) 523 | ap, auc = eval('val') 524 | if ap > best_ap: 525 | best_e = e 526 | best_ap = ap 527 | model_state = [4] * (args.num_gpus + 1) 528 | model_state[0] = 2 529 | my_model_state = [None] 530 | torch.distributed.scatter_object_list(my_model_state, model_state, src=args.num_gpus) 531 | # for memory based models, testing after validation is faster 532 | tap, tauc = eval('test') 533 | print('\ttrain loss:{:.4f} val ap:{:4f} val auc:{:4f}'.format(total_loss, ap, auc)) 534 | print('\ttotal time:{:.2f}s sample time:{:.2f}s'.format(time_tot, time_sample)) 535 | 536 | print('Best model at epoch {}.'.format(best_e)) 537 | print('\ttest ap:{:4f} test auc:{:4f}'.format(tap, tauc)) 538 | 539 | # let all process exit 540 | model_state = [-1] * (args.num_gpus + 1) 541 | my_model_state = [None] 542 | torch.distributed.scatter_object_list(my_model_state, model_state, src=args.num_gpus) -------------------------------------------------------------------------------- /train_node.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import hashlib 4 | 5 | parser=argparse.ArgumentParser() 6 | parser.add_argument('--data', type=str, help='dataset name') 7 | parser.add_argument('--config', type=str, default='', help='path to config file') 8 | parser.add_argument('--batch_size', type=int, default=4000) 9 | parser.add_argument('--epoch', type=int, default=100) 10 | parser.add_argument('--dim', type=int, default=100) 11 | parser.add_argument('--lr', type=float, default=0.001) 12 | parser.add_argument('--gpu', type=str, default='0', help='which GPU to use') 13 | parser.add_argument('--model', type=str, default='', help='name of stored model to load') 14 | parser.add_argument('--posneg', default=False, action='store_true', help='for positive negative detection, whether to sample negative nodes') 15 | args=parser.parse_args() 16 | 17 | os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu 18 | if args.data == 'WIKI' or args.data == 'REDDIT': 19 | args.posneg = True 20 | 21 | import torch 22 | import time 23 | import random 24 | import dgl 25 | import numpy as np 26 | import pandas as pd 27 | from modules import * 28 | from sampler import * 29 | from utils import * 30 | from tqdm import tqdm 31 | from sklearn.metrics import average_precision_score, f1_score 32 | 33 | ldf = pd.read_csv('DATA/{}/labels.csv'.format(args.data)) 34 | role = ldf['ext_roll'].values 35 | # train_node_end = ldf[ldf['ext_roll'].gt(0)].index[0] 36 | # val_node_end = ldf[ldf['ext_roll'].gt(1)].index[0] 37 | labels = ldf['label'].values.astype(np.int64) 38 | 39 | emb_file_name = hashlib.md5(str(torch.load(args.model, map_location=torch.device('cpu'))).encode('utf-8')).hexdigest() + '.pt' 40 | if not os.path.isdir('embs'): 41 | os.mkdir('embs') 42 | if not os.path.isfile('embs/' + emb_file_name): 43 | print('Generating temporal embeddings..') 44 | 45 | node_feats, edge_feats = load_feat(args.data) 46 | g, df = load_graph(args.data) 47 | sample_param, memory_param, gnn_param, train_param = parse_config(args.config) 48 | train_edge_end = df[df['ext_roll'].gt(0)].index[0] 49 | val_edge_end = df[df['ext_roll'].gt(1)].index[0] 50 | 51 | gnn_dim_node = 0 if node_feats is None else node_feats.shape[1] 52 | gnn_dim_edge = 0 if edge_feats is None else edge_feats.shape[1] 53 | combine_first = False 54 | if 'combine_neighs' in train_param and train_param['combine_neighs']: 55 | combine_first = True 56 | model = GeneralModel(gnn_dim_node, gnn_dim_edge, sample_param, memory_param, gnn_param, train_param, combined=combine_first).cuda() 57 | mailbox = MailBox(memory_param, g['indptr'].shape[0] - 1, gnn_dim_edge) if memory_param['type'] != 'none' else None 58 | creterion = torch.nn.BCEWithLogitsLoss() 59 | optimizer = torch.optim.Adam(model.parameters(), lr=train_param['lr']) 60 | if 'all_on_gpu' in train_param and train_param['all_on_gpu']: 61 | if node_feats is not None: 62 | node_feats = node_feats.cuda() 63 | if edge_feats is not None: 64 | edge_feats = edge_feats.cuda() 65 | if mailbox is not None: 66 | mailbox.move_to_gpu() 67 | 68 | sampler = None 69 | if not ('no_sample' in sample_param and sample_param['no_sample']): 70 | sampler = ParallelSampler(g['indptr'], g['indices'], g['eid'], g['ts'].astype(np.float32), 71 | sample_param['num_thread'], 1, sample_param['layer'], sample_param['neighbor'], 72 | sample_param['strategy']=='recent', sample_param['prop_time'], 73 | sample_param['history'], float(sample_param['duration'])) 74 | neg_link_sampler = NegLinkSampler(g['indptr'].shape[0] - 1) 75 | 76 | model.load_state_dict(torch.load(args.model)) 77 | 78 | processed_edge_id = 0 79 | 80 | def forward_model_to(time): 81 | global processed_edge_id 82 | if processed_edge_id >= len(df): 83 | return 84 | while df.time[processed_edge_id] < time: 85 | rows = df[processed_edge_id:min(processed_edge_id + train_param['batch_size'], len(df))] 86 | if processed_edge_id < train_edge_end: 87 | model.train() 88 | else: 89 | model.eval() 90 | root_nodes = np.concatenate([rows.src.values, rows.dst.values, neg_link_sampler.sample(len(rows))]).astype(np.int32) 91 | ts = np.concatenate([rows.time.values, rows.time.values, rows.time.values]).astype(np.float32) 92 | if sampler is not None: 93 | if 'no_neg' in sample_param and sample_param['no_neg']: 94 | pos_root_end = root_nodes.shape[0] * 2 // 3 95 | sampler.sample(root_nodes[:pos_root_end], ts[:pos_root_end]) 96 | else: 97 | sampler.sample(root_nodes, ts) 98 | ret = sampler.get_ret() 99 | if gnn_param['arch'] != 'identity': 100 | mfgs = to_dgl_blocks(ret, sample_param['history']) 101 | else: 102 | mfgs = node_to_dgl_blocks(root_nodes, ts) 103 | mfgs = prepare_input(mfgs, node_feats, edge_feats, combine_first=combine_first) 104 | if mailbox is not None: 105 | mailbox.prep_input_mails(mfgs[0]) 106 | with torch.no_grad(): 107 | pred_pos, pred_neg = model(mfgs) 108 | if mailbox is not None: 109 | eid = rows['Unnamed: 0'].values 110 | mem_edge_feats = edge_feats[eid] if edge_feats is not None else None 111 | block = None 112 | if memory_param['deliver_to'] == 'neighbors': 113 | block = to_dgl_blocks(ret, sample_param['history'], reverse=True)[0][0] 114 | mailbox.update_mailbox(model.memory_updater.last_updated_nid, model.memory_updater.last_updated_memory, root_nodes, ts, mem_edge_feats, block) 115 | mailbox.update_memory(model.memory_updater.last_updated_nid, model.memory_updater.last_updated_memory, model.memory_updater.last_updated_ts) 116 | processed_edge_id += train_param['batch_size'] 117 | if processed_edge_id >= len(df): 118 | return 119 | 120 | def get_node_emb(root_nodes, ts): 121 | forward_model_to(ts[-1]) 122 | if sampler is not None: 123 | sampler.sample(root_nodes, ts) 124 | ret = sampler.get_ret() 125 | if gnn_param['arch'] != 'identity': 126 | mfgs = to_dgl_blocks(ret, sample_param['history']) 127 | else: 128 | mfgs = node_to_dgl_blocks(root_nodes, ts) 129 | mfgs = prepare_input(mfgs, node_feats, edge_feats, combine_first=combine_first) 130 | if mailbox is not None: 131 | mailbox.prep_input_mails(mfgs[0]) 132 | with torch.no_grad(): 133 | ret = model.get_emb(mfgs) 134 | return ret.detach().cpu() 135 | 136 | emb = list() 137 | for _, rows in tqdm(ldf.groupby(ldf.index // args.batch_size)): 138 | emb.append(get_node_emb(rows.node.values.astype(np.int32), rows.time.values.astype(np.float32))) 139 | emb = torch.cat(emb, dim=0) 140 | torch.save(emb, 'embs/' + emb_file_name) 141 | print('Saved to embs/' + emb_file_name) 142 | else: 143 | print('Loading temporal embeddings from embs/' + emb_file_name) 144 | emb = torch.load('embs/' + emb_file_name) 145 | 146 | model = NodeClassificationModel(emb.shape[1], args.dim, labels.max() + 1).cuda() 147 | loss_fn = torch.nn.CrossEntropyLoss() 148 | optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) 149 | labels = torch.from_numpy(labels).type(torch.int32) 150 | role = torch.from_numpy(role).type(torch.int32) 151 | emb = emb 152 | 153 | class NodeEmbMinibatch(): 154 | 155 | def __init__(self, emb, role, label, batch_size): 156 | self.role = role 157 | self.label = label 158 | self.batch_size = batch_size 159 | self.train_emb = emb[role == 0] 160 | self.val_emb = emb[role == 1] 161 | self.test_emb = emb[role == 2] 162 | self.train_label = label[role == 0] 163 | self.val_label = label[role == 1] 164 | self.test_label = label[role == 2] 165 | self.mode = 0 166 | self.s_idx = 0 167 | 168 | def shuffle(self): 169 | perm = torch.randperm(self.train_emb.shape[0]) 170 | self.train_emb = self.train_emb[perm] 171 | self.train_label = self.train_label[perm] 172 | 173 | def set_mode(self, mode): 174 | if mode == 'train': 175 | self.mode = 0 176 | elif mode == 'val': 177 | self.mode = 1 178 | elif mode == 'test': 179 | self.mode = 2 180 | self.s_idx = 0 181 | 182 | def __iter__(self): 183 | return self 184 | 185 | def __next__(self): 186 | if self.mode == 0: 187 | emb = self.train_emb 188 | label = self.train_label 189 | elif self.mode == 1: 190 | emb = self.val_emb 191 | label = self.val_label 192 | else: 193 | emb = self.test_emb 194 | label = self.test_label 195 | if self.s_idx >= emb.shape[0]: 196 | raise StopIteration 197 | else: 198 | end = min(self.s_idx + self.batch_size, emb.shape[0]) 199 | curr_emb = emb[self.s_idx:end] 200 | curr_label = label[self.s_idx:end] 201 | self.s_idx += self.batch_size 202 | return curr_emb.cuda(), curr_label.cuda() 203 | 204 | if args.posneg: 205 | role = role[labels == 1] 206 | emb_neg = emb[labels == 0].cuda() 207 | emb = emb[labels == 1] 208 | labels = torch.ones(emb.shape[0], dtype=torch.int64).cuda() 209 | labels_neg = torch.zeros(emb_neg.shape[0], dtype=torch.int64).cuda() 210 | neg_node_sampler = NegLinkSampler(emb_neg.shape[0]) 211 | 212 | minibatch = NodeEmbMinibatch(emb, role, labels, args.batch_size) 213 | if not os.path.isdir('models'): 214 | os.mkdir('models') 215 | save_path = 'models/node_' + args.model.split('/')[-1] 216 | best_e = 0 217 | best_acc = 0 218 | for e in range(args.epoch): 219 | minibatch.set_mode('train') 220 | minibatch.shuffle() 221 | model.train() 222 | for emb, label in minibatch: 223 | optimizer.zero_grad() 224 | if args.posneg: 225 | neg_idx = neg_node_sampler.sample(emb.shape[0]) 226 | emb = torch.cat([emb, emb_neg[neg_idx]], dim=0) 227 | label = torch.cat([label, labels_neg[neg_idx]], dim=0) 228 | pred = model(emb) 229 | loss = loss_fn(pred, label.long()) 230 | loss.backward() 231 | optimizer.step() 232 | minibatch.set_mode('val') 233 | model.eval() 234 | accs = list() 235 | with torch.no_grad(): 236 | for emb, label in minibatch: 237 | if args.posneg: 238 | neg_idx = neg_node_sampler.sample(emb.shape[0]) 239 | emb = torch.cat([emb, emb_neg[neg_idx]], dim=0) 240 | label = torch.cat([label, labels_neg[neg_idx]], dim=0) 241 | pred = model(emb) 242 | if args.posneg: 243 | acc = average_precision_score(label.cpu(), pred.softmax(dim=1)[:, 1].cpu()) 244 | else: 245 | acc = f1_score(label.cpu(), torch.argmax(pred, dim=1).cpu(), average="micro") 246 | accs.append(acc) 247 | acc = float(torch.tensor(accs).mean()) 248 | print('Epoch: {}\tVal acc: {:.4f}'.format(e, acc)) 249 | if acc > best_acc: 250 | best_e = e 251 | best_acc = acc 252 | torch.save(model.state_dict(), save_path) 253 | print('Loading model at epoch {}...'.format(best_e)) 254 | model.load_state_dict(torch.load(save_path)) 255 | minibatch.set_mode('test') 256 | model.eval() 257 | accs = list() 258 | with torch.no_grad(): 259 | for emb, label in minibatch: 260 | if args.posneg: 261 | neg_idx = neg_node_sampler.sample(emb.shape[0]) 262 | emb = torch.cat([emb, emb_neg[neg_idx]], dim=0) 263 | label = torch.cat([label, labels_neg[neg_idx]], dim=0) 264 | pred = model(emb) 265 | if args.posneg: 266 | acc = average_precision_score(label.cpu(), pred.softmax(dim=1)[:, 1].cpu()) 267 | else: 268 | acc = f1_score(label.cpu(), torch.argmax(pred, dim=1).cpu(), average="micro") 269 | accs.append(acc) 270 | acc = float(torch.tensor(accs).mean()) 271 | print('Testing acc: {:.4f}'.format(acc)) -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import os 3 | import yaml 4 | import dgl 5 | import time 6 | import pandas as pd 7 | import numpy as np 8 | 9 | def load_feat(d, rand_de=0, rand_dn=0): 10 | node_feats = None 11 | if os.path.exists('DATA/{}/node_features.pt'.format(d)): 12 | node_feats = torch.load('DATA/{}/node_features.pt'.format(d)) 13 | if node_feats.dtype == torch.bool: 14 | node_feats = node_feats.type(torch.float32) 15 | edge_feats = None 16 | if os.path.exists('DATA/{}/edge_features.pt'.format(d)): 17 | edge_feats = torch.load('DATA/{}/edge_features.pt'.format(d)) 18 | if edge_feats.dtype == torch.bool: 19 | edge_feats = edge_feats.type(torch.float32) 20 | if rand_de > 0: 21 | if d == 'LASTFM': 22 | edge_feats = torch.randn(1293103, rand_de) 23 | elif d == 'MOOC': 24 | edge_feats = torch.randn(411749, rand_de) 25 | if rand_dn > 0: 26 | if d == 'LASTFM': 27 | node_feats = torch.randn(1980, rand_dn) 28 | elif d == 'MOOC': 29 | edge_feats = torch.randn(7144, rand_dn) 30 | return node_feats, edge_feats 31 | 32 | def load_graph(d): 33 | df = pd.read_csv('DATA/{}/edges.csv'.format(d)) 34 | g = np.load('DATA/{}/ext_full.npz'.format(d)) 35 | return g, df 36 | 37 | def parse_config(f): 38 | conf = yaml.safe_load(open(f, 'r')) 39 | sample_param = conf['sampling'][0] 40 | memory_param = conf['memory'][0] 41 | gnn_param = conf['gnn'][0] 42 | train_param = conf['train'][0] 43 | return sample_param, memory_param, gnn_param, train_param 44 | 45 | def to_dgl_blocks(ret, hist, reverse=False, cuda=True): 46 | mfgs = list() 47 | for r in ret: 48 | if not reverse: 49 | b = dgl.create_block((r.col(), r.row()), num_src_nodes=r.dim_in(), num_dst_nodes=r.dim_out()) 50 | b.srcdata['ID'] = torch.from_numpy(r.nodes()) 51 | b.edata['dt'] = torch.from_numpy(r.dts())[b.num_dst_nodes():] 52 | b.srcdata['ts'] = torch.from_numpy(r.ts()) 53 | else: 54 | b = dgl.create_block((r.row(), r.col()), num_src_nodes=r.dim_out(), num_dst_nodes=r.dim_in()) 55 | b.dstdata['ID'] = torch.from_numpy(r.nodes()) 56 | b.edata['dt'] = torch.from_numpy(r.dts())[b.num_src_nodes():] 57 | b.dstdata['ts'] = torch.from_numpy(r.ts()) 58 | b.edata['ID'] = torch.from_numpy(r.eid()) 59 | if cuda: 60 | mfgs.append(b.to('cuda:0')) 61 | else: 62 | mfgs.append(b) 63 | mfgs = list(map(list, zip(*[iter(mfgs)] * hist))) 64 | mfgs.reverse() 65 | return mfgs 66 | 67 | def node_to_dgl_blocks(root_nodes, ts, cuda=True): 68 | mfgs = list() 69 | b = dgl.create_block(([],[]), num_src_nodes=root_nodes.shape[0], num_dst_nodes=root_nodes.shape[0]) 70 | b.srcdata['ID'] = torch.from_numpy(root_nodes) 71 | b.srcdata['ts'] = torch.from_numpy(ts) 72 | if cuda: 73 | mfgs.insert(0, [b.to('cuda:0')]) 74 | else: 75 | mfgs.insert(0, [b]) 76 | return mfgs 77 | 78 | def mfgs_to_cuda(mfgs): 79 | for mfg in mfgs: 80 | for i in range(len(mfg)): 81 | mfg[i] = mfg[i].to('cuda:0') 82 | return mfgs 83 | 84 | def prepare_input(mfgs, node_feats, edge_feats, combine_first=False, pinned=False, nfeat_buffs=None, efeat_buffs=None, nids=None, eids=None): 85 | if combine_first: 86 | for i in range(len(mfgs[0])): 87 | if mfgs[0][i].num_src_nodes() > mfgs[0][i].num_dst_nodes(): 88 | num_dst = mfgs[0][i].num_dst_nodes() 89 | ts = mfgs[0][i].srcdata['ts'][num_dst:] 90 | nid = mfgs[0][i].srcdata['ID'][num_dst:].float() 91 | nts = torch.stack([ts, nid], dim=1) 92 | unts, idx = torch.unique(nts, dim=0, return_inverse=True) 93 | uts = unts[:, 0] 94 | unid = unts[:, 1] 95 | # import pdb; pdb.set_trace() 96 | b = dgl.create_block((idx + num_dst, mfgs[0][i].edges()[1]), num_src_nodes=unts.shape[0] + num_dst, num_dst_nodes=num_dst, device=torch.device('cuda:0')) 97 | b.srcdata['ts'] = torch.cat([mfgs[0][i].srcdata['ts'][:num_dst], uts], dim=0) 98 | b.srcdata['ID'] = torch.cat([mfgs[0][i].srcdata['ID'][:num_dst], unid], dim=0) 99 | b.edata['dt'] = mfgs[0][i].edata['dt'] 100 | b.edata['ID'] = mfgs[0][i].edata['ID'] 101 | mfgs[0][i] = b 102 | t_idx = 0 103 | t_cuda = 0 104 | i = 0 105 | if node_feats is not None: 106 | for b in mfgs[0]: 107 | if pinned: 108 | if nids is not None: 109 | idx = nids[i] 110 | else: 111 | idx = b.srcdata['ID'].cpu().long() 112 | torch.index_select(node_feats, 0, idx, out=nfeat_buffs[i][:idx.shape[0]]) 113 | b.srcdata['h'] = nfeat_buffs[i][:idx.shape[0]].cuda(non_blocking=True) 114 | i += 1 115 | else: 116 | srch = node_feats[b.srcdata['ID'].long()].float() 117 | b.srcdata['h'] = srch.cuda() 118 | i = 0 119 | if edge_feats is not None: 120 | for mfg in mfgs: 121 | for b in mfg: 122 | if b.num_src_nodes() > b.num_dst_nodes(): 123 | if pinned: 124 | if eids is not None: 125 | idx = eids[i] 126 | else: 127 | idx = b.edata['ID'].cpu().long() 128 | torch.index_select(edge_feats, 0, idx, out=efeat_buffs[i][:idx.shape[0]]) 129 | b.edata['f'] = efeat_buffs[i][:idx.shape[0]].cuda(non_blocking=True) 130 | i += 1 131 | else: 132 | srch = edge_feats[b.edata['ID'].long()].float() 133 | b.edata['f'] = srch.cuda() 134 | return mfgs 135 | 136 | def get_ids(mfgs, node_feats, edge_feats): 137 | nids = list() 138 | eids = list() 139 | if node_feats is not None: 140 | for b in mfgs[0]: 141 | nids.append(b.srcdata['ID'].long()) 142 | if 'ID' in mfgs[0][0].edata: 143 | if edge_feats is not None: 144 | for mfg in mfgs: 145 | for b in mfg: 146 | eids.append(b.edata['ID'].long()) 147 | else: 148 | eids = None 149 | return nids, eids 150 | 151 | def get_pinned_buffers(sample_param, batch_size, node_feats, edge_feats): 152 | pinned_nfeat_buffs = list() 153 | pinned_efeat_buffs = list() 154 | limit = int(batch_size * 3.3) 155 | if 'neighbor' in sample_param: 156 | for i in sample_param['neighbor']: 157 | limit *= i + 1 158 | if edge_feats is not None: 159 | for _ in range(sample_param['history']): 160 | pinned_efeat_buffs.insert(0, torch.zeros((limit, edge_feats.shape[1]), pin_memory=True)) 161 | if node_feats is not None: 162 | for _ in range(sample_param['history']): 163 | pinned_nfeat_buffs.insert(0, torch.zeros((limit, node_feats.shape[1]), pin_memory=True)) 164 | return pinned_nfeat_buffs, pinned_efeat_buffs 165 | 166 | --------------------------------------------------------------------------------