├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── empchat ├── __init__.py ├── bert_local.py ├── datasets │ ├── __init__.py │ ├── dailydialog.py │ ├── empchat.py │ ├── loader.py │ ├── parlai_dictionary.py │ ├── reddit.py │ └── tokens.py ├── models.py ├── transformer_local.py └── util.py ├── retrieval_eval_bleu.py ├── retrieval_train.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Distribution / packaging 2 | build/ 3 | dist/ 4 | *.egg-info/ 5 | 6 | # PyCharm 7 | .idea/ 8 | 9 | # Python 10 | *.pyc 11 | 12 | # Repo-specific 13 | retrieved_split_* 14 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please [read the full text](https://code.fb.com/codeofconduct) so that you can understand what actions will and will not be tolerated. 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to EmpatheticDialogues 2 | We want to make contributing to this project as easy and transparent as possible. 3 | 4 | ## Pull Requests 5 | We actively welcome your pull requests. 6 | 7 | 1. Fork the repo and create your branch from `main`. 8 | 2. If you've added code that should be tested, add tests. 9 | 3. If you've changed APIs, update the documentation. 10 | 4. Ensure the test suite passes. 11 | 5. Make sure your code lints. 12 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 13 | 14 | ## Contributor License Agreement ("CLA") 15 | In order to accept your pull request, we need you to submit a CLA. You only need to do this once to work on any of Facebook's open source projects. 16 | 17 | Complete your CLA here: 18 | 19 | ## Issues 20 | We use GitHub issues to track public bugs. Please ensure your description is clear and has sufficient instructions to be able to reproduce the issue. 21 | 22 | Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. In those cases, please go through the process outlined on that page and do not file a public issue. 23 | 24 | ## License 25 | By contributing to EmpatheticDialogues, you agree that your contributions will be licensed under the LICENSE file in the root directory of this source tree. 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | Section 1 -- Definitions. 71 | 72 | a. Adapted Material means material subject to Copyright and Similar 73 | Rights that is derived from or based upon the Licensed Material 74 | and in which the Licensed Material is translated, altered, 75 | arranged, transformed, or otherwise modified in a manner requiring 76 | permission under the Copyright and Similar Rights held by the 77 | Licensor. For purposes of this Public License, where the Licensed 78 | Material is a musical work, performance, or sound recording, 79 | Adapted Material is always produced where the Licensed Material is 80 | synched in timed relation with a moving image. 81 | 82 | b. Adapter's License means the license You apply to Your Copyright 83 | and Similar Rights in Your contributions to Adapted Material in 84 | accordance with the terms and conditions of this Public License. 85 | 86 | c. Copyright and Similar Rights means copyright and/or similar rights 87 | closely related to copyright including, without limitation, 88 | performance, broadcast, sound recording, and Sui Generis Database 89 | Rights, without regard to how the rights are labeled or 90 | categorized. For purposes of this Public License, the rights 91 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 92 | Rights. 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. NonCommercial means not primarily intended for or directed towards 116 | commercial advantage or monetary compensation. For purposes of 117 | this Public License, the exchange of the Licensed Material for 118 | other material subject to Copyright and Similar Rights by digital 119 | file-sharing or similar means is NonCommercial provided there is 120 | no payment of monetary compensation in connection with the 121 | exchange. 122 | 123 | j. Share means to provide material to the public by any means or 124 | process that requires permission under the Licensed Rights, such 125 | as reproduction, public display, public performance, distribution, 126 | dissemination, communication, or importation, and to make material 127 | available to the public including in ways that members of the 128 | public may access the material from a place and at a time 129 | individually chosen by them. 130 | 131 | k. Sui Generis Database Rights means rights other than copyright 132 | resulting from Directive 96/9/EC of the European Parliament and of 133 | the Council of 11 March 1996 on the legal protection of databases, 134 | as amended and/or succeeded, as well as other essentially 135 | equivalent rights anywhere in the world. 136 | 137 | l. You means the individual or entity exercising the Licensed Rights 138 | under this Public License. Your has a corresponding meaning. 139 | 140 | Section 2 -- Scope. 141 | 142 | a. License grant. 143 | 144 | 1. Subject to the terms and conditions of this Public License, 145 | the Licensor hereby grants You a worldwide, royalty-free, 146 | non-sublicensable, non-exclusive, irrevocable license to 147 | exercise the Licensed Rights in the Licensed Material to: 148 | 149 | a. reproduce and Share the Licensed Material, in whole or 150 | in part, for NonCommercial purposes only; and 151 | 152 | b. produce, reproduce, and Share Adapted Material for 153 | NonCommercial purposes only. 154 | 155 | 2. Exceptions and Limitations. For the avoidance of doubt, where 156 | Exceptions and Limitations apply to Your use, this Public 157 | License does not apply, and You do not need to comply with 158 | its terms and conditions. 159 | 160 | 3. Term. The term of this Public License is specified in Section 161 | 6(a). 162 | 163 | 4. Media and formats; technical modifications allowed. The 164 | Licensor authorizes You to exercise the Licensed Rights in 165 | all media and formats whether now known or hereafter created, 166 | and to make technical modifications necessary to do so. The 167 | Licensor waives and/or agrees not to assert any right or 168 | authority to forbid You from making technical modifications 169 | necessary to exercise the Licensed Rights, including 170 | technical modifications necessary to circumvent Effective 171 | Technological Measures. For purposes of this Public License, 172 | simply making modifications authorized by this Section 2(a) 173 | (4) never produces Adapted Material. 174 | 175 | 5. Downstream recipients. 176 | 177 | a. Offer from the Licensor -- Licensed Material. Every 178 | recipient of the Licensed Material automatically 179 | receives an offer from the Licensor to exercise the 180 | Licensed Rights under the terms and conditions of this 181 | Public License. 182 | 183 | b. No downstream restrictions. You may not offer or impose 184 | any additional or different terms or conditions on, or 185 | apply any Effective Technological Measures to, the 186 | Licensed Material if doing so restricts exercise of the 187 | Licensed Rights by any recipient of the Licensed 188 | Material. 189 | 190 | 6. No endorsement. Nothing in this Public License constitutes or 191 | may be construed as permission to assert or imply that You 192 | are, or that Your use of the Licensed Material is, connected 193 | with, or sponsored, endorsed, or granted official status by, 194 | the Licensor or others designated to receive attribution as 195 | provided in Section 3(a)(1)(A)(i). 196 | 197 | b. Other rights. 198 | 199 | 1. Moral rights, such as the right of integrity, are not 200 | licensed under this Public License, nor are publicity, 201 | privacy, and/or other similar personality rights; however, to 202 | the extent possible, the Licensor waives and/or agrees not to 203 | assert any such rights held by the Licensor to the limited 204 | extent necessary to allow You to exercise the Licensed 205 | Rights, but not otherwise. 206 | 207 | 2. Patent and trademark rights are not licensed under this 208 | Public License. 209 | 210 | 3. To the extent possible, the Licensor waives any right to 211 | collect royalties from You for the exercise of the Licensed 212 | Rights, whether directly or through a collecting society 213 | under any voluntary or waivable statutory or compulsory 214 | licensing scheme. In all other cases the Licensor expressly 215 | reserves any right to collect such royalties, including when 216 | the Licensed Material is used other than for NonCommercial 217 | purposes. 218 | 219 | Section 3 -- License Conditions. 220 | 221 | Your exercise of the Licensed Rights is expressly made subject to the 222 | following conditions. 223 | 224 | a. Attribution. 225 | 226 | 1. If You Share the Licensed Material (including in modified 227 | form), You must: 228 | 229 | a. retain the following if it is supplied by the Licensor 230 | with the Licensed Material: 231 | 232 | i. identification of the creator(s) of the Licensed 233 | Material and any others designated to receive 234 | attribution, in any reasonable manner requested by 235 | the Licensor (including by pseudonym if 236 | designated); 237 | 238 | ii. a copyright notice; 239 | 240 | iii. a notice that refers to this Public License; 241 | 242 | iv. a notice that refers to the disclaimer of 243 | warranties; 244 | 245 | v. a URI or hyperlink to the Licensed Material to the 246 | extent reasonably practicable; 247 | 248 | b. indicate if You modified the Licensed Material and 249 | retain an indication of any previous modifications; and 250 | 251 | c. indicate the Licensed Material is licensed under this 252 | Public License, and include the text of, or the URI or 253 | hyperlink to, this Public License. 254 | 255 | 2. You may satisfy the conditions in Section 3(a)(1) in any 256 | reasonable manner based on the medium, means, and context in 257 | which You Share the Licensed Material. For example, it may be 258 | reasonable to satisfy the conditions by providing a URI or 259 | hyperlink to a resource that includes the required 260 | information. 261 | 262 | 3. If requested by the Licensor, You must remove any of the 263 | information required by Section 3(a)(1)(A) to the extent 264 | reasonably practicable. 265 | 266 | 4. If You Share Adapted Material You produce, the Adapter's 267 | License You apply must not prevent recipients of the Adapted 268 | Material from complying with this Public License. 269 | 270 | Section 4 -- Sui Generis Database Rights. 271 | 272 | Where the Licensed Rights include Sui Generis Database Rights that 273 | apply to Your use of the Licensed Material: 274 | 275 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 276 | to extract, reuse, reproduce, and Share all or a substantial 277 | portion of the contents of the database for NonCommercial purposes 278 | only; 279 | 280 | b. if You include all or a substantial portion of the database 281 | contents in a database in which You have Sui Generis Database 282 | Rights, then the database in which You have Sui Generis Database 283 | Rights (but not its individual contents) is Adapted Material; and 284 | 285 | c. You must comply with the conditions in Section 3(a) if You Share 286 | all or a substantial portion of the contents of the database. 287 | 288 | For the avoidance of doubt, this Section 4 supplements and does not 289 | replace Your obligations under this Public License where the Licensed 290 | Rights include other Copyright and Similar Rights. 291 | 292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 293 | 294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 304 | 305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 314 | 315 | c. The disclaimer of warranties and limitation of liability provided 316 | above shall be interpreted in a manner that, to the extent 317 | possible, most closely approximates an absolute disclaimer and 318 | waiver of all liability. 319 | 320 | Section 6 -- Term and Termination. 321 | 322 | a. This Public License applies for the term of the Copyright and 323 | Similar Rights licensed here. However, if You fail to comply with 324 | this Public License, then Your rights under this Public License 325 | terminate automatically. 326 | 327 | b. Where Your right to use the Licensed Material has terminated under 328 | Section 6(a), it reinstates: 329 | 330 | 1. automatically as of the date the violation is cured, provided 331 | it is cured within 30 days of Your discovery of the 332 | violation; or 333 | 334 | 2. upon express reinstatement by the Licensor. 335 | 336 | For the avoidance of doubt, this Section 6(b) does not affect any 337 | right the Licensor may have to seek remedies for Your violations 338 | of this Public License. 339 | 340 | c. For the avoidance of doubt, the Licensor may also offer the 341 | Licensed Material under separate terms or conditions or stop 342 | distributing the Licensed Material at any time; however, doing so 343 | will not terminate this Public License. 344 | 345 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 346 | License. 347 | 348 | Section 7 -- Other Terms and Conditions. 349 | 350 | a. The Licensor shall not be bound by any additional or different 351 | terms or conditions communicated by You unless expressly agreed. 352 | 353 | b. Any arrangements, understandings, or agreements regarding the 354 | Licensed Material not stated herein are separate from and 355 | independent of the terms and conditions of this Public License. 356 | 357 | Section 8 -- Interpretation. 358 | 359 | a. For the avoidance of doubt, this Public License does not, and 360 | shall not be interpreted to, reduce, limit, restrict, or impose 361 | conditions on any use of the Licensed Material that could lawfully 362 | be made without permission under this Public License. 363 | 364 | b. To the extent possible, if any provision of this Public License is 365 | deemed unenforceable, it shall be automatically reformed to the 366 | minimum extent necessary to make it enforceable. If the provision 367 | cannot be reformed, it shall be severed from this Public License 368 | without affecting the enforceability of the remaining terms and 369 | conditions. 370 | 371 | c. No term or condition of this Public License will be waived and no 372 | failure to comply consented to unless expressly agreed to by the 373 | Licensor. 374 | 375 | d. Nothing in this Public License constitutes or may be interpreted 376 | as a limitation upon, or waiver of, any privileges and immunities 377 | that apply to the Licensor or You, including from the legal 378 | processes of any jurisdiction or authority. 379 | 380 | ======================================================================= 381 | 382 | Creative Commons is not a party to its public 383 | licenses. Notwithstanding, Creative Commons may elect to apply one of 384 | its public licenses to material it publishes and in those instances 385 | will be considered the “Licensor.” The text of the Creative Commons 386 | public licenses is dedicated to the public domain under the CC0 Public 387 | Domain Dedication. Except for the limited purpose of indicating that 388 | material is shared under a Creative Commons public license or as 389 | otherwise permitted by the Creative Commons policies published at 390 | creativecommons.org/policies, Creative Commons does not authorize the 391 | use of the trademark "Creative Commons" or any other trademark or logo 392 | of Creative Commons without its prior written consent including, 393 | without limitation, in connection with any unauthorized modifications 394 | to any of its public licenses or any other arrangements, 395 | understandings, or agreements concerning use of licensed material. For 396 | the avoidance of doubt, this paragraph does not form part of the 397 | public licenses. 398 | 399 | Creative Commons may be contacted at creativecommons.org. 400 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EmpatheticDialogues 2 | 3 | PyTorch original implementation of Towards Empathetic Open-domain Conversation Models: a New Benchmark and Dataset (https://arxiv.org/abs/1811.00207). 4 | 5 | We provide a novel dataset of 25k conversations grounded in emotional situations. The code in this repo demonstrates that automated metrics (P@1,100 and BLEU) are improved both when using candidates from our dataset and when fine-tuning on it. 6 | 7 | This repo contains code for: 8 | - Transformer-based retrieval (pretraining, fine-tuning) 9 | - BERT-based retrieval (pretraining, fine-tuning) 10 | - Prepending classifier labels (e.g. EmoPrepend-1) 11 | 12 | ## Dataset 13 | 14 | To download the EmpatheticDialogues dataset: 15 | 16 | ``` 17 | wget https://dl.fbaipublicfiles.com/parlai/empatheticdialogues/empatheticdialogues.tar.gz 18 | ``` 19 | 20 | ## Models 21 | 22 | To reproduce paper numbers, see the evaluation commands in the Commands section, and use the following trained models: 23 | 24 | ``` 25 | wget https://dl.fbaipublicfiles.com/parlai/empatheticdialogues/models/normal_transformer_pretrained.mdl # Normal Transformer, pretrained 26 | wget https://dl.fbaipublicfiles.com/parlai/empatheticdialogues/models/normal_transformer_finetuned.mdl # Normal Transformer, fine-tuned 27 | wget https://dl.fbaipublicfiles.com/parlai/empatheticdialogues/models/bert_pretrained.mdl # BERT, pretrained 28 | wget https://dl.fbaipublicfiles.com/parlai/empatheticdialogues/models/bert_finetuned.mdl # BERT, fine-tuned 29 | wget https://dl.fbaipublicfiles.com/parlai/empatheticdialogues/models/bert_finetuned_emoprepend1.mdl # BERT, fine-tuned (EmoPrepend-1) 30 | wget https://dl.fbaipublicfiles.com/parlai/empatheticdialogues/models/fasttext_empathetic_dialogues.mdl # fastText classifier used for EmoPrepend-1 31 | ``` 32 | 33 | ## Dependencies 34 | 35 | Versions given are what the code has been tested on. 36 | 37 | ### Required 38 | - [numpy](https://www.numpy.org/) (1.14.3) 39 | - [PyTorch](https://pytorch.org/) (1.0.1.post2) 40 | - [tqdm](https://tqdm.github.io/) (4.19.7) 41 | 42 | ### Optional 43 | - [fairseq](https://fairseq.readthedocs.io/en/latest/) (0.6.2; for BLEU calculation in `retrieval_eval_bleu.py`) 44 | - [fastText](https://fasttext.cc/) (0.9.1; for Prepend models) 45 | - [pandas](https://pandas.pydata.org/) (0.22.0; for DailyDialog dataset) 46 | - [ParlAI](https://parl.ai/) ([commit used](https://github.com/facebookresearch/ParlAI/commit/471db18c47d322d814f4e1bba6e35d9da6ac31ff); for BERT model) 47 | - [pytorch-pretrained-BERT](https://github.com/huggingface/pytorch-pretrained-BERT) (0.5.1; for BERT model) 48 | 49 | ## Commands 50 | 51 | ### Transformer-based retrieval 52 | 53 | #### Pretraining 54 | ``` 55 | python retrieval_train.py \ 56 | --batch-size 512 \ 57 | --cuda \ 58 | --dataset-name reddit \ 59 | --dict-max-words 250000 \ 60 | --display-iter 250 \ 61 | --embeddings ${REDDIT_EMBEDDINGS_PATH} \ 62 | --empchat-folder ${EMPATHETIC_DIALOGUES_DATA_FOLDER} \ 63 | --learn-embeddings \ 64 | --learning-rate 8e-4 \ 65 | --model transformer \ 66 | --model-dir ${TRAIN_SAVE_FOLDER} \ 67 | --model-name model \ 68 | --n-layers 4 \ 69 | --num-epochs 10000 \ 70 | --optimizer adamax \ 71 | --reddit-folder ${REDDIT_DATA_FOLDER} \ 72 | --transformer-dim 300 \ 73 | --transformer-n-heads 6 74 | ``` 75 | 76 | #### Fine-tuning 77 | ``` 78 | python retrieval_train.py \ 79 | --batch-size 512 \ 80 | --cuda \ 81 | --dataset-name empchat \ 82 | --dict-max-words 250000 \ 83 | --display-iter 250 \ 84 | --empchat-folder ${EMPATHETIC_DIALOGUES_DATA_FOLDER} \ 85 | --learn-embeddings \ 86 | --learning-rate 8e-4 \ 87 | --load-checkpoint ${PRETRAINED_MODEL_PATH} \ 88 | --max-hist-len 4 \ 89 | --model transformer \ 90 | --model-dir ${TRAIN_SAVE_FOLDER} \ 91 | --model-name model \ 92 | --n-layers 4 \ 93 | --num-epochs 10 \ 94 | --optimizer adamax \ 95 | --reddit-folder ${REDDIT_DATA_FOLDER} \ 96 | --transformer-dim 300 \ 97 | --transformer-n-heads 6 98 | ``` 99 | 100 | #### Evaluation 101 | ``` 102 | # P@1,100 103 | python retrieval_train.py \ 104 | --batch-size 512 \ 105 | --cuda \ 106 | --dataset-name empchat \ 107 | --dict-max-words 250000 \ 108 | --display-iter 250 \ 109 | --empchat-folder ${EMPATHETIC_DIALOGUES_DATA_FOLDER} \ 110 | --max-hist-len 4 \ 111 | --model transformer \ 112 | --model-dir ${EVAL_SAVE_FOLDER} \ 113 | --model-name model \ 114 | --n-layers 4 \ 115 | --optimizer adamax \ 116 | --pretrained ${TRAIN_SAVE_FOLDER}/model.mdl \ 117 | --reactonly \ 118 | --transformer-dim 300 \ 119 | --transformer-n-heads 6 120 | 121 | # BLEU (EmpatheticDialogues context/candidates) 122 | python retrieval_eval_bleu.py \ 123 | --empchat-cands \ 124 | --empchat-folder ${EMPATHETIC_DIALOGUES_DATA_FOLDER} \ 125 | --max-hist-len 4 \ 126 | --model ${TRAIN_SAVE_FOLDER}/model.mdl \ 127 | --name model \ 128 | --output-folder ${EVAL_SAVE_FOLDER} \ 129 | --reactonly \ 130 | --task empchat 131 | ``` 132 | 133 | ### BERT-based retrieval 134 | 135 | #### Pretraining 136 | ``` 137 | python retrieval_train.py \ 138 | --batch-size 256 \ 139 | --bert-dim 300 \ 140 | --cuda \ 141 | --dataset-name reddit \ 142 | --dict-max-words 250000 \ 143 | --display-iter 100 \ 144 | --embeddings None \ 145 | --empchat-folder ${EMPATHETIC_DIALOGUES_DATA_FOLDER} \ 146 | --learning-rate 6e-5 \ 147 | --model bert \ 148 | --model-dir ${TRAIN_SAVE_FOLDER} \ 149 | --model-name model \ 150 | --num-epochs 10000 \ 151 | --optimizer adamax \ 152 | --reddit-folder ${BERT_TOKENIZED_REDDIT_DATA_FOLDER} 153 | ``` 154 | 155 | #### Fine-tuning 156 | ``` 157 | python retrieval_train.py \ 158 | --batch-size 256 \ 159 | --bert-dim 300 \ 160 | --cuda \ 161 | --dataset-name empchat \ 162 | --dict-max-words 250000 \ 163 | --display-iter 100 \ 164 | --embeddings None \ 165 | --empchat-folder ${EMPATHETIC_DIALOGUES_DATA_FOLDER} \ 166 | --learning-rate 1e-5 \ 167 | --load-checkpoint ${PRETRAINED_MODEL_PATH} \ 168 | --max-hist-len 4 \ 169 | --model bert \ 170 | --model-dir ${TRAIN_SAVE_FOLDER} \ 171 | --model-name model \ 172 | --num-epochs 100 \ 173 | --optimizer adamax \ 174 | --stop-crit-num-epochs 10 175 | ``` 176 | 177 | #### Evaluation 178 | ``` 179 | # P@1,100 180 | python retrieval_train.py \ 181 | --batch-size 256 \ 182 | --bert-dim 300 \ 183 | --cuda \ 184 | --dataset-name empchat \ 185 | --dict-max-words 250000 \ 186 | --display-iter 100 \ 187 | --embeddings None \ 188 | --empchat-folder ${EMPATHETIC_DIALOGUES_DATA_FOLDER} \ 189 | --max-hist-len 4 \ 190 | --model bert \ 191 | --model-dir ${EVAL_SAVE_FOLDER} \ 192 | --model-name model \ 193 | --optimizer adamax \ 194 | --pretrained ${TRAIN_SAVE_FOLDER}/model.mdl \ 195 | --reactonly 196 | 197 | # BLEU (EmpatheticDialogues context/candidates) 198 | python retrieval_eval_bleu.py \ 199 | --bleu-dict ${PATH_TO_MODEL_WITH_TRANSFORMER_DICT} \ 200 | --empchat-cands \ 201 | --empchat-folder ${EMPATHETIC_DIALOGUES_DATA_FOLDER} \ 202 | --max-hist-len 4 \ 203 | --model ${TRAIN_SAVE_FOLDER}/model.mdl \ 204 | --name model \ 205 | --output-folder ${EVAL_SAVE_FOLDER} \ 206 | --reactonly \ 207 | --task empchat 208 | ``` 209 | 210 | Note: we pass in a separate dictionary (`--bleu-dict`) in order to use the same tokenization when calculating the BLEU of both Transformer and BERT models. For this, you can use the pretrained normal Transformer model listed in the Models section above. 211 | 212 | #### EmoPrepend-1 213 | 214 | Add the following flags when calling `retrieval_train.py` or `retrieval_eval_bleu.py`: 215 | ``` 216 | --fasttext 1 \ 217 | --fasttext-path ${PATH_TO_TRAINED_FASTTEXT_MODEL} \ 218 | --fasttext-type emo 219 | ``` 220 | For `${PATH_TO_TRAINED_FASTTEXT_MODEL}`, you can pass in the fastText classifier in the Models section above. 221 | 222 | ## References 223 | 224 | Please cite [[1]](https://arxiv.org/abs/1811.00207) if you found the resources in this repository useful. 225 | 226 | ### Towards Empathetic Open-domain Conversation Models: a New Benchmark and Dataset 227 | 228 | [1] H. Rashkin, E. M. Smith, M. Li, Y. Boureau [*Towards Empathetic Open-domain Conversation Models: a New Benchmark and Dataset*](https://arxiv.org/abs/1811.00207) 229 | 230 | ``` 231 | @inproceedings{rashkin2019towards, 232 | title = {Towards Empathetic Open-domain Conversation Models: a New Benchmark and Dataset}, 233 | author = {Hannah Rashkin and Eric Michael Smith and Margaret Li and Y-Lan Boureau}, 234 | booktitle = {ACL}, 235 | year = {2019}, 236 | } 237 | ``` 238 | 239 | ## License 240 | 241 | See the LICENSE file in the root repo folder for more details. 242 | -------------------------------------------------------------------------------- /empchat/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | -------------------------------------------------------------------------------- /empchat/bert_local.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import torch 9 | import torch.nn as nn 10 | 11 | from empchat.datasets.tokens import ( 12 | BERT_ID, 13 | EMPTYPERSONA_TOKEN, 14 | PAD_TOKEN, 15 | PARLAI_PAD_TOKEN, 16 | START_OF_COMMENT, 17 | ) 18 | 19 | 20 | class BertAdapter(nn.Module): 21 | def __init__(self, opt, dictionary): 22 | from parlai.agents.bert_ranker.helpers import BertWrapper 23 | 24 | try: 25 | from pytorch_pretrained_bert import BertModel 26 | except ImportError: 27 | raise Exception( 28 | "BERT rankers needs pytorch-pretrained-BERT installed. " 29 | "\npip install pytorch-pretrained-bert" 30 | ) 31 | super().__init__() 32 | self.opt = opt 33 | self.pad_idx = dictionary[PAD_TOKEN] 34 | self.ctx_bert = BertWrapper( 35 | bert_model=BertModel.from_pretrained(BERT_ID), 36 | output_dim=opt.bert_dim, 37 | add_transformer_layer=opt.bert_add_transformer_layer, 38 | ) 39 | self.cand_bert = BertWrapper( 40 | bert_model=BertModel.from_pretrained(BERT_ID), 41 | output_dim=opt.bert_dim, 42 | add_transformer_layer=opt.bert_add_transformer_layer, 43 | ) 44 | 45 | # Reset the embeddings for the until-now unused BERT tokens 46 | orig_embedding_weights = BertModel.from_pretrained( 47 | BERT_ID 48 | ).embeddings.word_embeddings.weight 49 | mean_val = orig_embedding_weights.mean().item() 50 | std_val = orig_embedding_weights.std().item() 51 | unused_tokens = [START_OF_COMMENT, PARLAI_PAD_TOKEN, EMPTYPERSONA_TOKEN] 52 | unused_token_idxes = [dictionary[token] for token in unused_tokens] 53 | for token_idx in unused_token_idxes: 54 | rand_embedding = orig_embedding_weights.new_empty( 55 | (1, orig_embedding_weights.size(1)) 56 | ).normal_(mean=mean_val, std=std_val) 57 | for embeddings in [ 58 | self.ctx_bert.bert_model.embeddings.word_embeddings, 59 | self.cand_bert.bert_model.embeddings.word_embeddings, 60 | ]: 61 | embeddings.weight[token_idx] = rand_embedding 62 | self.ctx_bert.bert_model.embeddings.word_embeddings.weight.detach_() 63 | self.cand_bert.bert_model.embeddings.word_embeddings.weight.detach_() 64 | 65 | def forward(self, context_w, cands_w): 66 | if context_w is not None: 67 | context_segments = torch.zeros_like(context_w) 68 | context_mask = context_w != self.pad_idx 69 | context_h = self.ctx_bert( 70 | token_ids=context_w, 71 | segment_ids=context_segments, 72 | attention_mask=context_mask, 73 | ) 74 | if self.opt.normalize_sent_emb: 75 | context_h = context_h / context_h.norm(2, dim=1, keepdim=True) 76 | else: 77 | context_h = None 78 | if cands_w is not None: 79 | cands_segments = torch.zeros_like(cands_w) 80 | cands_mask = cands_w != self.pad_idx 81 | cands_h = self.cand_bert( 82 | token_ids=cands_w, segment_ids=cands_segments, attention_mask=cands_mask 83 | ) 84 | if self.opt.normalize_sent_emb: 85 | cands_h = cands_h / cands_h.norm(2, dim=1, keepdim=True) 86 | else: 87 | cands_h = None 88 | return context_h, cands_h 89 | -------------------------------------------------------------------------------- /empchat/datasets/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | -------------------------------------------------------------------------------- /empchat/datasets/dailydialog.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import os 9 | import os.path 10 | 11 | import numpy as np 12 | import pandas as pd 13 | import torch 14 | from torch.utils.data import Dataset 15 | 16 | 17 | def getmode(array, removenone=False): 18 | counts = dict() 19 | for a in array: 20 | if not removenone or a.lower() != "none": 21 | counts[a] = counts.get(a, 0) + 1.0 22 | if len(counts) == 0: 23 | return [] 24 | max_c = max(counts.values()) 25 | modes = [] 26 | for a in counts: 27 | if counts[a] == max_c: 28 | modes.append(a) 29 | return modes 30 | 31 | 32 | def multifeel_to_one(emo_context): 33 | maxemo = getmode(emo_context, removenone=True) 34 | if len(maxemo) > 1: 35 | np.random.shuffle(maxemo) 36 | return maxemo[0] 37 | elif len(maxemo) < 1: 38 | return "none" 39 | else: 40 | return maxemo[0] 41 | 42 | 43 | def sentence_to_tensor(dic, sentence): 44 | """ 45 | simply convert a sentence to a torch tensor. 46 | """ 47 | indexes = dic.txt2vec(sentence) 48 | return torch.LongTensor(indexes) 49 | 50 | 51 | class DDDataset(Dataset): 52 | def __init__(self, splitname, dic, data_folder, maxlen=100, history_len=1): 53 | df = self.read_dailydialog_data(data_folder, splitname) 54 | self.max_hist_len = history_len 55 | self.data = [] 56 | for i in range(df.shape[0]): 57 | row = df.iloc[i] 58 | sent = row["line"] 59 | history = row["context"] 60 | if len(history) == 0: 61 | continue 62 | prev_str = " ".join(history[-self.max_hist_len :]) 63 | contextt = sentence_to_tensor(dic, prev_str)[:maxlen] 64 | label = sentence_to_tensor(dic, sent)[:maxlen] 65 | self.data.append((contextt, label)) 66 | 67 | def __len__(self): 68 | return len(self.data) 69 | 70 | def __getitem__(self, index): 71 | return self.data[index] 72 | 73 | @staticmethod 74 | def read_dailydialog_data(floc, traindevtest): 75 | emolookup = { 76 | 0: "none", 77 | 1: "anger", 78 | 2: "disgust", 79 | 3: "fear", 80 | 4: "happiness", 81 | 5: "sadness", 82 | 6: "surprise", 83 | } 84 | split_name = {"train": "train", "valid": "validation", "test": "test"}[ 85 | traindevtest 86 | ] 87 | conversations = open( 88 | os.path.join(floc, split_name, "dialogues_" + split_name + ".txt") 89 | ).readlines() 90 | totemot = open( 91 | os.path.join(floc, split_name, "dialogues_emotion_" + split_name + ".txt") 92 | ).readlines() 93 | datarows = [] 94 | for i in range(len(conversations)): 95 | lines = conversations[i].strip().split("__eou__") 96 | emotions = totemot[i].strip().split(" ") 97 | prev_context = [] 98 | prev_emot_context = [] 99 | if len(lines) - 1 != len(emotions): 100 | print("error") 101 | for j in range(len(lines) - 1): 102 | item = [ 103 | i, 104 | prev_context.copy(), 105 | multifeel_to_one(prev_emot_context.copy()), 106 | lines[j], 107 | emolookup[int(emotions[j])], 108 | ] 109 | datarows.append(item) 110 | prev_context.append(lines[j]) 111 | prev_emot_context.append(emolookup[int(emotions[j])]) 112 | return pd.DataFrame( 113 | datarows, columns=["convid", "context", "emo", "line", "nextemo"] 114 | ) 115 | -------------------------------------------------------------------------------- /empchat/datasets/empchat.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import os 9 | import re 10 | 11 | import torch 12 | from torch.utils.data import Dataset 13 | 14 | from empchat.datasets.parlai_dictionary import ParlAIDictionary 15 | from empchat.datasets.tokens import get_bert_token_mapping, tokenize 16 | 17 | 18 | def txt2vec(dic, text, fasttext_type=None): 19 | if hasattr(dic, "bert_tokenizer"): 20 | orig_mapping = get_bert_token_mapping(fasttext_type) 21 | mapping = dict((re.escape(k), v) for k, v in orig_mapping.items()) 22 | pattern = re.compile("|".join(mapping.keys())) 23 | cleaned_text = pattern.sub(lambda m: mapping[re.escape(m.group(0))], text) 24 | tokenized_text = dic.bert_tokenizer.tokenize(cleaned_text) 25 | return dic.bert_tokenizer.convert_tokens_to_ids(tokenized_text) 26 | elif type(dic) is ParlAIDictionary: 27 | return dic.txt2vec(text) 28 | else: 29 | return [dic.index(token) for token in tokenize(text)] 30 | 31 | 32 | def sentence_to_tensor(dic, sentence, maxlen=None, fasttext_type=None): 33 | """ 34 | simply convert a sentence to a torch tensor. 35 | """ 36 | indexes = txt2vec(dic, sentence, fasttext_type) 37 | if maxlen is not None and maxlen <= len(indexes): 38 | indexes = indexes[: maxlen - 1] 39 | if type(dic) is ParlAIDictionary: 40 | return torch.LongTensor(indexes) 41 | else: 42 | indexes.append(dic.eos()) 43 | return torch.LongTensor(indexes) 44 | 45 | 46 | class EmpDataset(Dataset): 47 | def __init__( 48 | self, 49 | splitname, 50 | dic, 51 | data_folder, 52 | maxlen=100, 53 | history_len=1, 54 | reactonly=False, 55 | fasttext=None, 56 | fasttext_type=None, 57 | fasttext_path=None, 58 | ): 59 | topicmap = { 60 | "alt.atheism": "atheism", 61 | "comp.graphics": "graphics", 62 | "comp.os.ms-windows.misc": "windows", 63 | "comp.sys.ibm.pc.hardware": "pc", 64 | "comp.sys.mac.hardware": "mac", 65 | "comp.windows.x": "x", 66 | "misc.forsale": "sale", 67 | "rec.autos": "autos", 68 | "rec.motorcycles": "motorcycles", 69 | "rec.sport.baseball": "baseball", 70 | "rec.sport.hockey": "hockey", 71 | "sci.crypt": "cryptography", 72 | "sci.electronics": "electronics", 73 | "sci.med": "medicine", 74 | "sci.space": "space", 75 | "soc.religion.christian": "christian", 76 | "talk.politics.guns": "guns", 77 | "talk.politics.mideast": "mideast", 78 | "talk.politics.misc": "politics", 79 | "talk.religion.misc": "religion", 80 | "windows.misc": "windows", 81 | } 82 | # ^ 'windows.misc' was included for compatibility because the code below 83 | # splits topics on hyphens 84 | df = open(os.path.join(data_folder, f"{splitname}.csv")).readlines() 85 | newmaxlen = maxlen 86 | self.max_hist_len = history_len 87 | if fasttext is not None: 88 | import fasttext as fasttext_module 89 | 90 | assert fasttext_type is not None and fasttext_path is not None 91 | self.ftmodel = fasttext_module.FastText.load_model(fasttext_path) 92 | newmaxlen += fasttext 93 | maxlen += fasttext 94 | if hasattr(dic, "bert_tokenizer"): 95 | try: 96 | from pytorch_pretrained_bert import BertTokenizer 97 | except ImportError: 98 | raise Exception( 99 | "BERT rankers needs pytorch-pretrained-BERT installed. " 100 | "\npip install pytorch-pretrained-bert" 101 | ) 102 | # Replace the tokenizer with a new one that won't split any of 103 | # the fastText labels 104 | new_tokenizer = BertTokenizer.from_pretrained( 105 | "bert-base-cased", 106 | do_lower_case=False, 107 | never_split=( 108 | ["[CLS]", "[MASK]"] 109 | + list(get_bert_token_mapping(fasttext_type).values()) 110 | ), 111 | ) 112 | assert new_tokenizer.vocab.keys() == dic.bert_tokenizer.vocab.keys() 113 | # ^ This should fail if the original tokenizer was not from the 114 | # 'bert-base-cased' model 115 | dic.bert_tokenizer = new_tokenizer 116 | self.reactonly = reactonly 117 | self.data = [] 118 | self.ids = [] 119 | history = [] 120 | for i in range(1, len(df)): 121 | cparts = df[i - 1].strip().split(",") 122 | sparts = df[i].strip().split(",") 123 | if cparts[0] == sparts[0]: 124 | prevsent = cparts[5].replace("_comma_", ",") 125 | history.append(prevsent) 126 | idx = int(sparts[1]) 127 | if not self.reactonly or ((idx % 2) == 0): 128 | prev_str = " ".join(history[-self.max_hist_len :]) 129 | if fasttext is not None: 130 | gettop, _ = self.ftmodel.predict( 131 | " ".join(history[-self.max_hist_len :]), k=fasttext 132 | ) 133 | for f in gettop: 134 | prev_str = ( 135 | topicmap.get( 136 | f.split("_")[-1].split("-")[-1], 137 | f.split("_")[-1].split("-")[-1], 138 | ) 139 | + " " 140 | + prev_str 141 | ) 142 | contextt = sentence_to_tensor( 143 | dic, prev_str, fasttext_type=fasttext_type 144 | )[:newmaxlen] 145 | sent = sparts[5].replace("_comma_", ",") 146 | if fasttext is not None: 147 | gettop, _ = self.ftmodel.predict(sent, k=fasttext) 148 | for f in gettop: 149 | sent = ( 150 | topicmap.get( 151 | f.split("_")[-1].split("-")[-1], 152 | f.split("_")[-1].split("-")[-1], 153 | ) 154 | + " " 155 | + sent 156 | ) 157 | label = sentence_to_tensor(dic, sent, fasttext_type=fasttext_type)[ 158 | :maxlen 159 | ] 160 | lbl_min = torch.LongTensor([[dic[sparts[2]]]]) 161 | self.data.append((contextt, label, lbl_min)) 162 | self.ids.append((sparts[0], sparts[1])) 163 | else: 164 | history = [] 165 | 166 | def __len__(self): 167 | return len(self.data) 168 | 169 | def __getitem__(self, index): 170 | return self.data[index] 171 | 172 | def getid(self, index): 173 | return self.ids[index] 174 | -------------------------------------------------------------------------------- /empchat/datasets/loader.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import logging 9 | import os 10 | import os.path 11 | 12 | import torch 13 | from torch.utils.data import DataLoader 14 | 15 | from empchat.datasets.empchat import EmpDataset 16 | from empchat.datasets.dailydialog import DDDataset 17 | from empchat.datasets.reddit import RedditDataset 18 | from empchat.datasets.parlai_dictionary import ParlAIDictionary 19 | from empchat.datasets.tokens import ( 20 | get_bert_token_mapping, 21 | BERT_ID, 22 | EMPTYPERSONA_TOKEN, 23 | END_OF_COMMENT, 24 | PAD_TOKEN, 25 | PARLAI_PAD_TOKEN, 26 | START_OF_COMMENT, 27 | UNK_TOKEN, 28 | ) 29 | 30 | 31 | def build_dictionary(opt): 32 | if opt.model == "bert": 33 | return build_bert_dictionary(opt) 34 | else: 35 | dict_ = torch.load(os.path.join(opt.reddit_folder, "word_dictionary")) 36 | dict_["iwords"] = dict_["iwords"][: opt.dict_max_words] 37 | dict_["iwords"].append(UNK_TOKEN) 38 | dict_["iwords"].append(PAD_TOKEN) 39 | dict_["iwords"].append(PARLAI_PAD_TOKEN) 40 | # Workaround for external ParlAI token 41 | dict_["iwords"].append(EMPTYPERSONA_TOKEN) 42 | dict_["iwords"].append(START_OF_COMMENT) 43 | dict_["iwords"].append(END_OF_COMMENT) 44 | dict_["words"] = {w: i for i, w in enumerate(dict_["iwords"])} 45 | return dict_ 46 | 47 | 48 | def build_bert_dictionary(opt): 49 | try: 50 | from pytorch_pretrained_bert import BertTokenizer 51 | except ImportError: 52 | raise Exception( 53 | "BERT rankers needs pytorch-pretrained-BERT installed. " 54 | "\npip install pytorch-pretrained-bert" 55 | ) 56 | if BERT_ID != "bert-base-cased" and opt.dataset_name == "reddit": 57 | raise NotImplementedError( 58 | "Currently, only bert-base-cased can be used with reddit!" 59 | ) 60 | if BERT_ID != "bert-base-cased" and opt.fasttext_type is not None: 61 | raise NotImplementedError( 62 | 'Currently, "bert-base-cased" is the only BERT model for which we ' 63 | "have defined lists of fastText labels without BERT tokens!" 64 | ) 65 | is_cased = BERT_ID.split("-")[2] == "cased" 66 | tokenizer = BertTokenizer.from_pretrained( 67 | BERT_ID, 68 | do_lower_case=not is_cased, 69 | never_split=( 70 | ["[CLS]", "[MASK]"] 71 | + list(get_bert_token_mapping(opt.fasttext_type).values()) 72 | ), 73 | ) 74 | dict_ = dict() 75 | 76 | # Create dictionary from HuggingFace version. Note that the special tokens 77 | # have been replicated from build_dictionary() above, and I have used the 78 | # BERT token equivalence mapping suggested by ParlAI's 79 | # parlai/agents/bert_ranker/bert_dictionary.py, except for START_OF_COMMENT, 80 | # which I am setting to a token that hasn't been used before. 81 | if opt.dict_max_words is not None: 82 | logging.warning( 83 | "--dict-max-words will be ignored because we are using the BERT " 84 | "tokenizer." 85 | ) 86 | dict_["iwords"] = list(tokenizer.vocab.keys()) 87 | for orig_token, bert_token in get_bert_token_mapping(opt.fasttext_type).items(): 88 | dict_["iwords"][tokenizer.convert_tokens_to_ids([bert_token])[0]] = orig_token 89 | dict_["words"] = {w: i for i, w in enumerate(dict_["iwords"])} 90 | dict_["wordcounts"] = None # Not used here 91 | dict_["bert_tokenizer"] = tokenizer 92 | 93 | return dict_ 94 | 95 | 96 | class TrainEnvironment: 97 | def __init__(self, opt, dictionary=None): 98 | self.opt = opt 99 | self.dataset_name = opt.dataset_name 100 | if self.dataset_name in ["dailydialog", "empchat"]: 101 | if dictionary is not None: 102 | self.temp_dict = ParlAIDictionary.create_from_reddit_style(dictionary) 103 | else: 104 | self.dict = build_dictionary(opt) 105 | if EMPTYPERSONA_TOKEN not in self.dict["words"]: 106 | self.dict["iwords"].append(EMPTYPERSONA_TOKEN) 107 | self.dict["words"] = { 108 | w: i for i, w in enumerate(self.dict["iwords"]) 109 | } 110 | self.temp_dict = ParlAIDictionary.create_from_reddit_style(self.dict) 111 | self.dict = dictionary or self.temp_dict.as_reddit_style_dict() 112 | elif self.dataset_name == "reddit": 113 | self.dict = dictionary or build_dictionary(opt) 114 | if EMPTYPERSONA_TOKEN not in self.dict["words"]: 115 | self.dict["iwords"].append(EMPTYPERSONA_TOKEN) 116 | self.dict["words"] = {w: i for i, w in enumerate(self.dict["iwords"])} 117 | else: 118 | raise ValueError("Dataset name unrecognized!") 119 | self.pad_idx = self.dict["words"][PAD_TOKEN] 120 | 121 | def build_reddit_dataset(self, chunk_id): 122 | return RedditDataset( 123 | self.opt.reddit_folder, 124 | chunk_id, 125 | self.dict, 126 | max_len=self.opt.max_sent_len, 127 | rm_long_sent=self.opt.rm_long_sent, 128 | max_hist_len=self.opt.max_hist_len, 129 | rm_long_contexts=self.opt.rm_long_contexts, 130 | ) 131 | 132 | def build_train_dataloader(self, epoch_id): 133 | if self.dataset_name == "empchat": 134 | dataset = EmpDataset( 135 | "train", 136 | self.temp_dict, 137 | data_folder=self.opt.empchat_folder, 138 | maxlen=self.opt.max_sent_len, 139 | reactonly=self.opt.reactonly, 140 | history_len=self.opt.max_hist_len, 141 | fasttext=self.opt.fasttext, 142 | fasttext_type=self.opt.fasttext_type, 143 | fasttext_path=self.opt.fasttext_path, 144 | ) 145 | return DataLoader( 146 | dataset, 147 | batch_size=self.opt.batch_size, 148 | shuffle=not self.opt.no_shuffle, 149 | num_workers=0, 150 | collate_fn=self.batchify, 151 | pin_memory=self.opt.cuda, 152 | ) 153 | elif self.dataset_name == "reddit": 154 | dataset = self.build_reddit_dataset(epoch_id % 999) 155 | return DataLoader( 156 | dataset, 157 | batch_size=self.opt.batch_size, 158 | shuffle=not self.opt.no_shuffle, 159 | num_workers=8, 160 | collate_fn=self.batchify, 161 | pin_memory=self.opt.cuda, 162 | ) 163 | else: 164 | raise ValueError("Dataset name unrecognized!") 165 | 166 | def build_valid_dataloader(self, shuffle=True, test=False): 167 | if self.dataset_name == "dailydialog": 168 | splitname = "valid" if not test else "test" 169 | dataset = DDDataset( 170 | splitname=splitname, 171 | dic=self.temp_dict, 172 | data_folder=self.opt.dailydialog_folder, 173 | maxlen=self.opt.max_sent_len, 174 | history_len=self.opt.max_hist_len, 175 | ) 176 | elif self.dataset_name == "empchat": 177 | splitname = "valid" if not test else "test" 178 | dataset = EmpDataset( 179 | splitname, 180 | self.temp_dict, 181 | data_folder=self.opt.empchat_folder, 182 | maxlen=self.opt.max_sent_len, 183 | reactonly=self.opt.reactonly, 184 | history_len=self.opt.max_hist_len, 185 | fasttext=self.opt.fasttext, 186 | fasttext_type=self.opt.fasttext_type, 187 | fasttext_path=self.opt.fasttext_path, 188 | ) 189 | elif self.dataset_name == "reddit": 190 | dataset = self.build_reddit_dataset(999) 191 | else: 192 | raise ValueError("Dataset name unrecognized!") 193 | return DataLoader( 194 | dataset, 195 | batch_size=self.opt.batch_size, 196 | collate_fn=self.batchify, 197 | num_workers=0, 198 | shuffle=shuffle, 199 | pin_memory=self.opt.cuda, 200 | ) 201 | 202 | def batchify(self, batch): 203 | input_list = list(zip(*batch)) 204 | contexts, next_ = [ 205 | pad(ex, self.pad_idx) for ex in [input_list[0], input_list[1]] 206 | ] 207 | return contexts, next_ 208 | 209 | def to_words(self, tensor): 210 | return " ".join(self.dict["iwords"][x] for x in tensor.tolist()) 211 | 212 | 213 | def pad(tensors, padding_value=-1): 214 | """ 215 | Concatenate and pad the input tensors, which may be 1D or 2D. 216 | """ 217 | max_len = max(t.size(-1) for t in tensors) 218 | if tensors[0].dim() == 1: 219 | out = torch.LongTensor(len(tensors), max_len).fill_(padding_value) 220 | for i, t in enumerate(tensors): 221 | out[i, : t.size(0)] = t 222 | return out 223 | elif tensors[0].dim() == 2: 224 | max_width = max(t.size(0) for t in tensors) 225 | out = torch.LongTensor(len(tensors), max_width, max_len).fill_(padding_value) 226 | for i, t in enumerate(tensors): 227 | out[i, : t.size(0), : t.size(1)] = t 228 | return out 229 | else: 230 | raise ValueError("Input tensors must be either 1D or 2D!") 231 | -------------------------------------------------------------------------------- /empchat/datasets/parlai_dictionary.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | # I don't really want to import all of ParlAI for just a dictionary 9 | # This very simple dictionary mimics what the one of ParlAI does, 10 | # without the long chain of dependency. 11 | # Thanks to the fact that python is not typed whatsoever, this should work 12 | 13 | from empchat.datasets.tokens import tokenize 14 | 15 | 16 | class ParlAIDictionary: 17 | def __init__(self, file_path=None): 18 | """ 19 | Initializes the dictionary with the same type of file that ParlAI's 20 | dictionary uses: tab separated dics 21 | """ 22 | self.tok2ind = {} 23 | self.ind2tok = {} 24 | self.freq = {} 25 | print(f"Loading dictionary from {file_path}") 26 | if file_path is not None: 27 | with open(file_path, "r") as f: 28 | counter = 0 29 | for line in f: 30 | splited = line[0:-1].split("\t") 31 | if splited[0] not in self.tok2ind: 32 | self.tok2ind[splited[0]] = counter 33 | self.ind2tok[counter] = splited[0] 34 | self.freq[splited[0]] = int(splited[1]) 35 | counter += 1 36 | self.null_token = self.ind2tok[counter - 1] 37 | self.unk_token = self.ind2tok[counter - 2] 38 | 39 | def vec2txt(self, vec): 40 | raw = " ".join(self.ind2tok[idx] for idx in vec) 41 | return ( 42 | raw.replace("__END__", "") 43 | .replace(" . ", ". ") 44 | .replace(" ! ", "! ") 45 | .replace(" , ", ", ") 46 | .replace(" ? ", "? ") 47 | ) 48 | 49 | def txt2vec(self, text): 50 | return [ 51 | self.tok2ind.get(token, self.tok2ind.get(self.unk_token, None)) 52 | for token in tokenize(text) 53 | ] 54 | 55 | def as_reddit_style_dict(self): 56 | """ 57 | Turned out reddit dataset also has a weird style dict. Convert this one 58 | to this style so that later in the code they speak the same language. 59 | """ 60 | words = self.tok2ind 61 | iwords = [] 62 | for i in range(len(self.tok2ind)): 63 | iwords.append(self.ind2tok[i]) 64 | res = {"words": words, "iwords": iwords, "wordcounts": self.freq} 65 | if hasattr(self, "bert_tokenizer"): 66 | res["bert_tokenizer"] = self.bert_tokenizer 67 | return res 68 | 69 | @staticmethod 70 | def create_from_reddit_style(reddit_style_dic): 71 | res = ParlAIDictionary() 72 | for w in reddit_style_dic["words"].keys(): 73 | res.tok2ind[w] = reddit_style_dic["words"][w] 74 | for i in range(len(reddit_style_dic["iwords"])): 75 | res.ind2tok[i] = reddit_style_dic["iwords"][i] 76 | res.null_token = "" # res.ind2tok[len(res.ind2tok)-1] 77 | res.unk_token = "" # res.ind2tok[len(res.ind2tok)-2] 78 | if "bert_tokenizer" in reddit_style_dic: 79 | res.bert_tokenizer = reddit_style_dic["bert_tokenizer"] 80 | return res 81 | 82 | def __getitem__(self, key): 83 | if type(key) == int: 84 | return self.ind2tok.get(key, self.unk_token) 85 | elif type(key) == str: 86 | return self.tok2ind.get(key, self.tok2ind.get(self.unk_token, None)) 87 | 88 | def __len__(self): 89 | return len(self.tok2ind) 90 | -------------------------------------------------------------------------------- /empchat/datasets/reddit.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import logging 9 | import os 10 | import os.path 11 | 12 | import torch 13 | from torch.utils.data import Dataset 14 | 15 | from empchat.datasets.tokens import BERT_ID, START_OF_COMMENT, UNK_TOKEN 16 | 17 | 18 | class RedditDataset(Dataset): 19 | def __init__( 20 | self, 21 | data_folder, 22 | chunk_id, 23 | dict_, 24 | max_len=100, 25 | rm_long_sent=False, 26 | max_hist_len=1, 27 | rm_long_contexts=False, 28 | rm_blank_sentences=False, 29 | ): 30 | data_path = os.path.join(data_folder, f"chunk{chunk_id}.pth") 31 | logging.info(f"Loading reddit dataset from {data_path}") 32 | data = torch.load(data_path) 33 | self.dictionary = dict_["words"] # w -> i 34 | self.iwords = dict_["iwords"] # i -> w 35 | self.words = data["w"] 36 | self.starts = data["cstart"] 37 | self.ends = data["cend"] 38 | self.uids = data["uid"] 39 | self.p2c = data["p2c"] 40 | self.unk_index = self.dictionary[UNK_TOKEN] 41 | if "bert_tokenizer" in dict_: 42 | self.using_bert = True 43 | assert BERT_ID == "bert-base-cased" 44 | deleted_uid = -1 45 | else: 46 | self.using_bert = False 47 | deleted_uid = 6 48 | # This was the deleted uid in the original Reddit binary chunks 49 | self.max_hist_len = max_hist_len 50 | self.max_len = max_len 51 | if self.max_hist_len > 1: 52 | self.start_of_comment = torch.LongTensor( 53 | [self.dictionary[START_OF_COMMENT]] 54 | ) 55 | valid_comments = (self.uids != deleted_uid) * (self.p2c != -1) 56 | parent_ids = self.p2c.clamp(min=0) 57 | valid_comments *= ( 58 | self.uids[parent_ids] != deleted_uid 59 | ) # Remove comments whose parent has been deleted 60 | if rm_long_sent: 61 | valid_comments *= (self.ends - self.starts) <= max_len 62 | if rm_blank_sentences: 63 | valid_comments *= (self.ends - self.starts) > 0 64 | # In retrieve.py, length-0 sentences are removed when retrieving 65 | # candidates; rm_blank_sentences allows length-0 sentence removal 66 | # when retrieving contexts as well 67 | if rm_long_contexts: 68 | valid_comments *= ( 69 | self.ends[parent_ids] - self.starts[parent_ids] 70 | ) <= max_len 71 | valid_comment_index = valid_comments.nonzero() 72 | self.datasetIndex2wIndex = valid_comment_index 73 | self.n_comments = self.datasetIndex2wIndex.numel() 74 | logging.info( 75 | f"Loaded {self.p2c.numel()} comments from {data_path}" 76 | f" of which {self.n_comments} are valid" 77 | ) 78 | 79 | def __len__(self): 80 | return self.n_comments 81 | 82 | def __getitem__(self, index): 83 | i = self.datasetIndex2wIndex[index] 84 | hist = [] 85 | parent_index = self.p2c[i] 86 | if self.max_hist_len <= 1: 87 | context = self.get_words(parent_index) 88 | else: 89 | while len(hist) < 2 * self.max_hist_len and parent_index != -1: 90 | hist.append(self.get_words(parent_index)) 91 | hist.append(self.start_of_comment) 92 | parent_index = self.p2c[parent_index] 93 | hist.reverse() 94 | context = torch.cat(hist) 95 | pos = self.get_words(i) 96 | return context, pos 97 | 98 | def get_words(self, index): 99 | start = self.starts[index] 100 | end = min(self.ends[index], start + self.max_len) 101 | selected_words = self.words[start:end] 102 | if self.using_bert: 103 | return selected_words 104 | else: 105 | return selected_words.clamp(-1, self.unk_index) 106 | -------------------------------------------------------------------------------- /empchat/datasets/tokens.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | from collections import OrderedDict 9 | from typing import Optional 10 | 11 | 12 | UNK_TOKEN = "" 13 | PAD_TOKEN = "" 14 | PARLAI_PAD_TOKEN = "__PAD__" 15 | EMPTYPERSONA_TOKEN = "" 16 | START_OF_COMMENT = "" 17 | END_OF_COMMENT = "" 18 | BERT_ID = "bert-base-cased" 19 | 20 | # Used to separate empchat utterances + responses 21 | UNUSED_BERT_TOKEN_1 = "[unused1]" 22 | 23 | # Both of these should actually be unused by this repo, because the first token is set 24 | # to '__PAD__', which only exists for ParlAI compatibility, and the second token is only 25 | # used for personas, which are no longer used 26 | UNUSED_BERT_TOKEN_2 = "[unused2]" 27 | UNUSED_BERT_TOKEN_3 = "[unused3]" 28 | 29 | # Possible fastText labels that aren't BERT tokens and would thus get broken if we 30 | # didn't map them to unused tokens 31 | SETS_TO_BROKEN_LABELS = { 32 | "emo": ["anticipating", "apprehensive", "joyful", "nostalgic", "sentimental"], 33 | "reuters": [ 34 | "acq", 35 | "alum", 36 | "barley", 37 | "bop", 38 | "carcass", 39 | "castor-oil", 40 | "cocoa", 41 | "coconut-oil", 42 | "copra-cake", 43 | "cotton-oil", 44 | "cpi", 45 | "cpu", 46 | "dfl", 47 | "dlr", 48 | "dmk", 49 | "gnp", 50 | "groundnut", 51 | "groundnut-oil", 52 | "hog", 53 | "instal-debt", 54 | "ipi", 55 | "iron-steel", 56 | "l-cattle", 57 | "lei", 58 | "lin-oil", 59 | "meal-feed", 60 | "money-fx", 61 | "money-supply", 62 | "naphtha", 63 | "nat-gas", 64 | "nkr", 65 | "nzdlr", 66 | "oat", 67 | "oilseed", 68 | "palladium", 69 | "palm-oil", 70 | "palmkernel", 71 | "pet-chem", 72 | "propane", 73 | "rand", 74 | "rape-oil", 75 | "rapeseed", 76 | "rye", 77 | "sorghum", 78 | "soy-meal", 79 | "soy-oil", 80 | "soybean", 81 | "strategic-metal", 82 | "sun-meal", 83 | "sun-oil", 84 | "sunseed", 85 | "veg-oil", 86 | "wpi", 87 | "yen", 88 | ], 89 | "twenty_newsgroups": [ 90 | "atheism", 91 | "autos", 92 | "christian", 93 | "cryptography", 94 | "mideast", 95 | "pc", 96 | ], 97 | } 98 | 99 | 100 | def get_bert_token_mapping(label_set=None): 101 | label_set_pairs = [] 102 | unused_token_idx = 3 103 | if label_set is not None: 104 | for label in SETS_TO_BROKEN_LABELS[label_set]: 105 | unused_token_idx += 1 106 | label_set_pairs.append((label, f"[unused{unused_token_idx:d}]")) 107 | return OrderedDict( 108 | [ 109 | (UNK_TOKEN, "[UNK]"), 110 | (PAD_TOKEN, "[PAD]"), 111 | (PARLAI_PAD_TOKEN, UNUSED_BERT_TOKEN_2), 112 | (EMPTYPERSONA_TOKEN, UNUSED_BERT_TOKEN_3), 113 | (START_OF_COMMENT, UNUSED_BERT_TOKEN_1), 114 | (END_OF_COMMENT, "[SEP]"), 115 | ] 116 | + label_set_pairs 117 | ) 118 | 119 | 120 | def tokenize(text, split_sep: Optional[str] = " "): 121 | return ( 122 | text.replace(".", " . ") 123 | .replace(". . .", "...") 124 | .replace(",", " , ") 125 | .replace(";", " ; ") 126 | .replace(":", " : ") 127 | .replace("!", " ! ") 128 | .replace("'", " ' ") 129 | .replace("?", " ? ") 130 | .replace(" ", " ") 131 | .replace(" ", " ") 132 | .strip() 133 | .split(split_sep) 134 | ) 135 | -------------------------------------------------------------------------------- /empchat/models.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import logging 9 | 10 | import torch 11 | import torch.nn as nn 12 | 13 | from empchat.bert_local import BertAdapter 14 | from empchat.datasets.tokens import PAD_TOKEN 15 | from empchat.transformer_local import TransformerAdapter 16 | 17 | 18 | def load_embeddings(opt, dictionary, model): 19 | path = opt.embeddings 20 | logging.info(f"Loading embeddings file from {path}") 21 | emb_table = model.embeddings.weight 22 | requires_grad = emb_table.requires_grad 23 | emb_table[dictionary[PAD_TOKEN]].zero_() # Zero-out padding index 24 | n_added = 0 25 | missing_dict = set(dictionary.keys()) 26 | with open(path) as f: 27 | for line in f: 28 | parsed = line.rstrip().split(" ") 29 | assert len(parsed) == opt.embeddings_size + 1 30 | w = parsed[0] 31 | if w in dictionary: 32 | n_added += 1 33 | vec = torch.Tensor([float(i) for i in parsed[1:]]) 34 | if opt.normalize_emb: 35 | vec = vec / vec.norm(2) 36 | emb_table.data[dictionary[w]] = vec 37 | missing_dict.remove(w) 38 | sample = ", ".join(list(missing_dict)[:8]) 39 | logging.info( 40 | f"Loaded {n_added} vectors from embeddings file; {len(missing_dict)} are " 41 | f"missing, among which: {sample}" 42 | ) 43 | emb_table.detach_() 44 | emb_table.requires_grad = requires_grad 45 | 46 | 47 | def save(filename, net, dictionary, optimizer): 48 | if isinstance(net, (nn.DataParallel, nn.parallel.DistributedDataParallel)): 49 | net = net.module 50 | state_dict = net.state_dict() 51 | params = { 52 | "state_dict": state_dict, 53 | "word_dict": dictionary, 54 | "opt": net.opt, 55 | "optim_dict": optimizer.state_dict(), 56 | } 57 | torch.save(params, filename) 58 | 59 | 60 | def load(filename, new_opt): 61 | logging.info(f"Loading model {filename}") 62 | saved_params = torch.load(filename, map_location=lambda storage, loc: storage) 63 | word_dict = saved_params["word_dict"] 64 | state_dict = saved_params["state_dict"] 65 | saved_opt = saved_params["opt"] 66 | for k, v in vars(new_opt).items(): 67 | if not hasattr(saved_opt, k): 68 | logging.warning(f"Setting {k} to {v}") 69 | setattr(saved_opt, k, v) 70 | if not (hasattr(new_opt, "fasttext")): 71 | setattr(saved_opt, "fasttext", new_opt.fasttext) 72 | if new_opt.model == "bert": 73 | assert "bert_tokenizer" in word_dict 74 | net = create(saved_opt, word_dict["words"]) 75 | net.load_state_dict(state_dict, strict=False) 76 | return net, word_dict 77 | 78 | 79 | def create(opt, dict_words): 80 | if opt.model == "bert": 81 | return BertAdapter(opt, dict_words) 82 | elif opt.model == "transformer": 83 | return TransformerAdapter(opt, dict_words) 84 | else: 85 | raise ValueError("Model not recognized!") 86 | 87 | 88 | def score_candidates(all_context, all_cands, top_k=20, normalize=False): 89 | # all_context is of size [ctx, d] 90 | # all_cands is of size [cand, d] 91 | dot_products = all_context.mm(all_cands.t()) # [ctx, cand] 92 | if normalize: 93 | dot_products /= all_context.norm(2, dim=1).unsqueeze(1) 94 | dot_products /= all_cands.norm(2, dim=1).unsqueeze(0) 95 | scores, answers = dot_products.topk(top_k, dim=1) 96 | # Index of top-k items in decreasing order. Answers is of size [ctx, top_k] 97 | return scores, answers 98 | -------------------------------------------------------------------------------- /empchat/transformer_local.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import math 9 | 10 | import numpy as np 11 | import torch 12 | import torch.nn as nn 13 | import torch.nn.functional as F 14 | 15 | from empchat.datasets.tokens import PAD_TOKEN 16 | 17 | 18 | def create_position_codes(n_pos, dim, out): 19 | position_enc = np.array( 20 | [ 21 | [pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] 22 | for pos in range(n_pos) 23 | ] 24 | ) 25 | out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2])) 26 | out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2])) 27 | out.detach_() 28 | out.requires_grad = False 29 | 30 | 31 | class TransformerModel(nn.Module): 32 | def __init__( 33 | self, 34 | transformer_n_heads, 35 | transformer_n_layers, 36 | transformer_dim, 37 | vocabulary_dim, 38 | embedding=None, 39 | fix_mean=True, 40 | dropout=0, 41 | padding_idx=None, 42 | ): 43 | super(TransformerModel, self).__init__() 44 | self.n_layers = transformer_n_layers 45 | self.fix_mean = fix_mean 46 | n_heads = transformer_n_heads # 8 by default 47 | dim = transformer_dim # 512 by default 48 | self.out_dim = dim 49 | dim_hidden = dim * 4 # 2048 by default 50 | assert dim % n_heads == 0, "transformer dim must be a multiple of n_heads" 51 | n_positions = 1000 52 | self.position_embeddings = nn.Embedding(n_positions, dim) 53 | create_position_codes(n_positions, dim, out=self.position_embeddings.weight) 54 | if embedding is not None: 55 | self.embeddings = embedding 56 | elif padding_idx is not None: 57 | self.embeddings = nn.Embedding(vocabulary_dim, dim, padding_idx=padding_idx) 58 | else: 59 | self.embeddings = nn.Embedding(vocabulary_dim, dim) 60 | self.dim = dim 61 | self.attentions = nn.ModuleList() 62 | self.layer_norm1 = nn.ModuleList() 63 | self.ffns = nn.ModuleList() 64 | self.layer_norm2 = nn.ModuleList() 65 | 66 | for _ in range(self.n_layers): 67 | self.attentions.append(MultiHeadAttention(n_heads, dim, dropout=dropout)) 68 | self.layer_norm1.append(nn.LayerNorm([dim])) 69 | self.ffns.append(TransformerFFN(dim, dim_hidden, dropout=dropout)) 70 | self.layer_norm2.append(nn.LayerNorm([dim])) 71 | 72 | def forward(self, input_, mask): 73 | """ 74 | input data is a LongTensor of shape [batch, seq_len], containing each 75 | word's index in the embeddings table. 76 | mask is a ByteTensor of shape [batch, seq_len], filled with 1 when 77 | inside the sequence and 0 outside. 78 | """ 79 | seq_len = input_.size(1) 80 | positions = input_.new(seq_len).long() 81 | positions = torch.arange(seq_len, out=positions).unsqueeze(0) 82 | tensor = self.embeddings(input_) 83 | tensor = tensor + self.position_embeddings(positions).expand_as(tensor) 84 | tensor *= mask.unsqueeze(-1).float() 85 | for i in range(self.n_layers): 86 | tensor = tensor + self.attentions[i](tensor, mask) 87 | tensor = self.normalize(tensor, self.layer_norm1[i]) 88 | tensor = tensor + self.ffns[i](tensor, mask) 89 | tensor = self.normalize(tensor, self.layer_norm2[i]) 90 | tensor *= mask.unsqueeze(-1).float() 91 | if self.fix_mean: 92 | output = tensor.sum(dim=1) / mask.float().sum(dim=1).unsqueeze(-1) 93 | else: 94 | output = tensor.mean(dim=1) 95 | return output 96 | 97 | def normalize(self, tensor, norm_layer): 98 | size = tensor.size() 99 | return norm_layer(tensor.view(-1, self.dim)).view(size) 100 | 101 | 102 | class MultiHeadAttention(nn.Module): 103 | def __init__(self, n_heads, dim, dropout=0): 104 | super(MultiHeadAttention, self).__init__() 105 | self.n_heads = n_heads 106 | self.dim = dim 107 | # multi head is seen as one layer, dropout is only applied to the input 108 | self.in_dropout = nn.Dropout(p=dropout) 109 | self.q_lin = nn.Linear(dim, dim) 110 | self.k_lin = nn.Linear(dim, dim) 111 | self.v_lin = nn.Linear(dim, dim) 112 | nn.init.xavier_normal_(self.q_lin.weight) 113 | nn.init.xavier_normal_(self.k_lin.weight) 114 | nn.init.xavier_normal_(self.v_lin.weight) 115 | self.out_lin = nn.Linear(dim, dim) 116 | nn.init.xavier_normal_(self.out_lin.weight) 117 | 118 | def forward(self, input_, mask): 119 | # Input is [B, seq_len, dim] 120 | # Mask is [B, seq_len] 121 | batch_size, seq_len, dim = input_.size() 122 | assert ( 123 | dim == self.dim 124 | ), f"Dimensions do not match: {dim} input vs {self.dim} configured" 125 | n_heads = self.n_heads 126 | dim_per_head = dim // n_heads 127 | 128 | def prepare_head(tensor): 129 | # input is [batch_size, seq_len, n_heads * dim_per_head] 130 | # output is [batch_size * n_heads, seq_len, dim_per_head] 131 | tensor = tensor.view(batch_size, seq_len, n_heads, dim_per_head) 132 | tensor = ( 133 | tensor.transpose(1, 2) 134 | .contiguous() 135 | .view(batch_size * n_heads, seq_len, dim_per_head) 136 | ) 137 | return tensor 138 | 139 | in_droped = self.in_dropout(input_) 140 | query = prepare_head(self.q_lin(in_droped)) 141 | keys = prepare_head(self.k_lin(in_droped)) 142 | values = prepare_head(self.v_lin(in_droped)) 143 | scale = math.sqrt(dim_per_head) 144 | dot_prod = query.bmm(keys.transpose(1, 2)) 145 | # [B * n_heads, seq_len, seq_len] 146 | attn_mask = ( 147 | (mask == 0) 148 | .view(batch_size, 1, 1, seq_len) 149 | .repeat(1, n_heads, seq_len, 1) 150 | .view(batch_size * n_heads, seq_len, seq_len) 151 | ) 152 | dot_prod.masked_fill_(attn_mask, -float("inf")) 153 | attn_weights = F.softmax(dot_prod / scale, dim=-1) 154 | attentioned = attn_weights.bmm(values) 155 | attentioned = ( 156 | attentioned.view(batch_size, n_heads, seq_len, dim_per_head) 157 | .transpose(1, 2) 158 | .contiguous() 159 | .view(batch_size, seq_len, dim) 160 | ) 161 | return self.out_lin(attentioned) 162 | 163 | 164 | class TransformerFFN(nn.Module): 165 | def __init__(self, dim, dim_hidden, dropout=0): 166 | super(TransformerFFN, self).__init__() 167 | self.in_dropout = nn.Dropout(p=dropout) 168 | self.lin1 = nn.Linear(dim, dim_hidden) 169 | self.lin2 = nn.Linear(dim_hidden, dim) 170 | nn.init.xavier_normal_(self.lin1.weight) 171 | nn.init.xavier_normal_(self.lin2.weight) 172 | 173 | def forward(self, input_, mask): 174 | return self.lin2(F.relu(self.lin1(self.in_dropout(input_)))) 175 | 176 | 177 | class TransformerAdapter(nn.Module): 178 | def __init__(self, opt, dictionary): 179 | super(TransformerAdapter, self).__init__() 180 | self.opt = opt 181 | self.pad_idx = dictionary[PAD_TOKEN] 182 | self.embeddings = nn.Embedding( 183 | len(dictionary), opt.embeddings_size, padding_idx=self.pad_idx 184 | ) 185 | if not opt.learn_embeddings: 186 | self.embeddings.weight.requires_grad = False 187 | nn.init.normal_(self.embeddings.weight, mean=0, std=0.05) 188 | dropout = opt.transformer_dropout if opt.transformer_dropout else 0 189 | self.ctx_transformer = TransformerModel( 190 | opt.transformer_n_heads, 191 | opt.n_layers, 192 | opt.transformer_dim, 193 | len(dictionary), 194 | embedding=self.embeddings, 195 | dropout=dropout, 196 | ) 197 | self.cand_transformer = TransformerModel( 198 | opt.transformer_n_heads, 199 | opt.n_layers, 200 | opt.transformer_dim, 201 | len(dictionary), 202 | embedding=self.embeddings, 203 | dropout=dropout, 204 | ) 205 | self.embeddings = self.ctx_transformer.embeddings 206 | 207 | def forward(self, context_w, cands_w): 208 | if context_w is not None: 209 | context_mask = context_w != self.pad_idx 210 | context_h = self.ctx_transformer(context_w, context_mask) 211 | if self.opt.normalize_sent_emb: 212 | context_h = context_h / context_h.norm(2, dim=1, keepdim=True) 213 | else: 214 | context_h = None 215 | if cands_w is not None: 216 | cands_mask = cands_w != self.pad_idx 217 | cands_h = self.cand_transformer(cands_w, cands_mask) 218 | if self.opt.normalize_sent_emb: 219 | cands_h = cands_h / cands_h.norm(2, dim=1, keepdim=True) 220 | else: 221 | cands_h = None 222 | return context_h, cands_h 223 | -------------------------------------------------------------------------------- /empchat/util.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | # 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # 7 | 8 | import argparse 9 | import json 10 | import logging 11 | import os 12 | import sys 13 | 14 | 15 | def get_opt(existing_opt=None): 16 | parser = get_parser() 17 | opt = parser.parse_args([]) if existing_opt is not None else parser.parse_args() 18 | # If we have an existing set of options, just use defaults for our new set. We'll 19 | # transfer over needed existing option values below 20 | set_defaults(opt=opt, existing_opt=existing_opt) 21 | return opt 22 | 23 | 24 | def get_parser(): 25 | parser = argparse.ArgumentParser() 26 | parser.add_argument( 27 | "-bs", "--batch-size", type=int, default=32, help="Training/eval batch size" 28 | ) 29 | parser.add_argument( 30 | "--bert-add-transformer-layer", 31 | action="store_true", 32 | help="Add final Transformer layer to BERT model", 33 | ) 34 | parser.add_argument( 35 | "--bert-dim", 36 | type=int, 37 | default=512, 38 | help="Final BERT Transformer layer output dim", 39 | ) 40 | parser.add_argument("--cuda", action="store_true", help="Use CUDA") 41 | parser.add_argument( 42 | "--dailydialog-folder", type=str, help="Path to DailyDialog data folder" 43 | ) 44 | parser.add_argument( 45 | "--dataset-name", 46 | type=str, 47 | default="reddit", 48 | choices=["reddit", "empchat", "dailydialog"], 49 | help="Data to train/eval on", 50 | ) 51 | parser.add_argument( 52 | "--dict-max-words", 53 | type=int, 54 | default=250000, 55 | help="Max dictionary size (not used with BERT)", 56 | ) 57 | parser.add_argument( 58 | "--display-iter", type=int, default=250, help="Frequency of train logging" 59 | ) 60 | parser.add_argument("--embeddings", type=str, help="Path to embeddings file") 61 | parser.add_argument( 62 | "--embeddings-size", type=int, default=300, help="Transformer embedding size" 63 | ) 64 | parser.add_argument( 65 | "--empchat-folder", type=str, help="Path to EmpatheticDialogues data folder" 66 | ) 67 | parser.add_argument( 68 | "-e", 69 | "--epoch-start", 70 | type=int, 71 | default=0, 72 | help="Initial epoch number when resuming training", 73 | ) 74 | parser.add_argument( 75 | "--fasttext", 76 | type=int, 77 | default=None, 78 | help="Number of fastText labels to prepend", 79 | ) 80 | parser.add_argument( 81 | "--fasttext-path", type=str, default=None, help="Path to fastText classifier" 82 | ) 83 | parser.add_argument( 84 | "--fasttext-type", 85 | type=str, 86 | default=None, 87 | help="Specifies labels of fastText classifier", 88 | ) 89 | parser.add_argument( 90 | "--hits-at-nb-cands", 91 | type=int, 92 | default=100, 93 | help="Num candidates to calculate precision out of", 94 | ) 95 | parser.add_argument( 96 | "--learn-embeddings", action="store_true", help="Train on embeddings" 97 | ) 98 | parser.add_argument( 99 | "-lr", 100 | "--learning-rate", 101 | type=float, 102 | default=None, 103 | help="Training learning rate", 104 | ) 105 | parser.add_argument("--load-checkpoint", type=str, help="Path to model checkpoint") 106 | parser.add_argument("--log-file", type=str, help="Path to log file") 107 | parser.add_argument( 108 | "--max-hist-len", 109 | type=int, 110 | default=1, 111 | help="Max num conversation turns to use in context", 112 | ) 113 | parser.add_argument( 114 | "--max-sent-len", type=int, default=100, help="Max num tokens per sentence" 115 | ) 116 | parser.add_argument( 117 | "--model", 118 | type=str, 119 | choices=["bert", "transformer"], 120 | help="Choice of retrieval model", 121 | ) 122 | parser.add_argument("--model-dir", type=str, help="Model save folder") 123 | parser.add_argument("--model-name", type=str, help="Model save name") 124 | parser.add_argument( 125 | "--n-layers", type=int, default=6, help="Num Transformer layers" 126 | ) 127 | parser.add_argument( 128 | "--no-shuffle", action="store_true", help="Don't shuffle data during training" 129 | ) 130 | parser.add_argument( 131 | "--normalize-emb", action="store_true", help="Normalize loaded embeddings" 132 | ) 133 | parser.add_argument( 134 | "--normalize-sent-emb", 135 | action="store_true", 136 | help="Normalize context/candidate embeddings", 137 | ) 138 | parser.add_argument("--num-epochs", type=int, default=1000, help="Num epochs") 139 | parser.add_argument( 140 | "--optimizer", 141 | type=str, 142 | choices=["sgd", "adamax"], 143 | default="adamax", 144 | help="Choice of optimizer", 145 | ) 146 | parser.add_argument( 147 | "--pretrained", type=str, help="Path to pretrained model (will run eval only)" 148 | ) 149 | parser.add_argument("--random-seed", type=int, default=92179, help="Seed") 150 | parser.add_argument( 151 | "--reactonly", 152 | action="store_true", 153 | help="EmpatheticDialogues: only consider Listener responses", 154 | ) 155 | parser.add_argument("--reddit-folder", type=str, help="Path to Reddit data folder") 156 | parser.add_argument( 157 | "--rm-long-sent", 158 | action="store_true", 159 | help="Completely remove long Reddit sentences", 160 | ) 161 | parser.add_argument( 162 | "--rm-long-contexts", 163 | action="store_true", 164 | help="Completely remove long Reddit contexts", 165 | ) 166 | parser.add_argument( 167 | "--stop-crit-num-epochs", 168 | type=int, 169 | default=-1, 170 | help="Num epochs to stop after if loss is not decreasing", 171 | ) 172 | parser.add_argument( 173 | "--transformer-dim", 174 | type=int, 175 | default=512, 176 | help="Input Transformer embedding dim", 177 | ) 178 | parser.add_argument( 179 | "--transformer-dropout", 180 | type=float, 181 | default=0, 182 | help="Transformer attention/FFN dropout", 183 | ) 184 | parser.add_argument( 185 | "--transformer-n-heads", 186 | type=int, 187 | default=8, 188 | help="Num Transformer attention heads", 189 | ) 190 | return parser 191 | 192 | 193 | def set_defaults(opt, existing_opt=None): 194 | if opt.model_dir is None: 195 | # retrieval_eval_bleu.py uses an `output_folder` arg instead 196 | assert existing_opt.output_folder is not None 197 | opt.model_dir = existing_opt.output_folder 198 | 199 | # Set model directory 200 | os.makedirs(opt.model_dir, exist_ok=True) 201 | 202 | # Set model name 203 | if not opt.model_name: 204 | import uuid 205 | import time 206 | 207 | opt.model_name = time.strftime("%Y%m%d-") + str(uuid.uuid4())[:8] 208 | 209 | # Set log + model file names 210 | if opt.log_file is None: 211 | opt.log_file = os.path.join(opt.model_dir, opt.model_name + ".txt") 212 | opt.model_file = os.path.join(opt.model_dir, opt.model_name + ".mdl") 213 | 214 | 215 | def get_logger(opt): 216 | logger = logging.getLogger() 217 | logger.setLevel(logging.INFO) 218 | fmt = logging.Formatter("%(asctime)s: [ %(message)s ]", "%m/%d/%Y %I:%M:%S %p") 219 | console = logging.StreamHandler() 220 | console.setFormatter(fmt) 221 | logger.addHandler(console) 222 | if opt.log_file: 223 | logfile = logging.FileHandler(opt.log_file, "a") 224 | logfile.setFormatter(fmt) 225 | logger.addHandler(logfile) 226 | command = " ".join(sys.argv) 227 | logger.info(f"COMMAND: {command}") 228 | logger.info("-" * 100) 229 | config = json.dumps(vars(opt), indent=4, sort_keys=True) 230 | logger.info(f"CONFIG:\n{config}") 231 | return logger 232 | -------------------------------------------------------------------------------- /retrieval_eval_bleu.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # All rights reserved. 5 | # 6 | # This source code is licensed under the license found in the 7 | # LICENSE file in the root directory of this source tree. 8 | # 9 | 10 | import argparse 11 | import logging 12 | import os 13 | 14 | import torch 15 | from fairseq import bleu 16 | from tqdm import tqdm 17 | 18 | from empchat.datasets.dailydialog import DDDataset 19 | from empchat.datasets.empchat import EmpDataset 20 | from empchat.datasets.reddit import RedditDataset 21 | from empchat.datasets.parlai_dictionary import ParlAIDictionary 22 | from empchat.datasets.tokens import tokenize, PAD_TOKEN, START_OF_COMMENT, UNK_TOKEN 23 | from empchat.models import load as load_model, score_candidates 24 | from empchat.util import get_opt 25 | 26 | 27 | logger = logging.getLogger() 28 | logger.setLevel(logging.INFO) 29 | fmt = logging.Formatter("%(asctime)s: [ %(message)s ]", "%m/%d/%Y %I:%M:%S %p") 30 | console = logging.StreamHandler() 31 | console.setFormatter(fmt) 32 | logger.addHandler(console) 33 | 34 | # ------------------------------------------------------------------------------ 35 | # Commandline arguments & init 36 | # ------------------------------------------------------------------------------ 37 | 38 | parser = argparse.ArgumentParser() 39 | parser.add_argument( 40 | "--bleu-dict", 41 | type=str, 42 | default=None, 43 | help=( 44 | "Path to dictionary to use for BLEU calculation (if " 45 | "not the same as the dictionary to use for retrieval)" 46 | ), 47 | ) 48 | parser.add_argument( 49 | "--candidates", type=str, default=None, help="Path to candidates to use" 50 | ) 51 | parser.add_argument( 52 | "--dailydialog-cands", action="store_true", help="Include DailyDialog candidates" 53 | ) 54 | parser.add_argument( 55 | "--dailydialog-folder", type=str, help="Path to DailyDialog data folder" 56 | ) 57 | parser.add_argument( 58 | "--empchat-cands", 59 | action="store_true", 60 | help="Include EmpatheticDialogues candidates", 61 | ) 62 | parser.add_argument( 63 | "--empchat-folder", type=str, help="Path to EmpatheticDialogues data folder" 64 | ) 65 | parser.add_argument( 66 | "--fasttext", type=int, default=None, help="Number of fastText labels to prepend" 67 | ) 68 | parser.add_argument( 69 | "--fasttext-path", type=str, default=None, help="Path to fastText classifier" 70 | ) 71 | parser.add_argument( 72 | "--fasttext-type", 73 | type=str, 74 | default=None, 75 | help="Specifies labels of fastText classifier", 76 | ) 77 | parser.add_argument("--gpu", type=int, default=-1, help="Specify GPU device id to use") 78 | parser.add_argument( 79 | "--max-cand-length", 80 | type=int, 81 | default=20, 82 | help="Max candidate length in number of tokens", 83 | ) 84 | parser.add_argument( 85 | "--max-hist-len", 86 | type=int, 87 | default=1, 88 | help="Max num conversation turns to use in context", 89 | ) 90 | parser.add_argument( 91 | "--model", "--pretrained", type=str, default=None, help="Path to model to use" 92 | ) 93 | parser.add_argument( 94 | "--n-candidates", type=int, default=int(1e6), help="Max number of candidates" 95 | ) 96 | parser.add_argument("--name", type=str, help="Part of name of response output file") 97 | parser.add_argument("--no-cuda", action="store_true", help="Use CPU only") 98 | parser.add_argument( 99 | "--normalize-cands", action="store_true", help="Normalize encoded candidates" 100 | ) 101 | parser.add_argument( 102 | "--output-folder", type=str, default=None, help="Path to output folder" 103 | ) 104 | parser.add_argument( 105 | "--reactonly", 106 | action="store_true", 107 | help="EmpatheticDialogues: only consider Listener responses", 108 | ) 109 | parser.add_argument( 110 | "--reddit-cands", action="store_true", help="Include Reddit candidates" 111 | ) 112 | parser.add_argument("--reddit-folder", type=str, help="Path to Reddit data folder") 113 | parser.add_argument( 114 | "--save-candidates", action="store_true", help="If true, save candidate files" 115 | ) 116 | parser.add_argument( 117 | "--task", 118 | type=str, 119 | choices=["dailydialog", "empchat", "reddit"], 120 | default="empchat", 121 | help="Dataset for context/target-response pairs", 122 | ) 123 | args = parser.parse_args() 124 | args.cuda = not args.no_cuda and torch.cuda.is_available() 125 | if args.cuda: 126 | torch.cuda.set_device(args.gpu) 127 | logger.info(f"CUDA enabled (GPU {args.gpu:d})") 128 | else: 129 | logger.info("Running on CPU only.") 130 | if args.fasttext is not None: 131 | args.max_cand_length += args.fasttext 132 | net, net_dictionary = load_model(args.model, get_opt(existing_opt=args)) 133 | if "bert_tokenizer" in net_dictionary: 134 | if args.task == "dailydialog": 135 | raise NotImplementedError("BERT model currently incompatible with DailyDialog!") 136 | if args.bleu_dict is not None: 137 | _, bleu_dictionary = load_model(args.bleu_dict, get_opt(existing_opt=args)) 138 | else: 139 | bleu_dictionary = net_dictionary 140 | paramnum = 0 141 | trainable = 0 142 | for parameter in net.parameters(): 143 | if parameter.requires_grad: 144 | trainable += parameter.numel() 145 | paramnum += parameter.numel() 146 | print(paramnum, trainable) 147 | print(type(net_dictionary)) 148 | NET_PAD_IDX = net_dictionary["words"][PAD_TOKEN] 149 | NET_UNK_IDX = net_dictionary["words"][UNK_TOKEN] 150 | print(type(bleu_dictionary)) 151 | BLEU_PAD_IDX = bleu_dictionary["words"][PAD_TOKEN] 152 | BLEU_UNK_IDX = bleu_dictionary["words"][UNK_TOKEN] 153 | BLEU_EOS_IDX = bleu_dictionary["words"][START_OF_COMMENT] 154 | args.cuda = not args.no_cuda and torch.cuda.is_available() 155 | if args.cuda: 156 | torch.cuda.set_device(args.gpu) 157 | logger.info(f"CUDA enabled (GPU {args.gpu:d})") 158 | else: 159 | logger.info("Running on CPU only.") 160 | actual_ct = [0, 0, 0] 161 | if args.cuda: 162 | net = torch.nn.DataParallel(net) 163 | net.cuda() 164 | net.eval() 165 | 166 | 167 | def pad(items): 168 | max_len = max(len(i) for i in items) 169 | tensor = torch.LongTensor(len(items), max_len).fill_(NET_PAD_IDX) 170 | for i, sentence in enumerate(items): 171 | tensor[i, : sentence.size(0)] = sentence 172 | return tensor 173 | 174 | 175 | def build_candidates( 176 | max_cand_length, n_cands=int(1e7), rm_duplicates=True, rm_starting_gt=True 177 | ): 178 | global actual_ct 179 | global args 180 | tensor = torch.LongTensor(n_cands, max_cand_length).fill_(NET_PAD_IDX) 181 | i = 0 182 | chunk = 422 183 | if "bert_tokenizer" in net_dictionary: 184 | gt_tokens = torch.LongTensor( 185 | net_dictionary["bert_tokenizer"].convert_tokens_to_ids(["&", "g", "##t"]) 186 | ) 187 | else: 188 | gt_index = net_dictionary["words"][">"] 189 | lt_index = net_dictionary["words"]["<"] 190 | unk_index = net_dictionary["words"][""] 191 | n_duplicates = n_start_gt = 0 192 | if rm_duplicates: 193 | all_sent = set() 194 | 195 | def _has_lts(sentence_) -> bool: 196 | if "bert_tokenizer" in net_dictionary: 197 | tokens = net_dictionary["bert_tokenizer"].convert_ids_to_tokens( 198 | sentence_.tolist() 199 | ) 200 | return "& l ##t" in " ".join(tokens) 201 | else: 202 | return torch.sum(sentence_ == lt_index).gt(0) 203 | 204 | def _starts_with_gt(sentence_) -> bool: 205 | if "bert_tokenizer" in net_dictionary: 206 | if sentence_.size(0) < 3: 207 | return False 208 | else: 209 | return torch.eq(sentence_[:3], gt_tokens).all() 210 | else: 211 | return sentence_[0].item == gt_index 212 | 213 | parlai_dict = ParlAIDictionary.create_from_reddit_style(net_dictionary) 214 | if args.empchat_cands: 215 | dataset = EmpDataset( 216 | "train", 217 | parlai_dict, 218 | data_folder=args.empchat_folder, 219 | reactonly=False, 220 | fasttext=args.fasttext, 221 | fasttext_type=args.fasttext_type, 222 | fasttext_path=args.fasttext_path, 223 | ) 224 | sample_index = range(len(dataset)) 225 | for data_idx in sample_index: 226 | _context, sentence, _ = dataset[data_idx] 227 | sent_length = sentence.size(0) 228 | if torch.sum(sentence == unk_index).gt(0): 229 | continue 230 | if _has_lts(sentence): 231 | continue 232 | if sent_length <= max_cand_length: 233 | if _starts_with_gt(sentence) and rm_starting_gt: 234 | n_start_gt += 1 235 | continue 236 | if rm_duplicates: 237 | tuple_sent = tuple(sentence.numpy()) 238 | if tuple_sent in all_sent: 239 | n_duplicates += 1 240 | continue 241 | all_sent.add(tuple_sent) 242 | tensor[i, : sentence.size(0)] = sentence 243 | i += 1 244 | if i >= n_cands: 245 | break 246 | breakpoint_ = i 247 | actual_ct[1] = i 248 | if args.dailydialog_cands: 249 | dataset = DDDataset("train", parlai_dict, data_folder=args.dailydialog_folder) 250 | sample_index = range(len(dataset)) 251 | for data_idx in sample_index: 252 | _context, sentence = dataset[data_idx] 253 | sent_length = sentence.size(0) 254 | if torch.sum(sentence == unk_index).gt(0): 255 | continue 256 | if _has_lts(sentence): 257 | continue 258 | if sent_length <= max_cand_length: 259 | if _starts_with_gt(sentence) and rm_starting_gt: 260 | n_start_gt += 1 261 | continue 262 | if rm_duplicates: 263 | tuple_sent = tuple(sentence.numpy()) 264 | if tuple_sent in all_sent: 265 | n_duplicates += 1 266 | continue 267 | all_sent.add(tuple_sent) 268 | tensor[i, : sentence.size(0)] = sentence 269 | i += 1 270 | if i >= n_cands: 271 | break 272 | bp2 = i 273 | actual_ct[2] = i - breakpoint_ 274 | if args.reddit_cands: 275 | while i < n_cands: 276 | chunk += 1 277 | logging.info(f"Loaded {i} / {n_cands} candidates") 278 | dataset = RedditDataset(args.reddit_folder, chunk, net_dictionary) 279 | sample_index = range(len(dataset)) 280 | for data_idx in sample_index: 281 | _context, sentence = dataset[data_idx] 282 | sent_length = sentence.size(0) 283 | if sent_length == 0: 284 | print(f"Reddit sentence {data_idx} is of length 0.") 285 | continue 286 | if torch.sum(sentence == unk_index).gt(0): 287 | continue 288 | if _has_lts(sentence): 289 | continue 290 | if sent_length <= max_cand_length: 291 | if _starts_with_gt(sentence) and rm_starting_gt: 292 | n_start_gt += 1 293 | continue 294 | if rm_duplicates: 295 | tuple_sent = tuple(sentence.numpy()) 296 | if tuple_sent in all_sent: 297 | n_duplicates += 1 298 | continue 299 | all_sent.add(tuple_sent) 300 | tensor[i, : sentence.size(0)] = sentence 301 | i += 1 302 | if i >= n_cands: 303 | break 304 | actual_ct[0] = i - bp2 305 | logging.info( 306 | f"Loaded {i} candidates, {n_start_gt} start with >, {n_duplicates} duplicates" 307 | ) 308 | args.n_candidates = i 309 | return tensor[:i, :], breakpoint_, bp2 310 | 311 | 312 | def embed_candidates(candidates): 313 | out_tensor = None 314 | i = 0 315 | ch = candidates.split(2048, dim=0) 316 | for chunk in tqdm(range(len(ch))): 317 | _, encoded_cand = net(None, ch[chunk]) 318 | if out_tensor is None: 319 | out_tensor = torch.FloatTensor(candidates.size(0), encoded_cand.size(1)) 320 | if args.cuda: 321 | out_tensor = out_tensor.cuda() 322 | if args.normalize_cands: 323 | encoded_cand /= encoded_cand.norm(2, dim=1, keepdim=True) 324 | batch_size = encoded_cand.size(0) 325 | out_tensor[i : i + batch_size] = encoded_cand 326 | i += batch_size 327 | return out_tensor 328 | 329 | 330 | def get_token_tensor(sentence): 331 | words = net_dictionary["words"] 332 | tokenized = tokenize(sentence, split_sep=None) 333 | return torch.LongTensor([words.get(w, NET_UNK_IDX) for w in tokenized]) 334 | 335 | 336 | def stringify(tensor): 337 | iwords = net_dictionary["iwords"] 338 | assert tensor.squeeze().dim() == 1, "Wrong tensor size!" 339 | return " ".join( 340 | iwords[i] for i in tensor.squeeze().cpu().numpy() if i != NET_PAD_IDX 341 | ).replace(" ##", "") 342 | # Remove any BPE tokenization 343 | 344 | 345 | if args.candidates: 346 | fixed_candidates = torch.load(args.candidates) 347 | if args.n_candidates < fixed_candidates.size(0): 348 | logging.warning( 349 | f"Keeping only {args.n_candidates} / {fixed_candidates.size(0)} candidates" 350 | ) 351 | fixed_candidates = fixed_candidates[: args.n_candidates] 352 | else: 353 | fixed_candidates, breakingpt, breakingpt2 = build_candidates( 354 | args.max_cand_length, args.n_candidates 355 | ) 356 | if args.cuda: 357 | fixed_candidates = fixed_candidates.cuda(non_blocking=True) 358 | logging.warning("Embedding candidates") 359 | with torch.no_grad(): 360 | cand_embs = embed_candidates(fixed_candidates) 361 | logging.warning("Done with candidates") 362 | if args.save_candidates: 363 | cand_path = os.path.join(args.output_folder, "reddit_cands_tokens.bin") 364 | logging.warning(f"Saving candidates in {cand_path}") 365 | torch.save(fixed_candidates, cand_path) 366 | emb_path = os.path.join(args.output_folder, "reddit_cands.bin") 367 | logging.warning(f"Saving candidate embs in {emb_path}") 368 | torch.save(cand_embs, emb_path) 369 | txt_path = os.path.join(args.output_folder, "reddit_cands.txt") 370 | logging.warning(f"Saving candidate texts in {txt_path}") 371 | with open(txt_path, "w") as f: 372 | for candidate in fixed_candidates: 373 | f.write(stringify(candidate)) 374 | f.write("\n") 375 | logging.warning("Done saving files") 376 | 377 | # ------------------------------------------------------------------------------ 378 | # Drop in to interactive mode 379 | # ------------------------------------------------------------------------------ 380 | 381 | 382 | def predict(context, top_n=5, normalize=False): 383 | """ 384 | returns a list of top_n tuples ("sentence", "score") 385 | """ 386 | with torch.no_grad(): 387 | context = context.unsqueeze(0) 388 | candidates = fixed_candidates 389 | if args.cuda: 390 | context = context.cuda(non_blocking=True) 391 | ctx, _ = net(context, None) 392 | scores, index = score_candidates(ctx, cand_embs, top_n, normalize) 393 | response = [] 394 | outputs = [] 395 | for i, (score, index) in enumerate(zip(scores.squeeze(0), index.squeeze(0)), 1): 396 | response.append((stringify(candidates[index]), float(score))) 397 | if index < breakingpt: 398 | outputs.append("EmpChat") 399 | elif index < breakingpt2: 400 | outputs.append("DailyDialog") 401 | else: 402 | outputs.append("Reddit") 403 | return response, outputs 404 | 405 | 406 | def get_bleu4(split, history_len=1): 407 | """ 408 | Print BLEU scores and output contexts and retrieved responses. 409 | """ 410 | if history_len < 1: 411 | history_len = 1 412 | source_ct = [0, 0, 0] 413 | net_parlai_dict = ParlAIDictionary.create_from_reddit_style(net_dictionary) 414 | bleu_parlai_dict = ParlAIDictionary.create_from_reddit_style(bleu_dictionary) 415 | scorer = bleu.Scorer(BLEU_PAD_IDX, BLEU_EOS_IDX, BLEU_UNK_IDX) 416 | outf = open("retrieved_split_" + args.name + "_" + split + ".txt", "w") 417 | 418 | def _get_dataset(reddit_dict, parlai_dict): 419 | if args.task == "dailydialog": 420 | return DDDataset( 421 | split, 422 | parlai_dict, 423 | data_folder=args.dailydialog_folder, 424 | history_len=history_len, 425 | ) 426 | elif args.task == "empchat": 427 | return EmpDataset( 428 | split, 429 | parlai_dict, 430 | data_folder=args.empchat_folder, 431 | history_len=history_len, 432 | reactonly=args.reactonly, 433 | fasttext=args.fasttext, 434 | fasttext_type=args.fasttext_type, 435 | fasttext_path=args.fasttext_path, 436 | ) 437 | elif args.task == "reddit": 438 | return RedditDataset( 439 | data_folder=args.reddit_folder, 440 | chunk_id=999, 441 | dict_=reddit_dict, 442 | max_hist_len=history_len, 443 | rm_blank_sentences=True, 444 | ) 445 | else: 446 | raise ValueError("Task unrecognized!") 447 | 448 | net_dataset = _get_dataset(net_dictionary, net_parlai_dict) 449 | bleu_dataset = _get_dataset(bleu_dictionary, bleu_parlai_dict) 450 | sample_index = range(len(bleu_dataset)) 451 | for data_idx in sample_index: 452 | net_context, _ = net_dataset[data_idx][:2] 453 | bleu_context, bleu_sentence = bleu_dataset[data_idx][:2] 454 | target_tokens = bleu_sentence 455 | if args.fasttext is not None: 456 | target_tokens = target_tokens[args.fasttext :] 457 | context = bleu_parlai_dict.vec2txt(bleu_context.numpy().tolist()) 458 | responses, sources = predict(net_context) 459 | response = responses[0][0] 460 | source = sources[0] 461 | if source == "Reddit": 462 | source_ct[0] += 1 463 | elif source == "EmpChat": 464 | source_ct[1] += 1 465 | else: 466 | source_ct[2] += 1 467 | if args.task == "empchat": 468 | cid, sid = bleu_dataset.getid(data_idx) 469 | else: 470 | cid = sid = -1 471 | # This is a hack, because the other datasets have no .getid() method 472 | if args.fasttext is not None: 473 | response = " ".join(response.split()[args.fasttext :]) 474 | outf.write("\t".join([str(cid), str(sid), context, response, source]) + "\n") 475 | hypo_tokens = torch.IntTensor(bleu_parlai_dict.txt2vec(response)) 476 | # Use this tokenization even if a BERT tokenizer exists, to match the BLEU 477 | # calculation when not using BERT 478 | scorer.add(target_tokens.type(torch.IntTensor), hypo_tokens) 479 | print(scorer.result_string(order=1)) 480 | print(scorer.result_string(order=2)) 481 | print(scorer.result_string(order=3)) 482 | print(scorer.result_string(order=4)) 483 | print(actual_ct) 484 | print( 485 | f"EmpatheticDialogues {int(source_ct[1]):d}: selected " 486 | f"{float(source_ct[1]) / sum(source_ct)}%, but total: " 487 | f"{float(actual_ct[1]) / sum(actual_ct)}" 488 | ) 489 | print( 490 | f"DailyDialog {int(source_ct[2]):d}: selected " 491 | f"{float(source_ct[2]) / sum(source_ct)}%, but total: " 492 | f"{float(actual_ct[2]) / sum(actual_ct)}" 493 | ) 494 | print( 495 | f"Reddit {int(source_ct[0]):d}: selected " 496 | f"{float(source_ct[0]) / sum(source_ct)}%, but total: " 497 | f"{float(actual_ct[0]) / sum(actual_ct)}" 498 | ) 499 | 500 | 501 | get_bleu4("valid", history_len=args.max_hist_len) 502 | get_bleu4("test", history_len=args.max_hist_len) 503 | -------------------------------------------------------------------------------- /retrieval_train.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # All rights reserved. 5 | # 6 | # This source code is licensed under the license found in the 7 | # LICENSE file in the root directory of this source tree. 8 | # 9 | 10 | import logging 11 | import time 12 | 13 | import torch 14 | import torch.nn.functional as F 15 | import torch.optim as optim 16 | 17 | from empchat.datasets.loader import TrainEnvironment 18 | from empchat.models import ( 19 | create as create_model, 20 | load as load_model, 21 | load_embeddings, 22 | save as save_model, 23 | score_candidates, 24 | ) 25 | from empchat.util import get_logger, get_opt 26 | 27 | 28 | def loss_fn(ctx, labels): 29 | assert ( 30 | ctx.size() == labels.size() 31 | ), f"ctx.size : {ctx.size()}, labels.size: {labels.size()}" 32 | # both are [batch, dim] 33 | batch_size = ctx.size(0) 34 | dot_products = ctx.mm(labels.t()) 35 | # [batch, batch] 36 | log_prob = F.log_softmax(dot_products, dim=1) 37 | targets = log_prob.new_empty(batch_size).long() 38 | targets = torch.arange(batch_size, out=targets) 39 | loss = F.nll_loss(log_prob, targets) 40 | nb_ok = (log_prob.max(dim=1)[1] == targets).float().sum() 41 | return loss, nb_ok 42 | 43 | 44 | def train(epoch, start_time, model, optimizer, opt_, data_loader): 45 | """Run through one epoch of model training with the provided data loader.""" 46 | model.train() 47 | # Initialize meters + timers 48 | train_loss = 0 49 | nb_ok = 0 50 | nb_exs = 0 51 | nb_losses = 0 52 | epoch_start = time.time() 53 | # Run one epoch 54 | for idx, ex in enumerate(data_loader, 1): 55 | params = [ 56 | field.cuda(non_blocking=True) 57 | if opt_.cuda 58 | else field 59 | if field is not None 60 | else None 61 | for field in ex 62 | ] 63 | loss, ok = loss_fn(*model(*params)) 64 | nb_ok += ok 65 | nb_exs += ex[0].size(0) 66 | optimizer.zero_grad() 67 | loss.backward() 68 | optimizer.step() 69 | train_loss += loss.sum().item() 70 | nb_losses += 1 71 | if idx % opt_.display_iter == 0 or idx == len(data_loader): 72 | avg_loss = train_loss / nb_losses 73 | acc = 100 * nb_ok / nb_exs 74 | elapsed = time.time() - start_time 75 | logging.info( 76 | f"train: Epoch = {epoch} | iter = {idx}/{len(data_loader)} | loss = " 77 | f"{avg_loss:.3f} | batch P@1 = {acc:.2f} % | elapsed time = " 78 | f"{elapsed:.2f} (s)" 79 | ) 80 | train_loss = 0 81 | nb_losses = 0 82 | epoch_elapsed = time.time() - epoch_start 83 | logging.info( 84 | f"train: Epoch {epoch:d} done. Time for epoch = {epoch_elapsed:.2f} (s)" 85 | ) 86 | 87 | 88 | def validate( 89 | epoch, 90 | model, 91 | data_loader, 92 | max_exs=100000, 93 | is_test=False, 94 | nb_candidates=100, 95 | shuffled_str="shuffled", 96 | ): 97 | model.eval() 98 | examples = 0 99 | eval_start = time.time() 100 | sum_losses = 0 101 | n_losses = 0 102 | correct = 0 103 | all_context = [] 104 | all_cands = [] 105 | n_skipped = 0 106 | dtype = model.module.opt.dataset_name 107 | for i, ex in enumerate(data_loader): 108 | batch_size = ex[0].size(0) 109 | if dtype == "reddit" and is_test and n_skipped < max_exs: 110 | n_skipped += batch_size 111 | continue 112 | params = [ 113 | field.cuda(non_blocking=True) 114 | if opt.cuda 115 | else field 116 | if field is not None 117 | else None 118 | for field in ex 119 | ] 120 | ctx, cands = model(*params) 121 | all_context.append(ctx) 122 | all_cands.append(cands) 123 | loss, nb_ok = loss_fn(ctx, cands) 124 | sum_losses += loss 125 | correct += nb_ok 126 | n_losses += 1 127 | examples += batch_size 128 | if examples >= max_exs and dtype == "reddit": 129 | break 130 | n_examples = 0 131 | if len(all_context) > 0: 132 | logging.info("Processing candidate top-K") 133 | all_context = torch.cat(all_context, dim=0) # [:50000] # [N, 2h] 134 | all_cands = torch.cat(all_cands, dim=0) # [:50000] # [N, 2h] 135 | acc_ranges = [1, 3, 10] 136 | n_correct = {r: 0 for r in acc_ranges} 137 | for context, cands in list( 138 | zip(all_context.split(nb_candidates), all_cands.split(nb_candidates)) 139 | )[:-1]: 140 | _, top_answers = score_candidates(context, cands) 141 | n_cands = cands.size(0) 142 | gt_index = torch.arange(n_cands, out=top_answers.new(n_cands, 1)) 143 | for acc_range in acc_ranges: 144 | n_acc = (top_answers[:, :acc_range] == gt_index).float().sum() 145 | n_correct[acc_range] += n_acc 146 | n_examples += n_cands 147 | accuracies = {r: 100 * n_acc / n_examples for r, n_acc in n_correct.items()} 148 | avg_loss = sum_losses / (n_losses + 0.00001) 149 | avg_acc = 100 * correct / (examples + 0.000001) 150 | valid_time = time.time() - eval_start 151 | logging.info( 152 | f"Valid ({shuffled_str}): Epoch = {epoch:d} | avg loss = {avg_loss:.3f} | " 153 | f"batch P@1 = {avg_acc:.2f} % | " 154 | + f" | ".join( 155 | f"P@{k},{nb_candidates} = {v:.2f}%" for k, v in accuracies.items() 156 | ) 157 | + f" | valid time = {valid_time:.2f} (s)" 158 | ) 159 | return avg_loss 160 | return 10 161 | 162 | 163 | def train_model(opt_): 164 | env = TrainEnvironment(opt_) 165 | dictionary = env.dict 166 | if opt_.load_checkpoint: 167 | net, dictionary = load_model(opt_.load_checkpoint, opt_) 168 | env = TrainEnvironment(opt_, dictionary) 169 | env.dict = dictionary 170 | else: 171 | net = create_model(opt_, dictionary["words"]) 172 | if opt_.embeddings and opt_.embeddings != "None": 173 | load_embeddings(opt_, dictionary["words"], net) 174 | paramnum = 0 175 | trainable = 0 176 | for name, parameter in net.named_parameters(): 177 | if parameter.requires_grad: 178 | trainable += parameter.numel() 179 | paramnum += parameter.numel() 180 | print("TRAINABLE", paramnum, trainable) 181 | if opt_.cuda: 182 | net = torch.nn.DataParallel(net) 183 | net = net.cuda() 184 | if opt_.optimizer == "adamax": 185 | lr = opt_.learning_rate or 0.002 186 | named_params_to_optimize = filter( 187 | lambda p: p[1].requires_grad, net.named_parameters() 188 | ) 189 | params_to_optimize = (p[1] for p in named_params_to_optimize) 190 | optimizer = optim.Adamax(params_to_optimize, lr=lr) 191 | if opt_.epoch_start != 0: 192 | saved_params = torch.load( 193 | opt_.load_checkpoint, map_location=lambda storage, loc: storage 194 | ) 195 | optimizer.load_state_dict(saved_params["optim_dict"]) 196 | else: 197 | lr = opt_.learning_rate or 0.01 198 | optimizer = optim.SGD( 199 | filter(lambda p: p.requires_grad, net.parameters()), lr=lr 200 | ) 201 | start_time = time.time() 202 | best_loss = float("+inf") 203 | test_data_shuffled = env.build_valid_dataloader(True) 204 | test_data_not_shuffled = env.build_valid_dataloader(False) 205 | with torch.no_grad(): 206 | validate( 207 | 0, 208 | net, 209 | test_data_shuffled, 210 | nb_candidates=opt_.hits_at_nb_cands, 211 | shuffled_str="shuffled", 212 | ) 213 | train_data = None 214 | for epoch in range(opt_.epoch_start, opt_.num_epochs): 215 | if train_data is None or opt_.dataset_name == "reddit": 216 | train_data = env.build_train_dataloader(epoch) 217 | train(epoch, start_time, net, optimizer, opt_, train_data) 218 | with torch.no_grad(): 219 | # We compute the loss both for shuffled and not shuffled case. 220 | # however, the loss that determines if the model is better is the 221 | # same as the one used for training. 222 | loss_shuffled = validate( 223 | epoch, 224 | net, 225 | test_data_shuffled, 226 | nb_candidates=opt_.hits_at_nb_cands, 227 | shuffled_str="shuffled", 228 | ) 229 | loss_not_shuffled = validate( 230 | epoch, 231 | net, 232 | test_data_not_shuffled, 233 | nb_candidates=opt_.hits_at_nb_cands, 234 | shuffled_str="not-shuffled", 235 | ) 236 | if opt_.no_shuffle: 237 | loss = loss_not_shuffled 238 | else: 239 | loss = loss_shuffled 240 | if loss < best_loss: 241 | best_loss = loss 242 | best_loss_epoch = epoch 243 | logging.info(f"New best loss, saving model to {opt_.model_file}") 244 | save_model(opt_.model_file, net, dictionary, optimizer) 245 | # Stop if it's been too many epochs since the loss has decreased 246 | if opt_.stop_crit_num_epochs != -1: 247 | if epoch - best_loss_epoch >= opt_.stop_crit_num_epochs: 248 | break 249 | return net, dictionary 250 | 251 | 252 | def main(opt_): 253 | if opt_.pretrained: 254 | net, dictionary = load_model(opt_.pretrained, opt_) 255 | net.opt.dataset_name = opt_.dataset_name 256 | net.opt.reddit_folder = opt_.reddit_folder 257 | net.opt.reactonly = opt_.reactonly 258 | net.opt.max_hist_len = opt_.max_hist_len 259 | env = TrainEnvironment(net.opt, dictionary) 260 | if opt_.cuda: 261 | net = torch.nn.DataParallel(net.cuda()) 262 | valid_data = env.build_valid_dataloader(False) 263 | test_data = env.build_valid_dataloader(False, test=True) 264 | with torch.no_grad(): 265 | logging.info("Validating on the valid set -unshuffled") 266 | validate( 267 | 0, net, valid_data, is_test=False, nb_candidates=opt_.hits_at_nb_cands 268 | ) 269 | logging.info("Validating on the hidden test set -unshuffled") 270 | validate( 271 | 0, net, test_data, is_test=True, nb_candidates=opt_.hits_at_nb_cands 272 | ) 273 | valid_data = env.build_valid_dataloader(True) 274 | test_data = env.build_valid_dataloader(True, test=True) 275 | with torch.no_grad(): 276 | logging.info("Validating on the valid set -shuffle") 277 | validate( 278 | 0, net, valid_data, is_test=False, nb_candidates=opt_.hits_at_nb_cands 279 | ) 280 | logging.info("Validating on the hidden test set -shuffle") 281 | validate( 282 | 0, net, test_data, is_test=True, nb_candidates=opt_.hits_at_nb_cands 283 | ) 284 | else: 285 | train_model(opt_) 286 | 287 | 288 | if __name__ == "__main__": 289 | opt = get_opt() 290 | # Set random state 291 | torch.manual_seed(opt.random_seed) 292 | opt.cuda = opt.cuda and torch.cuda.is_available() 293 | if opt.cuda: 294 | torch.cuda.manual_seed(opt.random_seed) 295 | # Set logging 296 | logger = get_logger(opt) 297 | main(opt) 298 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # All rights reserved. 5 | # 6 | # This source code is licensed under the license found in the 7 | # LICENSE file in the root directory of this source tree. 8 | # 9 | 10 | 11 | from setuptools import setup, find_packages 12 | import sys 13 | 14 | if sys.version_info < (3, 6): 15 | sys.exit("Sorry, Python >=3.6 is required for EmpatheticDialogues.") 16 | 17 | with open("README.md", encoding="utf8") as f: 18 | readme = f.read() 19 | 20 | with open("LICENSE") as f: 21 | license_ = f.read() 22 | 23 | setup( 24 | name="empchat", 25 | version="0.1.0", 26 | description=( 27 | "PyTorch original implementation of Towards Empathetic Open-domain " 28 | "Conversation Models: a New Benchmark and Dataset " 29 | "(https://arxiv.org/abs/1811.00207)." 30 | ), 31 | long_description=readme, 32 | url="https://arxiv.org/abs/1811.00207", 33 | license=license_, 34 | python_requires=">=3.6", 35 | packages=find_packages(), 36 | ) 37 | --------------------------------------------------------------------------------