├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── download_models.sh ├── example_input.txt ├── install_tools.sh ├── requirements.txt └── unsupervisedqa ├── __init__.py ├── baseline_translators.py ├── configs.py ├── constituency_parsing.py ├── data_classes.py ├── generate_clozes.py ├── generate_synthetic_qa_data.py ├── parsers_and_writers.py └── unmt_translation.py /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | Facebook has adopted a Code of Conduct that we expect project participants to adhere to. 2 | Please read the [full text](https://code.fb.com/codeofconduct/) 3 | so that you can understand what actions will and will not be tolerated. 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to UnsupervisedQA 2 | We want to make contributing to this project as easy and transparent as 3 | possible. 4 | 5 | ## Pull Requests 6 | We actively welcome your pull requests. 7 | 8 | 1. Fork the repo and create your branch from `master`. 9 | 2. If you've added code that should be tested, add tests. 10 | 3. If you've changed APIs, update the documentation. 11 | 4. Ensure the test suite passes. 12 | 5. Make sure your code lints. 13 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 14 | 15 | ## Contributor License Agreement ("CLA") 16 | In order to accept your pull request, we need you to submit a CLA. You only need 17 | to do this once to work on any of Facebook's open source projects. 18 | 19 | Complete your CLA here: 20 | 21 | ## Issues 22 | We use GitHub issues to track public bugs. Please ensure your description is 23 | clear and has sufficient instructions to be able to reproduce the issue. 24 | 25 | ## Coding Style 26 | We follow the PEP style guidelines and encourage you to as well. 27 | 28 | ## License 29 | By contributing to UnsupervisedQA, you agree that your contributions will be licensed 30 | under the LICENSE file in the root directory of this source tree. 31 | -------------------------------------------------------------------------------- /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 | # UnsupervisedQA 2 | 3 | Code, Data and models supporting the experiments in the ACL 2019 Paper: [Unsupervised Question Answering by Cloze Translation](https://arxiv.org/abs/1906.04980). 4 | 5 | Obtaining training data for Question Answering (QA) is time-consuming and resource-intensive, and existing QA datasets are only available for limited domains and languages. In this work, we take some of the first steps towards unsupervised QA, and develop an approach that, *without using the SQuAD training data at all*, achieves 56.4 F1 on SQuAD v1.1, and 64.5 F1 when the answer is a named entity mention. 6 | 7 |
8 |

9 | figure 10 |

11 |
12 | 13 | This repository provides code to run pre-trained models to generate sythetic question answering question data. We also make a very large synthetic training dataset for extractive question answering available. 14 | 15 | ## Dataset Downloads 16 | 17 | We make available a dataset of 4 million SQuAD-like question answering datapoints, automatically generated by the unsupervised system described in the system. 18 | 19 | The data can be downloaded [here](https://dl.fbaipublicfiles.com/UnsupervisedQA/UnsupervisedQAData.tar.gz). 20 | The data is in the SQuAD v1 format, and contains: 21 | 22 | | Fold | # Paragraphs | # QA pairs | 23 | | :-----------------: | :-----------: | :-----------: | 24 | | `unsupervised_qa_train.json` | 782,556 | 3,915,498 | 25 | | `unsupervised_qa_dev.json` | 1,000 | 4,795 | 26 | | `unsupervised_qa_test.json` | 1,000 | 4,804 | 27 | 28 | 29 | Using this training data to fine-tune BERT-Large for reading comprehension will achieve over 50.0 F1 on the SQuAD V1.1 development set using an appropriate early stopping strategy on the unsupervised_qa dev set. 30 | 31 | 32 | ## Models and Code 33 | 34 | In addition the above data, this repository provides functionality to generate synthetic training data from user-provided documents 35 | 36 | ### Installation: 37 | 38 | The code is built to run on top of [UnsupervisedMT](https://github.com/facebookresearch/UnsupervisedMT), and requires all of its its dependencies. 39 | Additional requirements are [spaCy](https://spacy.io/) (for NER and noun chunking), [attrs](https://www.attrs.org/en/stable/), and [NLTK](https://www.nltk.org/) and [allennlp](https://github.com/allenai/allennlp) (for constituency parsing). 40 | It was developed to run on Ubuntu Linux 18.04 and Python 3.7, with CUDA 9 41 | 42 | (Optionally) Create a conda environment to keep things clean: 43 | 44 | ``` 45 | conda create -n uqa37 python=3.7 && conda activate uqa37 46 | 47 | ``` 48 | 49 | The recommended way to install is shown below, which should install and handle all dependencies: 50 | ``` 51 | # clone the repo 52 | git clone https://github.com/facebookresearch/UnsupervisedQA.git 53 | cd UnsupervisedQA 54 | 55 | # install python dependencies: 56 | pip install -r requirements.txt 57 | 58 | # install UnsupervisedMT and its dependencies 59 | ./install_tools.sh 60 | ``` 61 | 62 | ### Models: 63 | 64 | Four UNMT models are made available for download 65 | 66 | * Sentence Cloze boundaries, Noun Phrase Answers 67 | * Sentence Cloze boundaries, Named Entity Answers 68 | * Sub-clause Cloze boundaries, Named Entity Answers 69 | * Sub-cluase Cloze boundaries, Named Entity Answers, Wh Heuristics (best downstream performance) 70 | 71 | The models can be downloaded using the script: 72 | 73 | ``` 74 | ./download_models.sh 75 | ``` 76 | 77 | This will download all the models and unzip them to the appropriate directory. Each unzipped model is about 850MB, so total space requirement is 3.5GB. 78 | 79 | 80 | ### Usage: 81 | 82 | You can generate reading comprehension training data using `unsupervisedqa.generate_synthetic_qa_data` 83 | 84 | This script will allow you to generate unsupervised question answering data using the `identity`, `noisy cloze` or `unsupervised NMT` methods explored in the paper, 85 | as well as specifying several different configurations (i.e. whether to use subclause shortening, use named entity answers and whether to use the wh heuristic). 86 | 87 | This script provides the following command line arguments: 88 | 89 | ``` 90 | usage: generate_synthetic_qa_data.py [-h] [--input_file_format {txt,jsonl}] 91 | [--output_file_formats OUTPUT_FILE_FORMATS] 92 | [--translation_method {identity,noisy_cloze,unmt}] 93 | [--use_subclause_clozes] 94 | [--use_named_entity_clozes] 95 | [--use_wh_heuristic] 96 | input_file output_file 97 | 98 | Generate synthetic training data for extractive QA tasks without supervision 99 | 100 | positional arguments: 101 | input_file input file, see readme for formatting info 102 | output_file Path to write generated data to, see readme for 103 | formatting info 104 | 105 | optional arguments: 106 | -h, --help show this help message and exit 107 | --input_file_format {txt,jsonl} 108 | input file format, see readme for more info, default 109 | is txt 110 | --output_file_formats OUTPUT_FILE_FORMATS 111 | comma-seperated list of output file formats, from 112 | [jsonl, squad], an output file will be created for 113 | each format. Default is 'jsonl,squad' 114 | --translation_method {identity,noisy_cloze,unmt} 115 | define the method to generate clozes -- either the 116 | Unsupervised NMT method (unmt), or the identity or 117 | noisy cloze baseline methods. UNMT is recommended for 118 | downstream performance, but the noisy_cloze is 119 | relatively stong on downstream QA and fast to 120 | generate. Default is unmt 121 | --use_subclause_clozes 122 | pass this flag to shorten clozes with constituency 123 | parsing instead of using sentence boundaries 124 | (recommended for downstream performance) 125 | --use_named_entity_clozes 126 | pass this flag to use named entity answer prior 127 | instead of noun phrases (recommended for downstream 128 | performance) 129 | --use_wh_heuristic pass this flag to use the wh-word heuristic 130 | (recommended for downstream performance). Only 131 | compatable with named entity clozes 132 | ``` 133 | 134 | 135 | 136 | The input format is specified by the `--input_file format` argument, and can either be a `.txt` file of paragraphs, one per line, for questions and answers to be generated from, 137 | or a `.jsonl` file with each line containing a json-serialised dict of the format `{"text": text of paragraph, "paragraph_id" : your unique identifier for the paragraph}` 138 | 139 | The output format can be specified by the user using the `--output_file_formats` argument. The user can choose between `jsonl` and `squad` format. Requesting the `squad` format will output a file using the squad v1.1 format, ready to be plugged into downstream extractive QA tasks. The `jsonl` format provides more metadata than the squad format, the fields are explained below: 140 | ``` 141 | { 142 | "cloze_id": unique identifier for this datapoint 143 | "paragraph": data on the paragraph this datapoint was generated from 144 | "source_text": the text from the paragraph the cloze was generated from 145 | "source_start": character index in paragraph where "source_text" starts 146 | "cloze_text": the text of the cloze question the question is generated from 147 | "answer_text": the answer text of the (cloze) question 148 | "answer_start": the character index that the answer starts at in the paragraph 149 | "constituency_parse": the constituency parse of the "source_text" if available, otherwise null, 150 | "root_label": the node label of the root of the constituency parse if available, otherwise null, 151 | "answer_type": The named entity label of the answer (if using named entity clozes) otherwise "NOUNPHRASE" 152 | "question_text": the text of the natural question, translated from "cloze_text" 153 | } 154 | ``` 155 | 156 | A working example to produce unsupervised NMT-translated questions using the model trained with wh heuristics, named entity answers, subclause shortening is below: 157 | 158 | ``` 159 | python -m unsupervisedqa.generate_synthetic_qa_data example_input.txt example_output \ 160 | --input_file_format "txt" \ 161 | --output_file_format "jsonl,squad" \ 162 | --translation_method unmt \ 163 | --use_named_entity_clozes \ 164 | --use_subclause_clozes \ 165 | --use_wh_heuristic 166 | ``` 167 | 168 | ### I'm running out of GPU memory 169 | 170 | The repository requires a CUDA-enabled GPU (this is a requirement of UnsupervisedMT), but you can reduce the amount of GPU memory required 171 | by adjusting the batch sizes. This can be done by modifying `unsupervisedqa/configs.py` file, adjusting `CONSTITUENCY_BATCH_SIZE` and `UNMT_BATCH_SIZE`. 172 | 173 | ### Training Your own question translation models 174 | 175 | This repository only provides functionality to run pre-trained unsupervised question translation models in the paper. 176 | For users who want to train new question translation models, they should use the training functionality in [UnsupervisedMT](https://github.com/facebookresearch/UnsupervisedMT), or consider the newer and more powerful [XLM](https://github.com/facebookresearch/XLM) repository. 177 | 178 | To train question translation models in [UnsupervisedMT](https://github.com/facebookresearch/UnsupervisedMT), first prepare large corpora of cloze questions (potentially using the functionality in this repository) and a large corpus of natural questions. 179 | Preprocess these corpora by adapting [UnsupervisedMT/NMT/get_data_enfr.sh](https://github.com/facebookresearch/UnsupervisedMT/blob/master/NMT/get_data_enfr.sh), and train using the example script in [UnsupervisedMT/README](https://github.com/facebookresearch/UnsupervisedMT#train-the-nmt-model), with appropriate edits to the args (e.g en->cloze and fr->question) and paths. 180 | 181 | ## References 182 | 183 | Please cite [[1]](https://arxiv.org/abs/1906.04980) and [[2]](https://arxiv.org/abs/1804.07755) if you found the resources in this repository useful. 184 | 185 | ### Unsupervised Question Answering by Cloze Translation 186 | 187 | [1] P. Lewis, L. Denoyer, S. Riedel [*Unsupervised Question Answering by Cloze Translation*](https://arxiv.org/abs/1906.04980) 188 | 189 | 190 | ``` 191 | @inproceedings{lewis2019unsupervisedqa, 192 | title={Unsupervised Question Answering by Cloze Translation}, 193 | author={Lewis, Patrick and Denoyer, Ludovic and Riedel, Sebastian}, 194 | booktitle={Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, 195 | year={2019} 196 | } 197 | ``` 198 | 199 | ### Phrase-Based \& Neural Unsupervised Machine Translation 200 | 201 | [2] G. Lample, M. Ott, A. Conneau, L. Denoyer, MA. Ranzato [*Phrase-Based & Neural Unsupervised Machine Translation*](https://arxiv.org/abs/1804.07755) 202 | 203 | ``` 204 | @inproceedings{lample2018phrase, 205 | title={Phrase-Based \& Neural Unsupervised Machine Translation}, 206 | author={Lample, Guillaume and Ott, Myle and Conneau, Alexis and Denoyer, Ludovic and Ranzato, Marc'Aurelio}, 207 | booktitle={Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing (EMNLP)}, 208 | year={2018} 209 | } 210 | ``` 211 | 212 | ## License 213 | 214 | See the [LICENSE](LICENSE) file for more details. 215 | 216 | ## Troubleshooting 217 | 218 | If you run into problems with installing dependencies (particularly allennlp) installing libffi may help: 219 | 220 | ``` 221 | apt-get install libffi6 libffi-dev 222 | ``` -------------------------------------------------------------------------------- /download_models.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Copyright (c) 2019-present, Facebook, Inc. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | # 8 | HERE=`dirname "$0"` 9 | HERE_ABS=`( cd "${HERE}" && pwd )` 10 | DATA_DIR=${HERE_ABS}/data 11 | BUCKET="https://dl.fbaipublicfiles.com/UnsupervisedQA" 12 | 13 | mkdir -p ${DATA_DIR} 14 | 15 | MODEL="subclause_ne_wh_heuristic" 16 | echo "Downloading Model: ${MODEL}" 17 | wget -P ${DATA_DIR} "${BUCKET}/${MODEL}.tar.gz" 18 | tar -zxvf "${DATA_DIR}/${MODEL}.tar.gz" -C ${DATA_DIR} 19 | rm "${DATA_DIR}/${MODEL}.tar.gz" 20 | 21 | MODEL="subclause_ne" 22 | echo "Downloading Model: ${MODEL}" 23 | wget -P ${DATA_DIR} "${BUCKET}/${MODEL}.tar.gz" 24 | tar -zxvf "${DATA_DIR}/${MODEL}.tar.gz" -C ${DATA_DIR} 25 | rm "${DATA_DIR}/${MODEL}.tar.gz" 26 | 27 | 28 | MODEL="sentence_ne" 29 | echo "Downloading Model: ${MODEL}" 30 | wget -P ${DATA_DIR} "${BUCKET}/${MODEL}.tar.gz" 31 | tar -zxvf "${DATA_DIR}/${MODEL}.tar.gz" -C ${DATA_DIR} 32 | rm "${DATA_DIR}/${MODEL}.tar.gz" 33 | 34 | 35 | MODEL="sentence_np" 36 | echo "Downloading Model: ${MODEL}" 37 | wget -P ${DATA_DIR} "${BUCKET}/${MODEL}.tar.gz" 38 | tar -zxvf "${DATA_DIR}/${MODEL}.tar.gz" -C ${DATA_DIR} 39 | rm "${DATA_DIR}/${MODEL}.tar.gz" 40 | 41 | 42 | -------------------------------------------------------------------------------- /example_input.txt: -------------------------------------------------------------------------------- 1 | Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. The American Football Conference (AFC) champions Denver Broncos defeated the National Football Conference (NFC) champions Carolina Panthers, 24–10. The game was played on February 7, 2016, at Levi's Stadium in Santa Clara, California, in the Bay Area. As this was the 50th Super Bowl game, the league emphasized the "golden anniversary" with various gold-themed initiatives during the 2015 season, as well as suspending the tradition of naming each Super Bowl game with Roman numerals (under which the game would have been known as "Super Bowl L"), so the logo could prominently feature the Arabic numerals 50. 2 | The Panthers finished the regular season with a 15–1 record, racking up the league's top offense, and quarterback Cam Newton was named the NFL Most Valuable Player (MVP). They defeated the Arizona Cardinals 49–15 in the NFC Championship Game and advanced to their second Super Bowl appearance since the franchise began playing in 1995. The Broncos finished the regular season with a 12–4 record, bolstered by having the league's top defense. The Broncos defeated the defending Super Bowl champion New England Patriots 20–18 in the AFC Championship Game joining the Patriots, Dallas Cowboys, and Pittsburgh Steelers as one of four teams that have made eight appearances in the Super Bowl. This record would later be broken the next season, in 2017, when the Patriots advanced to their ninth Super Bowl appearance in Super Bowl LI. 3 | The Broncos took an early lead in Super Bowl 50 and never trailed.[7] Denver recorded seven sacks and forced four turnovers.[8] Carolina likewise kept pace by recording five sacks and forcing two turnovers. Denver linebacker Von Miller was named Super Bowl MVP.[9][10] This game was also the final game of Peyton Manning's career; the Broncos quarterback, who also won Super Bowl XLI, announced his retirement in March 2016. 4 | CBS' broadcast of the game was the third most-watched program in American television history with an average of 111.9 million viewers. The network charged an average of $5 million for a 30-second commercial during the game.[12][13] It remains the highest-rated program in the history of CBS. The Super Bowl 50 halftime show was headlined by Coldplay,[14] with special guest performers Beyoncé and Bruno Mars. -------------------------------------------------------------------------------- /install_tools.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Copyright (c) 2019-present, Facebook, Inc. 3 | # All rights reserved. 4 | # 5 | # This source code is licensed under the license found in the 6 | # LICENSE file in the root directory of this source tree. 7 | # 8 | set -e 9 | 10 | # 11 | # Initialize tools and data paths 12 | # 13 | 14 | # main paths 15 | HERE=`dirname "$0"` 16 | HERE_ABS=`( cd "${HERE}" && pwd )` 17 | UNSUPERVISED_NMT_PATH=${HERE_ABS}/UnsupervisedMT/NMT 18 | TOOLS_PATH=${UNSUPERVISED_NMT_PATH}/tools 19 | 20 | cd ${HERE_ABS} 21 | 22 | # Download UNMT 23 | if [ ! -d "${UNSUPERVISED_NMT_PATH}" ]; then 24 | echo "Cloning Unsupervised NMT from GitHub repository..." 25 | git clone https://github.com/facebookresearch/UnsupervisedMT.git 26 | fi 27 | echo "Unsupervised NMT found in: ${UNSUPERVISED_NMT_PATH}" 28 | 29 | 30 | # create paths 31 | mkdir -p $TOOLS_PATH 32 | 33 | # UnsupervisedMT 34 | 35 | # moses 36 | MOSES=$TOOLS_PATH/mosesdecoder 37 | 38 | 39 | # fastBPE 40 | FASTBPE_DIR=$TOOLS_PATH/fastBPE 41 | FASTBPE=$FASTBPE_DIR/fast 42 | 43 | # fastText 44 | FASTTEXT_DIR=$TOOLS_PATH/fastText 45 | FASTTEXT=$FASTTEXT_DIR/fasttext 46 | 47 | 48 | # Download Moses 49 | cd $TOOLS_PATH 50 | if [ ! -d "$MOSES" ]; then 51 | echo "Cloning Moses from GitHub repository..." 52 | git clone https://github.com/moses-smt/mosesdecoder.git 53 | fi 54 | echo "Moses found in: $MOSES" 55 | 56 | # Download fastBPE 57 | cd $TOOLS_PATH 58 | if [ ! -d "$FASTBPE_DIR" ]; then 59 | echo "Cloning fastBPE from GitHub repository..." 60 | git clone https://github.com/glample/fastBPE 61 | fi 62 | echo "fastBPE found in: $FASTBPE_DIR" 63 | 64 | # Compile fastBPE 65 | cd $TOOLS_PATH 66 | if [ ! -f "$FASTBPE" ]; then 67 | echo "Compiling fastBPE..." 68 | cd $FASTBPE_DIR 69 | g++ -std=c++11 -pthread -O3 fastBPE/main.cc -IfastBPE -o fast 70 | fi 71 | echo "fastBPE compiled in: $FASTBPE" 72 | 73 | # Download fastText 74 | cd $TOOLS_PATH 75 | if [ ! -d "$FASTTEXT_DIR" ]; then 76 | echo "Cloning fastText from GitHub repository..." 77 | git clone https://github.com/facebookresearch/fastText.git 78 | fi 79 | echo "fastText found in: $FASTTEXT_DIR" 80 | 81 | # Compile fastText 82 | cd $TOOLS_PATH 83 | if [ ! -f "$FASTTEXT" ]; then 84 | echo "Compiling fastText..." 85 | cd $FASTTEXT_DIR 86 | make 87 | fi 88 | echo "fastText compiled in: $FASTTEXT" 89 | 90 | # download the spacy model 91 | echo "Downloading spacy model" 92 | python -m spacy download en 93 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | nltk==3.4.5 2 | numpy==1.15.4 3 | torch==0.4.1.post2 4 | spacy==2.0.16 5 | attrs==18.1 6 | allennlp==0.7.1 7 | -------------------------------------------------------------------------------- /unsupervisedqa/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Facebook, Inc. 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 | # -------------------------------------------------------------------------------- /unsupervisedqa/baseline_translators.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Facebook, Inc. 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 | Functionality to implement baseline cloze question translators, 9 | referred to as "identity" and "noisy cloze" baselien methods in the publication 10 | """ 11 | from .configs import HEURISTIC_CLOZE_TYPE_QUESTION_MAP 12 | import random 13 | import numpy as np 14 | import nltk 15 | 16 | 17 | class NoiserParams(object): 18 | word_shuffle = 3 19 | word_dropout = 0.1 20 | word_blank = 0.2 21 | blank_word = 'BLANKWORD' 22 | 23 | 24 | def _tokenize(x): 25 | return nltk.word_tokenize(x) 26 | 27 | 28 | def _word_shuffle(tokens, noiser_params): 29 | noise = np.random.uniform(0, noiser_params.word_shuffle, size=(len(tokens),)) 30 | permutation = np.argsort(np.arange(len(tokens)) + noise) 31 | return list(np.array(tokens)[permutation]) 32 | 33 | 34 | def _word_dropout(tokens, noiser_params): 35 | keep = np.random.rand(len(tokens), ) >= noiser_params.word_dropout 36 | return [w for i, w in enumerate(tokens) if keep[i]] 37 | 38 | 39 | def _word_blank(tokens, noiser_params): 40 | keep = np.random.rand(len(tokens), ) >= noiser_params.word_blank 41 | return [w if keep[i] else noiser_params.blank_word for i, w in enumerate(tokens)] 42 | 43 | 44 | def _add_noise(words, noiser_params): 45 | words = _word_shuffle(words, noiser_params) 46 | words = _word_dropout(words, noiser_params) 47 | words = _word_blank(words, noiser_params) 48 | return words 49 | 50 | 51 | def _get_wh_word(cloze, wh_heuristic): 52 | if wh_heuristic: 53 | repl = random.choice(HEURISTIC_CLOZE_TYPE_QUESTION_MAP[cloze.answer_type]) 54 | else: 55 | repl = random.choice(['Who', 'What', 'When', 'Where', 'How']) 56 | return repl 57 | 58 | 59 | def _add_wh(tokens, cloze, wh_heuristic): 60 | wh = _get_wh_word(cloze, wh_heuristic) 61 | return [wh] + tokens 62 | 63 | 64 | def _replace_mask(cloze, repl): 65 | return cloze.source_text[:cloze.answer_start] + repl + cloze.source_text[ 66 | cloze.answer_start + len(cloze.answer_text):] 67 | 68 | 69 | def _add_q_mark_and_fix_spaces(q): 70 | return q.replace(' ', ' ').rstrip(' ,.') + '?' 71 | 72 | 73 | def noisy_cloze_translation(cloze, wh_heuristic): 74 | cloze_no_mask = _replace_mask(cloze, ' ') 75 | cloze_no_mask_tokens = _tokenize(cloze_no_mask) 76 | noisy_cloze_tokens = _add_noise(cloze_no_mask_tokens, noiser_params=NoiserParams()) 77 | return _add_q_mark_and_fix_spaces(' '.join(_add_wh(noisy_cloze_tokens, cloze, wh_heuristic))) 78 | 79 | 80 | def identity_translation(cloze, wh_heuristic): 81 | repl = _get_wh_word(cloze, wh_heuristic) 82 | q = _replace_mask(cloze, repl) 83 | return _add_q_mark_and_fix_spaces(q) 84 | 85 | 86 | -------------------------------------------------------------------------------- /unsupervisedqa/configs.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Facebook, Inc. 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 | Config file for UnsupervisedQA 9 | """ 10 | import os 11 | 12 | HERE = os.path.dirname(os.path.realpath(__file__)) 13 | SEED = 10 14 | 15 | 16 | 17 | 18 | 19 | ## Sensible filter thresholds: 20 | ## Cloze selection criteria 21 | MIN_CLOZE_WORD_LEN = 5 22 | MAX_CLOZE_WORD_LEN = 40 23 | MIN_CLOZE_WORDSIZE = 1 24 | MAX_CLOZE_WORDSIZE = 20 25 | MIN_CLOZE_CHAR_LEN = 30 26 | MAX_CLOZE_CHAR_LEN = 300 27 | MIN_ANSWER_WORD_LEN = 1 28 | MAX_ANSWER_WORD_LEN = 20 29 | MIN_ANSWER_CHAR_LEN = 3 30 | MAX_ANSWER_CHAR_LEN = 50 31 | ## remove with more characters than this 32 | MAX_PARAGRAPH_CHAR_LEN_THRESHOLD = 2000 33 | MAX_QUESTION_CHAR_LEN_THRESHOLD = 200 34 | ## remove items with more words than this 35 | MAX_PARAGRAPH_WORD_LEN_THRESHOLD = 400 36 | MAX_QUESTION_WORD_LEN_THRESHOLD = 40 37 | ## remove items that have words with more characters than this 38 | MAX_PARAGRAPH_WORDSIZE_THRESHOLD = 20 39 | MAX_QUESTION_WORDSIZE_THRESHOLD = 20 40 | 41 | 42 | ## Spacy Configs: 43 | SPACY_MODEL = 'en' 44 | 45 | ## constituency parser configs: 46 | CONSTITUENCY_MODEL = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo-constituency-parser-2018.03.14.tar.gz" 47 | CONSTITUENCY_BATCH_SIZE = 32 48 | CONSTITUENCY_CUDA = 0 49 | CLOZE_SYNTACTIC_TYPES = {'S', } 50 | 51 | 52 | # UNMT configs: 53 | PATH_TO_UNMT = os.path.join(HERE, '../UnsupervisedMT/NMT') 54 | UNMT_DATA_DIR = os.path.join(HERE, '../data') 55 | UNMT_MODEL_SUBCLAUSE_NE_WH_HEURISTIC = os.path.join(UNMT_DATA_DIR, 'subclause_ne_wh_heuristic') 56 | UNMT_MODEL_SUBCLAUSE_NE = os.path.join(UNMT_DATA_DIR, 'subclause_ne') 57 | UNMT_MODEL_SENTENCE_NE = os.path.join(UNMT_DATA_DIR, 'sentence_ne') 58 | UNMT_MODEL_SENTENCE_NP = os.path.join(UNMT_DATA_DIR, 'sentence_np') 59 | 60 | 61 | # UNMT Tools: 62 | TOOLS_DIR = os.path.join(PATH_TO_UNMT, 'tools') 63 | MOSES_DIR = os.path.join(TOOLS_DIR, 'mosesdecoder') 64 | FASTBPE_DIR = os.path.join(TOOLS_DIR, 'fastBPE') 65 | N_THREADS_PREPRO = 16 66 | UNMT_BEAM_SIZE = 0 67 | UNMT_BATCH_SIZE = 30 68 | 69 | 70 | # CLOZE MASKS: 71 | NOUNPHRASE_LABEL = 'NOUNPHRASE' 72 | CLOZE_MASKS = { 73 | 'PERSON': 'IDENTITYMASK', 74 | 'NORP': 'IDENTITYMASK', 75 | 'FAC': 'PLACEMASK', 76 | 'ORG': 'IDENTITYMASK', 77 | 'GPE': 'PLACEMASK', 78 | 'LOC': 'PLACEMASK', 79 | 'PRODUCT': 'THINGMASK', 80 | 'EVENT': 'THINGMASK', 81 | 'WORKOFART': 'THINGMASK', 82 | 'WORK_OF_ART': 'THINGMASK', 83 | 'LAW': 'THINGMASK', 84 | 'LANGUAGE': 'THINGMASK', 85 | 'DATE': 'TEMPORALMASK', 86 | 'TIME': 'TEMPORALMASK', 87 | 'PERCENT': 'NUMERICMASK', 88 | 'MONEY': 'NUMERICMASK', 89 | 'QUANTITY': 'NUMERICMASK', 90 | 'ORDINAL': 'NUMERICMASK', 91 | 'CARDINAL': 'NUMERICMASK', 92 | NOUNPHRASE_LABEL: 'NOUNPHRASEMASK' 93 | } 94 | HEURISTIC_CLOZE_TYPE_QUESTION_MAP = { 95 | 'PERSON': ['Who', ], 96 | 'NORP': ['Who', ], 97 | 'FAC': ['Where', ], 98 | 'ORG': ['Who', ], 99 | 'GPE': ['Where', ], 100 | 'LOC': ['Where', ], 101 | 'PRODUCT': ['What', ], 102 | 'EVENT': ['What', ], 103 | 'WORKOFART': ['What', ], 104 | 'WORK_OF_ART': ['What', ], 105 | 'LAW': ['What', ], 106 | 'LANGUAGE': ['What', ], 107 | 'DATE': ['When', ], 108 | 'TIME': ['When', ], 109 | 'PERCENT': ['How much', 'How many'], 110 | 'MONEY': ['How much', 'How many'], 111 | 'QUANTITY': ['How much', 'How many'], 112 | 'ORDINAL': ['How much', 'How many'], 113 | 'CARDINAL': ['How much', 'How many'], 114 | } -------------------------------------------------------------------------------- /unsupervisedqa/constituency_parsing.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Facebook, Inc. 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 | Functionality to do constituency parsing, used for shortening cloze questions. We use AllenNLP and the 9 | Parsing model from Stern et. al, 2018 "A Minimal Span-Based Neural Constituency Parser" arXiv:1705.03919 10 | """ 11 | import attr 12 | from allennlp.models.archival import load_archive 13 | from allennlp.predictors import Predictor 14 | from tqdm import tqdm 15 | from nltk import Tree 16 | from .configs import CONSTITUENCY_MODEL, CONSTITUENCY_BATCH_SIZE, CONSTITUENCY_CUDA, CLOZE_SYNTACTIC_TYPES 17 | from .generate_clozes import mask_answer 18 | from .data_classes import Cloze 19 | 20 | 21 | def _load_constituency_parser(): 22 | archive = load_archive(CONSTITUENCY_MODEL, cuda_device=CONSTITUENCY_CUDA) 23 | return Predictor.from_archive(archive, 'constituency-parser') 24 | 25 | 26 | def get_constituency_parsed_clozes(clozes, predictor=None, verbose=True, desc='Running Constituency Parsing'): 27 | if predictor is None: 28 | predictor = _load_constituency_parser() 29 | jobs = range(0, len(clozes), CONSTITUENCY_BATCH_SIZE) 30 | for i in tqdm(jobs, desc=desc, ncols=80) if verbose else jobs: 31 | input_batch = clozes[i: i + CONSTITUENCY_BATCH_SIZE] 32 | output_batch = predictor.predict_batch_json([{'sentence': c.source_text} for c in input_batch]) 33 | for c, t in zip(input_batch, output_batch): 34 | root = _get_root_type(t['trees']) 35 | if root in CLOZE_SYNTACTIC_TYPES: 36 | c_with_parse = attr.evolve(c, constituency_parse=t['trees'], root_label=root) 37 | yield c_with_parse 38 | 39 | 40 | def _get_root_type(tree): 41 | try: 42 | t = Tree.fromstring(tree) 43 | label = t.label() 44 | except: 45 | label = 'FAIL' 46 | return label 47 | 48 | 49 | def _get_sub_clauses(root, clause_labels): 50 | """Simplify a sentence by getting clauses""" 51 | subtexts = [] 52 | for current in root.subtrees(): 53 | if current.label() in clause_labels: 54 | subtexts.append(' '.join(current.leaves())) 55 | return subtexts 56 | 57 | 58 | def _tokens2spans(sentence, tokens): 59 | off = 0 60 | spans = [] 61 | for t in tokens: 62 | span_start = sentence[off:].index(t) + off 63 | spans.append((span_start, span_start + len(t))) 64 | off = spans[-1][-1] 65 | for t, (s, e) in zip(tokens, spans): 66 | assert sentence[s:e] == t 67 | return spans 68 | 69 | 70 | def _subseq2sentence(sentence, tokens, token_spans, subsequence): 71 | subsequence_tokens = subsequence.split(' ') 72 | for ind in (i for i, t in enumerate(tokens) if t == subsequence_tokens[0]): 73 | if tokens[ind: ind + len(subsequence_tokens)] == subsequence_tokens: 74 | return sentence[token_spans[ind][0]:token_spans[ind + len(subsequence_tokens) - 1][1]] 75 | raise Exception('Failed to repair sentence from token list') 76 | 77 | 78 | def get_sub_clauses(sentence, tree): 79 | clause_labels = CLOZE_SYNTACTIC_TYPES 80 | root = Tree.fromstring(tree) 81 | subs = _get_sub_clauses(root, clause_labels) 82 | tokens = root.leaves() 83 | token_spans = _tokens2spans(sentence, tokens) 84 | return [_subseq2sentence(sentence, tokens, token_spans, sub) for sub in subs] 85 | 86 | 87 | def shorten_cloze(cloze): 88 | """Return a list of shortened cloze questions from the original cloze question""" 89 | simple_clozes = [] 90 | try: 91 | subs = get_sub_clauses(cloze.source_text, cloze.constituency_parse) 92 | subs = sorted(subs) 93 | for sub in subs: 94 | if sub != cloze.source_text: 95 | sub_start_index = cloze.source_text.index(sub) 96 | sub_answer_start_index = cloze.answer_start - sub_start_index 97 | good_start = 0 <= sub_answer_start_index <= len(sub) 98 | good_end = 0 <= sub_answer_start_index + len(cloze.answer_text) <= len(sub) 99 | if good_start and good_end: 100 | simple_clozes.append( 101 | Cloze( 102 | cloze_id=cloze.cloze_id + f'_{len(simple_clozes)}', 103 | paragraph=cloze.paragraph, 104 | source_text=sub, 105 | source_start=cloze.source_start + sub_start_index, 106 | cloze_text=mask_answer(sub, cloze.answer_text, sub_answer_start_index, cloze.answer_type), 107 | answer_text=cloze.answer_text, 108 | answer_start=sub_answer_start_index, 109 | constituency_parse=None, 110 | root_label=None, 111 | answer_type=cloze.answer_type, 112 | question_text=None 113 | ) 114 | ) 115 | except: 116 | print(f'Failed to parse cloze: ID {cloze.cloze_id} Text: {cloze.source_text}') 117 | return simple_clozes 118 | -------------------------------------------------------------------------------- /unsupervisedqa/data_classes.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Facebook, Inc. 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 | Data classes used in UnsupervisedQA are defined here 9 | """ 10 | import attr 11 | 12 | 13 | @attr.s(hash=True) 14 | class Paragraph: 15 | paragraph_id = attr.ib() 16 | text = attr.ib() 17 | 18 | 19 | @attr.s(hash=True) 20 | class Cloze: 21 | cloze_id = attr.ib() 22 | paragraph = attr.ib() 23 | source_text = attr.ib() 24 | source_start = attr.ib() 25 | cloze_text = attr.ib() 26 | answer_text = attr.ib() 27 | answer_start = attr.ib() 28 | constituency_parse = attr.ib() 29 | root_label = attr.ib() 30 | answer_type = attr.ib() 31 | question_text = attr.ib() 32 | -------------------------------------------------------------------------------- /unsupervisedqa/generate_clozes.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Facebook, Inc. 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 | Functionality to extract cloze questions from paragraphs of text 9 | """ 10 | import spacy 11 | import hashlib 12 | from .configs import MIN_ANSWER_CHAR_LEN, MAX_ANSWER_CHAR_LEN,\ 13 | MIN_ANSWER_WORD_LEN, MAX_ANSWER_WORD_LEN, CLOZE_MASKS, MIN_CLOZE_WORD_LEN, MAX_CLOZE_WORD_LEN,\ 14 | MIN_CLOZE_WORDSIZE, MAX_CLOZE_WORDSIZE, MIN_CLOZE_CHAR_LEN, MAX_CLOZE_CHAR_LEN, \ 15 | MAX_QUESTION_WORDSIZE_THRESHOLD, MAX_PARAGRAPH_WORDSIZE_THRESHOLD, MAX_PARAGRAPH_CHAR_LEN_THRESHOLD, \ 16 | MAX_PARAGRAPH_WORD_LEN_THRESHOLD, MAX_QUESTION_CHAR_LEN_THRESHOLD, MAX_QUESTION_WORD_LEN_THRESHOLD, \ 17 | NOUNPHRASE_LABEL, SPACY_MODEL 18 | from .data_classes import Cloze 19 | 20 | nlp = spacy.load(SPACY_MODEL) 21 | 22 | 23 | def mask_answer(text, answer_text, answer_start, answer_type): 24 | before, after = text[:answer_start], text[answer_start + len(answer_text):] 25 | return before + CLOZE_MASKS[answer_type] + after 26 | 27 | 28 | def noun_phrase_answer_generator(sent): 29 | return [(n_p.text, n_p.start_char - sent.start_char, NOUNPHRASE_LABEL) for n_p in sent.noun_chunks] 30 | 31 | 32 | def named_entity_answer_generator(sent): 33 | return [(e.text, e.start_char - sent.start_char, e.label_) for e in sent.ents] 34 | 35 | 36 | def is_appropriate_cloze(sentence): 37 | good_char_len = MIN_CLOZE_CHAR_LEN < len(sentence) < MAX_CLOZE_CHAR_LEN 38 | no_links = not (('https://' in sentence) or ('http://' in sentence)) 39 | tokens = sentence.split() 40 | good_word_lens = all([MIN_CLOZE_WORDSIZE <= len(tok) <= MAX_CLOZE_WORDSIZE for tok in tokens]) 41 | good_num_tokens = MIN_CLOZE_WORD_LEN <= len(tokens) <= MAX_CLOZE_WORD_LEN 42 | return good_char_len and no_links and good_word_lens and good_num_tokens 43 | 44 | 45 | def is_appropriate_answer(answer_text): 46 | correct_char_length = MIN_ANSWER_CHAR_LEN <= len(answer_text) <= MAX_ANSWER_CHAR_LEN 47 | correct_word_length = MIN_ANSWER_WORD_LEN <= len(answer_text.split()) <= MAX_ANSWER_WORD_LEN 48 | return correct_char_length and correct_word_length 49 | 50 | 51 | def is_appropriate_squad_datapoint(question_text, answer_text, paragraph_text): 52 | p_char_len_good = len(paragraph_text) <= MAX_PARAGRAPH_CHAR_LEN_THRESHOLD 53 | p_word_len_good = len(paragraph_text.split()) <= MAX_PARAGRAPH_WORD_LEN_THRESHOLD 54 | p_wordsize_good = all([len(w) <= MAX_PARAGRAPH_WORDSIZE_THRESHOLD for w in paragraph_text.split()]) 55 | p_good = p_char_len_good and p_word_len_good and p_wordsize_good 56 | 57 | q_char_len_good = len(question_text) <= MAX_QUESTION_CHAR_LEN_THRESHOLD 58 | q_word_len_good = len(question_text.split()) <= MAX_QUESTION_WORD_LEN_THRESHOLD 59 | q_wordsize_good = all([len(w) <= MAX_QUESTION_WORDSIZE_THRESHOLD for w in question_text.split()]) 60 | q_good = q_char_len_good and q_word_len_good and q_wordsize_good 61 | 62 | a_char_len_good = MIN_ANSWER_CHAR_LEN <= len(answer_text) <= MAX_ANSWER_CHAR_LEN 63 | a_word_len_good = MIN_ANSWER_WORD_LEN <= len(answer_text.split()) <= MAX_ANSWER_WORD_LEN 64 | a_good = a_char_len_good and a_word_len_good 65 | return p_good and q_good and a_good 66 | 67 | 68 | def get_cloze_id(paragraph_text, sentence_text, answer_text): 69 | rep = paragraph_text + sentence_text + answer_text 70 | return hashlib.sha1(rep.encode()).hexdigest() 71 | 72 | 73 | def generate_clozes_from_paragraph(paragraph, answer_generator): 74 | clozes = [] 75 | para_doc = nlp(paragraph.text) 76 | for sentence in para_doc.sents: 77 | is_good = is_appropriate_cloze(sentence.text) 78 | if is_good: 79 | answers = answer_generator(sentence) 80 | for answer_text, answer_start, answer_type in answers: 81 | if is_appropriate_answer(answer_text): 82 | yield Cloze( 83 | cloze_id=get_cloze_id(paragraph.text, sentence.text, answer_text), 84 | paragraph=paragraph, 85 | source_text=sentence.text, 86 | source_start=sentence.start_char, 87 | cloze_text=mask_answer(sentence.text, answer_text, answer_start, answer_type), 88 | answer_text=answer_text, 89 | answer_start=answer_start, 90 | constituency_parse=None, 91 | root_label=None, 92 | answer_type=answer_type, 93 | question_text=None 94 | ) 95 | return clozes 96 | -------------------------------------------------------------------------------- /unsupervisedqa/generate_synthetic_qa_data.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Facebook, Inc. 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 | Main interface to user 9 | """ 10 | import attr 11 | import argparse 12 | import os 13 | from .configs import UNMT_MODEL_SENTENCE_NE, \ 14 | UNMT_MODEL_SENTENCE_NP, UNMT_MODEL_SUBCLAUSE_NE, \ 15 | UNMT_MODEL_SUBCLAUSE_NE_WH_HEURISTIC 16 | from .parsers_and_writers import parse_paragraphs_from_jsonl, parse_paragraphs_from_txt, dump_clozes, clozes2squadformat 17 | from .generate_clozes import generate_clozes_from_paragraph, named_entity_answer_generator as ne_answer_gen, \ 18 | noun_phrase_answer_generator as np_answer_gen, is_appropriate_squad_datapoint 19 | from .constituency_parsing import get_constituency_parsed_clozes, shorten_cloze 20 | from .unmt_translation import get_unmt_questions_for_clozes 21 | from .baseline_translators import identity_translation, noisy_cloze_translation 22 | 23 | 24 | def _check_args(args): 25 | if args.use_wh_heuristic: 26 | assert args.use_named_entity_clozes, \ 27 | 'Wh heuristics can only be used in conjunction with Named Entity Answers, Pass --use_named_entity_clozes' 28 | 29 | if args.use_subclause_clozes: 30 | assert args.use_named_entity_clozes, \ 31 | "Subclause clozes can only be used in conjunction with Named Entity Answers Pass --use_named_entity_clozes" 32 | 33 | assert os.path.exists(args.input_file), f"Input File: {args.input_file} does not exist" 34 | 35 | for o in args.output_file_formats.split(','): 36 | assert o in {'jsonl', 'squad'},\ 37 | f"Unrecognised output file format requested: {o}, must be one of ['jsonl', 'squad'] " 38 | if o == 'jsonl': 39 | p = args.output_file + '.unsupervised_qa.jsonl' 40 | else: 41 | p = args.output_file + '.squad.json' 42 | assert not os.path.exists(p), f'Output file {p} already exists, terminating...' 43 | 44 | # check for downloaded models before allowing unmt 45 | def _assert_exists(path): 46 | assert os.path.exists(path), \ 47 | f"Requested model could not be found at {path}, download it using `download_models.sh`" 48 | 49 | if args.translation_method == 'unmt': 50 | if args.use_subclause_clozes: 51 | if args.use_wh_heuristic: 52 | _assert_exists(UNMT_MODEL_SUBCLAUSE_NE_WH_HEURISTIC) 53 | else: 54 | _assert_exists(UNMT_MODEL_SUBCLAUSE_NE) 55 | elif args.use_named_entity_clozes: 56 | _assert_exists(UNMT_MODEL_SENTENCE_NE) 57 | else: 58 | _assert_exists(UNMT_MODEL_SENTENCE_NP) 59 | 60 | 61 | def get_questions_for_clozes(clozes, 62 | subclause_clozes, 63 | ne_answers, 64 | wh_heuristic, 65 | translation_method): 66 | 67 | if translation_method == 'identity': 68 | clozes_with_questions = [attr.evolve(c, question_text=identity_translation(c, wh_heuristic)) for c in clozes] 69 | 70 | elif translation_method == 'noisy_cloze': 71 | clozes_with_questions = [attr.evolve(c, question_text=noisy_cloze_translation(c, wh_heuristic)) for c in clozes] 72 | 73 | elif translation_method == 'unmt': 74 | clozes_with_questions = get_unmt_questions_for_clozes( 75 | clozes, subclause_clozes, ne_answers, wh_heuristic) 76 | else: 77 | raise Exception(f'Unrecognised translation type: {translation_method}') 78 | 79 | return clozes_with_questions 80 | 81 | 82 | def generate_synthetic_training_data(args): 83 | _check_args(args) 84 | 85 | with open(args.input_file) as f: 86 | if args.input_file_format == 'jsonl': 87 | paragraphs = parse_paragraphs_from_jsonl(f) 88 | else: 89 | paragraphs = parse_paragraphs_from_txt(f) 90 | paragraphs = list(paragraphs) 91 | 92 | print('=' * 50) 93 | print(f'Parsed {len(paragraphs)} paragraphs from {args.input_file}') 94 | print('=' * 50) 95 | 96 | # Create clozes: 97 | answer_generator = ne_answer_gen if args.use_named_entity_clozes else np_answer_gen 98 | clozes = [c for p in paragraphs for c in generate_clozes_from_paragraph(p, answer_generator)] 99 | 100 | if args.use_subclause_clozes: 101 | syntax_clozes = get_constituency_parsed_clozes(clozes) 102 | clozes = [short_cloze for cloze in syntax_clozes for short_cloze in shorten_cloze(cloze)] 103 | #clozes = list(get_constituency_parsed_clozes(clozes)) 104 | print('=' * 50) 105 | print(f'{len(clozes)} Cloze questions extracted for Translation') 106 | print('=' * 50) 107 | # translate clozes to questions 108 | clozes_with_questions = get_questions_for_clozes( 109 | clozes, 110 | args.use_subclause_clozes, 111 | args.use_named_entity_clozes, 112 | args.use_wh_heuristic, 113 | args.translation_method 114 | ) 115 | 116 | # filter generations 117 | clozes_with_questions = [ 118 | c for c in clozes_with_questions 119 | if is_appropriate_squad_datapoint(c.question_text, c.answer_text, c.paragraph.text) 120 | ] 121 | 122 | # Dump the synthetic training data 123 | print('=' * 50) 124 | print('Dumping results') 125 | print('=' * 50) 126 | for o in args.output_file_formats.split(','): 127 | if o == 'jsonl': 128 | with open(args.output_file + '.unsupervised_qa.jsonl', 'w') as f: 129 | dump_clozes(clozes_with_questions, f) 130 | print(f"Exported {len(clozes_with_questions)} instances to {args.output_file + '.unsupervised_qa.jsonl'}") 131 | 132 | elif o == 'squad': 133 | with open(args.output_file + '.squad.json', 'w') as f: 134 | clozes2squadformat(clozes_with_questions, f) 135 | print(f"Exported {len(clozes_with_questions)} instances to {args.output_file + '.squad.json'}") 136 | 137 | print('=' * 50) 138 | print('Complete') 139 | print('=' * 50) 140 | 141 | 142 | if __name__ == '__main__': 143 | parser = argparse.ArgumentParser(description='Generate synthetic training data for extractive QA tasks without supervision') 144 | parser.add_argument("input_file", type=str, 145 | help="input file, see readme for formatting info") 146 | parser.add_argument("output_file", type=str, 147 | help="Path to write generated data to, see readme for formatting info") 148 | parser.add_argument("--input_file_format", type=str, default='txt', choices=['txt', 'jsonl'], 149 | help="input file format, see readme for more info, default is txt") 150 | parser.add_argument("--output_file_formats", type=str, default='jsonl,squad', 151 | help="comma-seperated list of output file formats, from [jsonl, squad]," 152 | " an output file will be created for each format. Default is 'jsonl,squad'") 153 | parser.add_argument("--translation_method", type=str, default="unmt", choices=['identity', 'noisy_cloze', 'unmt'], 154 | help="define the method to generate clozes -- either the Unsupervised NMT method (unmt)," 155 | " or the identity or noisy cloze baseline methods. UNMT is recommended for downstream performance, " 156 | " but the noisy_cloze is relatively stong on downstream QA and fast to generate. Default is unmt" 157 | ) 158 | parser.add_argument("--use_named_entity_clozes", action='store_true', 159 | help="pass this flag to use named entity answer prior instead of noun phrases (recommended for downstream performance) ") 160 | parser.add_argument('--use_subclause_clozes', action='store_true', 161 | help="pass this flag to shorten clozes with constituency parsing instead of using sentence boundaries (recommended for downstream performance)") 162 | parser.add_argument('--use_wh_heuristic', action='store_true', 163 | help="pass this flag to use the wh-word heuristic (recommended for downstream performance). Only compatable with named entity clozes") 164 | args = parser.parse_args() 165 | generate_synthetic_training_data(args) 166 | -------------------------------------------------------------------------------- /unsupervisedqa/parsers_and_writers.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Facebook, Inc. 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 | Module to handle reading, (de)seriaizing and dumping data 9 | """ 10 | import json 11 | import attr 12 | from .data_classes import Cloze, Paragraph 13 | import hashlib 14 | 15 | 16 | def clozes2squadformat(clozes, out_fobj): 17 | assert all([c.question_text is not None for c in clozes]), 'Translate these clozes firse, some dont have questions' 18 | data = {cloze.paragraph.paragraph_id: {'context': cloze.paragraph.text, 'qas': []} for cloze in clozes} 19 | for cloze in clozes: 20 | qas = data[cloze.paragraph.paragraph_id] 21 | qas['qas'].append({ 22 | 'question': cloze.question_text, 'id': cloze.cloze_id, 23 | 'answers': [{'text': cloze.answer_text, 'answer_start': cloze.answer_start}] 24 | }) 25 | squad_dataset = { 26 | 'version': 1.1, 27 | 'data': [{'title': para_id, 'paragraphs': [payload]} for para_id, payload in data.items()] 28 | } 29 | json.dump(squad_dataset, out_fobj) 30 | 31 | 32 | def _parse_attr_obj(cls, serialized): 33 | return cls(**json.loads(serialized)) 34 | 35 | 36 | def dumps_attr_obj(obj): 37 | return json.dumps(attr.asdict(obj)) 38 | 39 | 40 | def parse_clozes(fobj): 41 | for serialized in fobj: 42 | if serialized.strip('\n') != '': 43 | yield _parse_attr_obj(Cloze, serialized) 44 | 45 | 46 | def dump_clozes(clozes, fobj): 47 | for cloze in clozes: 48 | fobj.write(dumps_attr_obj(cloze)) 49 | fobj.write('\n') 50 | 51 | 52 | def _get_paragraph_id(text): 53 | return hashlib.sha1(text.encode()).hexdigest() 54 | 55 | 56 | def parse_paragraphs_from_txt(fobj): 57 | for paragraph_text in fobj: 58 | para_text = paragraph_text.strip('\n') 59 | if para_text != '': 60 | yield Paragraph( 61 | paragraph_id=_get_paragraph_id(para_text), 62 | text=para_text 63 | ) 64 | 65 | 66 | def parse_paragraphs_from_jsonl(fobj): 67 | for serialized in fobj: 68 | if serialized.strip('\n') != '': 69 | yield _parse_attr_obj(Paragraph, serialized) 70 | -------------------------------------------------------------------------------- /unsupervisedqa/unmt_translation.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-present, Facebook, Inc. 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 | Wrapper for UnsupervisedNMT inference-time functionality 9 | """ 10 | import attr 11 | import os 12 | from .configs import UNMT_MODEL_SENTENCE_NE, \ 13 | UNMT_MODEL_SENTENCE_NP, UNMT_MODEL_SUBCLAUSE_NE, \ 14 | UNMT_MODEL_SUBCLAUSE_NE_WH_HEURISTIC, \ 15 | PATH_TO_UNMT, MOSES_DIR, FASTBPE_DIR, N_THREADS_PREPRO, CLOZE_MASKS, UNMT_BATCH_SIZE, UNMT_BEAM_SIZE 16 | from .baseline_translators import identity_translation, noisy_cloze_translation 17 | import subprocess 18 | import tempfile 19 | import sys 20 | sys.path.append(PATH_TO_UNMT) # simple hack on the path to import Unsupervised NMT functionality 21 | from src.data.loader import check_all_data_params, load_data 22 | from src.utils import restore_segmentation 23 | from src.model import check_mt_model_params, build_mt_model 24 | from src.trainer import TrainerMT 25 | from src.evaluator import EvaluatorMT 26 | import torch 27 | 28 | 29 | def _tokenize_file(input_path, output_path): 30 | tokenizer = os.path.join(MOSES_DIR, 'scripts', 'tokenizer', 'tokenizer.perl') 31 | norm = os.path.join(MOSES_DIR, 'scripts', 'tokenizer', 'normalize-punctuation.perl') 32 | cmd = f'cat {input_path} | {norm} -l en | {tokenizer} -l en -no-escape -threads {N_THREADS_PREPRO} > {output_path}' 33 | subprocess.check_call(cmd, shell=True) 34 | 35 | 36 | def _apply_bpe(input_path, output_path, bpe_codes_path, vocab_path): 37 | fast_bpe = os.path.join(FASTBPE_DIR, 'fast') 38 | cmd = f'{fast_bpe} applybpe {output_path} {input_path} {bpe_codes_path} {vocab_path}' 39 | subprocess.check_call(cmd, shell=True) 40 | 41 | 42 | def _binarize_data(vocab_path, input_path): 43 | prepro = os.path.join(PATH_TO_UNMT, 'preprocess.py') 44 | cmd = f'{prepro} {vocab_path} {input_path}' 45 | subprocess.check_call(cmd, shell=True) 46 | 47 | 48 | def _dump_clozes_for_translation(clozes, dump_path, wh_heuristic): 49 | 50 | def _wh_heurisistic(cloze): 51 | cloze_mask = CLOZE_MASKS[cloze.answer_type] 52 | cloze_text = cloze_mask + ' ' + cloze.cloze_text.replace(cloze_mask, 'MASK') 53 | return cloze_text 54 | 55 | with open(dump_path, 'w') as fobj: 56 | for c in clozes: 57 | cloze_text = _wh_heurisistic(c) if wh_heuristic else c.cloze_text 58 | fobj.write(cloze_text) 59 | fobj.write('\n') 60 | 61 | 62 | def preprocessing(clozes, directory, vocab_path, bpe_codes_path, wh_heuristic): 63 | raw_cloze_file = os.path.join(directory, 'dev.cloze') 64 | tok_cloze_file = os.path.join(directory, 'dev.cloze.tok') 65 | bpe_cloze_file = os.path.join(directory, 'dev.cloze.tok.bpe') 66 | binarized_cloze_file = os.path.join(directory, 'dev.cloze.tok.bpe.pth') 67 | 68 | _dump_clozes_for_translation(clozes, raw_cloze_file, wh_heuristic) 69 | _tokenize_file(raw_cloze_file, tok_cloze_file) 70 | _apply_bpe(tok_cloze_file, bpe_cloze_file, bpe_codes_path, vocab_path) 71 | _binarize_data(vocab_path, bpe_cloze_file) 72 | return binarized_cloze_file 73 | 74 | 75 | def _get_model_paths(subclause_clozes, ne_answers, wh_heuristic): 76 | if subclause_clozes and ne_answers and wh_heuristic: 77 | data_dir = UNMT_MODEL_SUBCLAUSE_NE_WH_HEURISTIC 78 | model_dir = UNMT_MODEL_SUBCLAUSE_NE_WH_HEURISTIC 79 | elif subclause_clozes and ne_answers and (not wh_heuristic): 80 | data_dir = UNMT_MODEL_SUBCLAUSE_NE 81 | model_dir = UNMT_MODEL_SUBCLAUSE_NE 82 | elif (not subclause_clozes) and ne_answers and (not wh_heuristic): 83 | data_dir = UNMT_MODEL_SENTENCE_NE 84 | model_dir = UNMT_MODEL_SENTENCE_NE 85 | elif (not subclause_clozes) and (not ne_answers) and (not wh_heuristic): 86 | data_dir = UNMT_MODEL_SENTENCE_NP 87 | model_dir = UNMT_MODEL_SENTENCE_NP 88 | else: 89 | raise Exception('This model configuration doesnt exist') 90 | checkpoint_path = os.path.join(model_dir, 'periodic-20.pth') 91 | vocab_path = os.path.join(data_dir, 'vocab.cloze-question.60000') 92 | bpe_codes_path = os.path.join(data_dir, 'bpe_codes') 93 | fasttext_vectors_path = os.path.join(data_dir, 'all.cloze-question.60000.vec') 94 | return checkpoint_path, vocab_path, bpe_codes_path, fasttext_vectors_path 95 | 96 | 97 | def _associate_questions_to_clozes(clozes, translation_output_file, wh_heuristic): 98 | 99 | def _clean_wh_heurisistic(question_text): 100 | return ' '.join(question_text.split(' ')[1:]) 101 | 102 | clozes_with_questions = [] 103 | translations = [] 104 | 105 | for line in open(translation_output_file): 106 | if line.strip() != '': 107 | inp, outp = line.strip().split('\t') 108 | translations.append(_clean_wh_heurisistic(outp) if wh_heuristic else outp) 109 | 110 | assert len(clozes) == len(translations), "mismatch between number of clozes and translations" 111 | for c, q in zip(clozes, translations): 112 | c_with_q = attr.evolve(c, question_text=q) 113 | clozes_with_questions.append(c_with_q) 114 | return clozes_with_questions 115 | 116 | 117 | class Params: 118 | pass 119 | 120 | 121 | def get_params( 122 | exp_name, 123 | dump_path, 124 | cloze_train_path, 125 | question_train_path, 126 | cloze_test_path, 127 | fasttext_vectors_path, 128 | checkpoint_path 129 | ): 130 | params = Params() 131 | params.exp_name = exp_name 132 | params.exp_id = "" 133 | params.dump_path = dump_path 134 | params.save_periodic = False 135 | params.seed = -1 136 | params.emb_dim = 512 137 | params.n_enc_layers = 4 138 | params.n_dec_layers = 4 139 | params.hidden_dim = 512 140 | params.lstm_proj = False 141 | params.dropout = 0 142 | params.label_smoothing = 0 143 | params.attention = True 144 | params.transformer = True 145 | params.transformer_ffn_emb_dim = 2048 146 | params.attention_dropout = 0 147 | params.relu_dropout = 0 148 | params.encoder_attention_heads = 8 149 | params.decoder_attention_heads = 8 150 | params.encoder_normalize_before = False 151 | params.decoder_normalize_before = False 152 | params.share_lang_emb = True 153 | params.share_encdec_emb = False 154 | params.share_decpro_emb = False 155 | params.share_output_emb = True 156 | params.share_lstm_proj = False 157 | params.share_enc = 3 158 | params.share_dec = 3 159 | params.word_shuffle = 0 160 | params.word_dropout = 0 161 | params.word_blank = 0 162 | params.dis_layers = 3 163 | params.dis_hidden_dim = 128 164 | params.dis_dropout = 0 165 | params.dis_clip = 0 166 | params.dis_smooth = 0 167 | params.dis_input_proj = False 168 | params.langs = "cloze,question" 169 | params.vocab = "" 170 | params.vocab_min_count = 0 171 | params.mono_dataset = f"cloze:{cloze_train_path},,{cloze_test_path};question:{question_train_path},," 172 | params.para_dataset = "" 173 | params.back_dataset = "" 174 | params.n_mono = -1 175 | params.n_para = 0 176 | params.n_back = 0 177 | params.max_len = 175 178 | params.max_vocab = -1 179 | params.n_dis = 0 180 | params.mono_directions = 'cloze,question' 181 | params.para_directions = "" 182 | params.pivo_directions = "cloze-question-cloze,question-cloze-question" 183 | params.back_directions = "" 184 | params.otf_sample = -1 185 | params.otf_backprop_temperature = -1 186 | params.otf_sync_params_every = 1000 187 | params.otf_num_processes = 0 188 | params.otf_update_enc = True 189 | params.otf_update_dec = True 190 | params.lm_before = 0 191 | params.lm_after = 0 192 | params.lm_share_enc = 0 193 | params.lm_share_dec = 0 194 | params.lm_share_emb = False 195 | params.lm_share_proj = False 196 | params.batch_size = UNMT_BATCH_SIZE 197 | params.group_by_size = True 198 | params.lambda_xe_mono = "0:1,100000:0.1,300000:0" 199 | params.lambda_xe_para = "0" 200 | params.lambda_xe_back = "0" 201 | params.lambda_xe_otfd = "1" 202 | params.lambda_xe_otfa = "0" 203 | params.lambda_dis = "0" 204 | params.lambda_lm = "0" 205 | params.enc_optimizer = "adam,lr=0.0001" 206 | params.dec_optimizer = "enc_optimizer" 207 | params.dis_optimizer = "rmsprop,lr=0.0005" 208 | params.clip_grad_norm = 5 209 | params.epoch_size = 10 210 | params.max_epoch = 100000 211 | params.stopping_criterion = "" 212 | params.pretrained_emb = fasttext_vectors_path 213 | params.pretrained_out = True 214 | params.reload_model = checkpoint_path 215 | params.reload_enc = True 216 | params.reload_dec = True 217 | params.reload_dis = False 218 | params.freeze_enc_emb = False 219 | params.freeze_dec_emb = False 220 | params.eval_only = False 221 | params.beam_size = UNMT_BEAM_SIZE 222 | params.length_penalty = 1.0 223 | return params 224 | 225 | 226 | def convert_to_text(batch, lengths, dico, lang_id, params): 227 | """ 228 | Convert a batch of sentences to a list of text sentences. 229 | """ 230 | batch = batch.cpu().numpy() 231 | lengths = lengths.cpu().numpy() 232 | bos_index = params.bos_index[lang_id] 233 | 234 | slen, bs = batch.shape 235 | assert lengths.max() == slen and lengths.shape[0] == bs 236 | assert (batch[0] == bos_index).sum() == bs 237 | assert (batch == params.eos_index).sum() == bs 238 | sentences = [] 239 | 240 | for j in range(bs): 241 | words = [] 242 | for k in range(1, lengths[j]): 243 | if batch[k, j] == params.eos_index: 244 | break 245 | words.append(dico[batch[k, j]]) 246 | sentences.append(" ".join(words)) 247 | return sentences 248 | 249 | 250 | def perform_translation(input_file_path, 251 | translation_directory, 252 | cloze_train_path, 253 | question_train_path, 254 | fasttext_vectors_path, 255 | checkpoint_path 256 | ): 257 | params = get_params( 258 | exp_name='translation', 259 | dump_path=translation_directory, 260 | cloze_train_path=cloze_train_path, 261 | question_train_path=question_train_path, 262 | cloze_test_path=input_file_path, 263 | fasttext_vectors_path=fasttext_vectors_path, 264 | checkpoint_path=checkpoint_path, 265 | ) 266 | 267 | # check parameters 268 | assert params.exp_name 269 | check_all_data_params(params) 270 | check_mt_model_params(params) 271 | data = load_data(params, mono_only=True) 272 | encoder, decoder, discriminator, lm = build_mt_model(params, data) 273 | # initialize trainer / reload checkpoint / initialize evaluator 274 | trainer = TrainerMT(encoder, decoder, discriminator, lm, data, params) 275 | trainer.reload_checkpoint() 276 | trainer.test_sharing() # check parameters sharing 277 | evaluator = EvaluatorMT(trainer, data, params) 278 | 279 | with torch.no_grad(): 280 | lang1, lang2 = 'cloze', 'question' 281 | 282 | evaluator.encoder.eval() 283 | evaluator.decoder.eval() 284 | lang1_id = evaluator.params.lang2id[lang1] 285 | lang2_id = evaluator.params.lang2id[lang2] 286 | 287 | translations = [] 288 | dataset = evaluator.data['mono'][lang1]['test'] 289 | dataset.batch_size = params.batch_size 290 | 291 | for i, (sent1, len1) in enumerate(dataset.get_iterator(shuffle=False, group_by_size=False)()): 292 | encoded = evaluator.encoder(sent1.cuda(), len1, lang1_id) 293 | sent2_, len2_, _ = evaluator.decoder.generate(encoded, lang2_id) 294 | lang1_text = convert_to_text(sent1, len1, evaluator.dico[lang1], lang1_id, evaluator.params) 295 | lang2_text = convert_to_text(sent2_, len2_, evaluator.dico[lang2], lang2_id, evaluator.params) 296 | translations += zip(lang1_text, lang2_text) 297 | 298 | # export sentences to hypothesis file and restore BPE segmentation 299 | out_name = os.path.join(translation_directory, 'output_translations.txt') 300 | with open(out_name, 'w', encoding='utf-8') as f: 301 | f.write('\n'.join(['\t'.join(st) for st in translations]) + '\n') 302 | restore_segmentation(out_name) 303 | 304 | return out_name 305 | 306 | 307 | def get_unmt_questions_for_clozes(clozes, 308 | subclause_clozes, 309 | ne_answers, 310 | wh_heuristic, 311 | ): 312 | checkpoint_path, vocab_path, bpe_codes_path, fasttext_vectors_path = \ 313 | _get_model_paths(subclause_clozes, ne_answers, wh_heuristic) 314 | 315 | with tempfile.TemporaryDirectory() as tempdir: 316 | translation_input_path = preprocessing(clozes, tempdir, vocab_path, bpe_codes_path, wh_heuristic) 317 | translation_output_path = perform_translation( 318 | translation_input_path, 319 | tempdir, 320 | translation_input_path, 321 | translation_input_path, 322 | fasttext_vectors_path, 323 | checkpoint_path 324 | ) 325 | clozes_with_questions = _associate_questions_to_clozes(clozes, translation_output_path, wh_heuristic) 326 | 327 | return clozes_with_questions 328 | --------------------------------------------------------------------------------