├── LICENSE ├── LICENSES └── Apache-2.0.txt ├── README.md ├── README.md.license ├── data_reader.py ├── img ├── mex_illustration.png └── mex_illustration.png.license ├── main.py ├── requirements.txt ├── requirements.txt.license └── scorer.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSES/Apache-2.0.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution 10 | as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct 18 | or indirect, to cause the direction or management of such entity, whether 19 | by contract or otherwise, or (ii) ownership of fifty percent (50%) or more 20 | of the outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions 23 | granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation 30 | or translation of a Source form, including but not limited to compiled object 31 | code, generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, 34 | made available under the License, as indicated by a copyright notice that 35 | is included in or attached to the work (an example is provided in the Appendix 36 | below). 37 | 38 | "Derivative Works" shall mean any work, whether in Source or Object form, 39 | that is based on (or derived from) the Work and for which the editorial revisions, 40 | annotations, elaborations, or other modifications represent, as a whole, an 41 | original work of authorship. For the purposes of this License, Derivative 42 | Works shall not include works that remain separable from, or merely link (or 43 | bind by name) to the interfaces of, the Work and Derivative Works thereof. 44 | 45 | "Contribution" shall mean any work of authorship, including the original version 46 | of the Work and any modifications or additions to that Work or Derivative 47 | Works thereof, that is intentionally submitted to Licensor for inclusion in 48 | the Work by the copyright owner or by an individual or Legal Entity authorized 49 | to submit on behalf of the copyright owner. For the purposes of this definition, 50 | "submitted" means any form of electronic, verbal, or written communication 51 | sent to the Licensor or its representatives, including but not limited to 52 | communication on electronic mailing lists, source code control systems, and 53 | issue tracking systems that are managed by, or on behalf of, the Licensor 54 | for the purpose of discussing and improving the Work, but excluding communication 55 | that is conspicuously marked or otherwise designated in writing by the copyright 56 | owner as "Not a Contribution." 57 | 58 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 59 | of whom a Contribution has been received by Licensor and subsequently incorporated 60 | within the Work. 61 | 62 | 2. Grant of Copyright License. Subject to the terms and conditions of this 63 | License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, 64 | no-charge, royalty-free, irrevocable copyright license to reproduce, prepare 65 | Derivative Works of, publicly display, publicly perform, sublicense, and distribute 66 | the Work and such Derivative Works in Source or Object form. 67 | 68 | 3. Grant of Patent License. Subject to the terms and conditions of this License, 69 | each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, 70 | no-charge, royalty-free, irrevocable (except as stated in this section) patent 71 | license to make, have made, use, offer to sell, sell, import, and otherwise 72 | transfer the Work, where such license applies only to those patent claims 73 | licensable by such Contributor that are necessarily infringed by their Contribution(s) 74 | alone or by combination of their Contribution(s) with the Work to which such 75 | Contribution(s) was submitted. If You institute patent litigation against 76 | any entity (including a cross-claim or counterclaim in a lawsuit) alleging 77 | that the Work or a Contribution incorporated within the Work constitutes direct 78 | or contributory patent infringement, then any patent licenses granted to You 79 | under this License for that Work shall terminate as of the date such litigation 80 | is filed. 81 | 82 | 4. Redistribution. You may reproduce and distribute copies of the Work or 83 | Derivative Works thereof in any medium, with or without modifications, and 84 | in Source or Object form, provided that You meet the following conditions: 85 | 86 | (a) You must give any other recipients of the Work or Derivative Works a copy 87 | of this License; and 88 | 89 | (b) You must cause any modified files to carry prominent notices stating that 90 | You changed the files; and 91 | 92 | (c) You must retain, in the Source form of any Derivative Works that You distribute, 93 | all copyright, patent, trademark, and attribution notices from the Source 94 | form of the Work, excluding those notices that do not pertain to any part 95 | of the Derivative Works; and 96 | 97 | (d) If the Work includes a "NOTICE" text file as part of its distribution, 98 | then any Derivative Works that You distribute must include a readable copy 99 | of the attribution notices contained within such NOTICE file, excluding those 100 | notices that do not pertain to any part of the Derivative Works, in at least 101 | one of the following places: within a NOTICE text file distributed as part 102 | of the Derivative Works; within the Source form or documentation, if provided 103 | along with the Derivative Works; or, within a display generated by the Derivative 104 | Works, if and wherever such third-party notices normally appear. The contents 105 | of the NOTICE file are for informational purposes only and do not modify the 106 | License. You may add Your own attribution notices within Derivative Works 107 | that You distribute, alongside or as an addendum to the NOTICE text from the 108 | Work, provided that such additional attribution notices cannot be construed 109 | as modifying the License. 110 | 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, 113 | or distribution of Your modifications, or for any such Derivative Works as 114 | a whole, provided Your use, reproduction, and distribution of the Work otherwise 115 | complies with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. Unless You explicitly state otherwise, any 118 | Contribution intentionally submitted for inclusion in the Work by You to the 119 | Licensor shall be under the terms and conditions of this License, without 120 | any additional terms or conditions. Notwithstanding the above, nothing herein 121 | shall supersede or modify the terms of any separate license agreement you 122 | may have executed with Licensor regarding such Contributions. 123 | 124 | 6. Trademarks. This License does not grant permission to use the trade names, 125 | trademarks, service marks, or product names of the Licensor, except as required 126 | for reasonable and customary use in describing the origin of the Work and 127 | reproducing the content of the NOTICE file. 128 | 129 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to 130 | in writing, Licensor provides the Work (and each Contributor provides its 131 | Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 132 | KIND, either express or implied, including, without limitation, any warranties 133 | or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR 134 | A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness 135 | of using or redistributing the Work and assume any risks associated with Your 136 | exercise of permissions under this License. 137 | 138 | 8. Limitation of Liability. In no event and under no legal theory, whether 139 | in tort (including negligence), contract, or otherwise, unless required by 140 | applicable law (such as deliberate and grossly negligent acts) or agreed to 141 | in writing, shall any Contributor be liable to You for damages, including 142 | any direct, indirect, special, incidental, or consequential damages of any 143 | character arising as a result of this License or out of the use or inability 144 | to use the Work (including but not limited to damages for loss of goodwill, 145 | work stoppage, computer failure or malfunction, or any and all other commercial 146 | damages or losses), even if such Contributor has been advised of the possibility 147 | of such damages. 148 | 149 | 9. Accepting Warranty or Additional Liability. While redistributing the Work 150 | or Derivative Works thereof, You may choose to offer, and charge a fee for, 151 | acceptance of support, warranty, indemnity, or other liability obligations 152 | and/or rights consistent with this License. However, in accepting such obligations, 153 | You may act only on Your own behalf and on Your sole responsibility, not on 154 | behalf of any other Contributor, and only if You agree to indemnify, defend, 155 | and hold each Contributor harmless for any liability incurred by, or claims 156 | asserted against, such Contributor by reason of your accepting any such warranty 157 | or additional liability. 158 | 159 | END OF TERMS AND CONDITIONS 160 | 161 | APPENDIX: How to apply the Apache License to your work. 162 | 163 | To apply the Apache License to your work, attach the following boilerplate 164 | notice, with the fields enclosed by brackets "[]" replaced with your own identifying 165 | information. (Don't include the brackets!) The text should be enclosed in 166 | the appropriate comment syntax for the file format. We also recommend that 167 | a file or class name and description of purpose be included on the same "printed 168 | page" as the copyright notice for easier identification within third-party 169 | archives. 170 | 171 | Copyright [yyyy] [name of copyright owner] 172 | 173 | Licensed under the Apache License, Version 2.0 (the "License"); 174 | you may not use this file except in compliance with the License. 175 | You may obtain a copy of the License at 176 | 177 | http://www.apache.org/licenses/LICENSE-2.0 178 | 179 | Unless required by applicable law or agreed to in writing, software 180 | distributed under the License is distributed on an "AS IS" BASIS, 181 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 182 | See the License for the specific language governing permissions and 183 | limitations under the License. 184 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Contrastive Self-Supervised Learning for Commonsense Reasoning 3 | [![made-with-python](https://img.shields.io/badge/Made%20with-Python-red.svg)](#python) 4 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 5 | [![REUSE status](https://api.reuse.software/badge/github.com/SAP-samples/acl2020-commonsense)](https://api.reuse.software/info/github.com/SAP-samples/acl2020-commonsense) 6 | 7 | 8 | #### News 9 | - **07/17/2020: Provided source code** 10 | - 05/15/2020: Provided model for download 11 | 12 | This repository contains the source code for our paper [Contrastive Self-Supervised Learning for Commonsense Reasoning](https://arxiv.org/abs/2005.00669) to be presented at [ACL2020]( https://acl2020.org/). The code is in parts based on the code from [Huggingface Tranformers](https://github.com/huggingface/transformers) and the paper [A Surprisingly Robust Trick for Winograd Schema Challenge](https://github.com/vid-koci/bert-commonsense). 13 | 14 | ![Schematic Illustration of MEx](https://github.com/SAP-samples/acl2020-commonsense/blob/main/img/mex_illustration.png) 15 | 16 | We propose a self-supervised method to solve *Pronoun Disambiguation* and *Winograd Schema Challenge* problems. 17 | Our approach exploits the characteristic structure of training corpora related to so-called *trigger* words, which are responsible for flipping the answer in pronoun disambiguation. 18 | We achieve such commonsense reasoning by constructing pair-wise contrastive auxiliary predictions. To this end, we leverage a *mutual exclusive loss* regularized by a *contrastive* margin. 19 | Our architecture is based on the recently introduced transformer networks, BERT, that exhibits strong performance on many language understanding benchmarks. Empirical results show that our method alleviates the limitation of current supervised approaches for commonsense reasoning. This study opens up avenues for exploiting inexpensive self-supervision to achieve performance gain in commonsense reasoning tasks. 20 | 21 | #### Authors: 22 | - [Tassilo Klein](https://tjklein.github.io/) 23 | - [Moin Nabi](https://moinnabi.github.io/) 24 | 25 | ## Requirements 26 | - [Python](https://www.python.org/) (version 3.6 or later) 27 | - [PyTorch](https://pytorch.org/) 28 | - [Huggingface Tranformers](https://github.com/huggingface/transformers) 29 | 30 | 31 | ## Download and Installation 32 | 33 | 1. Install the requiremennts: 34 | 35 | ``` 36 | conda install --yes --file requirements.txt 37 | ``` 38 | 39 | or 40 | 41 | ``` 42 | pip install -r requirements.txt 43 | ``` 44 | 45 | 2. Clone this repository and install dependencies: 46 | ``` 47 | git clone https://github.com/SAP/acl2020-commonsense-reasoning 48 | cd acl2020-commonsense-reasoning 49 | pip install -r requirements.txt 50 | ``` 51 | 52 | 3. Create 'data' sub-directory and download files for PDP, WSC challenge, KnowRef and DPR.: 53 | ``` 54 | mkdir data 55 | wget https://cs.nyu.edu/faculty/davise/papers/WinogradSchemas/PDPChallenge2016.xml 56 | wget https://cs.nyu.edu/faculty/davise/papers/WinogradSchemas/WSCollection.xml 57 | wget https://raw.githubusercontent.com/aemami1/KnowRef/master/Knowref_dataset/knowref_test.json 58 | wget http://www.hlt.utdallas.edu/~vince/data/emnlp12/train.c.txt 59 | wget http://www.hlt.utdallas.edu/~vince/data/emnlp12/test.c.txt 60 | cd .. 61 | ``` 62 | 63 | 4. Training and evaluating the model 64 | ``` 65 | python main.py --task_name wscr --do_eval --do_train --eval_batch_size 10 --data_dir "data/" --bert_model bert-large-uncased --max_seq_length 128 --train_batch_size 4 --learning_rate 1.0e-5 --alpha_param 0.05 --beta_param 0.02 --num_train_epochs 25.0 --output_dir model_output/ --gamma_param 60.0 --shuffle 66 | 67 | ``` 68 | 69 | 5. (optional) Evaluating the model without training 70 | ``` 71 | python main.py --task_name wscr --do_eval --eval_batch_size 10 --data_dir "data/" --bert_model bert-large-uncased --max_seq_length 128 72 | 73 | ``` 74 | 75 | ## Model 76 | 77 | The BERT-Large model is available in the Huggingface repository as [sap-ai-research/BERT-Large-Contrastive-Self-Supervised-ACL2020](https://huggingface.co/sap-ai-research/BERT-Large-Contrastive-Self-Supervised-ACL2020). 78 | 79 | Loading the model in Python: 80 | 81 | ``` 82 | tokenizer = AutoTokenizer.from_pretrained("sap-ai-research/BERT-Large-Contrastive-Self-Supervised-ACL2020") 83 | 84 | model = AutoModelWithLMHead.from_pretrained("sap-ai-research/BERT-Large-Contrastive-Self-Supervised-ACL2020") 85 | ``` 86 | 87 | This model should reproduce the results reported in the paper: 88 | 89 | ``` 90 | Knowref-test: 0.6558966074313409 91 | DPR/WSCR-test: 0.8014184397163121 92 | WSC: 0.6959706959706959 93 | PDP: 0.9 94 | ``` 95 | 96 | ## Related work 97 | See our work accepted [ACL'19](http://acl2019.org/) - *Attention Is (not) All You Need for Commonsense Reasoning* - proposing BERT attention-guidance for commonsense reasoning. [arXiv](https://arxiv.org/abs/1905.13497), [GitHub](https://github.com/SAP-samples/acl2019-commonsense/) 98 | 99 | ## Known Issues 100 | No issues known 101 | 102 | 103 | ## How to obtain support 104 | This project is provided "as-is" and any bug reports are not guaranteed to be fixed. 105 | 106 | 107 | ## Citations 108 | If you use this code in your research, 109 | please cite: 110 | 111 | ``` 112 | @inproceedings{klein-nabi-2020-contrastive, 113 | title = "Contrastive Self-Supervised Learning for Commonsense Reasoning", 114 | author = "Klein, Tassilo and 115 | Nabi, Moin", 116 | booktitle = "Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics", 117 | month = jul, 118 | year = "2020", 119 | address = "Online", 120 | publisher = "Association for Computational Linguistics", 121 | url = "https://www.aclweb.org/anthology/2020.acl-main.671", 122 | pages = "7517--7523" 123 | } 124 | ``` 125 | 126 | 127 | ## License 128 | Copyright (c) 2024 SAP SE or an SAP affiliate company. All rights reserved. This project is licensed under the Apache Software License, version 2.0 except as noted otherwise in the [LICENSE](LICENSES/Apache-2.0.txt). 129 | -------------------------------------------------------------------------------- /README.md.license: -------------------------------------------------------------------------------- 1 | # 2 | # SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | -------------------------------------------------------------------------------- /data_reader.py: -------------------------------------------------------------------------------- 1 | # 2 | # SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | 6 | import os 7 | from tqdm import trange,tqdm 8 | #import gap_utils 9 | #import wnli_utils 10 | import json 11 | import re 12 | 13 | class InputExample(object): 14 | """A single training/test example for simple sequence classification.""" 15 | 16 | def __init__(self, guid, text_a, candidate_a, candidate_b, ex_true=True): 17 | """Constructs a InputExample. 18 | 19 | Args: 20 | guid: Unique id for the example. 21 | text_a: string. Sentence analysed with pronoun replaced for _ 22 | candidate_a: string, correct candidate 23 | candidate_b: string, incorrect candidate 24 | """ 25 | self.guid = guid 26 | self.text_a = text_a 27 | self.candidate_a = candidate_a 28 | self.candidate_b = candidate_b #only used for train 29 | self.ex_true = ex_true 30 | #ex_true only matters for testing and has following string values: 31 | #"true" - LM has to pick this over others, 32 | #"false" - LM should not pick this over others 33 | #"other" - not known, not important, this is "other" candidate 34 | #"err_true" - Correct candidate but Spacy failed to find it. Automatically wrong 35 | #"err_false" - Incorrect candidate but Spacy failed to find it. Automatically correct 36 | 37 | class DataProcessor(object): 38 | """Processor for the Wiki data set.""" 39 | 40 | def wnli_test(self,source): 41 | examples=[] 42 | for line in tqdm(list(open(source,'r'))[1:]): 43 | tokens = line.strip().split('\t') 44 | guid = tokens[0] 45 | premise = tokens[1] 46 | hypothesis = tokens[2] 47 | premise,candidates = wnli_utils.transform_wnli(premise,hypothesis) 48 | if premise==None: 49 | examples.append(InputExample(guid,"","",None,ex_true="err_false")) 50 | continue 51 | candidate_a = candidates[0] 52 | candidates_b = candidates[1:] 53 | examples.append(InputExample(guid,premise,candidate_a,None,ex_true="true"))#we don't really know if it's true, but as long as it's not "other" it's fine 54 | for cand in candidates_b: 55 | examples.append(InputExample(guid,premise,cand,None,ex_true="other")) 56 | return examples 57 | 58 | def gap_train(self, source): 59 | examples=[] 60 | for line in tqdm(list(open(source,'r'))[1:],desc="Reading and pre-processing data"): 61 | tokens = line.strip().split('\t') 62 | guid = tokens[0] 63 | sentence = tokens[1] 64 | pronoun = tokens[2] 65 | pronoun_offset = int(tokens[3]) 66 | sentence = sentence[:pronoun_offset]+"_"+sentence[pronoun_offset+len(pronoun):] 67 | candidate_a = tokens[4] 68 | candidate_b = tokens[7] 69 | if tokens[6].lower()=="true": 70 | examples.append(InputExample(guid,sentence,candidate_a,candidate_b)) 71 | if tokens[9].lower()=="true": 72 | examples.append(InputExample(guid,sentence,candidate_b,candidate_a)) 73 | return examples 74 | 75 | def gap_test(self,source): 76 | examples=[] 77 | for line in tqdm(list(open(source,'r'))[1:],desc="Reading and pre-processing data"): 78 | tokens = line.strip().split('\t') 79 | guid = tokens[0] 80 | sentence = tokens[1] 81 | pronoun = tokens[2] 82 | pronoun_offset = int(tokens[3]) 83 | sentence = sentence[:pronoun_offset]+"_"+sentence[pronoun_offset+len(pronoun):] 84 | candidate_a = tokens[4] 85 | candidate_b = tokens[7] 86 | other_candidates = gap_utils.get_candidates(sentence) 87 | if pronoun.casefold() == "his":#due to the abiguity of English language, the same cannot be done for "her" 88 | candidate_a = candidate_a+"\'s" 89 | candidate_b = candidate_b+"\'s" 90 | for i in range(len(other_candidates)): 91 | other_candidates[i]= other_candidates[i]+"\'s" 92 | if candidate_a.casefold() in [cand.casefold() for cand in other_candidates]:#candidate_a was detected by NER 93 | examples.append(InputExample(guid+"A",sentence,candidate_a,None,ex_true = tokens[6].lower())) 94 | for other in list(filter(lambda a: a.casefold()!= candidate_a.casefold(), other_candidates)): 95 | examples.append(InputExample(guid+"A",sentence,other,None,ex_true = "other")) 96 | else: 97 | examples.append(InputExample(guid+"A",sentence,candidate_a,None,ex_true = "err_"+tokens[6].lower())) 98 | if candidate_b.casefold() in [cand.casefold() for cand in other_candidates]: 99 | examples.append(InputExample(guid+"B",sentence,candidate_b,None,ex_true = tokens[9].lower())) 100 | for other in list(filter(lambda a: a.casefold()!= candidate_b.casefold(), other_candidates)): 101 | examples.append(InputExample(guid+"B",sentence,other,None,ex_true = "other")) 102 | else: 103 | examples.append(InputExample(guid+"B",sentence,candidate_b,None,ex_true = "err_"+tokens[9].lower())) 104 | return examples 105 | 106 | def read_dpr_format_train(self,source): 107 | examples = [] 108 | lines = list(open(source,'r')) 109 | for id_x,(sent,pronoun,candidates,candidate_a,_) in enumerate(zip(lines[0::5],lines[1::5],lines[2::5],lines[3::5],lines[4::5])): 110 | guid = id_x 111 | sent = sent.strip() 112 | text_a = sent.replace(' '+pronoun.strip()+' '," _ ",1) 113 | cnd = candidates.split(",") 114 | cnd = (cnd[0].strip().lstrip(),cnd[1].strip().lstrip()) 115 | candidate_a = candidate_a.strip().lstrip() 116 | if candidate_a.casefold()==cnd[0].casefold(): 117 | candidate_b = cnd[1] 118 | else: 119 | candidate_b=cnd[0] 120 | examples.append(InputExample(guid, text_a, candidate_a, candidate_b, ex_true="true")) 121 | return examples 122 | 123 | def read_dpr_format_test(self,source): 124 | examples = [] 125 | lines = list(open(source,'r')) 126 | for id_x,(sent,pronoun,candidates,candidate_a,_) in enumerate(zip(lines[0::5],lines[1::5],lines[2::5],lines[3::5],lines[4::5])): 127 | guid = id_x 128 | sent = sent.strip() 129 | text_a = sent.replace(' '+pronoun.strip()+' '," _ ",1) 130 | candidate_a = candidate_a.strip().lstrip() 131 | cnd = candidates.strip().split(",") 132 | cnd = (candidate.strip().lstrip() for candidate in cnd if candidate.strip().lstrip().casefold()!= candidate_a.casefold()) 133 | examples.append(InputExample(guid, text_a, candidate_a, None, ex_true="true")) 134 | for candidate in cnd: 135 | examples.append(InputExample(guid, text_a, candidate, None,ex_true="other")) 136 | return examples 137 | 138 | @classmethod 139 | def _read_jsonl(cls, input_file): 140 | """Reads a tab separated value file.""" 141 | records = [] 142 | with open(input_file, "r", encoding="utf-8-sig") as f: 143 | for line in f: 144 | records.append(json.loads(line)) 145 | return records 146 | 147 | 148 | @classmethod 149 | def _read_json(cls, input_file): 150 | """Reads a tab separated value file.""" 151 | with open(input_file, 'r') as f: 152 | records = json.load(f) 153 | 154 | return records 155 | 156 | 157 | def _create_examples_test(self, records): 158 | examples = [] 159 | for (i, record) in enumerate(records): 160 | guid = record['qID'] 161 | sentence = record['sentence'] 162 | 163 | name1 = record['option1'] 164 | name2 = record['option2'] 165 | if not 'answer' in record: 166 | # This is a dummy label for test prediction. 167 | # test.jsonl doesn't include the `answer`. 168 | label = "1" 169 | else: 170 | label = record['answer'] 171 | 172 | conj = "_" 173 | idx = sentence.index(conj) 174 | context = sentence[:idx] 175 | option_str = "_ " + sentence[idx + len(conj):].strip() 176 | 177 | option1 = option_str.replace("_", name1) 178 | option2 = option_str.replace("_", name2) 179 | 180 | if label == "1": 181 | examples.append(InputExample(guid,sentence,name1,None, ex_true="true")) 182 | examples.append(InputExample(guid,sentence,name2,None, ex_true="other")) 183 | elif label == "2": 184 | examples.append(InputExample(guid,sentence,name2,None, ex_true="true")) 185 | examples.append(InputExample(guid,sentence,name1,None, ex_true="other")) 186 | else: 187 | print('unknown label!') 188 | 189 | 190 | return examples 191 | 192 | 193 | def _create_examples_train(self, records): 194 | examples = [] 195 | for (i, record) in enumerate(records): 196 | guid = record['qID'] 197 | sentence = record['sentence'] 198 | 199 | name1 = record['option1'] 200 | name2 = record['option2'] 201 | if not 'answer' in record: 202 | # This is a dummy label for test prediction. 203 | # test.jsonl doesn't include the `answer`. 204 | label = "1" 205 | else: 206 | label = record['answer'] 207 | 208 | conj = "_" 209 | idx = sentence.index(conj) 210 | context = sentence[:idx] 211 | option_str = "_ " + sentence[idx + len(conj):].strip() 212 | 213 | option1 = option_str.replace("_", name1) 214 | option2 = option_str.replace("_", name2) 215 | 216 | if label == "1": 217 | mc_example = InputExample(guid,sentence,name1,name2) 218 | else: 219 | mc_example = InputExample(guid,sentence,name2,name1) 220 | 221 | examples.append(mc_example) 222 | 223 | return examples 224 | 225 | 226 | def _create_examples_knowref_test(self, records): 227 | examples = [] 228 | for (i, record) in enumerate(records): 229 | guid = record['oiginal_id'] 230 | sentence = record['sentence_with_pronoun'] 231 | 232 | sentence = re.sub("[\[].*?[\]]", "_", sentence) 233 | 234 | name1 = record['candidate0'][0] 235 | name2 = record['candidate1'][0] 236 | if not 'correct_candidate_idx' in record: 237 | # This is a dummy label for test prediction. 238 | # test.jsonl doesn't include the `answer`. 239 | label = "1" 240 | else: 241 | label = str(int(record['correct_candidate_idx'])+1) 242 | 243 | #conj = "_" 244 | #idx = sentence.index(conj) 245 | #context = sentence[:idx] 246 | #option_str = "_ " + sentence[idx + len(conj):].strip() 247 | 248 | #option1 = option_str.replace("_", name1) 249 | #option2 = option_str.replace("_", name2) 250 | 251 | if label == "1": 252 | examples.append(InputExample(guid,sentence,name1,None, ex_true="true")) 253 | examples.append(InputExample(guid,sentence,name2,None, ex_true="other")) 254 | elif label == "2": 255 | examples.append(InputExample(guid,sentence,name2,None, ex_true="true")) 256 | examples.append(InputExample(guid,sentence,name1,None, ex_true="other")) 257 | else: 258 | print('unknown label!') 259 | 260 | 261 | return examples 262 | 263 | 264 | 265 | def get_examples(self, data_dir, set_name):#works for differently for train! 266 | """See base class.""" 267 | file_names = { 268 | "wikicrem-train":"WikiCREM_train.txt", 269 | "wikicrem-dev":"WikiCREM_dev.txt", 270 | "gap-train": "gap-development.tsv", 271 | "gap-dev": "gap-validation.tsv", 272 | "gap-test": "gap-test.tsv", 273 | "dpr-train": "train.c.txt", 274 | "wscr-train": "train.c.txt", 275 | "dpr-test": "test.c.txt", 276 | "wscr-test": "test.c.txt", 277 | "dpr-train-small": "dpr_train_small.txt", 278 | "dpr-dev-small": "dpr_dev_small.txt", 279 | "wsc": "wsc273.txt", 280 | "pdp": "PDP.txt", 281 | "winogender": "WinoGender.txt", 282 | "winobias-pro1": "pro_stereotyped_1.txt", 283 | "winobias-anti1": "anti_stereotyped_1.txt", 284 | "winobias-pro2": "pro_stereotyped_2.txt", 285 | "winobias-anti2": "anti_stereotyped_2.txt", 286 | "winobias-dev": "winobias_dev.txt", 287 | "wnli":"wnli-test.tsv", 288 | "maskedwiki":"MaskedWiki_2.4Mtrain.txt", 289 | "winogrande-xl-train": "winogrande_1.1/train_xl.jsonl", 290 | "winogrande-l-train": "winogrande_1.1/train_l.jsonl", 291 | "winogrande-m-train": "winogrande_1.1/train_m.jsonl", 292 | "winogrande-s-train": "winogrande_1.1/train_s.jsonl", 293 | "winogrande-xs-train": "winogrande_1.1/train_xs.jsonl", 294 | "winogrande-dev": "winogrande_1.1/dev.jsonl", 295 | "winogrande-test": "winogrande_1.1/test2.jsonl", 296 | "knowref-test": "knowref_test.json" 297 | } 298 | source = os.path.join(data_dir,file_names[set_name]) 299 | if set_name == "gap-train": 300 | return self.gap_train(source) 301 | elif set_name in ["gap-dev","gap-test"]: 302 | return self.gap_test(source) 303 | elif set_name in ["dpr-train","wscr-train","dpr-train-small","wikicrem-train","maskedwiki"]: 304 | return self.read_dpr_format_train(source) 305 | elif set_name in ["dpr-test","wscr-test","dpr-dev-small","wsc","pdp","winogender","winobias-pro1","winobias-pro2","winobias-anti1","winobias-anti2","winobias-dev","wikicrem-dev"]: 306 | return self.read_dpr_format_test(source) 307 | elif set_name=="wnli": 308 | return self.wnli_test(source) 309 | elif set_name in ["winogrande-xl-train", "winogrande-l-train", "winogrande-m-train", "winogrande-s-train", "winogrande-xs-train"]: 310 | return self._create_examples_train( 311 | self._read_jsonl(source) ) 312 | elif set_name in [ "winogrande-dev"]: 313 | return self._create_examples_test( 314 | self._read_jsonl(source) ) 315 | elif set_name in [ "knowref-test"]: 316 | return self._create_examples_knowref_test( 317 | self._read_json(source) ) 318 | else: 319 | print("Unknown set_name: ",set_name) 320 | -------------------------------------------------------------------------------- /img/mex_illustration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SAP-samples/acl2020-commonsense/49dc9bc75fd0b8e1d92ce44018b8b2e4d53f7657/img/mex_illustration.png -------------------------------------------------------------------------------- /img/mex_illustration.png.license: -------------------------------------------------------------------------------- 1 | # 2 | # SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # 2 | # SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | # coding=utf-8 7 | # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team., 2019 Intelligent Systems Lab, University of Oxford, SAP SE 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); 10 | # you may not use this file except in compliance with the License. 11 | # You may obtain a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | # See the License for the specific language governing permissions and 19 | # limitations under the License. 20 | 21 | """BERT finetuning runner.""" 22 | from __future__ import absolute_import 23 | from __future__ import division 24 | from __future__ import print_function 25 | 26 | import sys 27 | import os 28 | 29 | import csv 30 | import json 31 | import logging 32 | import argparse 33 | import random 34 | import logging 35 | from tqdm import tqdm, trange 36 | import re 37 | import numpy as np 38 | import torch 39 | from torch.nn import CrossEntropyLoss 40 | from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler 41 | from torch.utils.data.distributed import DistributedSampler 42 | from torch.nn import functional as F 43 | from transformers import BertTokenizer 44 | from transformers import BertPreTrainedModel, BertModel 45 | from transformers.modeling_bert import BertOnlyMLMHead 46 | #from transformers import BertAdam 47 | from transformers import AdamW, get_linear_schedule_with_warmup 48 | from transformers import PYTORCH_PRETRAINED_BERT_CACHE 49 | from torch import nn, optim 50 | from data_reader import InputExample,DataProcessor 51 | from scorer import scorer 52 | 53 | logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', 54 | datefmt = '%m/%d/%Y %H:%M:%S', 55 | level = logging.INFO) 56 | logger = logging.getLogger(__name__) 57 | 58 | 59 | 60 | 61 | 62 | class BertForMaskedLM(BertPreTrainedModel): 63 | r""" 64 | **masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``: 65 | Labels for computing the masked language modeling loss. 66 | Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) 67 | Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels 68 | in ``[0, ..., config.vocab_size]`` 69 | **lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``: 70 | Labels for computing the left-to-right language modeling loss (next word prediction). 71 | Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) 72 | Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels 73 | in ``[0, ..., config.vocab_size]`` 74 | 75 | Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: 76 | **masked_lm_loss**: (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: 77 | Masked language modeling loss. 78 | **ltr_lm_loss**: (`optional`, returned when ``lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: 79 | Next token prediction loss. 80 | **prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)`` 81 | Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). 82 | **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``) 83 | list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings) 84 | of shape ``(batch_size, sequence_length, hidden_size)``: 85 | Hidden-states of the model at the output of each layer plus the initial embedding outputs. 86 | **attentions**: (`optional`, returned when ``config.output_attentions=True``) 87 | list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``: 88 | Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. 89 | 90 | Examples:: 91 | 92 | tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') 93 | model = BertForMaskedLM.from_pretrained('bert-base-uncased') 94 | input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1 95 | outputs = model(input_ids, masked_lm_labels=input_ids) 96 | loss, prediction_scores = outputs[:2] 97 | 98 | """ 99 | def __init__(self, config): 100 | super(BertForMaskedLM, self).__init__(config) 101 | 102 | self.bert = BertModel(config) 103 | self.cls = BertOnlyMLMHead(config) 104 | 105 | self.init_weights() 106 | 107 | def get_output_embeddings(self): 108 | return self.cls.predictions.decoder 109 | 110 | def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, 111 | masked_lm_labels=None, encoder_hidden_states=None, encoder_attention_mask=None, lm_labels=None, ): 112 | 113 | outputs = self.bert(input_ids, 114 | attention_mask=attention_mask, 115 | token_type_ids=token_type_ids, 116 | position_ids=position_ids, 117 | head_mask=head_mask, 118 | inputs_embeds=inputs_embeds, 119 | encoder_hidden_states=encoder_hidden_states, 120 | encoder_attention_mask=encoder_attention_mask) 121 | 122 | sequence_output = outputs[0] 123 | prediction_scores = self.cls(sequence_output) 124 | 125 | outputs = (prediction_scores,) + outputs[2:] # Add hidden states and attention if they are here 126 | 127 | # Although this may seem awkward, BertForMaskedLM supports two scenarios: 128 | # 1. If a tensor that contains the indices of masked labels is provided, 129 | # the cross-entropy is the MLM cross-entropy that measures the likelihood 130 | # of predictions for masked words. 131 | # 2. If `lm_labels` is provided we are in a causal scenario where we 132 | # try to predict the next token for each input in the decoder. 133 | if masked_lm_labels is not None: 134 | loss_fct = CrossEntropyLoss(ignore_index=-1, reduction='none') # -1 index = padding token 135 | 136 | masked_lm_loss = loss_fct(prediction_scores.permute(0,2,1), masked_lm_labels) 137 | 138 | 139 | masked_lm_loss_normalized = torch.div(torch.mean(masked_lm_loss,1),(masked_lm_labels > -1).sum(dim=1,dtype=torch.float32)) 140 | 141 | masked_lm_loss_normalized[torch.isnan(masked_lm_loss_normalized)] = 0.0 142 | 143 | outputs = (masked_lm_loss_normalized,) + outputs 144 | 145 | 146 | if lm_labels is not None: 147 | # we are doing next-token prediction; shift prediction scores and input ids by one 148 | prediction_scores = prediction_scores[:, :-1, :].contiguous() 149 | lm_labels = lm_labels[:, 1:].contiguous() 150 | loss_fct = CrossEntropyLoss(ignore_index=-1) 151 | ltr_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), lm_labels.view(-1)) 152 | outputs = (ltr_lm_loss,) + outputs 153 | 154 | return outputs # (masked_lm_loss), (ltr_lm_loss), prediction_scores, (hidden_states), (attentions) 155 | 156 | class InputFeatures(object): 157 | """A single set of features of data.""" 158 | 159 | def __init__(self, input_ids_1, input_ids_2, attention_mask_1, attention_mask_2, type_1, type_2, masked_lm_1, masked_lm_2, start, end_1, end_2, source_start_token_1, source_end_token_1, source_start_token_2, source_end_token_2): 160 | self.input_ids_1=input_ids_1 161 | self.attention_mask_1=attention_mask_1 162 | self.type_1=type_1 163 | self.masked_lm_1=masked_lm_1 164 | #These are only used for train examples 165 | self.input_ids_2=input_ids_2 166 | self.attention_mask_2=attention_mask_2 167 | self.type_2=type_2 168 | self.masked_lm_2=masked_lm_2 169 | self.start = start 170 | self.end_1 = end_1 171 | self.end_2 = end_2 172 | self.source_start_token_1 = source_start_token_1 173 | self.source_end_token_1 = source_end_token_1 174 | self.source_start_token_2 = source_start_token_2 175 | self.source_end_token_2 = source_end_token_2 176 | 177 | def convert_examples_to_features_train(examples, max_seq_len, tokenizer, mode='multimask'): 178 | """Loads a data file into a list of `InputBatch`s.""" 179 | 180 | features = [] 181 | count = [0,0] 182 | for (ex_index, example) in enumerate(examples): 183 | tokens_sent = tokenizer.tokenize(example.text_a) 184 | tokens_a = tokenizer.tokenize(example.candidate_a) 185 | tokens_b = tokenizer.tokenize(example.candidate_b) 186 | if len(tokens_a) == len(tokens_b): 187 | count[0]=count[0]+1 188 | else: 189 | count[1]=count[1]+1 190 | tokens_1, type_1, attention_mask_1, masked_lm_1 = [],[],[],[] 191 | tokens_2, type_2, attention_mask_2, masked_lm_2 = [],[],[],[] 192 | tokens_1.append("[CLS]") 193 | tokens_2.append("[CLS]") 194 | for token in tokens_sent: 195 | if token=="_": 196 | start = len(tokens_1) 197 | if mode == 'multimask': 198 | tokens_1.extend(["[MASK]" for _ in range(len(tokens_a))]) 199 | tokens_2.extend(["[MASK]" for _ in range(len(tokens_b))]) 200 | else: 201 | tokens_1.append("[MASK]") 202 | tokens_2.append("[MASK]") 203 | 204 | end_1 = len(tokens_1) 205 | end_2 = len(tokens_2) 206 | else: 207 | tokens_1.append(token) 208 | tokens_2.append(token) 209 | 210 | 211 | token_idx_1 = [] 212 | token_idx_2 = [] 213 | token_counter_1 = 0 214 | token_counter_2 = 0 215 | find_tokens_a = True 216 | find_tokens_b = True 217 | 218 | for idx, token in enumerate(tokens_a): 219 | 220 | if ( find_tokens_a and token.lower() == tokens_a[token_counter_1].lower()): 221 | token_idx_1.append(idx) 222 | token_counter_1 += 1 223 | if ( len(token_idx_1) >= len(tokens_a) ): 224 | find_tokens_a = False 225 | elif find_tokens_a: 226 | token_idx_1 = [] 227 | token_counter_1 = 0 228 | 229 | 230 | for idx, token in enumerate(tokens_b): 231 | 232 | if ( find_tokens_b and token.lower() == tokens_b[token_counter_2].lower()): 233 | token_idx_2.append(idx) 234 | token_counter_2 += 1 235 | if ( len(token_idx_2) >= len(tokens_b) ): 236 | find_tokens_b = False 237 | elif find_tokens_b: 238 | token_idx_2 = [] 239 | token_counter_2 = 0 240 | 241 | 242 | tokens_1 = tokens_1[:max_seq_len-1]#-1 because of [SEP] 243 | tokens_2 = tokens_2[:max_seq_len-1] 244 | if tokens_1[-1]!="[SEP]": 245 | tokens_1.append("[SEP]") 246 | if tokens_2[-1]!="[SEP]": 247 | tokens_2.append("[SEP]") 248 | 249 | type_1 = max_seq_len*[0]#We do not do any inference. 250 | type_2 = max_seq_len*[0]#These embeddings can thus be ignored 251 | 252 | attention_mask_1 = (len(tokens_1)*[1])+((max_seq_len-len(tokens_1))*[0]) 253 | attention_mask_2 = (len(tokens_2)*[1])+((max_seq_len-len(tokens_2))*[0]) 254 | 255 | #sentences 256 | input_ids_1 = tokenizer.convert_tokens_to_ids(tokens_1) 257 | input_ids_2 = tokenizer.convert_tokens_to_ids(tokens_2) 258 | #replacements 259 | input_ids_a = tokenizer.convert_tokens_to_ids(tokens_a) 260 | input_ids_b = tokenizer.convert_tokens_to_ids(tokens_b) 261 | 262 | for token in tokens_1: 263 | if token=="[MASK]": 264 | if len(input_ids_a)<=0: 265 | continue#broken case 266 | masked_lm_1.append(input_ids_a[0]) 267 | input_ids_a = input_ids_a[1:] 268 | else: 269 | masked_lm_1.append(-1) 270 | while len(masked_lm_1)= 1".format( 525 | args.gradient_accumulation_steps)) 526 | 527 | args.train_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps) 528 | 529 | random.seed(args.seed) 530 | np.random.seed(args.seed) 531 | torch.manual_seed(args.seed) 532 | if args.n_gpu > 0: 533 | torch.cuda.manual_seed_all(args.seed) 534 | 535 | if not args.do_train and not args.do_eval: 536 | raise ValueError("At least one of `do_train` or `do_eval` must be True.") 537 | 538 | if not os.path.exists(args.output_dir): 539 | os.makedirs(args.output_dir, exist_ok=True) 540 | 541 | task_name = args.task_name.lower() 542 | 543 | processor = DataProcessor() 544 | 545 | # Load pretrained model and tokenizer 546 | if args.local_rank not in [-1, 0]: 547 | torch.distributed.barrier() # Barrier to make sure only the first process in distributed training download model & vocab 548 | 549 | 550 | tokenizer = BertTokenizer.from_pretrained(args.bert_model) 551 | 552 | train_examples = None 553 | num_train_steps = None 554 | if args.do_train: 555 | train_name = {"gap":"gap-train", 556 | "wikicrem":"wikicrem-train", 557 | "dpr":"dpr-train-small", 558 | "wscr":"wscr-train", 559 | "winogrande": "winogrande-l-train", 560 | "maskedwiki":"maskedwiki", 561 | }[task_name] 562 | 563 | 564 | train_examples = processor.get_examples(args.data_dir, train_name) 565 | 566 | num_train_steps = int( 567 | len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps * args.num_train_epochs) 568 | 569 | # shuffle the data 570 | # random.shuffle(train_examples) 571 | if args.shuffle: 572 | # make sure that the labels are *not* used implicitly 573 | logger.info('Shuffling twin-pairs ...') 574 | for i in range(0, len(train_examples), 2): 575 | if random.choices([0,1]) == [0]: 576 | candidate_a = copy.deepcopy(train_examples[i].candidate_a) 577 | candidate_b = copy.deepcopy(train_examples[i].candidate_b) 578 | 579 | train_examples[i].candidate_a = candidate_b 580 | train_examples[i].candidate_b = candidate_a 581 | 582 | 583 | 584 | candidate_a = copy.deepcopy(train_examples[i+1].candidate_a) 585 | candidate_b = copy.deepcopy(train_examples[i+1].candidate_b) 586 | train_examples[i+1].candidate_a = candidate_b 587 | train_examples[i+1].candidate_b = candidate_a 588 | 589 | # Prepare model 590 | if args.load_from_file is None: 591 | model = BertForMaskedLM.from_pretrained(args.bert_model, 592 | cache_dir=PYTORCH_PRETRAINED_BERT_CACHE / 'distributed_{}'.format(args.local_rank), output_attentions=True) 593 | else: 594 | model = BertForMaskedLM.from_pretrained(args.bert_model, 595 | cache_dir=PYTORCH_PRETRAINED_BERT_CACHE / 'distributed_{}'.format(args.local_rank), untrained=True, output_attentions=True) 596 | model.to(device) 597 | 598 | 599 | if args.local_rank == 0: 600 | torch.distributed.barrier() # End of barrier to make sure only the first process in distributed training download model & vocab 601 | 602 | 603 | 604 | if not args.load_from_file is None: 605 | model_dict = torch.load(args.load_from_file) 606 | 607 | 608 | model.load_state_dict(new_dict) 609 | 610 | # Prepare optimizer 611 | param_optimizer = list(model.named_parameters()) 612 | 613 | no_decay = ['bias', 'gamma', 'beta'] 614 | optimizer_grouped_parameters = [ 615 | {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay_rate': args.weight_decay}, 616 | {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.0} 617 | ] 618 | t_total = num_train_steps 619 | if args.local_rank != -1: 620 | t_total = t_total // torch.distributed.get_world_size() 621 | 622 | 623 | 624 | optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) 625 | scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total) # PyTorch scheduler 626 | 627 | 628 | if args.fp16: 629 | # apex 630 | try: 631 | from apex import amp 632 | except ImportError: 633 | raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") 634 | model, optimizer = amp.initialize(model, optimizer, opt_level='O1') 635 | 636 | if args.local_rank != -1: 637 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], 638 | output_device=args.local_rank) 639 | else: 640 | model = torch.nn.DataParallel(model) 641 | 642 | global_step = 0 643 | tr_loss,nb_tr_steps = 0, 1 644 | if args.do_train: 645 | train_features = convert_examples_to_features_train( 646 | train_examples, args.max_seq_length, tokenizer, mode='multimask') 647 | logger.info("***** Running training *****") 648 | logger.info(" Num examples = %d", len(train_examples)) 649 | logger.info(" Batch size = %d", args.train_batch_size) 650 | logger.info(" Num steps = %d", num_train_steps) 651 | 652 | # Load data for even twin-pair sentences (% 2 == 0) 653 | all_input_ids_1 = torch.tensor([f.input_ids_1 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.long) 654 | all_input_ids_2 = torch.tensor([f.input_ids_2 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.long) 655 | all_attention_mask_1 = torch.tensor([f.attention_mask_1 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.long) 656 | all_attention_mask_2 = torch.tensor([f.attention_mask_2 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.long) 657 | all_segment_ids_1 = torch.tensor([f.type_1 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.long) 658 | all_segment_ids_2 = torch.tensor([f.type_2 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.long) 659 | all_masked_lm_1 = torch.tensor([f.masked_lm_1 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.long) 660 | all_masked_lm_2 = torch.tensor([f.masked_lm_2 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.long) 661 | all_start = torch.tensor([f.start for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.int16) 662 | all_end_1 = torch.tensor([f.end_1 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.int16) 663 | all_end_2 = torch.tensor([f.end_2 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.int16) 664 | all_source_start_1 = torch.tensor([f.source_start_token_1 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.int16) 665 | all_source_start_2 = torch.tensor([f.source_start_token_2 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.int16) 666 | all_source_end_1 = torch.tensor([f.source_end_token_1 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.int16) 667 | all_source_end_2 = torch.tensor([f.source_end_token_2 for index, f in enumerate(train_features) if index % 2 == 0], dtype=torch.int16) 668 | 669 | 670 | # Load data for odd twin-pair sentences (%2 == 1) 671 | _all_input_ids_1 = torch.tensor([f.input_ids_1 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.long) 672 | _all_input_ids_2 = torch.tensor([f.input_ids_2 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.long) 673 | _all_attention_mask_1 = torch.tensor([f.attention_mask_1 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.long) 674 | _all_attention_mask_2 = torch.tensor([f.attention_mask_2 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.long) 675 | _all_segment_ids_1 = torch.tensor([f.type_1 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.long) 676 | _all_segment_ids_2 = torch.tensor([f.type_2 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.long) 677 | _all_masked_lm_1 = torch.tensor([f.masked_lm_1 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.long) 678 | _all_masked_lm_2 = torch.tensor([f.masked_lm_2 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.long) 679 | _all_start = torch.tensor([f.start for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.int16) 680 | _all_end_1 = torch.tensor([f.end_1 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.int16) 681 | _all_end_2 = torch.tensor([f.end_2 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.int16) 682 | _all_source_start_1 = torch.tensor([f.source_start_token_1 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.int16) 683 | _all_source_start_2 = torch.tensor([f.source_start_token_2 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.int16) 684 | _all_source_end_1 = torch.tensor([f.source_end_token_1 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.int16) 685 | _all_source_end_2 = torch.tensor([f.source_end_token_2 for index, f in enumerate(train_features) if index % 2 == 1], dtype=torch.int16) 686 | 687 | 688 | 689 | 690 | 691 | 692 | train_data = TensorDataset(all_input_ids_1, all_input_ids_2, all_attention_mask_1, all_attention_mask_2, all_segment_ids_1, all_segment_ids_2, all_masked_lm_1, all_masked_lm_2, all_start, all_end_1, all_end_2, all_source_start_1, all_source_end_1, all_source_start_2, all_source_end_2, 693 | _all_input_ids_1, _all_input_ids_2, _all_attention_mask_1, _all_attention_mask_2, _all_segment_ids_1, _all_segment_ids_2, _all_masked_lm_1, _all_masked_lm_2, _all_start, _all_end_1, _all_end_2, _all_source_start_1, _all_source_end_1, _all_source_start_2, _all_source_end_2) 694 | if args.local_rank == -1: 695 | train_sampler = RandomSampler(train_data) 696 | else: 697 | train_sampler = DistributedSampler(train_data) 698 | train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size) 699 | validation_name = {"gap":"gap-dev", 700 | "wikicrem":"wikicrem-dev", 701 | "dpr":"dpr-dev-small", 702 | "maskedwiki":"wscr-test", 703 | "winogrande": "winogrande-dev", 704 | "wscr":"wscr-test", 705 | }[task_name] 706 | 707 | model.train() 708 | try:#This prevents overwriting if several scripts are running at the same time (for hyper-parameter search) 709 | best_accuracy = float(list(open(os.path.join(args.output_dir,"best_accuracy.txt"),'r'))[0]) 710 | except: 711 | best_accuracy = 0 712 | for it in trange(int(args.num_train_epochs), desc="Epoch"): 713 | tr_loss = 0 714 | tr_accuracy = 0 715 | nb_tr_examples, nb_tr_steps = 0, 0 716 | 717 | if it == 0: 718 | acc = test(processor, args, tokenizer, model, device, global_step = global_step, tr_loss = tr_loss/nb_tr_steps if nb_tr_steps>0 else 0, test_set=validation_name, verbose=True) 719 | logger.info("Initial Eval: {}\t{}\n".format(nb_tr_steps,acc)) 720 | for step, batch in enumerate(tqdm(train_dataloader)): 721 | input_ids_1,input_ids_2,input_mask_1,input_mask_2, segment_ids_1, segment_ids_2, label_ids_1, label_ids_2, target_start, target_end_1, target_end_2, source_start_1, source_end_1, source_start_2, source_end_2, _input_ids_1,_input_ids_2,_input_mask_1,_input_mask_2, _segment_ids_1, _segment_ids_2, _label_ids_1, _label_ids_2, _target_start, _target_end_1, _target_end_2, _source_start_1, _source_end_1, _source_start_2, _source_end_2 = (tens.to(device) for tens in batch) 722 | 723 | # First twin-pair sentence 724 | # Candidate A 725 | loss_1, score_1, attn_1 = model.forward(input_ids_1, token_type_ids = segment_ids_1, attention_mask = input_mask_1, masked_lm_labels = label_ids_1) 726 | # Candidate B 727 | loss_2, score_2, attn_2 = model.forward(input_ids_2, token_type_ids = segment_ids_2, attention_mask = input_mask_2, masked_lm_labels = label_ids_2) 728 | 729 | # Second twin-pair sentence 730 | # Candidate A 731 | _loss_1, _score_1, _attn_1 = model.forward(_input_ids_1, token_type_ids = _segment_ids_1, attention_mask = _input_mask_1, masked_lm_labels = _label_ids_1) 732 | # Candidate B 733 | _loss_2, _score_2, _attn_2 = model.forward(_input_ids_2, token_type_ids = _segment_ids_2, attention_mask = _input_mask_2, masked_lm_labels = _label_ids_2) 734 | 735 | 736 | # contrastive margin loss of first twin-pair sentences 737 | loss = args.alpha_param * torch.max(torch.zeros(loss_1.size(),device=device),torch.ones(loss_1.size(),device=device)*args.beta_param + loss_1 - loss_2.mean()) + args.alpha_param * torch.max(torch.zeros(loss_2.size(),device=device),torch.ones(loss_2.size(),device=device)*args.beta_param + loss_2 - loss_1.mean()) 738 | 739 | # constrastive margin loss of second twin-pair sentences 740 | loss += args.alpha_param * torch.max(torch.zeros(_loss_1.size(),device=device),torch.ones(_loss_1.size(),device=device)*args.beta_param + _loss_1 - _loss_2.mean()) + args.alpha_param * torch.max(torch.zeros(_loss_2.size(),device=device),torch.ones(_loss_2.size(),device=device)*args.beta_param + _loss_2 - _loss_1.mean()) 741 | mex = torch.zeros(1).cuda() 742 | 743 | # compute the mutual-exclusive loss 744 | for i in range(loss_1.shape[0]): 745 | 746 | #eps = 0.0001 747 | cexp_11 = torch.exp(-loss_1[i]) 748 | cexp_12 = torch.exp(-loss_2[i]) 749 | 750 | 751 | cexp_21 = torch.exp(-_loss_1[i]) 752 | cexp_22 = torch.exp(-_loss_2[i]) 753 | 754 | joint_exp_1 = (cexp_11 + cexp_12) 755 | joint_exp_2 = (cexp_21 + cexp_22) 756 | 757 | 758 | 759 | # First twin-pair sentences 760 | term_1 = cexp_11/joint_exp_1 * cexp_21/joint_exp_2 * (1. - (1.-cexp_11/joint_exp_1)*(1.-cexp_21/joint_exp_2)) 761 | # Second twin-pai sentences 762 | term_2 = cexp_12/joint_exp_1 * cexp_22/joint_exp_2 * (1. - (1.-cexp_12/joint_exp_1)*(1.-cexp_22/joint_exp_2)) 763 | 764 | # full mutual-exclusive term 765 | mex += -1.*((term_1) + (term_2)) 766 | 767 | 768 | if torch.isnan(term_1) or torch.isinf(term_1) or torch.isnan(term_2) or torch.isinf(term_2): 769 | logger.error("NaN or Inf") 770 | 771 | exit(1) 772 | 773 | 774 | 775 | 776 | 777 | loss = loss.mean()+ args.gamma_param*mex 778 | 779 | tr_accuracy += len(np.where(loss_1.detach().cpu().numpy()-loss_2.detach().cpu().numpy()<0.0)[0]) 780 | if args.n_gpu > 1: 781 | loss = loss.mean() # mean() to average on multi-gpu. 782 | if args.gradient_accumulation_steps > 1: 783 | loss = loss / args.gradient_accumulation_steps 784 | 785 | 786 | if args.fp16: 787 | with amp.scale_loss(loss, optimizer) as scaled_loss: 788 | scaled_loss.backward() 789 | torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm) 790 | else: 791 | loss.backward() 792 | torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) 793 | 794 | 795 | tr_loss += loss.item() 796 | nb_tr_examples += input_ids_1.size(0) 797 | nb_tr_steps += 1 798 | if (step + 1) % args.gradient_accumulation_steps == 0: 799 | optimizer.step() 800 | model.zero_grad() 801 | scheduler.step() 802 | global_step += 1 803 | if not (task_name in ["wscr","gap","dpr"]) and global_step % 50 == 0 and (step + 1) % args.gradient_accumulation_steps == 0:#testing during an epoch 804 | acc = test(processor, args, tokenizer, model, device, global_step = global_step, tr_loss = tr_loss/nb_tr_steps if nb_tr_steps>0 else 0, test_set=validation_name, verbose=True) 805 | logger.info("{}\t{}\n".format(nb_tr_steps,acc)) 806 | model.train() 807 | try:#If several processes are running in parallel this avoids overwriting results. 808 | updated_accuracy = float(list(open(os.path.join(args.output_dir,"best_accuracy.txt"),'r'))[0]) 809 | except: 810 | updated_accuracy = 0 811 | best_accuracy = max(best_accuracy,updated_accuracy) 812 | if acc>best_accuracy: 813 | best_accuracy = acc 814 | torch.save(model.state_dict(), os.path.join(args.output_dir, "best_model")) 815 | 816 | with open(os.path.join(args.output_dir,"best_config.txt"),'w') as f1_report: 817 | f1_report.write("{}".format(' '.join(sys.argv[1:]))) 818 | with open(os.path.join(args.output_dir,"best_accuracy.txt"),'w') as f1_report: 819 | f1_report.write("{}".format(best_accuracy)) 820 | if validation_name=="all": 821 | acc = (test(processor, args, tokenizer, model, device, global_step = global_step, tr_loss = tr_loss/nb_tr_steps if nb_tr_steps>0 else 0, test_set = "gap-dev", verbose=True) +\ 822 | test(processor, args, tokenizer, model, device, global_step = global_step, tr_loss = tr_loss/nb_tr_steps if nb_tr_steps>0 else 0, test_set = "winobias-dev", verbose=True))/2 823 | else: 824 | acc = test(processor, args, tokenizer, model, device, global_step = global_step, tr_loss = tr_loss/nb_tr_steps if nb_tr_steps>0 else 0, test_set = validation_name, verbose=True) 825 | logger.info("{}\t{}\n".format(nb_tr_steps,acc)) 826 | model.train() 827 | try: 828 | updated_accuracy = float(list(open(os.path.join(args.output_dir,"best_accuracy.txt"),'r'))[0]) 829 | except: 830 | updated_accuracy = 0 831 | best_accuracy = max(best_accuracy,updated_accuracy) 832 | if acc>best_accuracy: 833 | best_accuracy = acc 834 | torch.save(model.state_dict(), os.path.join(args.output_dir, "best_model")) 835 | with open(os.path.join(args.output_dir,"best_accuracy.txt"),'w') as f1_report: 836 | f1_report.write("{}".format(best_accuracy)) 837 | #reload the best model 838 | logger.info("Best dev acc {}".format(best_accuracy)) 839 | model_dict = torch.load(os.path.join(args.output_dir, "best_model")) 840 | model.load_state_dict(model_dict) 841 | 842 | if args.do_eval and (args.local_rank == -1 or torch.distributed.get_rank() == 0): 843 | if True: 844 | print("Knowref-test: ",test(processor, args, tokenizer, model, device, global_step = global_step, tr_loss = tr_loss/nb_tr_steps, test_set="knowref-test")) 845 | print("DPR/WSCR-test: ",test(processor, args, tokenizer, model, device, global_step = global_step, tr_loss = tr_loss/nb_tr_steps, test_set="dpr-test")) 846 | print("WSC: ",test(processor, args, tokenizer, model, device, global_step = global_step, tr_loss = tr_loss/nb_tr_steps, test_set="wsc", output_file='wsc-eval.tsv')) 847 | print("PDP: ",test(processor, args, tokenizer, model, device, global_step = global_step, tr_loss = tr_loss/nb_tr_steps, test_set="pdp")) 848 | if __name__ == "__main__": 849 | main() 850 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | transformers>=2.8.0 2 | torch>=1.5.0 3 | torchvision>=0.6.0 4 | tqdm>==4.45.0 5 | numpy>=1.18.1 6 | -------------------------------------------------------------------------------- /requirements.txt.license: -------------------------------------------------------------------------------- 1 | # 2 | # SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | -------------------------------------------------------------------------------- /scorer.py: -------------------------------------------------------------------------------- 1 | # 2 | # SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | 6 | import pickle 7 | import numpy as np 8 | 9 | def compute_f1(ans_stats, gap_output=None): 10 | other_by_guid={} 11 | target_by_guid={} 12 | gold_by_guid={} 13 | for guid,ex_true,loss in ans_stats: 14 | if ex_true=="other": 15 | if guid in other_by_guid: 16 | other_by_guid[guid]=min(other_by_guid[guid],loss) 17 | else: 18 | other_by_guid[guid]=loss 19 | else: 20 | target_by_guid[guid]=loss 21 | gold_by_guid[guid]=ex_true 22 | tp,fp,tn,fn = 0,0,0,0 23 | output=[] 24 | for guid,gold in gold_by_guid.items(): 25 | if gold=="err_true": 26 | fn+=1 27 | output.append((guid,"FALSE")) 28 | elif gold=="err_false": 29 | tn+=1 30 | output.append((guid,"FALSE")) 31 | elif gold=="true": 32 | if (guid in other_by_guid) and other_by_guid[guid] < target_by_guid[guid]: 33 | fn+=1 34 | output.append((guid,"FALSE")) 35 | else: 36 | tp+=1 37 | output.append((guid,"TRUE")) 38 | else: 39 | if (guid in other_by_guid) and other_by_guid[guid] < target_by_guid[guid]: 40 | tn+=1 41 | output.append((guid,"FALSE")) 42 | else: 43 | fp+=1 44 | output.append((guid,"TRUE")) 45 | if not gap_output is None: 46 | out_file = open(gap_output,'w') 47 | output.sort() 48 | for out in output: 49 | if out[0][-1]=='A': 50 | out_file.write("{}\t{}".format(out[0][:-1],out[1])) 51 | else: 52 | out_file.write("\t{}\n".format(out[1])) 53 | out_file.close() 54 | precision = float(tp)/(tp+fp) 55 | recall = float(tp)/(tp+fn) 56 | return 2*(precision*recall)/(precision+recall) 57 | 58 | def compute_accuracy(ans_stats, wnli_output=None, sort=True): 59 | other_by_guid={} 60 | target_by_guid={} 61 | gold_by_guid={} 62 | for guid,ex_true,loss in ans_stats: 63 | if ex_true=="other": 64 | if guid in other_by_guid: 65 | other_by_guid[guid]=min(other_by_guid[guid],loss) 66 | else: 67 | other_by_guid[guid]=loss 68 | else: 69 | target_by_guid[guid]=loss 70 | gold_by_guid[guid]=ex_true 71 | n_correct=0 72 | n_overall=0 73 | output=[] 74 | 75 | if not wnli_output is None: 76 | pickle.dump( [target_by_guid, gold_by_guid, other_by_guid], open( wnli_output+".tmp", "wb" ) ) 77 | 78 | for guid,gold in gold_by_guid.items(): 79 | if gold=="err_true" or gold=="err_false": 80 | n_overall+=1 81 | output.append((guid,"0")) 82 | else: 83 | if (guid in other_by_guid and other_by_guid[guid] <= target_by_guid[guid]) or np.isnan(target_by_guid[guid]) or np.isinf(target_by_guid[guid]): 84 | n_overall+=1 85 | output.append((guid,"0")) 86 | else: 87 | n_correct+=1 88 | n_overall+=1 89 | output.append((guid,"1")) 90 | 91 | if not wnli_output is None: 92 | 93 | out_file = open(wnli_output,'w') 94 | if sort: 95 | output.sort(key=lambda x:int(x[0])) 96 | for out in output: 97 | out_file.write("{}\t{}\n".format(out[0],out[1])) 98 | out_file.close() 99 | return float(n_correct)/n_overall 100 | 101 | def scorer(ans_stats, test_set, output_file=None): 102 | if test_set=="gap-dev": 103 | return compute_f1(ans_stats) 104 | elif test_set=="gap-test": 105 | return compute_f1(ans_stats, gap_output=output_file) 106 | elif test_set in ["dpr-test","dpr-dev-small","wscr-test","pdp","winogender","winobias-pro1","winobias-pro2","winobias-anti1","winobias-anti2","winobias-dev","wikicrem-dev", "knowref-test"]: 107 | return compute_accuracy(ans_stats) 108 | elif test_set in [ "winogrande-test", "wsc", "winogrande-dev"]: 109 | return compute_accuracy(ans_stats,wnli_output=output_file, sort=False) 110 | 111 | elif test_set=="wnli": 112 | return compute_accuracy(ans_stats,wnli_output=output_file) 113 | 114 | --------------------------------------------------------------------------------