├── .gitignore ├── LICENSE ├── README.md ├── environment.yml ├── generation ├── .gitattributes ├── Complexity Control Expirements.ipynb └── Definition Modeling Expirements.ipynb ├── lib ├── jargon_utils.py └── utils.py └── models ├── .DS_Store ├── run_def_finetuning.sh └── run_summarization.sh /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Generating Scientific Definitions with Controllable Complexity 2 | 3 | 4 | By Tal August, Katharina Reinecke, and Noah A. Smith 5 | 6 | Abstract: Unfamiliar terminology and complex language can present barriers to understanding science. Natural language processing stands to help address these issues by automatically defining unfamiliar terms. We introduce a new task and dataset for defining scientific terms and controlling the complexity of gen- erated definitions as a way of adapting to a specific reader’s background knowledge. We test four definition generation methods for this new task, finding that a sequence-to-sequence approach is most successful. We then explore the version of the task in which definitions are generated at a target complexity level. We in- troduce a novel reranking approach and find in human evaluations that it offers superior fluency while also controlling complexity, compared to several controllable generation base- lines. 7 | 8 | ## Data 9 | 10 | We use two sources for scientific definitions: 11 | 12 | * [MedQuAD](https://github.com/abachaa/MedQuAD) 13 | * [Wikipedia Science Glossaries](https://en.wikipedia.org/wiki/Category:Glossaries_of_science) 14 | 15 | For both sources, all terms and definitions are formatted as "What is (are) X?" or "Do you have more information about X" with the answer being the definition of X. 16 | 17 | The data is avaliable on the [HuggingFace dataset hub](https://huggingface.co/datasets/talaugust/sci-definition). 18 | 19 | 20 | ## Models 21 | `models/` has training scripts for our models. All training and finetuning was done on a NVIDIA Titan X 12GB GPU. Details on hyperparameter settings are in the paper, though the scripts include the best performing settings we used. You can download our best-performing model (BART finetuned with the support documents) from the [HuggingFace Hub](https://huggingface.co/talaugust/bart-sci-definition). 22 | 23 | ## Code 24 | `generation/` includes notebooks for generating and evaluating definitions at different levels of complexity. 25 | 26 | ## Citation 27 | 28 | If you use our work, please cite our paper 29 | 30 | ``` 31 | @inproceedings{august-2022-definition-complexity, 32 | title={Generating Scientific Definitions with Controllable Complexity}, 33 | author={Tal August, Katharina Reinecke, and Noah A. Smith}, 34 | booktitle={ACL}, 35 | year={2022} 36 | } 37 | ``` 38 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: allennlp 2 | channels: 3 | - pytorch 4 | - defaults 5 | dependencies: 6 | - _libgcc_mutex=0.1=main 7 | - backcall=0.2.0=py_0 8 | - blas=1.0=mkl 9 | - ca-certificates=2020.10.14=0 10 | - certifi=2020.6.20=pyhd3eb1b0_3 11 | - cudatoolkit=9.2=0 12 | - decorator=4.4.2=py_0 13 | - freetype=2.10.4=h5ab3b9f_0 14 | - intel-openmp=2020.2=254 15 | - ipykernel=5.3.4=py37h5ca1d4c_0 16 | - ipython=7.18.1=py37h5ca1d4c_0 17 | - ipython_genutils=0.2.0=py37_0 18 | - jedi=0.17.2=py37_0 19 | - jpeg=9b=h024ee3a_2 20 | - jupyter_client=6.1.7=py_0 21 | - jupyter_core=4.6.3=py37_0 22 | - lcms2=2.11=h396b838_0 23 | - ld_impl_linux-64=2.33.1=h53a641e_7 24 | - libedit=3.1.20191231=h14c3975_1 25 | - libffi=3.3=he6710b0_2 26 | - libgcc-ng=9.1.0=hdf63c60_0 27 | - libpng=1.6.37=hbc83047_0 28 | - libsodium=1.0.18=h7b6447c_0 29 | - libstdcxx-ng=9.1.0=hdf63c60_0 30 | - libtiff=4.1.0=h2733197_1 31 | - lz4-c=1.9.2=heb0550a_3 32 | - mkl=2020.2=256 33 | - mkl-service=2.3.0=py37he904b0f_0 34 | - mkl_fft=1.2.0=py37h23d657b_0 35 | - mkl_random=1.1.1=py37h0573a6f_0 36 | - ncurses=6.2=he6710b0_1 37 | - ninja=1.10.1=py37hfd86e86_0 38 | - numpy=1.19.2=py37h54aff64_0 39 | - numpy-base=1.19.2=py37hfa32c7d_0 40 | - olefile=0.46=py37_0 41 | - openssl=1.1.1h=h7b6447c_0 42 | - pandas=1.1.3=py37he6710b0_0 43 | - parso=0.7.0=py_0 44 | - pexpect=4.8.0=py37_1 45 | - pickleshare=0.7.5=py37_1001 46 | - pillow=8.0.1=py37he98fc37_0 47 | - pip=20.2.4=py37_0 48 | - prompt-toolkit=3.0.8=py_0 49 | - ptyprocess=0.6.0=py37_0 50 | - pygments=2.7.1=py_0 51 | - python=3.7.9=h7579374_0 52 | - python-dateutil=2.8.1=py_0 53 | - pytz=2020.1=py_0 54 | - pyzmq=19.0.2=py37he6710b0_1 55 | - readline=8.0=h7b6447c_0 56 | - setuptools=50.3.0=py37hb0f4dca_1 57 | - six=1.15.0=py_0 58 | - sqlite=3.33.0=h62c20be_0 59 | - tk=8.6.10=hbc83047_0 60 | - torchvision=0.7.0=py37_cu92 61 | - tornado=6.0.4=py37h7b6447c_1 62 | - traitlets=5.0.5=py_0 63 | - wcwidth=0.2.5=py_0 64 | - wheel=0.35.1=py_0 65 | - xz=5.2.5=h7b6447c_0 66 | - zeromq=4.3.3=he6710b0_3 67 | - zlib=1.2.11=h7b6447c_3 68 | - zstd=1.4.5=h9ceee32_0 69 | - pip: 70 | - allennlp==1.2.2 71 | - allennlp-models==1.2.2 72 | - antlr4-python3-runtime==4.8 73 | - argon2-cffi==20.1.0 74 | - async-generator==1.10 75 | - attrs==20.2.0 76 | - bleach==3.2.1 77 | - blis==0.4.1 78 | - boto3==1.16.5 79 | - botocore==1.19.5 80 | - catalogue==1.0.0 81 | - cffi==1.14.3 82 | - chardet==3.0.4 83 | - click==7.1.2 84 | - conllu==4.2.1 85 | - cymem==2.0.3 86 | - cython==0.29.21 87 | - dataclasses==0.6 88 | - datasets==1.1.2 89 | - defusedxml==0.6.0 90 | - dill==0.3.2 91 | - editdistance==0.5.3 92 | - elasticsearch==7.9.1 93 | - en-core-web-sm==2.3.1 94 | - entrypoints==0.3 95 | - fairseq==0.10.0 96 | - faiss==1.5.3 97 | - faiss-gpu==1.6.4 98 | - filelock==3.0.12 99 | - ftfy==5.8 100 | - future==0.18.2 101 | - h5py==2.10.0 102 | - hydra-core==1.0.4 103 | - idna==2.10 104 | - importlib-metadata==2.0.0 105 | - importlib-resources==3.3.0 106 | - iniconfig==1.1.1 107 | - ipywidgets==7.5.1 108 | - jinja2==2.11.2 109 | - jmespath==0.10.0 110 | - joblib==0.17.0 111 | - jsonnet==0.16.0 112 | - jsonpickle==1.4.1 113 | - jsonschema==3.2.0 114 | - jupyter==1.0.0 115 | - jupyter-console==6.2.0 116 | - jupyterlab-pygments==0.1.2 117 | - markupsafe==1.1.1 118 | - mistune==0.8.4 119 | - multiprocess==0.70.10 120 | - murmurhash==1.0.2 121 | - nbclient==0.5.1 122 | - nbconvert==6.0.7 123 | - nbformat==5.0.8 124 | - nest-asyncio==1.4.2 125 | - nlp==0.4.0 126 | - nltk==3.5 127 | - notebook==6.1.4 128 | - omegaconf==2.0.5 129 | - overrides==3.1.0 130 | - packaging==20.4 131 | - pandocfilters==1.4.3 132 | - patsy==0.5.1 133 | - plac==1.1.3 134 | - pluggy==0.13.1 135 | - portalocker==2.0.0 136 | - preshed==3.0.2 137 | - prometheus-client==0.8.0 138 | - protobuf==3.13.0 139 | - py==1.9.0 140 | - py-rouge==1.1 141 | - pyarrow==2.0.0 142 | - pycparser==2.20 143 | - pyparsing==2.4.7 144 | - pyrsistent==0.17.3 145 | - pytest==6.1.1 146 | - pyyaml==5.3.1 147 | - qtconsole==4.7.7 148 | - qtpy==1.9.0 149 | - regex==2020.10.23 150 | - requests==2.24.0 151 | - s3transfer==0.3.3 152 | - sacrebleu==1.4.14 153 | - sacremoses==0.0.43 154 | - scikit-learn==0.23.2 155 | - scipy==1.5.3 156 | - send2trash==1.5.0 157 | - sentencepiece==0.1.91 158 | - spacy==2.3.2 159 | - srsly==1.0.2 160 | - statsmodels==0.12.1 161 | - tensorboardx==2.1 162 | - termcolor==1.1.0 163 | - terminado==0.9.1 164 | - testpath==0.4.4 165 | - thinc==7.4.1 166 | - threadpoolctl==2.1.0 167 | - tokenizers==0.9.3 168 | - toml==0.10.1 169 | - torch==1.6.0 170 | - tqdm==4.49.0 171 | - transformers==3.5.1 172 | - typing-extensions==3.7.4.3 173 | - urllib3==1.25.11 174 | - wasabi==0.8.0 175 | - webencodings==0.5.1 176 | - widgetsnbextension==3.5.1 177 | - word2number==1.1 178 | - xlrd==1.2.0 179 | - xxhash==2.0.0 180 | - zipp==3.4.0 181 | prefix: /homes/gws/taugust/miniconda3/envs/allennlp 182 | 183 | -------------------------------------------------------------------------------- /generation/.gitattributes: -------------------------------------------------------------------------------- 1 | *.ipynb filter=strip-notebook-output -------------------------------------------------------------------------------- /generation/Complexity Control Expirements.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Complexity Control Expirements\n", 8 | "\n", 9 | "Main notebook for using a base model (at this point it is BART) for generating with controllable complexity. List of things to try: \n", 10 | "\n", 11 | "- ```GeDi```: Using the discriminator guided generation. Dataset is arxiv vs. science news. \n", 12 | "- ```DExperts```: Using a pretrained model as an expert and anti experts. The two pretrained models are one of arxiv text, one on science news text. \n", 13 | "- ```Rerankers```: An SVM trained on same DS as above (arxiv and science news). \n", 14 | "- ```PPLM```: Not included here, run seperately based on the HUF code (https://github.com/huggingface/transformers/tree/main/examples/research_projects/pplm)\n" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "from transformers import (\n", 24 | " AutoTokenizer,\n", 25 | " AutoModelForSeq2SeqLM,\n", 26 | " AutoConfig, \n", 27 | " LogitsProcessorList,\n", 28 | " MinLengthLogitsProcessor,\n", 29 | " TopKLogitsWarper,\n", 30 | " NoBadWordsLogitsProcessor,\n", 31 | " TemperatureLogitsWarper,\n", 32 | " BeamSearchScorer,\n", 33 | " LogitsProcessor,\n", 34 | " NoRepeatNGramLogitsProcessor,\n", 35 | " LogitsProcessorList,\n", 36 | ")\n", 37 | "\n", 38 | "import seaborn as sn\n", 39 | "import matplotlib.pyplot as plt\n", 40 | "import torch\n", 41 | "from torch.nn import functional as F\n", 42 | "\n", 43 | "from importlib import reload \n", 44 | "from joblib import dump, load\n", 45 | "\n", 46 | "import os\n", 47 | "import sys\n", 48 | "from importlib import reload \n", 49 | "import pandas as pd\n", 50 | "import numpy as np\n", 51 | "import csv\n", 52 | "import datasets\n", 53 | "import json\n", 54 | "import random\n", 55 | "import uuid\n", 56 | "import spacy \n", 57 | "import scispacy\n", 58 | "from tqdm import tqdm\n", 59 | "from spacy.pipeline import Sentencizer\n", 60 | "import re\n", 61 | "from typing import Iterable, List\n", 62 | "from transformers import BertTokenizer, glue_convert_examples_to_features, BertForSequenceClassification, Trainer, TrainingArguments\n", 63 | "from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\n", 64 | "\n", 65 | "random.seed(42)\n", 66 | "\n", 67 | "sys.path.append('/lib')\n", 68 | "\n", 69 | "import utils\n", 70 | "import jargon_utils\n", 71 | "\n", 72 | "MODEL_DIR = ''\n", 73 | "RESOURCE_DIR = ''\n", 74 | "GEDI_PATH = ''\n", 75 | "DATA_DIR = ''\n", 76 | "\n", 77 | "sys.path.append(GEDI_PATH)\n", 78 | "sys.path.append(RESOURCE_DIR)\n", 79 | "\n", 80 | "import GeDi\n", 81 | "from GeDi import generate_GeDi\n" 82 | ] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "metadata": {}, 87 | "source": [ 88 | "# Data\n", 89 | "\n", 90 | "For now, just use the medq wiki dataset (which is what the base model is finetuned oned), but might want to also try the sci defs or the simple and normal wiki paired" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": null, 96 | "metadata": {}, 97 | "outputs": [], 98 | "source": [ 99 | "##### Dataset reloading \n", 100 | "df_wiki_medq_strat_train = pd.read_csv('{}/model_data/medquad_wikipedia_k_means_with_sd_train.csv'.format(DATA_DIR))\n", 101 | "df_wiki_medq_strat_dev = pd.read_csv('{}/model_data/medquad_wikipedia_k_means_with_sd_dev.csv'.format(DATA_DIR))\n", 102 | "df_wiki_medq_strat_test = pd.read_csv('{}/model_data/medquad_wikipedia_k_means_with_sd_test.csv'.format(DATA_DIR))\n", 103 | "\n", 104 | "#### for testing without running through the whole df\n", 105 | "df_test = df_wiki_medq_strat_test\n", 106 | "\n", 107 | "#### for just running the human eval (and then not human eval)\n", 108 | "selected_questions = pd.read_csv('{}/model_data/human_eval_test_questions.txt'.format(DATA_DIR))\n", 109 | "df_test_human_eval = df_test[df_test['question'].isin(selected_questions['question'])]\n", 110 | "df_test_not_human_eval = df_test[~df_test['question'].isin(selected_questions['question'])]\n" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": null, 116 | "metadata": {}, 117 | "outputs": [], 118 | "source": [ 119 | "GPU_NUMBER = '' \n", 120 | "CUDA_DEVICE = '0'\n", 121 | "os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n", 122 | "os.environ['CUDA_VISIBLE_DEVICES'] = GPU_NUMBER\n", 123 | "\n", 124 | "DEVICE = 'cuda:0' " 125 | ] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "metadata": {}, 130 | "source": [ 131 | "# Generation Types \n", 132 | "\n" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": null, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "\n", 142 | "# This is similar to the function from the definition modelling notebook but simplified to ignore gpt2 and added parts fo ranking scores\n", 143 | "def generate_answers(df, model, tokenizer, model_type,\n", 144 | " num_return_sequences=1,\n", 145 | " num_beams=5,\n", 146 | " max_length=64,\n", 147 | " min_length=8,\n", 148 | " early_stopping=True,\n", 149 | " temperature=1,\n", 150 | " do_sample=True,\n", 151 | " top_k=50,\n", 152 | " top_p=0.9,\n", 153 | " max_input_length=1024,\n", 154 | " no_repeat_ngram_size=3,\n", 155 | " device=None):\n", 156 | " \n", 157 | " answer_df_lists = []\n", 158 | " for i, r in tqdm(df.iterrows()):\n", 159 | " \n", 160 | " row = r.to_dict()\n", 161 | " \n", 162 | " ### make input\n", 163 | " q_doc = row['q_s2orc_doc']\n", 164 | " inputs = tokenizer(q_doc, return_tensors='pt', max_length=max_input_length, truncation=True)\n", 165 | " \n", 166 | " \n", 167 | " outputs = model.generate(**inputs.to(device),\n", 168 | " decoder_start_token_id=tokenizer.bos_token_id,\n", 169 | " num_return_sequences=num_return_sequences,\n", 170 | " num_beams=num_beams, \n", 171 | " min_length=min_length,\n", 172 | " max_length=max_length, \n", 173 | " early_stopping=early_stopping, \n", 174 | " temperature=temperature,\n", 175 | " do_sample=do_sample,\n", 176 | " top_k=top_k,\n", 177 | " top_p=top_p,\n", 178 | " eos_token_id=tokenizer.eos_token_id,\n", 179 | " no_repeat_ngram_size=no_repeat_ngram_size,\n", 180 | " output_scores=True,\n", 181 | " return_dict_in_generate=True)\n", 182 | "\n", 183 | " # save all the answers with their associated scores in a df\n", 184 | " answers = [tokenizer.decode(ans_ids, skip_special_tokens=True).strip() for ans_ids in outputs[0]]\n", 185 | " df_answers = pd.DataFrame(zip(answers, outputs['sequences_scores'].tolist()), columns=['response', 'scores'])\n", 186 | " df_answers['model-type'] = model_type\n", 187 | " \n", 188 | " # save information about the question\n", 189 | " df_answers['question'] = row['question']\n", 190 | " df_answers['category'] = row['category']\n", 191 | " df_answers['first_sentence'] = row['first_sentence']\n", 192 | " \n", 193 | " # append the df\n", 194 | " answer_df_lists.append(df_answers)\n", 195 | " \n", 196 | " return pd.concat(answer_df_lists)\n" 197 | ] 198 | }, 199 | { 200 | "cell_type": "markdown", 201 | "metadata": {}, 202 | "source": [ 203 | "# Reranker\n", 204 | "\n", 205 | "Taking a slightly different approach from last time, where we will generate on the base model then score seperately here. \n", 206 | "\n", 207 | "For scoring, do so grouped by question, because I think the svm decision function matters for that and maybe the bart one does too" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": null, 213 | "metadata": {}, 214 | "outputs": [], 215 | "source": [ 216 | "#### Helpful functions\n", 217 | "\n", 218 | "def get_svm_score(answers, clf, response_col):\n", 219 | " feature_cols = ['avl_occ', 'function_words_prop', 'te_oov', 'response_gpt_ppl_score', 'word_count']\n", 220 | " answers = jargon_utils.make_jargon_features(answers, response_col)\n", 221 | " answers['predictions'] = clf.decision_function(answers[feature_cols])\n", 222 | " return answers\n", 223 | "\n", 224 | "\n", 225 | "def get_bert_logits(answers, bert_tokenizer, bert_ranker_model, prefix='', device=None):\n", 226 | " answers['input_ids'] = [bert_tokenizer(a, return_tensors=\"pt\") for a in answers['response']]\n", 227 | " answers[prefix+'bert_logits'] = [bert_ranker_model(**inputs.to(device)).logits.cpu().detach().numpy()[0] for inputs in answers['input_ids']]\n", 228 | " answers[[prefix+'bert_logits_news', prefix+'bert_logits_academic']] = answers[prefix+'bert_logits'].apply(pd.Series)\n", 229 | " \n", 230 | " return answers\n" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": null, 236 | "metadata": {}, 237 | "outputs": [], 238 | "source": [ 239 | "#### get generator and rankers\n", 240 | "\n", 241 | "### Base Model\n", 242 | "bart_tokenizer = AutoTokenizer.from_pretrained(\"{}/bart_medq_wiki_s2orc/default\".format(MODEL_DIR))\n", 243 | "bart_model = AutoModelForSeq2SeqLM.from_pretrained(\"{}/bart_medq_wiki_s2orc/default\".format(MODEL_DIR)).to(DEVICE)\n", 244 | "\n", 245 | "_ = bart_model.eval()\n", 246 | "\n", 247 | "\n", 248 | "#### SVM \n", 249 | "ranker_path = ''\n", 250 | "feature_cols = ['avl_occ', 'function_words_prop', 'te_oov', 'response_gpt_ppl_score', 'word_count']\n", 251 | "arxiv_sci_train_clf = load('{}/svm_train_arxiv.joblib'.format(ranker_path)) \n", 252 | "\n" 253 | ] 254 | }, 255 | { 256 | "cell_type": "code", 257 | "execution_count": null, 258 | "metadata": {}, 259 | "outputs": [], 260 | "source": [ 261 | "### Generating some answers based on the base model\n", 262 | "\n", 263 | "### Because of cuda issues, loop through 20 times (*5 per time) for 100 answers each\n", 264 | "all_bart_test_answers = []\n", 265 | "for _ in range(20):\n", 266 | " bart_test_answers = generate_answers(df=df_test, num_return_sequences=5, model=bart_model, tokenizer=bart_tokenizer, model_type='bart-base', use_decoder_prefix=False, device=DEVICE)\n", 267 | " all_bart_test_answers.append(bart_test_answers)\n", 268 | " " 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": null, 274 | "metadata": {}, 275 | "outputs": [], 276 | "source": [ 277 | "# replacing the bart_dev_answers var because that is what is used below\n", 278 | "bart_test_answers = pd.concat(all_bart_test_answers)" 279 | ] 280 | }, 281 | { 282 | "cell_type": "code", 283 | "execution_count": null, 284 | "metadata": {}, 285 | "outputs": [], 286 | "source": [ 287 | "#### Scoring the answers\n", 288 | "\n", 289 | "bart_test_answers_svm = bart_test_answers.groupby(['question']).apply(lambda g: get_svm_score(g, arxiv_sci_train_clf, response_col='response')).reset_index(drop=True)\n" 290 | ] 291 | }, 292 | { 293 | "cell_type": "code", 294 | "execution_count": null, 295 | "metadata": {}, 296 | "outputs": [], 297 | "source": [ 298 | "### take models off the gpu \n", 299 | "bart_model=bart_model.cpu()\n" 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": null, 305 | "metadata": {}, 306 | "outputs": [], 307 | "source": [ 308 | "##### Save everything seperately\n", 309 | "bart_test_answers_svm.to_csv('{}/bart_test_answers_svm.csv'.format(DATA_DIR))\n" 310 | ] 311 | }, 312 | { 313 | "cell_type": "markdown", 314 | "metadata": {}, 315 | "source": [ 316 | "# DExperts\n", 317 | "\n" 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": null, 323 | "metadata": {}, 324 | "outputs": [], 325 | "source": [ 326 | "#### These models are bart-large pretrained on the two datasets (but not finetuned on our task)\n", 327 | "### rather than the DAPT models, which are pretrained on top of the finetuned bart\n", 328 | "\n", 329 | "bart_article_model = AutoModelForSeq2SeqLM.from_pretrained(\"{}/bart_medq_wiki_s2orc/articles\".format(MODEL_DIR)).to(DEVICE)\n", 330 | "_ = bart_article_model.eval()\n", 331 | "\n", 332 | "bart_journal_model = AutoModelForSeq2SeqLM.from_pretrained(\"{}/bart_medq_wiki_s2orc/journals\".format(MODEL_DIR)).to(DEVICE)\n", 333 | "_ = bart_journal_model.eval()\n" 334 | ] 335 | }, 336 | { 337 | "cell_type": "code", 338 | "execution_count": null, 339 | "metadata": {}, 340 | "outputs": [], 341 | "source": [ 342 | "# mostly taken from https://huggingface.co/transformers/_modules/transformers/generation_utils.html#GenerationMixin.generate\n", 343 | "# for encoder-decoder networks like BART \n", 344 | "def setup_s2s_generation(context, s2s_model, s2s_tokenizer, max_length=50):\n", 345 | " inputs = s2s_tokenizer(context, return_tensors=\"pt\", max_length=1024, truncation=True)\n", 346 | " \n", 347 | " model_kwargs = s2s_model._prepare_encoder_decoder_kwargs_for_generation(inputs['input_ids'], {})\n", 348 | "\n", 349 | " input_ids = s2s_model._prepare_decoder_input_ids_for_generation(\n", 350 | " inputs['input_ids'], decoder_start_token_id=s2s_model.config.decoder_start_token_id, bos_token_id=s2s_model.config.bos_token_id\n", 351 | " )\n", 352 | " \n", 353 | " sequence_lengths, unfinished_sequences, cur_len = s2s_model._init_sequence_length_for_generation(\n", 354 | " input_ids, max_length\n", 355 | " )\n", 356 | " \n", 357 | " return input_ids, model_kwargs, sequence_lengths, unfinished_sequences\n", 358 | "\n", 359 | "\n", 360 | "def generate_s2s_DEexperts(context,\n", 361 | " model,\n", 362 | " expert_model,\n", 363 | " anti_model,\n", 364 | " tokenizer,\n", 365 | " top_k=50,\n", 366 | " top_p=0.9,\n", 367 | " num_beams=5,\n", 368 | " max_length=64,\n", 369 | " min_length=8,\n", 370 | " no_repeat_ngram_size=3,\n", 371 | " expert_alpha = 2.0,\n", 372 | " early_stopping=True,\n", 373 | " temperature=1.0,\n", 374 | " do_sample=True, # not used, assumed\n", 375 | " device=None,\n", 376 | " num_return_sequences=1):\n", 377 | "\n", 378 | " input_ids, model_kwargs, sequence_lengths, unfinished_sequences = setup_s2s_generation(context, model, tokenizer, max_length)\n", 379 | "\n", 380 | " \n", 381 | " # make the beam search scorer\n", 382 | " beam_scorer = BeamSearchScorer(\n", 383 | " batch_size=1,\n", 384 | " max_length=max_length,\n", 385 | " num_beams=num_beams,\n", 386 | " device=device,\n", 387 | " length_penalty=model.config.length_penalty,\n", 388 | " do_early_stopping=early_stopping,\n", 389 | " num_beam_hyps_to_keep=num_return_sequences)\n", 390 | " \n", 391 | " \n", 392 | " logits_processors = model._get_logits_processor(\n", 393 | " repetition_penalty=None,\n", 394 | " no_repeat_ngram_size=no_repeat_ngram_size,\n", 395 | " bad_words_ids=None,\n", 396 | " min_length=min_length,\n", 397 | " eos_token_id=model.config.eos_token_id,\n", 398 | " prefix_allowed_tokens_fn=None,\n", 399 | " num_beams=num_beams,\n", 400 | " num_beam_groups=1,\n", 401 | " diversity_penalty=None,\n", 402 | " )\n", 403 | " \n", 404 | "\n", 405 | " logits_warper = model._get_logits_warper(\n", 406 | " top_k=top_k, top_p=top_p, temperature=temperature, num_beams=num_beams\n", 407 | " )\n", 408 | "\n", 409 | " eos_token_id = model.config.eos_token_id\n", 410 | " pad_token_id = model.config.pad_token_id\n", 411 | "\n", 412 | " \n", 413 | " # interleave with `num_beams`\n", 414 | " input_ids, model_kwargs = model._expand_inputs_for_generation(\n", 415 | " input_ids, expand_size=num_beams, is_encoder_decoder=model.config.is_encoder_decoder, **model_kwargs\n", 416 | " )\n", 417 | " \n", 418 | " # initalize for beam search\n", 419 | " batch_size = len(beam_scorer._beam_hyps)\n", 420 | " num_beams = beam_scorer.num_beams\n", 421 | "\n", 422 | " batch_beam_size, cur_len = input_ids.shape\n", 423 | "\n", 424 | " beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)\n", 425 | " beam_scores = beam_scores.view((batch_size * num_beams,))\n", 426 | " \n", 427 | " \n", 428 | "\n", 429 | " while cur_len < max_length:\n", 430 | " # prepare inputs\n", 431 | " model_inputs = model.prepare_inputs_for_generation(input_ids, **model_kwargs)\n", 432 | "\n", 433 | " # run forward of model\n", 434 | " output = model(**model_inputs)\n", 435 | "\n", 436 | " next_token_logits = output.logits[:, -1, :]\n", 437 | " \n", 438 | " \n", 439 | " # hack from transformers: adjust tokens for Marian. For Marian we have to make sure that the `pad_token_id`\n", 440 | " # cannot be generated both before and after the `F.log_softmax` operation.\n", 441 | " next_token_logits = model.adjust_logits_during_generation(\n", 442 | " next_token_logits, cur_len=cur_len, max_length=max_length\n", 443 | " )\n", 444 | " \n", 445 | " next_token_scores = F.log_softmax(next_token_logits, dim=-1)\n", 446 | " \n", 447 | " # pre-process distribution\n", 448 | " next_token_scores = logits_processors(input_ids, next_token_logits)\n", 449 | " next_token_scores = next_token_scores + beam_scores[:, None].expand_as(next_token_scores)\n", 450 | " next_token_scores = logits_warper(input_ids, next_token_scores)\n", 451 | "\n", 452 | " # get the anti-expert and expert\n", 453 | " expert_output = expert_model(**model_inputs)\n", 454 | " anti_output = anti_model(**model_inputs)\n", 455 | " \n", 456 | "\n", 457 | " next_token_scores = next_token_scores + (expert_alpha * (expert_output.logits[:, -1, :] - anti_output.logits[:, -1, :]))\n", 458 | "\n", 459 | " \n", 460 | " # reshape for beam search\n", 461 | " vocab_size = next_token_scores.shape[-1]\n", 462 | " next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)\n", 463 | "\n", 464 | " probs = F.softmax(next_token_scores, dim=-1)\n", 465 | "\n", 466 | " next_tokens = torch.multinomial(probs, num_samples=(2 * num_beams))\n", 467 | " next_token_scores = torch.gather(next_token_scores, -1, next_tokens)\n", 468 | "\n", 469 | " next_token_scores, _indices = torch.sort(next_token_scores, descending=True, dim=1)\n", 470 | " next_tokens = torch.gather(next_tokens, -1, _indices)\n", 471 | "\n", 472 | " next_indices = next_tokens // vocab_size\n", 473 | " next_tokens = next_tokens % vocab_size\n", 474 | "\n", 475 | " # stateless\n", 476 | " beam_outputs = beam_scorer.process(\n", 477 | " input_ids,\n", 478 | " next_token_scores,\n", 479 | " next_tokens,\n", 480 | " next_indices,\n", 481 | " pad_token_id=pad_token_id,\n", 482 | " eos_token_id=eos_token_id,\n", 483 | " )\n", 484 | " beam_scores = beam_outputs[\"next_beam_scores\"]\n", 485 | " beam_next_tokens = beam_outputs[\"next_beam_tokens\"]\n", 486 | " beam_idx = beam_outputs[\"next_beam_indices\"]\n", 487 | " \n", 488 | " \n", 489 | " input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)\n", 490 | "\n", 491 | " cur_len += 1\n", 492 | " \n", 493 | " # update kwargs\n", 494 | " model_kwargs = model._update_model_kwargs_for_generation(\n", 495 | " output, model_kwargs, is_encoder_decoder=model.config.is_encoder_decoder\n", 496 | " )\n", 497 | " \n", 498 | " # update sequence length\n", 499 | " if eos_token_id is not None:\n", 500 | " sequence_lengths, unfinished_sequences = model._update_seq_length_for_generation(\n", 501 | " sequence_lengths, unfinished_sequences, cur_len, next_tokens == eos_token_id\n", 502 | " )\n", 503 | "\n", 504 | "\n", 505 | " # pretty sure this is early stopping\n", 506 | " if unfinished_sequences.max() == 0:\n", 507 | " break\n", 508 | " \n", 509 | "\n", 510 | " # pretty sure this is early stopping for the beam scorer\n", 511 | " if beam_scorer.is_done:\n", 512 | " break\n", 513 | " \n", 514 | " sequence_outputs = beam_scorer.finalize(\n", 515 | " input_ids, beam_scores, next_tokens, next_indices, pad_token_id=pad_token_id, eos_token_id=eos_token_id\n", 516 | " )\n", 517 | " \n", 518 | " return sequence_outputs[\"sequences\"], model_kwargs, sequence_outputs[\"sequence_scores\"]" 519 | ] 520 | }, 521 | { 522 | "cell_type": "code", 523 | "execution_count": null, 524 | "metadata": {}, 525 | "outputs": [], 526 | "source": [ 527 | "###### Journal \n", 528 | "journal_answer_df_lists = []\n", 529 | "\n", 530 | "for i, r in tqdm(df_test_not_human_eval.iterrows()):\n", 531 | "\n", 532 | " row = r.to_dict()\n", 533 | "\n", 534 | " ### make input\n", 535 | " q_doc = row['q_s2orc_doc']\n", 536 | " output_ids, model_kwargs, seq_scores = generate_s2s_DEexperts(context=q_doc, \n", 537 | " model=bart_model,\n", 538 | " expert_model=bart_journal_model,\n", 539 | " anti_model=bart_article_model,\n", 540 | " tokenizer=bart_tokenizer,\n", 541 | " top_k=50,\n", 542 | " top_p=.9,\n", 543 | " num_beams=10,\n", 544 | " max_length=64,\n", 545 | " min_length=8,\n", 546 | " no_repeat_ngram_size=3,\n", 547 | " expert_alpha = 1.0,\n", 548 | " num_return_sequences=10\n", 549 | " )\n", 550 | "\n", 551 | " # save all the answers with their associated scores in a df\n", 552 | " answers = [bart_tokenizer.decode(ans_ids, skip_special_tokens=True).strip() for ans_ids in output_ids]\n", 553 | " df_answers = pd.DataFrame(zip(answers, seq_scores), columns=['response', 'scores'])\n", 554 | " \n", 555 | " df_answers['model-type'] = 'DExpert-journal'\n", 556 | "\n", 557 | " # save information about the question\n", 558 | " df_answers['question'] = row['question']\n", 559 | " df_answers['category'] = row['category']\n", 560 | " df_answers['first_sentence'] = row['first_sentence']\n", 561 | "\n", 562 | " # append the df\n", 563 | " journal_answer_df_lists.append(df_answers)\n", 564 | "\n", 565 | " \n", 566 | "###### News\n", 567 | "article_answer_df_lists = []\n", 568 | "\n", 569 | "for i, r in tqdm(df_test_not_human_eval.iterrows()):\n", 570 | "\n", 571 | " row = r.to_dict()\n", 572 | "\n", 573 | " ### make input\n", 574 | " q_doc = row['q_s2orc_doc']\n", 575 | " output_ids, model_kwargs, seq_scores = generate_s2s_DEexperts(context=q_doc, \n", 576 | " model=bart_model,\n", 577 | " expert_model=bart_article_model,\n", 578 | " anti_model=bart_journal_model,\n", 579 | " tokenizer=bart_tokenizer,\n", 580 | " top_k=50,\n", 581 | " top_p=.9,\n", 582 | " num_beams=10,\n", 583 | " max_length=64,\n", 584 | " min_length=8,\n", 585 | " no_repeat_ngram_size=3,\n", 586 | " expert_alpha = 1.0,\n", 587 | " num_return_sequences=10\n", 588 | " )\n", 589 | "\n", 590 | " # save all the answers with their associated scores in a df\n", 591 | " answers = [bart_tokenizer.decode(ans_ids, skip_special_tokens=True).strip() for ans_ids in output_ids]\n", 592 | " df_answers = pd.DataFrame(zip(answers, seq_scores), columns=['response', 'scores'])\n", 593 | " df_answers['model-type'] = 'DExpert-article'\n", 594 | "\n", 595 | " # save information about the question\n", 596 | " df_answers['question'] = row['question']\n", 597 | " df_answers['category'] = row['category']\n", 598 | " df_answers['first_sentence'] = row['first_sentence']\n", 599 | "\n", 600 | " # append the df\n", 601 | " article_answer_df_lists.append(df_answers)\n", 602 | "\n", 603 | "\n", 604 | "\n", 605 | "DExperts_journal_test_answers = pd.concat(journal_answer_df_lists)\n", 606 | "DExperts_article_test_answers = pd.concat(article_answer_df_lists)\n" 607 | ] 608 | }, 609 | { 610 | "cell_type": "code", 611 | "execution_count": null, 612 | "metadata": {}, 613 | "outputs": [], 614 | "source": [ 615 | "# DExperts_journal_test_answers = pd.concat(journal_answer_df_lists)\n", 616 | "DExperts_journal_test_answers.to_csv('{}/model_answers/DExperts_journal_test_answers.csv'.format(DATA_DIR))\n", 617 | "DExperts_article_test_answers.to_csv('{}/model_answers/DExperts_article_test_answers.csv'.format(DATA_DIR))\n" 618 | ] 619 | }, 620 | { 621 | "cell_type": "markdown", 622 | "metadata": {}, 623 | "source": [ 624 | "# GeDi\n", 625 | "\n", 626 | "\n", 627 | "This has to be run twice, one for each of the arg sets (journal or news)\n" 628 | ] 629 | }, 630 | { 631 | "cell_type": "code", 632 | "execution_count": null, 633 | "metadata": {}, 634 | "outputs": [], 635 | "source": [ 636 | "# for namespacing the args\n", 637 | "class Bunch(object):\n", 638 | " def __init__(self, adict):\n", 639 | " self.__dict__.update(adict)\n", 640 | " \n", 641 | "args = {'model_type': 'bart',\n", 642 | " 'gedi_model_type': 'bart',\n", 643 | " 'gen_model_name_or_path': '{}/bart_medq_wiki_s2orc/default/'.format(MODEL_DIR),\n", 644 | " 'gedi_model_name_or_path': '/homes/gws/taugust/Projects/ARK/sci_comm/resources/GeDi/topic_GeDi_journal_news_bart_medq_wiki',\n", 645 | " 'fp16': True, 'load_in_half_prec': False,\n", 646 | " 'config_name': '', 'tokenizer_name': '',\n", 647 | " 'cache_dir': '', 'do_lower_case': False,\n", 648 | " 'no_cuda': False, 'gen_length': 64,\n", 649 | " 'stop_token': None, 'temperature': 1.0,\n", 650 | " 'disc_weight': 30.0, 'filter_p': 0.8, \n", 651 | " 'class_bias': None, 'target_p': 0.8,\n", 652 | " 'do_sample': True, 'repetition_penalty': 1.2,\n", 653 | " 'rep_penalty_scale': 10.0, 'penalize_cond': True,\n", 654 | " 'k': 50, 'p': 0.9, 'gen_type': 'gedi',\n", 655 | " 'mode': 'topic', 'secondary_code': 'journal', \n", 656 | " 'gpt3_api_key': None, \n", 657 | " 'prompt': None,\n", 658 | " 'num_return_sequences':10,\n", 659 | " 'device':DEVICE}\n", 660 | "\n", 661 | "args = Bunch(args_template)" 662 | ] 663 | }, 664 | { 665 | "cell_type": "code", 666 | "execution_count": null, 667 | "metadata": {}, 668 | "outputs": [], 669 | "source": [ 670 | "\n", 671 | "answer_df_lists_gedi_rows = []\n", 672 | "\n", 673 | "for i, r in tqdm(df_test.iterrows()):\n", 674 | " \n", 675 | " row = r.to_dict() \n", 676 | " \n", 677 | " args.prompt = row['q_s2orc_doc']\n", 678 | " args.term_start = None\n", 679 | " \n", 680 | " returned_answers = generate_GeDi.generate_GeDi_simple(args, tokenizer, model, gedi_model)\n", 681 | " \n", 682 | " # handle all the returned sequences\n", 683 | " for answer, output in returned_answers:\n", 684 | " new_row = row.copy()\n", 685 | " new_row['response'] = answer.strip('')\n", 686 | " new_row['output'] = output[1].cpu().numpy()[0]\n", 687 | " answer_df_lists_gedi_rows.append(new_row)\n", 688 | "\n", 689 | " \n", 690 | "### make the df -- curently for journal\n", 691 | "bart_gedi_journal_test_answers = pd.DataFrame(answer_df_lists_gedi_rows)\n", 692 | "\n", 693 | "\n", 694 | " " 695 | ] 696 | }, 697 | { 698 | "cell_type": "code", 699 | "execution_count": null, 700 | "metadata": {}, 701 | "outputs": [], 702 | "source": [ 703 | "### Saving (change to news when running that one)\n", 704 | "bart_gedi_journal_test_answers.to_csv('{}/model_answers/bart_gedi_journal_test_answers.csv'.format(DATA_DIR))\n" 705 | ] 706 | }, 707 | { 708 | "cell_type": "markdown", 709 | "metadata": {}, 710 | "source": [ 711 | "# Combining\n", 712 | "\n", 713 | "Combine all the answers into one df for evaluation\n" 714 | ] 715 | }, 716 | { 717 | "cell_type": "code", 718 | "execution_count": null, 719 | "metadata": {}, 720 | "outputs": [], 721 | "source": [ 722 | "\n", 723 | "#### Here taking the top 10, for the rest take all of them \n", 724 | "\n", 725 | "### Reranking SVM\n", 726 | "bart_test_answers_svm_journal = bart_test_answers_svm.groupby(['question']).apply(lambda g: utils.get_top(g, col='predictions', n=10)).reset_index(drop=True)\n", 727 | "bart_test_answers_svm_news = bart_test_answers_svm.groupby(['question']).apply(lambda g: utils.get_top(g, col='predictions', ascending=True, n=10)).reset_index(drop=True)\n", 728 | "\n" 729 | ] 730 | }, 731 | { 732 | "cell_type": "code", 733 | "execution_count": null, 734 | "metadata": {}, 735 | "outputs": [], 736 | "source": [ 737 | "### make sure all responses have model type\n", 738 | "\n", 739 | "### Rerankers\n", 740 | "bart_test_answers_svm_journal['model-type'] = 'svm-rerank-journal'\n", 741 | "bart_test_answers_svm_news['model-type'] = 'svm-rerank-news'\n", 742 | "\n", 743 | "### Gedi\n", 744 | "bart_gedi_news_test_answers['model-type'] = 'gedi-news'\n", 745 | "bart_gedi_journal_test_answers['model-type'] = 'gedi-journal'\n", 746 | "\n", 747 | "\n", 748 | "### DExperts \n", 749 | "DExperts_news_test_answers = DExperts_article_test_answers\n", 750 | "DExperts_journal_test_answers['model-type'] = 'DExpert-journal'\n", 751 | "DExperts_news_test_answers['model-type'] = 'DExpert-news'\n", 752 | "\n", 753 | "\n", 754 | "### PPLM\n", 755 | "bart_pplm_journal_test_answers['model-type'] = 'PPLM-journal'\n", 756 | "bart_pplm_news_test_answers['model-type'] = 'PPLM-news'" 757 | ] 758 | }, 759 | { 760 | "cell_type": "code", 761 | "execution_count": null, 762 | "metadata": {}, 763 | "outputs": [], 764 | "source": [ 765 | "common_columns = ['response', 'model-type', 'question', 'first_sentence', 'category']\n", 766 | "\n", 767 | "dfs = [bart_test_answers_bert_journal, bart_test_answers_bert_news,\n", 768 | " bart_test_answers_svm_journal, bart_test_answers_svm_news,\n", 769 | " bart_gedi_journal_test_answers, bart_gedi_news_test_answers,\n", 770 | " DExperts_journal_test_answers, DExperts_news_test_answers,\n", 771 | " bart_journals_test_answers, bart_articles_test_answers,\n", 772 | " bart_pplm_journal_test_answers, bart_pplm_news_test_answers]\n", 773 | "\n", 774 | "df = pd.concat([d[common_columns] for d in dfs])" 775 | ] 776 | }, 777 | { 778 | "cell_type": "code", 779 | "execution_count": null, 780 | "metadata": {}, 781 | "outputs": [], 782 | "source": [ 783 | "\n", 784 | "df.to_csv('{}/model_answers/test_complexity_responses.csv'.format(DATA_DIR))" 785 | ] 786 | }, 787 | { 788 | "cell_type": "markdown", 789 | "metadata": {}, 790 | "source": [ 791 | "# Complexity Measures\n", 792 | "\n", 793 | "Includes FK by concatting all definitions together" 794 | ] 795 | }, 796 | { 797 | "cell_type": "code", 798 | "execution_count": null, 799 | "metadata": {}, 800 | "outputs": [], 801 | "source": [ 802 | "from readability import Readability\n" 803 | ] 804 | }, 805 | { 806 | "cell_type": "code", 807 | "execution_count": null, 808 | "metadata": {}, 809 | "outputs": [], 810 | "source": [ 811 | "df = pd.read_csv('{}/model_answers/test_complexity_responses.csv'.format(DATA_DIR))" 812 | ] 813 | }, 814 | { 815 | "cell_type": "code", 816 | "execution_count": null, 817 | "metadata": {}, 818 | "outputs": [], 819 | "source": [ 820 | "df = df[df['word_count'] > 0] \n", 821 | "df = jargon_utils.make_jargon_features(df, text_col='response')" 822 | ] 823 | }, 824 | { 825 | "cell_type": "markdown", 826 | "metadata": {}, 827 | "source": [ 828 | "## Flesch Kincaid " 829 | ] 830 | }, 831 | { 832 | "cell_type": "code", 833 | "execution_count": null, 834 | "metadata": {}, 835 | "outputs": [], 836 | "source": [ 837 | "\n", 838 | "### function for getting the overall Flesch Kincaid score by concating all definitions in a df together \n", 839 | "def get_overall_fk(df, def_col='response'):\n", 840 | " all_defs = df[def_col].str.cat(sep=' ') \n", 841 | " all_defs_readability = Readability(all_defs)\n", 842 | " return all_defs_readability.flesch_kincaid()\n", 843 | "\n", 844 | "\n", 845 | "df.groupby(['model-type']).apply(lambda g: get_overall_fk(g))" 846 | ] 847 | } 848 | ], 849 | "metadata": { 850 | "kernelspec": { 851 | "display_name": "transformers", 852 | "language": "python", 853 | "name": "transformers" 854 | }, 855 | "language_info": { 856 | "codemirror_mode": { 857 | "name": "ipython", 858 | "version": 3 859 | }, 860 | "file_extension": ".py", 861 | "mimetype": "text/x-python", 862 | "name": "python", 863 | "nbconvert_exporter": "python", 864 | "pygments_lexer": "ipython3", 865 | "version": "3.7.6" 866 | } 867 | }, 868 | "nbformat": 4, 869 | "nbformat_minor": 4 870 | } 871 | -------------------------------------------------------------------------------- /generation/Definition Modeling Expirements.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Definition Modeling Expirements\n", 8 | "\n", 9 | "Notebook for what I imagine the first set of expirements will be. It will consist of testing a few different basic modeling approaches. \n", 10 | "\n", 11 | "1) **Sequence-to-Sequence**: Includes finetuned BART (question: {} context: {}) setup. \n", 12 | "\n", 13 | "2) **Language Modeling**: Includes off-the-shelf few-shot GPT2 and GPT3 (from the paper: ```We append two held-out term and definition pairs, along with the first abstract drawn from each supporting document (we use the first abstract only to keep the full input within the models’ context windows)```. Also finetuned GPT2 (with ``` term q context doc definition``` tags).\n", 14 | "\n", 15 | "3) **Informational Retrieval**: An extractive approach over the support docs, using BiDAF\n", 16 | "\n" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "from transformers import (\n", 26 | " AutoTokenizer,\n", 27 | " AutoModelForSeq2SeqLM,\n", 28 | " AutoConfig, \n", 29 | " AutoModelForCausalLM,\n", 30 | ")\n", 31 | "\n", 32 | "from importlib import reload \n", 33 | "from joblib import dump, load\n", 34 | "\n", 35 | "import os\n", 36 | "import sys\n", 37 | "from importlib import reload \n", 38 | "import pandas as pd\n", 39 | "import numpy as np\n", 40 | "import csv\n", 41 | "import nlp\n", 42 | "import json\n", 43 | "from sklearn.feature_extraction.text import TfidfVectorizer\n", 44 | "from sklearn.metrics.pairwise import cosine_similarity\n", 45 | "from nltk.tokenize import word_tokenize, sent_tokenize\n", 46 | "import random\n", 47 | "import uuid\n", 48 | "import spacy \n", 49 | "from tqdm import tqdm\n", 50 | "from spacy.pipeline import Sentencizer\n", 51 | "import re\n", 52 | "from typing import Iterable, List\n", 53 | "\n", 54 | "\n", 55 | "random.seed(42)\n", 56 | "\n", 57 | "sys.path.append('/lib')\n", 58 | "import utils\n", 59 | "\n", 60 | "MODEL_DIR = ''\n", 61 | "RESOURCE_DIR = ''\n", 62 | "DATA_DIR = ''\n", 63 | "\n", 64 | "\n" 65 | ] 66 | }, 67 | { 68 | "cell_type": "markdown", 69 | "metadata": {}, 70 | "source": [ 71 | "# Data" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "##### Dataset reloading - Ignore all of the above\n", 81 | "df_wiki_medq_strat_train = pd.read_csv('{}/model_data/train.csv'.format(DATA_DIR))\n", 82 | "df_wiki_medq_strat_dev = pd.read_csv('{}/model_data/dev.csv'.format(DATA_DIR))\n", 83 | "df_wiki_medq_strat_test = pd.read_csv('{}/model_data/test.csv'.format(DATA_DIR))\n", 84 | "\n", 85 | "\n", 86 | "df_medq_wiki = pd.concat([df_wiki_medq_strat_train, df_wiki_medq_strat_dev, df_wiki_medq_strat_test])\n", 87 | "\n", 88 | "# we use the dev set for testing the base generators, and reserve our test set for \n", 89 | "# complexity control, for training the generators we use splits of the train set\n", 90 | "df_test = df_wiki_medq_strat_dev " 91 | ] 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "metadata": {}, 96 | "source": [ 97 | "# GPUs" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": null, 103 | "metadata": {}, 104 | "outputs": [], 105 | "source": [ 106 | "GPU_NUMBER = ''\n", 107 | "CUDA_DEVICE = ''\n", 108 | "os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n", 109 | "os.environ['CUDA_VISIBLE_DEVICES'] = GPU_NUMBER\n", 110 | "\n", 111 | "DEVICE = 'cuda:0'\n" 112 | ] 113 | }, 114 | { 115 | "cell_type": "markdown", 116 | "metadata": {}, 117 | "source": [ 118 | "# Model Generations" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": null, 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [ 127 | "\n", 128 | "\n", 129 | "# function for wrapping the rather long code for generating answers across a df\n", 130 | "def generate_answers(df, model, tokenizer, model_type,\n", 131 | " num_return_sequences=1,\n", 132 | " num_beams=5,\n", 133 | " max_length=64,\n", 134 | " min_length=8,\n", 135 | " early_stopping=True,\n", 136 | " temperature=None,\n", 137 | " do_sample=True,\n", 138 | " top_k=50,\n", 139 | " top_p=0.9,\n", 140 | " max_input_length=1024,\n", 141 | " no_repeat_ngram_size=3,\n", 142 | " device=None):\n", 143 | " \n", 144 | " answer_df_lists = []\n", 145 | " for i, r in tqdm(df.iterrows()):\n", 146 | " \n", 147 | " # set, or reset lengths (mostly for gpt2)\n", 148 | " current_max_input = max_input_length\n", 149 | " max_output_length = max_length\n", 150 | " min_output_length = min_length\n", 151 | " \n", 152 | " row = r.to_dict()\n", 153 | "\n", 154 | " # make the input, doing truncation differently depending on if it is bart or gpt2\n", 155 | " if 'bart' in model_type.lower():\n", 156 | " \n", 157 | " # for bart, just truncate to max input length\n", 158 | " q_doc = row['q_s2orc_doc'] \n", 159 | " inputs = tokenizer(q_doc, return_tensors='pt', max_length=current_max_input, truncation=True)\n", 160 | " \n", 161 | " \n", 162 | " elif 'gpt'in model_type.lower():\n", 163 | " # for gpt2 truncate from the front to preserve the question at the end.\n", 164 | " q_doc = r['gpt2_task_row']\n", 165 | " \n", 166 | " # make space for input based on max output allowed \n", 167 | " current_max_input -= max_output_length \n", 168 | " \n", 169 | " inputs = tokenizer(q_doc, return_tensors='pt', truncation=False) \n", 170 | " input_length = inputs['input_ids'].shape[1]\n", 171 | " if input_length > current_max_input:\n", 172 | " print('Input length of {} is too long for max input of {}, truncating to {}.'.format(input_length, current_max_input, current_max_input))\n", 173 | " # this is truncating from the back\n", 174 | " inputs['input_ids'] = inputs['input_ids'][:, -current_max_input:]\n", 175 | " inputs['attention_mask'] = inputs['attention_mask'][:, -current_max_input:]\n", 176 | " input_length = current_max_input\n", 177 | " \n", 178 | " else:\n", 179 | " raise Exception('Model type {} not found!'.format(model_type))\n", 180 | " \n", 181 | " eos_token_id = tokenizer.eos_token_id\n", 182 | " \n", 183 | " \n", 184 | " # resize max length based on the size of the input for gpt models\n", 185 | " if 'gpt'in model_type.lower():\n", 186 | " max_output_length += input_length\n", 187 | " min_output_length += input_length\n", 188 | " if 'ootb' not in model_type.lower():\n", 189 | " # also set the special end token (if this is a finetuned gpt model) to the context token\n", 190 | " eos_token_id = tokenizer.additional_special_tokens_ids[1]\n", 191 | " \n", 192 | " outputs = model.generate(**inputs.to(device),\n", 193 | " decoder_start_token_id=tokenizer.bos_token_id,\n", 194 | " num_return_sequences=num_return_sequences,\n", 195 | " num_beams=num_beams, \n", 196 | " min_length=min_output_length,\n", 197 | " max_length=max_output_length, \n", 198 | " early_stopping=early_stopping, \n", 199 | " temperature=temperature,\n", 200 | " do_sample=do_sample,\n", 201 | " top_k=top_k,\n", 202 | " top_p=top_p,\n", 203 | " eos_token_id=eos_token_id,\n", 204 | " no_repeat_ngram_size=no_repeat_ngram_size,\n", 205 | " output_scores=True,\n", 206 | " return_dict_in_generate=True)\n", 207 | "\n", 208 | " # save all the answers with their associated scores in a df\n", 209 | " # because GPT2 includes what the answer was conditioned on, we have to strip that\n", 210 | " if 'gpt'in model_type.lower():\n", 211 | " answers = [tokenizer.decode(ans_ids[input_length:], skip_special_tokens=True).strip() for ans_ids in outputs[0]]\n", 212 | " else:\n", 213 | " answers = [tokenizer.decode(ans_ids, skip_special_tokens=True).strip() for ans_ids in outputs[0]]\n", 214 | " \n", 215 | " df_answers = pd.DataFrame(zip(answers, outputs['sequences_scores'].tolist()), columns=['response', 'scores'])\n", 216 | " \n", 217 | " df_answers['model-type'] = model_type\n", 218 | " \n", 219 | " # save information about the question\n", 220 | " df_answers['question'] = row['question']\n", 221 | " df_answers['category'] = row['category']\n", 222 | " df_answers['first_sentence'] = row['first_sentence']\n", 223 | " \n", 224 | " # append the df\n", 225 | " answer_df_lists.append(df_answers)\n", 226 | " \n", 227 | " return pd.concat(answer_df_lists)\n" 228 | ] 229 | }, 230 | { 231 | "cell_type": "markdown", 232 | "metadata": {}, 233 | "source": [ 234 | "## BART" 235 | ] 236 | }, 237 | { 238 | "cell_type": "code", 239 | "execution_count": null, 240 | "metadata": {}, 241 | "outputs": [], 242 | "source": [ 243 | "# Bart model - finetuned on medq s2orc\n", 244 | "bart_tokenizer = AutoTokenizer.from_pretrained(\"{}/bart_medq_wiki_gen\".format(MODEL_DIR))\n", 245 | "bart_model = AutoModelForSeq2SeqLM.from_pretrained(\"{}/bart_medq_wiki_gen\".format(MODEL_DIR))\n", 246 | "_ = bart_model.eval()\n" 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": null, 252 | "metadata": {}, 253 | "outputs": [], 254 | "source": [ 255 | "bart_answers = generate_answers(df=df_test, model=bart_model, tokenizer=bart_tokenizer, model_type='bart', use_decoder_prefix=False, device=DEVICE)" 256 | ] 257 | }, 258 | { 259 | "cell_type": "code", 260 | "execution_count": null, 261 | "metadata": {}, 262 | "outputs": [], 263 | "source": [ 264 | "with pd.option_context('display.max_colwidth', None):\n", 265 | " display(bart_answers[['question', 'first_sentence', 'response', 'scores']].sample(10))" 266 | ] 267 | }, 268 | { 269 | "cell_type": "code", 270 | "execution_count": null, 271 | "metadata": {}, 272 | "outputs": [], 273 | "source": [ 274 | "# move the bart model off the gpu\n", 275 | "bart_model=bart_model.cpu()" 276 | ] 277 | }, 278 | { 279 | "cell_type": "markdown", 280 | "metadata": {}, 281 | "source": [ 282 | "## Finetuned GPT2" 283 | ] 284 | }, 285 | { 286 | "cell_type": "code", 287 | "execution_count": null, 288 | "metadata": {}, 289 | "outputs": [], 290 | "source": [ 291 | "df_test['gpt2_task_row'] = [utils.make_gpt_doc(r['question'], r['support_doc_sparse_s2orc'], None, testing=True) for _,r in df_test.iterrows()] " 292 | ] 293 | }, 294 | { 295 | "cell_type": "code", 296 | "execution_count": null, 297 | "metadata": {}, 298 | "outputs": [], 299 | "source": [ 300 | "# GPT2 model - finetuned on medq and s2orc\n", 301 | "finetuned_gpt2_model_path = '/homes/gws/taugust/Projects/ARK/sci_comm/models/gpt2_full_gen'\n", 302 | "\n", 303 | "gpt2_model = AutoModelForCausalLM.from_pretrained(finetuned_gpt2_model_path).to(DEVICE)\n", 304 | "gpt2_tokenizer = AutoTokenizer.from_pretrained(finetuned_gpt2_model_path)" 305 | ] 306 | }, 307 | { 308 | "cell_type": "code", 309 | "execution_count": null, 310 | "metadata": {}, 311 | "outputs": [], 312 | "source": [ 313 | "gpt2_answers = generate_answers(df=df_test, model=gpt2_model, tokenizer=gpt2_tokenizer, model_type='gpt2', device=DEVICE)" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": null, 319 | "metadata": {}, 320 | "outputs": [], 321 | "source": [ 322 | "with pd.option_context('display.max_colwidth', None):\n", 323 | " display(gpt2_dev_answers[['question', 'first_sentence', 'response', 'scores']])" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": null, 329 | "metadata": {}, 330 | "outputs": [], 331 | "source": [ 332 | "gpt2_model=gpt2_model.cpu()" 333 | ] 334 | }, 335 | { 336 | "cell_type": "markdown", 337 | "metadata": {}, 338 | "source": [ 339 | "# OOTB GPT2\n", 340 | "\n", 341 | "Right now we are using the first two rows as a few shot setting, so MAKE SURE YOU TAKE THEM OUT IN SCORING" 342 | ] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": null, 347 | "metadata": {}, 348 | "outputs": [], 349 | "source": [ 350 | "### Input should be the context doc + 2 new lines + a templated question\n", 351 | "\n", 352 | "def make_templated_input(support_doc, question):\n", 353 | " return '{}\\n\\n{}'.format(support_doc, question)\n", 354 | "\n", 355 | "\n", 356 | "def make_few_shot_templated_input(support_doc, question, few_shot_prefix):\n", 357 | " return '{}\\n {}\\n\\n{}'.format(few_shot_prefix, support_doc, question)" 358 | ] 359 | }, 360 | { 361 | "cell_type": "code", 362 | "execution_count": null, 363 | "metadata": {}, 364 | "outputs": [], 365 | "source": [ 366 | "#### Ignoring the support doc\n", 367 | "\n", 368 | "def make_qa_prompt(q, definition):\n", 369 | " return 'question: {} \\ndefinition: {}'.format(q, definition)\n", 370 | "\n", 371 | "def make_task_row(few_shot_prefix, row):\n", 372 | " return '{}{}'.format(qa_few_shot_prefix, make_qa_prompt(row['question'], ''))\n", 373 | "\n", 374 | "\n", 375 | "row1=df_wiki_medq_strat_dev.iloc[0]\n", 376 | "row2=df_wiki_medq_strat_dev.iloc[1]\n", 377 | "\n", 378 | "\n", 379 | "ex1 = make_qa_prompt(row1['question'], row1['first_sentence'])\n", 380 | "ex2 = make_qa_prompt(row2['question'], row2['first_sentence'])\n", 381 | "\n", 382 | "qa_few_shot_prefix = '{}\\n\\n###\\n\\n{}\\n\\n###\\n\\n'.format(ex1, ex2)\n" 383 | ] 384 | }, 385 | { 386 | "cell_type": "code", 387 | "execution_count": null, 388 | "metadata": {}, 389 | "outputs": [], 390 | "source": [ 391 | "# to make this work with the above function, just remake the task row\n", 392 | "df_test['gpt2_task_row'] = [make_task_row(qa_few_shot_prefix, r) for _,r in df_test.iterrows()] " 393 | ] 394 | }, 395 | { 396 | "cell_type": "code", 397 | "execution_count": null, 398 | "metadata": {}, 399 | "outputs": [], 400 | "source": [ 401 | "ootb_gpt2_model = AutoModelForCausalLM.from_pretrained('gpt2-medium').to(DEVICE)\n", 402 | "ootb_gpt2_tokenizer = AutoTokenizer.from_pretrained('gpt2-medium')" 403 | ] 404 | }, 405 | { 406 | "cell_type": "code", 407 | "execution_count": null, 408 | "metadata": {}, 409 | "outputs": [], 410 | "source": [ 411 | "ootb_gpt2_answers = generate_answers(df=df_test[2:], model=ootb_gpt2_model, tokenizer=ootb_gpt2_tokenizer, model_type='ootb-gpt2', device=DEVICE)" 412 | ] 413 | }, 414 | { 415 | "cell_type": "code", 416 | "execution_count": null, 417 | "metadata": {}, 418 | "outputs": [], 419 | "source": [ 420 | "with pd.option_context('display.max_colwidth', None):\n", 421 | " display(ootb_gpt2_dev_answers[['question', 'first_sentence', 'generated_def', 'scores']])" 422 | ] 423 | }, 424 | { 425 | "cell_type": "code", 426 | "execution_count": null, 427 | "metadata": {}, 428 | "outputs": [], 429 | "source": [ 430 | "# at the end move the model off the gpu (if it was there)\n", 431 | "ootb_gpt2_model=ootb_gpt2_model.cpu()" 432 | ] 433 | }, 434 | { 435 | "cell_type": "markdown", 436 | "metadata": {}, 437 | "source": [ 438 | "# OOTB GPT3 - maxed out " 439 | ] 440 | }, 441 | { 442 | "cell_type": "code", 443 | "execution_count": null, 444 | "metadata": {}, 445 | "outputs": [], 446 | "source": [ 447 | "import openai\n", 448 | "ENV_DIR = ''\n", 449 | "\n", 450 | "# get the api key \n", 451 | "with open('{}/vars.txt'.format(ENV_DIR), 'r') as f:\n", 452 | " env_vars = f.readlines()\n", 453 | " \n", 454 | "env_vars = [tuple(v.split('=')) for v in env_vars]\n", 455 | "assert(env_vars[0][0] == 'OPENAI_API_KEY')\n", 456 | "open_api_key = env_vars[0][1]\n", 457 | "openai.api_key = open_api_key.strip()" 458 | ] 459 | }, 460 | { 461 | "cell_type": "code", 462 | "execution_count": null, 463 | "metadata": {}, 464 | "outputs": [], 465 | "source": [ 466 | "\n", 467 | "# from: https://beta.openai.com/docs/introduction/factual-responses\n", 468 | "def get_gpt3_output(openai, prompt, max_tokens=64):\n", 469 | " response = openai.Completion.create(\n", 470 | " engine=\"davinci\",\n", 471 | " prompt=prompt,\n", 472 | " max_tokens=max_tokens,\n", 473 | " top_p=0.9,\n", 474 | " frequency_penalty=0,\n", 475 | " presence_penalty=0,\n", 476 | " stop=[\"###\"]\n", 477 | " )\n", 478 | " return response['choices'][0]['text']" 479 | ] 480 | }, 481 | { 482 | "cell_type": "code", 483 | "execution_count": null, 484 | "metadata": {}, 485 | "outputs": [], 486 | "source": [ 487 | "prompt = '{}{}'.format(qa_few_shot_prefix, make_qa_prompt(test_row['question'], ''))" 488 | ] 489 | }, 490 | { 491 | "cell_type": "code", 492 | "execution_count": null, 493 | "metadata": {}, 494 | "outputs": [], 495 | "source": [ 496 | "ootb_gpt3_answers = df_test.sample(100, random_state=84, replace=False).copy()\n" 497 | ] 498 | }, 499 | { 500 | "cell_type": "code", 501 | "execution_count": null, 502 | "metadata": {}, 503 | "outputs": [], 504 | "source": [ 505 | "### because gpt3 just gives back out answers, duplicate the df_dev and set the response column to the output\n", 506 | "ootb_gpt3_answers['model-type'] = 'ootb-gpt3'\n", 507 | "ootb_gpt3_answers['response'] = [get_gpt3_output(openai, p, max_tokens=64) for p in tqdm(ootb_gpt3_dev_answers['gpt2_task_row'])]" 508 | ] 509 | }, 510 | { 511 | "cell_type": "code", 512 | "execution_count": null, 513 | "metadata": {}, 514 | "outputs": [], 515 | "source": [ 516 | "# ootb_gpt3_dev_answers = df[df['model-type'] == 'ootb-gpt3']\n", 517 | "with pd.option_context('display.max_colwidth', None):\n", 518 | " display(ootb_gpt3_answers[['question', 'first_sentence', 'response']])" 519 | ] 520 | }, 521 | { 522 | "cell_type": "markdown", 523 | "metadata": {}, 524 | "source": [ 525 | "# Evaluating \n", 526 | "\n", 527 | "Doing ROUGE and BERTscore" 528 | ] 529 | }, 530 | { 531 | "cell_type": "code", 532 | "execution_count": null, 533 | "metadata": {}, 534 | "outputs": [], 535 | "source": [ 536 | "from datasets import list_metrics, load_metric\n", 537 | "\n", 538 | "bert_score = load_metric(\"bertscore\")\n", 539 | "rouge = load_metric(\"rouge\")" 540 | ] 541 | }, 542 | { 543 | "cell_type": "code", 544 | "execution_count": null, 545 | "metadata": {}, 546 | "outputs": [], 547 | "source": [ 548 | "def calc_rouge(df, rouge_metric, ref_col, response_col):\n", 549 | " scores = rouge_metric.compute(\n", 550 | " predictions=df[response_col], references=df[ref_col],\n", 551 | " rouge_types=['rouge1', 'rouge2', 'rougeL', 'rougeLsum'],\n", 552 | " use_agregator=True, use_stemmer=False\n", 553 | " )\n", 554 | " rows = []\n", 555 | " measure_mapping = {'F':lambda x: x.mid.fmeasure}\n", 556 | "\n", 557 | " for t in scores.keys():\n", 558 | " for measure in ['F']:\n", 559 | " rows.append({'score_type':t, 'score_measure':measure, 'score':measure_mapping[measure](scores[t])})\n", 560 | " \n", 561 | " return pd.DataFrame(rows)" 562 | ] 563 | }, 564 | { 565 | "cell_type": "code", 566 | "execution_count": null, 567 | "metadata": {}, 568 | "outputs": [], 569 | "source": [ 570 | "df = pd.concat([ootb_gpt2_answers, gpt2_answers, bart_answers, df_extracted_answers])" 571 | ] 572 | }, 573 | { 574 | "cell_type": "code", 575 | "execution_count": null, 576 | "metadata": {}, 577 | "outputs": [], 578 | "source": [ 579 | "df.groupby(['model-type']).apply(lambda g: calc_rouge(g, rouge, ref_col='first_sentence', response_col='response'))" 580 | ] 581 | }, 582 | { 583 | "cell_type": "code", 584 | "execution_count": null, 585 | "metadata": {}, 586 | "outputs": [], 587 | "source": [ 588 | "scores = bert_score.compute(\n", 589 | " predictions=df['response'], references=df['first_sentence'], lang='en', verbose=False, device=None)\n", 590 | "\n", 591 | "df['bert_scores'] = scores['f1']\n", 592 | "df.groupby(['model-type'])['bert_scores'].describe()" 593 | ] 594 | }, 595 | { 596 | "cell_type": "code", 597 | "execution_count": null, 598 | "metadata": {}, 599 | "outputs": [], 600 | "source": [] 601 | } 602 | ], 603 | "metadata": { 604 | "kernelspec": { 605 | "display_name": "transformers", 606 | "language": "python", 607 | "name": "transformers" 608 | }, 609 | "language_info": { 610 | "codemirror_mode": { 611 | "name": "ipython", 612 | "version": 3 613 | }, 614 | "file_extension": ".py", 615 | "mimetype": "text/x-python", 616 | "name": "python", 617 | "nbconvert_exporter": "python", 618 | "pygments_lexer": "ipython3", 619 | "version": "3.7.6" 620 | } 621 | }, 622 | "nbformat": 4, 623 | "nbformat_minor": 4 624 | } 625 | -------------------------------------------------------------------------------- /lib/jargon_utils.py: -------------------------------------------------------------------------------- 1 | # extra functions for jargon constraints 2 | 3 | from nltk.stem import WordNetLemmatizer 4 | from nltk.tokenize import word_tokenize 5 | import numpy as np 6 | import csv as csv 7 | import pandas as pd 8 | import string 9 | import re 10 | from collections import Counter 11 | import spacy 12 | import requests 13 | from transformers import OpenAIGPTTokenizer, OpenAIGPTLMHeadModel 14 | import math 15 | from tqdm import tqdm 16 | import torch 17 | 18 | import os 19 | 20 | SCI_ARTICLES_DATA_DIR = '' 21 | SCI_ARTICLES_RESOURCE_DIRECTORY = '{}/resources'.format(SCI_ARTICLES_DATA_DIR) 22 | SPACY_EN = spacy.load("en_core_web_sm") 23 | 24 | wnl = WordNetLemmatizer() 25 | 26 | def lemmatize(wnl, tokens): 27 | return [wnl.lemmatize(t) for t in tokens] 28 | 29 | def num_words(tokens, word_list, return_words=False): 30 | counts = Counter(tokens) 31 | word_counts = {k: counts[k] for k in counts.keys() & set(word_list)} 32 | if return_words: 33 | return word_counts 34 | return sum(word_counts.values()) 35 | 36 | def jargon_normalized(passage, jargon_words): 37 | tokens = word_tokenize(passage) 38 | text_len = len(tokens) 39 | token_lemmas = lemmatize(wnl, tokens) 40 | 41 | return num_words(token_lemmas, jargon_words)/text_len 42 | 43 | 44 | def get_jargon_lists(): 45 | df_word_list_dejargonizer = pd.read_csv(SCI_ARTICLES_RESOURCE_DIRECTORY+'/jargon_word_list.csv') 46 | 47 | AVL_core = pd.read_excel(SCI_ARTICLES_RESOURCE_DIRECTORY+'/acadCore.xlsx', sheet_name=1) 48 | 49 | jargon_words = df_word_list_dejargonizer['General science jargon'] 50 | jargon_words = jargon_words.append(df_word_list_dejargonizer['Science common words']) 51 | jargon_words = jargon_words.append(AVL_core['word']) 52 | 53 | return jargon_words 54 | 55 | 56 | # using spacy now, and masking any word that falls in the jargon list 57 | def mask_jargon(passage, jargon_words, nlp_spacy=SPACY_EN): 58 | doc = nlp_spacy(passage) 59 | masked_doc = [] 60 | for token in doc: 61 | if token.lemma_ in list(jargon_words): 62 | masked_doc.append('<'+token.pos_+'>') 63 | else: 64 | masked_doc.append(token.text) 65 | return masked_doc 66 | 67 | 68 | #### loading 69 | with open('{}/full_avl_set.txt'.format(JARGON_RESOURCE_DIRECTORY), 'r') as f: 70 | AVL_set = f.readlines() 71 | 72 | AVL_set = set([t.strip('\n') for t in AVL_set]) 73 | 74 | def get_avl_occ(text, AVL_core_lemmas_set=AVL_set): 75 | lemmas = [t.lemma_ for t in text] 76 | return sum(x in AVL_core_lemmas_set for x in lemmas)/len(lemmas) 77 | 78 | 79 | ################################ 80 | ### Thing Explainer 81 | ################################ 82 | response = requests.get('https://splasho.com/upgoer5/phpspellcheck/dictionaries/1000.dicin') 83 | top_1000 = response.text.split('\n')[:-1] # last one is TRUE? 84 | 85 | def get_thing_explainer_oov(r, top_1000): 86 | # lemmatize 87 | lemmas = [t.lemma_ for t in r] 88 | 89 | # get occurances tokens out of top 1000 90 | return sum(x not in set(top_1000) for x in lemmas)/len(lemmas) 91 | 92 | 93 | ################################ 94 | ### Readability 95 | ################################ 96 | # do it for the full dataset 97 | def get_readability(r): 98 | try: 99 | return Readability(r).flesch_kincaid().score 100 | except: 101 | return None 102 | 103 | ################################ 104 | ### Function Words 105 | ################################ 106 | funct_pos_tags = ['DET', 'ADP', 'PRON', 'CONJ', 'SCONJ', 'AUX', 'PART', 'INTJ'] 107 | 108 | def get_num_function_words(text, funct_pos_tags): 109 | counts = Counter([t.pos_ for t in text]) 110 | return sum([counts[k] for k in funct_pos_tags]) 111 | 112 | 113 | ################################ 114 | ### GPT Perplexity 115 | ################################ 116 | 117 | 118 | tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt') 119 | model = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt') 120 | _ = model.eval() 121 | 122 | # from: https://github.com/huggingface/transformers/issues/473 123 | def score(sentence, tokenizer, model): 124 | # tokenize_input = tokenizer.tokenize(sentence, truncate) 125 | # tensor_input = torch.tensor([tokenizer.convert_tokens_to_ids(tokenize_input)]) 126 | tensor_input = torch.tensor([tokenizer(sentence, truncation=True)['input_ids']]) 127 | 128 | outputs=model(tensor_input, labels=tensor_input) 129 | return math.exp(outputs[0]) 130 | 131 | 132 | ##### Make the features -- assumes many variables from the cell above, so don't move 133 | def make_jargon_features(df, text_col='sentence'): 134 | # tokenize first - check that it doesn't exist already because it is a hassle to do over 135 | if 'sent_tokens' not in df.columns: 136 | print('Tokenizing....', end='') 137 | df['sent_tokens'] = [SPACY_EN(s) for s in tqdm(df[text_col])] 138 | print('Done') 139 | 140 | # Word count 141 | df['word_count'] = [len(s) for s in df['sent_tokens']] 142 | 143 | # AVL 144 | df['avl_occ'] = [get_avl_occ(t) for t in df['sent_tokens']] 145 | 146 | # Thing Explainer 147 | df['te_oov'] = [get_thing_explainer_oov(r, top_1000) for r in df['sent_tokens']] 148 | 149 | # Function Words 150 | df['function_words'] = [get_num_function_words(t, funct_pos_tags) for t in df['sent_tokens']] 151 | df['function_words_prop'] = df['function_words']/df['word_count'] 152 | 153 | if 'response_gpt_ppl_score' not in df.columns: 154 | # GPT Perplexity 155 | print('Getting GPT perplexity....', end='') 156 | df['response_gpt_ppl_score'] = [score(s, tokenizer, model) for s in tqdm(df[text_col])] 157 | print('Done') 158 | return df.copy() 159 | 160 | -------------------------------------------------------------------------------- /lib/utils.py: -------------------------------------------------------------------------------- 1 | # extra functions for analysis of sci_comm notebooks 2 | 3 | 4 | import statsmodels.formula.api as smf 5 | from scipy import stats 6 | from statsmodels.formula.api import ols 7 | import re 8 | # from sklearn.metrics.pairwise import cosine_similarity 9 | # from nltk.tokenize import word_tokenize, sent_tokenize 10 | 11 | 12 | DOI_PATTERN = r'\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\'<>])\S)+)\b' 13 | DOI_REGEX = re.compile(DOI_PATTERN) 14 | 15 | 16 | 17 | 18 | # function for extracting different top answer types 19 | # ascending=False means that taking the top number is the largest (least negative a lot of the time) 20 | def get_top(df, col, ascending=False, n=1): 21 | return df.sort_values(by=col, ascending=ascending).iloc[0:0+n] 22 | 23 | def make_q_doc(q, doc): 24 | return "question: {} context: {}".format(q, doc) 25 | 26 | def make_gpt_doc(q, doc, definition, testing=False): 27 | if testing: 28 | return "{}{}".format(doc, q) 29 | else: 30 | return "{}{}{}".format(doc, q, definition) 31 | 32 | # function for constraining each generation to start with 'Term is' 33 | def make_term_start(question): 34 | q_regex = re.compile('(What is \(are\) )|(Do you have information about )|(\?)') 35 | 36 | term = re.sub(q_regex, '', question) 37 | term_start = '{} is '.format(term) 38 | 39 | return term_start 40 | 41 | def make_decoder_inputs(tokenizer, question): 42 | 43 | term_start = make_term_start(question) 44 | 45 | decoder_inputs = tokenizer([term_start], max_length=24, return_tensors='pt', add_special_tokens=True) 46 | decoder_input_ids = decoder_inputs['input_ids'][:1, :-1] # strip of eos token 47 | 48 | return decoder_input_ids 49 | 50 | 51 | # first get rouge, to just make sure these responses are reasonable 52 | def calc_rouge(df, rouge_metric, ref_col, response_col): 53 | scores = rouge_metric.compute( 54 | predictions=df[response_col], references=df[ref_col], 55 | rouge_types=['rouge1', 'rouge2', 'rougeL', 'rougeLsum'], 56 | # rouge_types=['rougeL'], 57 | 58 | use_agregator=True, use_stemmer=False 59 | ) 60 | rows = [] 61 | measure_mapping = {'F':lambda x: x.mid.fmeasure} 62 | 63 | for t in scores.keys(): 64 | for measure in ['F']: 65 | rows.append({'score_type':t, 'score_measure':measure, 'score':measure_mapping[measure](scores[t])}) 66 | 67 | return pd.DataFrame(rows) 68 | 69 | 70 | # I just use this too much to not have it here 71 | def flatten_list(list_of_lists): 72 | return [item for sublist in list_of_lists for item in sublist] 73 | 74 | 75 | ##### Extractive Baseline Utils 76 | def get_tfidf(query, doc_sentences, vectorizer, n_results=7): 77 | 78 | docs_tfidf = vectorizer.fit_transform(doc_sentences) 79 | query_tfidf = vectorizer.transform([query]) 80 | 81 | cosine_similarities = cosine_similarity(query_tfidf, docs_tfidf).flatten() 82 | 83 | sentence_similarity = list(zip(cosine_similarities, doc_sentences)) 84 | 85 | return sorted(sentence_similarity, reverse=True, key=lambda tup: tup[0])[:n_results] 86 | 87 | 88 | 89 | def get_sentences(support_doc): 90 | return flatten_list([sent_tokenize(passage) for passage in support_doc.split('

')]) 91 | 92 | 93 | def chunks(lst, n): 94 | """Yield successive n-sized chunks from lst.""" 95 | for i in range(0, len(lst), n): 96 | yield lst[i:i + n] 97 | 98 | 99 | def combine_chunks(chunks): 100 | return [' '.join(c) for c in chunks] 101 | 102 | 103 | def get_and_chunk_sentences(support_doc, n=5): 104 | 105 | chunk_list = [] 106 | passages = support_doc.split('

') 107 | 108 | for p in passages: 109 | sentences = sent_tokenize(p) 110 | chunk_list.extend(combine_chunks(chunks(sentences, n))) 111 | 112 | return chunk_list 113 | 114 | 115 | 116 | 117 | 118 | def find_doi_links(links, regex=DOI_REGEX): 119 | return list(filter(regex.search, links)) 120 | 121 | 122 | # because some people wrote it weird or put it in the tags 123 | def is_int_annotation(annotation): 124 | text = annotation.text 125 | tags = annotation.tags # while tags technically is a list, it takes long to evaluate it as such, so just search it like a string 126 | return ('INT' in text) or ('INT' in tags) 127 | 128 | 129 | def run_logit(f, df, display_summary=False): 130 | logitfit = smf.logit(formula = str(f), data=df, missing = 'drop').fit() 131 | print('---------------------------------------') 132 | print(f, 'AIC:', logitfit.aic) 133 | if display_summary: 134 | display(logitfit.summary2()) 135 | print('---------------------------------------') 136 | return logitfit 137 | 138 | def run_ols(f, df, display_summary=False): 139 | results = ols(f, data=df, missing = 'drop').fit() 140 | print('---------------------------------------') 141 | print(f, 'AIC:', results.aic, 'Cohen\'s F2:', cohen_f2(results.rsquared_adj)) 142 | if display_summary: 143 | display(results.summary()) 144 | print('---------------------------------------') 145 | return results 146 | 147 | def run_mixed_effects(f, df, groups, display_summary=False): 148 | results = smf.mixedlm(f, data=df, missing = 'drop', groups=groups).fit() 149 | print('---------------------------------------') 150 | print(f, 'AIC:', results.aic, 'Cohen\'s F2:', cohen_f2(results.rsquared_adj)) 151 | if display_summary: 152 | display(results.summary()) 153 | print('---------------------------------------') 154 | return results 155 | 156 | # from: https://www.danielsoper.com/statcalc/calculator.aspx?id=5 157 | def cohen_f2(r_squared): 158 | return r_squared / (1 - r_squared) -------------------------------------------------------------------------------- /models/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/talaugust/definition-complexity/bcde113bafeb3aec728776af4d10d741bc365672/models/.DS_Store -------------------------------------------------------------------------------- /models/run_def_finetuning.sh: -------------------------------------------------------------------------------- 1 | # Bash script for finetuning gpt2 on definition generation 2 | # for args: https://github.com/huggingface/transformers/blob/master/src/transformers/training_args.py 3 | export DATA_DIR= 4 | export OUTPUT_DIR= 5 | 6 | 7 | ##### Best Params from HP tuning 8 | num_train_epochs=3 9 | block_size=1024 10 | learning_rate=4e-04 11 | gradient_accumulation_steps=16 12 | adam_epsilon=1e-07 13 | 14 | python run_clm.py \ 15 | --model_name_or_path gpt2 \ 16 | --train_file $DATA_DIR/medquad_wikipedia_with_sd_train.txt \ 17 | --validation_file $DATA_DIR/medquad_wikipedia_with_sd_dev.txt \ 18 | --num_train_epochs 3 \ 19 | --overwrite_output_dir \ 20 | --per_device_train_batch_size 1\ 21 | --per_device_eval_batch_size 1 \ 22 | --gradient_accumulation_steps $gradient_accumulation_steps \ 23 | --do_train \ 24 | --do_eval \ 25 | --output_dir $OUTPUT_DIR \ 26 | --block_size $block_size \ 27 | --save_strategy "no" \ 28 | --learning_rate $learning_rate \ 29 | --adam_epsilon $adam_epsilon \ 30 | --fp16 -------------------------------------------------------------------------------- /models/run_summarization.sh: -------------------------------------------------------------------------------- 1 | # Bash script for finetuning bart on definition generation 2 | 3 | export DATA_DIR= 4 | export OUTPUT_DIR= 5 | 6 | ##### Best Params from HP tuning -- turns out to be the default actually max_source == 1024 7 | num_train_epochs=3 8 | max_target_length=64 9 | max_source_length=512 10 | learning_rate=5e-05 11 | gradient_accumulation_steps=8 12 | adam_epsilon=1e-08 13 | 14 | python run_summarization.py \ 15 | --model_name_or_path facebook/bart-large \ 16 | --do_train \ 17 | --do_eval \ 18 | --num_train_epochs $num_train_epochs \ 19 | --train_file $DATA_DIR/medquad_wikipedia_with_sd_train.csv \ 20 | --validation_file $DATA_DIR/medquad_wikipedia_with_sd_dev.csv \ 21 | --text_column q_s2orc_doc \ 22 | --summary_column first_sentence \ 23 | --output_dir $OUTPUT_DIR \ 24 | --overwrite_output_dir \ 25 | --per_device_train_batch_size 1 \ 26 | --per_device_eval_batch_size 1 \ 27 | --gradient_accumulation_steps $gradient_accumulation_steps \ 28 | --predict_with_generate \ 29 | --max_source_length $max_source_length \ 30 | --max_target_length $max_target_length \ 31 | --save_strategy "no" \ 32 | --learning_rate $learning_rate \ 33 | --adam_epsilon $adam_epsilon \ 34 | --fp16 \ 35 | # --max_train_samples 500 \ 36 | # --max_val_samples 500 \ 37 | # --no_cuda \ 38 | # --save_steps 1500 \ 39 | --------------------------------------------------------------------------------