├── .gitignore ├── .vscode └── launch.json ├── DATA_LICENSE ├── LICENSE ├── README.md ├── WEIGHT_DIFF_LICENSE ├── data ├── README.md ├── alpaca_plus │ ├── README.md │ ├── alpaca_plus_train.json │ ├── alpaca_plus_validation_human.json │ ├── alpaca_plus_validation_seen.json │ └── alpaca_plus_validation_unseen.json ├── benchmarking │ ├── pytorch-flan-t5-xxl-benchmarking-human.csv │ ├── pytorch-llama-7b-benchmarking-human.csv │ └── pytorch-llama-7b-benchmarking-prompt-human.csv ├── create_alpaca_plus_data.py └── results │ ├── chatgpt │ ├── chatgpt-FLAN-T5-gist-1-vs-FLAN-T5-pos_control-1-validation_human-16000.json │ ├── chatgpt-FLAN-T5-gist-1-vs-FLAN-T5-pos_control-1-validation_seen-16000.json │ ├── chatgpt-FLAN-T5-gist-1-vs-FLAN-T5-pos_control-1-validation_unseen-16000.json │ ├── chatgpt-FLAN-T5-gist-10-vs-FLAN-T5-pos_control-1-validation_human-16000.json │ ├── chatgpt-FLAN-T5-gist-10-vs-FLAN-T5-pos_control-1-validation_seen-16000.json │ ├── chatgpt-FLAN-T5-gist-10-vs-FLAN-T5-pos_control-1-validation_unseen-16000.json │ ├── chatgpt-FLAN-T5-gist-2-vs-FLAN-T5-pos_control-1-validation_human-16000.json │ ├── chatgpt-FLAN-T5-gist-2-vs-FLAN-T5-pos_control-1-validation_seen-16000.json │ ├── chatgpt-FLAN-T5-gist-2-vs-FLAN-T5-pos_control-1-validation_unseen-16000.json │ ├── chatgpt-FLAN-T5-gist-5-vs-FLAN-T5-pos_control-1-validation_human-16000.json │ ├── chatgpt-FLAN-T5-gist-5-vs-FLAN-T5-pos_control-1-validation_seen-16000.json │ ├── chatgpt-FLAN-T5-gist-5-vs-FLAN-T5-pos_control-1-validation_unseen-16000.json │ ├── chatgpt-FLAN-T5-neg_control-1-vs-FLAN-T5-pos_control-1-validation_human-16000.json │ ├── chatgpt-FLAN-T5-neg_control-1-vs-FLAN-T5-pos_control-1-validation_seen-16000.json │ ├── chatgpt-FLAN-T5-neg_control-1-vs-FLAN-T5-pos_control-1-validation_unseen-16000.json │ ├── chatgpt-LLaMA-gist-1-vs-LLaMA-pos_control-1-validation_human-3000.json │ ├── chatgpt-LLaMA-gist-1-vs-LLaMA-pos_control-1-validation_seen-3000.json │ ├── chatgpt-LLaMA-gist-1-vs-LLaMA-pos_control-1-validation_unseen-3000.json │ ├── chatgpt-LLaMA-gist-10-vs-LLaMA-pos_control-1-validation_human-3000.json │ ├── chatgpt-LLaMA-gist-10-vs-LLaMA-pos_control-1-validation_seen-3000.json │ ├── chatgpt-LLaMA-gist-10-vs-LLaMA-pos_control-1-validation_unseen-3000.json │ ├── chatgpt-LLaMA-gist-2-vs-LLaMA-pos_control-1-validation_human-3000.json │ ├── chatgpt-LLaMA-gist-2-vs-LLaMA-pos_control-1-validation_seen-3000.json │ ├── chatgpt-LLaMA-gist-2-vs-LLaMA-pos_control-1-validation_unseen-3000.json │ ├── chatgpt-LLaMA-gist-5-vs-LLaMA-pos_control-1-validation_human-3000.json │ ├── chatgpt-LLaMA-gist-5-vs-LLaMA-pos_control-1-validation_seen-3000.json │ ├── chatgpt-LLaMA-gist-5-vs-LLaMA-pos_control-1-validation_unseen-3000.json │ ├── chatgpt-LLaMA-neg_control-1-vs-LLaMA-pos_control-1-validation_human-3000.json │ ├── chatgpt-LLaMA-neg_control-1-vs-LLaMA-pos_control-1-validation_seen-3000.json │ └── chatgpt-LLaMA-neg_control-1-vs-LLaMA-pos_control-1-validation_unseen-3000.json │ ├── model_outputs │ ├── FLAN-T5-gist-1 │ │ ├── outputs-16000-validation_human.csv │ │ ├── outputs-16000-validation_seen.csv │ │ └── outputs-16000-validation_unseen.csv │ ├── FLAN-T5-gist-10 │ │ ├── outputs-16000-validation_human.csv │ │ ├── outputs-16000-validation_seen.csv │ │ └── outputs-16000-validation_unseen.csv │ ├── FLAN-T5-gist-2 │ │ ├── outputs-16000-validation_human.csv │ │ ├── outputs-16000-validation_seen.csv │ │ └── outputs-16000-validation_unseen.csv │ ├── FLAN-T5-gist-5 │ │ ├── outputs-16000-validation_human.csv │ │ ├── outputs-16000-validation_seen.csv │ │ └── outputs-16000-validation_unseen.csv │ ├── FLAN-T5-neg_control-1 │ │ ├── outputs-16000-validation_human.csv │ │ ├── outputs-16000-validation_seen.csv │ │ └── outputs-16000-validation_unseen.csv │ ├── FLAN-T5-pos_control-1 │ │ ├── outputs-16000-validation_human.csv │ │ ├── outputs-16000-validation_seen.csv │ │ └── outputs-16000-validation_unseen.csv │ ├── LLaMA-gist-1 │ │ ├── outputs-3000-validation_human.csv │ │ ├── outputs-3000-validation_seen.csv │ │ └── outputs-3000-validation_unseen.csv │ ├── LLaMA-gist-10 │ │ ├── outputs-3000-validation_human.csv │ │ ├── outputs-3000-validation_seen.csv │ │ └── outputs-3000-validation_unseen.csv │ ├── LLaMA-gist-2 │ │ ├── outputs-3000-validation_human.csv │ │ ├── outputs-3000-validation_seen.csv │ │ └── outputs-3000-validation_unseen.csv │ ├── LLaMA-gist-5 │ │ ├── outputs-3000-validation_human.csv │ │ ├── outputs-3000-validation_seen.csv │ │ └── outputs-3000-validation_unseen.csv │ ├── LLaMA-neg_control-1 │ │ ├── outputs-3000-validation_human.csv │ │ ├── outputs-3000-validation_seen.csv │ │ └── outputs-3000-validation_unseen.csv │ └── LLaMA-pos_control-1 │ │ ├── outputs-3000-validation_human.csv │ │ ├── outputs-3000-validation_seen.csv │ │ └── outputs-3000-validation_unseen.csv │ └── rouge.csv ├── ds_configs ├── README.md └── stage3.json ├── requirements.txt ├── run_deepspeed.sh ├── scripts ├── eval_all.py └── eval_chatgpt.py └── src ├── __init__.py ├── arguments.py ├── benchmarking.py ├── compress.py ├── conf ├── config.yaml ├── experiment │ └── debug.yaml ├── launcher │ └── slurm.yaml └── model │ ├── README.md │ ├── flan-t5-base.yaml │ ├── flan-t5-large.yaml │ ├── flan-t5-xxl.yaml │ ├── llama-7b.yaml │ └── llama-debug.yaml ├── data ├── __init__.py ├── alpaca │ ├── __init__.py │ ├── alpaca.py │ └── collator.py ├── gist.py └── utils.py ├── generation_utils.py ├── gist_caching.py ├── gist_llama.py ├── gist_t5.py ├── integrations.py ├── metrics.py ├── train.py ├── trainer_seq2seq.py ├── utils.py └── weight_diff.py /.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 | 131 | wandb/ 132 | 133 | # VSCode 134 | .vscode/* 135 | !.vscode/settings.json 136 | !.vscode/tasks.json 137 | !.vscode/launch.json 138 | !.vscode/extensions.json 139 | 140 | # Hydra 141 | .hydra 142 | multirun.yaml 143 | .submitit 144 | 145 | # These should be symlinked. 146 | exp 147 | .cache 148 | llama-7b 149 | 150 | # Download data manually. 151 | data/all_instances_82K.jsonl 152 | data/alpaca_data.json 153 | data/user_oriented_instructions.jsonl 154 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "debug_flan_t5", 9 | "type": "python", 10 | "request": "launch", 11 | "module": "src.train", 12 | "justMyCode": false, 13 | "args": [ 14 | "+experiment=debug", 15 | "wandb.log=true", 16 | ], 17 | "env": { 18 | "CUDA_VISIBLE_DEVICES": "0", 19 | "CUDA_LAUNCH_BLOCKING": "1", 20 | } 21 | }, 22 | { 23 | "name": "debug_llama", 24 | "type": "python", 25 | "request": "launch", 26 | "module": "src.train", 27 | "justMyCode": false, 28 | "args": [ 29 | "+experiment=debug", 30 | "+model=llama-debug", 31 | "wandb.log=true", 32 | ], 33 | "env": { 34 | "CUDA_VISIBLE_DEVICES": "0", 35 | "CUDA_LAUNCH_BLOCKING": "1", 36 | } 37 | }, 38 | { 39 | "name": "debug_benchmarking", 40 | "type": "python", 41 | "request": "launch", 42 | "module": "src.train", 43 | "console": "integratedTerminal", 44 | "justMyCode": false, 45 | "args": [ 46 | "+model=llama-debug", 47 | // "+model=flan-t5-base", 48 | "training.do_train=false", 49 | "training.do_benchmarking=true", 50 | "training.do_benchmarking_sanity_checks=true", 51 | "training.max_benchmarking_samples=5", 52 | "training.gist.num_gist_tokens=1", 53 | "training.gist.condition=gist", 54 | "training.benchmarking_profiler=pytorch", 55 | "training.benchmarking_output_file=standard.csv", 56 | // Set llama-debug above and uncomment these lines to do prompt 57 | // caching rather than gist caching. 58 | // "training.benchmarking_output_file=standard-prompt.csv", 59 | // "training.benchmarking_prompt_caching=true", 60 | ], 61 | "env": { 62 | "CUDA_VISIBLE_DEVICES": "1", 63 | } 64 | }, 65 | ] 66 | } -------------------------------------------------------------------------------- /DATA_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 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. Copyright and Similar Rights means copyright and/or similar rights 88 | closely related to copyright including, without limitation, 89 | performance, broadcast, sound recording, and Sui Generis Database 90 | Rights, without regard to how the rights are labeled or 91 | categorized. For purposes of this Public License, the rights 92 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 93 | Rights. 94 | d. Effective Technological Measures means those measures that, in the 95 | absence of proper authority, may not be circumvented under laws 96 | fulfilling obligations under Article 11 of the WIPO Copyright 97 | Treaty adopted on December 20, 1996, and/or similar international 98 | agreements. 99 | 100 | e. Exceptions and Limitations means fair use, fair dealing, and/or 101 | any other exception or limitation to Copyright and Similar Rights 102 | that applies to Your use of the Licensed Material. 103 | 104 | f. Licensed Material means the artistic or literary work, database, 105 | or other material to which the Licensor applied this Public 106 | License. 107 | 108 | g. Licensed Rights means the rights granted to You subject to the 109 | terms and conditions of this Public License, which are limited to 110 | all Copyright and Similar Rights that apply to Your use of the 111 | Licensed Material and that the Licensor has authority to license. 112 | 113 | h. Licensor means the individual(s) or entity(ies) granting rights 114 | under this Public License. 115 | 116 | i. NonCommercial means not primarily intended for or directed towards 117 | commercial advantage or monetary compensation. For purposes of 118 | this Public License, the exchange of the Licensed Material for 119 | other material subject to Copyright and Similar Rights by digital 120 | file-sharing or similar means is NonCommercial provided there is 121 | no payment of monetary compensation in connection with the 122 | exchange. 123 | 124 | j. Share means to provide material to the public by any means or 125 | process that requires permission under the Licensed Rights, such 126 | as reproduction, public display, public performance, distribution, 127 | dissemination, communication, or importation, and to make material 128 | available to the public including in ways that members of the 129 | public may access the material from a place and at a time 130 | individually chosen by them. 131 | 132 | k. Sui Generis Database Rights means rights other than copyright 133 | resulting from Directive 96/9/EC of the European Parliament and of 134 | the Council of 11 March 1996 on the legal protection of databases, 135 | as amended and/or succeeded, as well as other essentially 136 | equivalent rights anywhere in the world. 137 | 138 | l. You means the individual or entity exercising the Licensed Rights 139 | under this Public License. Your has a corresponding meaning. 140 | 141 | 142 | Section 2 -- Scope. 143 | 144 | a. License grant. 145 | 146 | 1. Subject to the terms and conditions of this Public License, 147 | the Licensor hereby grants You a worldwide, royalty-free, 148 | non-sublicensable, non-exclusive, irrevocable license to 149 | exercise the Licensed Rights in the Licensed Material to: 150 | 151 | a. reproduce and Share the Licensed Material, in whole or 152 | in part, for NonCommercial purposes only; and 153 | 154 | b. produce, reproduce, and Share Adapted Material for 155 | NonCommercial purposes only. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. No downstream restrictions. You may not offer or impose 186 | any additional or different terms or conditions on, or 187 | apply any Effective Technological Measures to, the 188 | Licensed Material if doing so restricts exercise of the 189 | Licensed Rights by any recipient of the Licensed 190 | Material. 191 | 192 | 6. No endorsement. Nothing in this Public License constitutes or 193 | may be construed as permission to assert or imply that You 194 | are, or that Your use of the Licensed Material is, connected 195 | with, or sponsored, endorsed, or granted official status by, 196 | the Licensor or others designated to receive attribution as 197 | provided in Section 3(a)(1)(A)(i). 198 | 199 | b. Other rights. 200 | 201 | 1. Moral rights, such as the right of integrity, are not 202 | licensed under this Public License, nor are publicity, 203 | privacy, and/or other similar personality rights; however, to 204 | the extent possible, the Licensor waives and/or agrees not to 205 | assert any such rights held by the Licensor to the limited 206 | extent necessary to allow You to exercise the Licensed 207 | Rights, but not otherwise. 208 | 209 | 2. Patent and trademark rights are not licensed under this 210 | Public License. 211 | 212 | 3. To the extent possible, the Licensor waives any right to 213 | collect royalties from You for the exercise of the Licensed 214 | Rights, whether directly or through a collecting society 215 | under any voluntary or waivable statutory or compulsory 216 | licensing scheme. In all other cases the Licensor expressly 217 | reserves any right to collect such royalties, including when 218 | the Licensed Material is used other than for NonCommercial 219 | purposes. 220 | 221 | 222 | Section 3 -- License Conditions. 223 | 224 | Your exercise of the Licensed Rights is expressly made subject to the 225 | following conditions. 226 | 227 | a. Attribution. 228 | 229 | 1. If You Share the Licensed Material (including in modified 230 | form), You must: 231 | 232 | a. retain the following if it is supplied by the Licensor 233 | with the Licensed Material: 234 | 235 | i. identification of the creator(s) of the Licensed 236 | Material and any others designated to receive 237 | attribution, in any reasonable manner requested by 238 | the Licensor (including by pseudonym if 239 | designated); 240 | 241 | ii. a copyright notice; 242 | 243 | iii. a notice that refers to this Public License; 244 | 245 | iv. a notice that refers to the disclaimer of 246 | warranties; 247 | 248 | v. a URI or hyperlink to the Licensed Material to the 249 | extent reasonably practicable; 250 | 251 | b. indicate if You modified the Licensed Material and 252 | retain an indication of any previous modifications; and 253 | 254 | c. indicate the Licensed Material is licensed under this 255 | Public License, and include the text of, or the URI or 256 | hyperlink to, this Public License. 257 | 258 | 2. You may satisfy the conditions in Section 3(a)(1) in any 259 | reasonable manner based on the medium, means, and context in 260 | which You Share the Licensed Material. For example, it may be 261 | reasonable to satisfy the conditions by providing a URI or 262 | hyperlink to a resource that includes the required 263 | information. 264 | 265 | 3. If requested by the Licensor, You must remove any of the 266 | information required by Section 3(a)(1)(A) to the extent 267 | reasonably practicable. 268 | 269 | 4. If You Share Adapted Material You produce, the Adapter's 270 | License You apply must not prevent recipients of the Adapted 271 | Material from complying with this Public License. 272 | 273 | 274 | Section 4 -- Sui Generis Database Rights. 275 | 276 | Where the Licensed Rights include Sui Generis Database Rights that 277 | apply to Your use of the Licensed Material: 278 | 279 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 280 | to extract, reuse, reproduce, and Share all or a substantial 281 | portion of the contents of the database for NonCommercial purposes 282 | only; 283 | 284 | b. if You include all or a substantial portion of the database 285 | contents in a database in which You have Sui Generis Database 286 | Rights, then the database in which You have Sui Generis Database 287 | Rights (but not its individual contents) is Adapted Material; and 288 | 289 | c. You must comply with the conditions in Section 3(a) if You Share 290 | all or a substantial portion of the contents of the database. 291 | 292 | For the avoidance of doubt, this Section 4 supplements and does not 293 | replace Your obligations under this Public License where the Licensed 294 | Rights include other Copyright and Similar Rights. 295 | 296 | 297 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 298 | 299 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 300 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 301 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 302 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 303 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 304 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 305 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 306 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 307 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 308 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 309 | 310 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 311 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 312 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 313 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 314 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 315 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 316 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 317 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 318 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 319 | 320 | c. The disclaimer of warranties and limitation of liability provided 321 | above shall be interpreted in a manner that, to the extent 322 | possible, most closely approximates an absolute disclaimer and 323 | waiver of all liability. 324 | 325 | 326 | Section 6 -- Term and Termination. 327 | 328 | a. This Public License applies for the term of the Copyright and 329 | Similar Rights licensed here. However, if You fail to comply with 330 | this Public License, then Your rights under this Public License 331 | terminate automatically. 332 | 333 | b. Where Your right to use the Licensed Material has terminated under 334 | Section 6(a), it reinstates: 335 | 336 | 1. automatically as of the date the violation is cured, provided 337 | it is cured within 30 days of Your discovery of the 338 | violation; or 339 | 340 | 2. upon express reinstatement by the Licensor. 341 | 342 | For the avoidance of doubt, this Section 6(b) does not affect any 343 | right the Licensor may have to seek remedies for Your violations 344 | of this Public License. 345 | 346 | c. For the avoidance of doubt, the Licensor may also offer the 347 | Licensed Material under separate terms or conditions or stop 348 | distributing the Licensed Material at any time; however, doing so 349 | will not terminate this Public License. 350 | 351 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 352 | License. 353 | 354 | 355 | Section 7 -- Other Terms and Conditions. 356 | 357 | a. The Licensor shall not be bound by any additional or different 358 | terms or conditions communicated by You unless expressly agreed. 359 | 360 | b. Any arrangements, understandings, or agreements regarding the 361 | Licensed Material not stated herein are separate from and 362 | independent of the terms and conditions of this Public License. 363 | 364 | 365 | Section 8 -- Interpretation. 366 | 367 | a. For the avoidance of doubt, this Public License does not, and 368 | shall not be interpreted to, reduce, limit, restrict, or impose 369 | conditions on any use of the Licensed Material that could lawfully 370 | be made without permission under this Public License. 371 | 372 | b. To the extent possible, if any provision of this Public License is 373 | deemed unenforceable, it shall be automatically reformed to the 374 | minimum extent necessary to make it enforceable. If the provision 375 | cannot be reformed, it shall be severed from this Public License 376 | without affecting the enforceability of the remaining terms and 377 | conditions. 378 | 379 | c. No term or condition of this Public License will be waived and no 380 | failure to comply consented to unless expressly agreed to by the 381 | Licensor. 382 | 383 | d. Nothing in this Public License constitutes or may be interpreted 384 | as a limitation upon, or waiver of, any privileges and immunities 385 | that apply to the Licensor or You, including from the legal 386 | processes of any jurisdiction or authority. 387 | 388 | ======================================================================= 389 | 390 | Creative Commons is not a party to its public 391 | licenses. Notwithstanding, Creative Commons may elect to apply one of 392 | its public licenses to material it publishes and in those instances 393 | will be considered the “Licensor.” The text of the Creative Commons 394 | public licenses is dedicated to the public domain under the CC0 Public 395 | Domain Dedication. Except for the limited purpose of indicating that 396 | material is shared under a Creative Commons public license or as 397 | otherwise permitted by the Creative Commons policies published at 398 | creativecommons.org/policies, Creative Commons does not authorize the 399 | use of the trademark "Creative Commons" or any other trademark or logo 400 | of Creative Commons without its prior written consent including, 401 | without limitation, in connection with any unauthorized modifications 402 | to any of its public licenses or any other arrangements, 403 | understandings, or agreements concerning use of licensed material. For 404 | the avoidance of doubt, this paragraph does not form part of the 405 | public licenses. 406 | 407 | Creative Commons may be contacted at creativecommons.org. 408 | -------------------------------------------------------------------------------- /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 | # Learning to Compress Prompts with Gist Tokens 2 | 3 | This repository contains code and data for "Learning to Compress Prompts with Gist Tokens." 4 | 5 | ## Setup 6 | 7 | This codebase has been tested with python 3.9.16 and pytorch 2.0.0. I recommend creating a new virtual env (e.g. with Conda), then installing torch manually from `pytorch.org`. `pip install -r requirements.txt` should take care of the remaining dependencies. 8 | 9 | > [!IMPORTANT] 10 | > This codebase requires a specific version of Transformers: commit [fb366b9a](https://github.com/huggingface/transformers/tree/fb366b9a2a94b38171896f6ba9fb9ae8bffd77af). Installing from `requirements.txt` should install the correct version. **Newer Transformers releases will not work, as some function signatures have changed in `modeling_llama.py`** (see [this issue](https://github.com/jayelm/gisting/issues/10)). 11 | 12 | > [!IMPORTANT] 13 | > Training results are reproducible only with **DeepSpeed version 0.8.3.** For some (currently unknown) reason, newer DeepSpeed versions result in some performance degradation (see [this issue](https://github.com/jayelm/gisting/issues/9)). 14 | 15 | ### Setup local directories 16 | 17 | By default, experiment runs and model checkpoints are saved to `exp/` directory 18 | in root directory, and cached models (downloaded from the Huggingface Hub) and 19 | datasets are saved to `.cache/`. Be sure to create these directories before 20 | running for the first time. 21 | 22 | I recommend either changing these directories in the config, or symlinking them 23 | to wherever you have plenty of space on your machine. 24 | 25 | LLaMA-7B experiments expect a folder called `llama-7b` in the root directory 26 | with model weights and tokenizer. 27 | 28 | ### Setup Weights & Biases (training only) 29 | 30 | If you'd like to train models (not just use them), set up a [Weights & Biases account](https://wandb.ai/) for experiment logging, and replace my username with yours in the `wandb.entity` field of `src/conf/config.yaml` [here](https://github.com/jayelm/gisting/blob/main/src/conf/config.yaml#L22). 31 | 32 | ## Demo + Checkpoints 33 | 34 | Checkpoints for the 1 token gist models for LLaMA-7B and FLAN-T5-XXL (as well as positive and negative controls) are now available on Hugging Face: 35 | 36 | - **LLaMA-7B** 37 | - [Gist](https://huggingface.co/jayelm/llama-7b-gist-1) 38 | - [Pos Control](https://huggingface.co/jayelm/llama-7b-pos_control-1) 39 | - [Neg Control](https://huggingface.co/jayelm/llama-7b-neg_control-1) 40 | - **FLAN-T5-XXL** 41 | - [Gist](https://huggingface.co/jayelm/flan-t5-xxl-gist-1) 42 | - [Pos Control](https://huggingface.co/jayelm/flan-t5-xxl-pos_control-1) 43 | - [Neg Control](https://huggingface.co/jayelm/flan-t5-xxl-neg_control-1) 44 | 45 | > [!NOTE] 46 | > The released LLaMA-7B checkpoints are **weight diffs**. You must have the base LLaMA-7B weights to recover the original model. Please use the `src/weight_diff.py` script to recover the original model given the weight diffs above, following the instructions [in the Alpaca repository](https://github.com/tatsu-lab/stanford_alpaca#recovering-alpaca-weights) (**but using my script instead**). Alternatively, if you use the `compress.py` script below and specify one of the Hugging Face diffs, the weight diff will be automatically applied for you if you supply `--base_llama_path`. 47 | 48 | To use the model and try out gist caching, use the `src/compress.py` script, e.g. 49 | 50 | ``` 51 | python -m src.compress --model_name_or_path jayelm/llama-7b-gist-1 --base_llama_path llama-7b \ 52 | --instruction "Name the top cities in France that should not be missed. Include the best aspects of each place as well." 53 | ``` 54 | 55 | Here, `--instruction` is the prompt to be compressed and cached, and `--input` is an (optional) input you can supply that is not compressed. 56 | 57 | `compress.py` is well documented; use the `--help` flag for more details and browse the code to see how gist caching is done. If you're loading a FLAN-T5-XXL checkpoint, you do not need to supply `--base_llama_path`. 58 | 59 | > [!NOTE] 60 | > Gist compression is currently only supported for `batch_size = 1`. Larger batch sizes are mostly implemented in FLAN-T5-XXL, but I haven't checked correctness as carefully. For LLaMA-7B, larger batch sizes will require modifying the rotary position embedings to account for gist offsets [here](https://github.com/jayelm/gisting/blob/main/src/gist_llama.py#L115-L125). 61 | 62 | ## Training 63 | 64 | If you'd like to retrain the Gist models, the command 65 | 66 | ``` 67 | python -m src.train \ 68 | training.gist.num_gist_tokens=2 training.gist.condition=gist wandb.tag=yourtaghere 69 | ``` 70 | 71 | Trains a small model (FLAN-T5-base) on the Alpaca+ training dataset with **2** 72 | gist tokens and **gist** masking, while logging to wandb. 73 | 74 | Change the number of gist tokens with `num_gist_tokens`. `condition` should be 75 | set to `gist`, `pos_control` (no masking), or `neg_control` (masking that simply 76 | masks out the instruction entirely). 77 | 78 | For debugging, you may be interested in setting the `+experiment=debug` flag, which runs a small model (FLAN-T5-small) on a tiny number of samples and evaluations, just to check that the train/eval loop is working. 79 | 80 | > [!NOTE] 81 | > If you're not familiar with the CLI syntax, check out [Hydra](https://hydra.cc/). 82 | 83 | > [!NOTE] 84 | > If you receive a `ConfigValueError`, see [this issue](https://github.com/jayelm/gisting/issues/6) for a workaround. 85 | 86 | > [!NOTE] 87 | > For VSCode users, some example launch configurations for debugging are in `.vscode/launch.json`. 88 | 89 | To train the larger models in the paper (FLAN-T5-XXL, LLaMA-7B), multi-gpu 90 | training is required with DeepSpeed. `./run_deepspeed.sh` contains an example, but the basic idea is: 91 | 92 | ``` 93 | deepspeed --num_gpus=4 --no_local_rank --module src.train \ 94 | +model={flan-t5-xxl,llama-7b} \ 95 | deepspeed=ds_configs/stage3.json \ 96 | training.gist.num_gist_tokens 2 \ 97 | training.gist.condition=gist 98 | ``` 99 | 100 | This trains either `flan-t5-xxl`/`llama-7b` with the same gist configuration as the 101 | first flan-t5-base command above, using the hyperparameters in the paper. See 102 | `src/conf/{flan-t5-xxl,llama-7b}.yaml` for the hyperparameter configurations. 103 | 104 | These experiments all assume a machine with 4 A100 80GB GPUs and at least 400GB 105 | of CPU RAM. Other machine configurations will necessitate changing the batch 106 | size and/or deepspeed config setting. 107 | 108 | Take a look at other model configs in `src/conf/model`. In particular there's a 109 | `llama-debug.yaml` file which trains a small randomly initialized LLaMA model 110 | for debugging. 111 | 112 | ### Logging 113 | 114 | Be sure to set your `wandb` entity name correctly in `src/conf/config.yaml`, if it is not your username. 115 | 116 | By default this logs an experiment to wandb under a group name that begins with `wandb.tag` (i.e. in the example above, `yourgroupname`); check out `src/conf/config.yaml` to see the full group name. Metrics are also logged to stdout, but there's a lot of other noise in stdout/stderr. 117 | 118 | The main metrics to pay attention to in the wandb interface are `{seen,unseen,human}_{rouge1,rouge2,rougeL}`, which are the ROUGE scores for the seen/unseen/human splits, respectively. 119 | 120 | The wandb group and run names define a directory which will save model checkpoints and outputs. By default it is `exp/{wandb.group}/{wandb.run}`. For example, if you run with the `+experiment=debug` setting, then the wandb group is set to `debug-alpaca-plus`. Saving model checkpoints is disabled in the debug config, but model outputs are nevertheless saved to `exp/debug-alpaca-plus/debug-alpaca-plus-run-42`. For example, `exp/debug-alpaca-plus/debug-alpaca-plus-run-42/outputs-100-validation_seen.csv` contains model outputs (greedy decode) on the seen split after 100 steps of training. These are useful for manual inspection, and also are the input for ChatGPT evaluation (see below). 121 | 122 | ### Launching via SLURM 123 | 124 | Use `sbatch run_deepspeed.sh` to submit multi-GPU DeepSpeed jobs to a SLURM cluster, or just run in an interactive session. 125 | 126 | If you are not using DeepSpeed, i.e. training smaller models (e.g. FLAN-T5-base, LLaMA-debug) on a single GPU, you can also use `hydra-submitit-launcher` to conveniently transform a local run into a SLURM batch job submission. Do `pip install hydra-submitit-launcher`, then specify `+launcher=slurm` via CLI to send a job to slurm. Use of `-m` or `--multirun` as a Hydra option is required for the SLURM launcher to be picked up. Configure slurm parameters (e.g. partition, account, etc) in `src/conf/launcher/slurm.yaml`. 127 | 128 | This is particularly useful with hydra's sweep functionality. E.g. the command 129 | 130 | ``` 131 | python -m src.train -m +experiment=flan-t5-base wandb.tag=sweep-demo \ 132 | training.gist.condition=gist,pos_control,neg_control 133 | ``` 134 | 135 | submits an array of 3 jobs to slurm, sweeping across the gist conditions. 136 | 137 | ## ChatGPT Evaluation 138 | 139 | ROUGE results are logged automatically during training above, but ChatGPT evaluation results need to be done manually. 140 | 141 | Obtain filepaths to the predictions from two models you'd like to compare. Outputs used for evaluation in the paper are in `data/results/{FLAN-T5,LLaMA}-{gist,pos_control,neg_control}-{1,2,5,10}`, sweeping over the model, gist condition, and number of gist tokens respectively. 142 | 143 | For example, say we want to compare the LLaMA single gist token model to its pos control. You can use the `scripts/eval_chatgpt.py` script: 144 | 145 | ``` 146 | python scripts/eval_chatgpt.py \ 147 | --a data/results/model_outputs/LLaMA-gist-1/outputs-3000-validation_human.csv \ 148 | --a_name LLaMA-gist-1 \ 149 | --b data/results/model_outputs/LLaMA-pos_control-1/outputs-3000-validation_human.csv \ 150 | --b_name LLaMA-pos-control-1 \ 151 | --results_file my_comparison.json 152 | ``` 153 | 154 | You will need a valid OpenAI key---follow OpenAI API setup instructions. 155 | 156 | Occasionally ChatGPT will spit out something that cannot be parsed by the JSON parser. In these cases it will log to stderr and the json for the result will have a "COULD NOT PARSE JSON" message. You can search for these messages in the results file, manually fix the responses, and change the overall scores accordingly. 157 | 158 | The ChatGPT comparisons reported in the paper are located in `data/results/chatgpt`. 159 | 160 | ## Benchmarking 161 | 162 | The training script has benchmarking functionality which is used to obtain the benchmarking results. 163 | 164 | Benchmarking was done without DeepSpeed on a single A100 80GB GPU, though a 40GB GPU is likely fine too. An example command for benchmarking is (also available as a VSCode launch config): 165 | 166 | ``` 167 | python -m src.train \ 168 | training.do_train=false \ 169 | training.do_eval=true \ 170 | training.do_benchmarking=true \ 171 | training.do_benchmarking_sanity_checks=true \ 172 | training.gist.num_gist_tokens=1 \ 173 | training.gist.condition=gist \ 174 | model.model_name_or_path=YOUR_PATH_TO_PRETRAINED_GIST_MODEL \ 175 | training.benchmarking_profiler=pytorch \ 176 | training.benchmarking_output_file=my_benchmarking.csv 177 | ``` 178 | 179 | Some notes here: 180 | 181 | - If you trained with the DeepSpeed config above, you will likely need to convert the DeepSpeed model checkpoint into a standard fp32 PyTorch model file by running `./zero_to_fp32.py . pytorch_model.bin` in the checkpoint you'd like to benchmark. 182 | - You can use either the [PyTorch default profiler](https://pytorch.org/docs/stable/profiler.html) or the [DeepSpeed FLOPs profiler](https://www.deepspeed.ai/tutorials/flops-profiler/) by setting `training.benchmarking_profiler`. Paper uses PyTorch default profiler. 183 | - `do_benchmarking_sanity_checks=true` activates gist caching sanity checking, where we verify that model outputs and decodes are same with and without gist caching. 184 | 185 | > [!NOTE] 186 | > For the larger models, we actually found that we would often fail gist sanity checks due to floating point errors. If you run the larger models with sanity checking on, you will find some torch assertion errors where 99% of the model states are identical, except for one value here or there. 187 | 188 | > [!NOTE] 189 | > We did not heavily optimize the gist caching implementation, so wall clock speedups (especially CPU times) are likely small or even non-existent due to the increased Python logic for gist caching. The main point of the gist caching implementation in this paper is to show it can be done and sanity check that the attention masking during training works for such caching behavior at inference time. The biggest gains from gist caching are likely to be achieved using custom, lower-level implementations of gist caching that optimize for inference latency. 190 | 191 | Like the other sections, the benchmarking results used in the paper are available in the `data/benchmarking` folder. See `data/README.md` for more details. 192 | 193 | ## Data 194 | 195 | The Alpaca+ data is located in `data/alpaca_plus`. ChatGPT evaluations, raw model outputs, and benchmarking stats used for the paper are located in `data/results` and `data/benchmarking`. 196 | 197 | ## License 198 | 199 | The codebase is licensed Apache 2.0 (see `LICENSE`). The data is a mixture of 200 | Self-Instruct (Apache 2.0) and Stanford Alpaca (CC BY-NC 4.0). By training on a 201 | mixture of the data you inherit both licenses. 202 | 203 | ## Thanks 204 | 205 | To the Stanford Alpaca team for assistance with the Alpaca data and finetuning. 206 | 207 | ## Citation 208 | 209 | If you found this work useful, please cite 210 | 211 | ```bibtex 212 | @article{mu2023learning, 213 | title={Learning to Compress Prompts with Gist Tokens}, 214 | author={Jesse Mu and Xiang Lisa Li and Noah Goodman}, 215 | year={2023}, 216 | eprint={2304.08467}, 217 | archivePrefix={arXiv}, 218 | primaryClass={cs.CL} 219 | } 220 | ``` 221 | -------------------------------------------------------------------------------- /WEIGHT_DIFF_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 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. Copyright and Similar Rights means copyright and/or similar rights 88 | closely related to copyright including, without limitation, 89 | performance, broadcast, sound recording, and Sui Generis Database 90 | Rights, without regard to how the rights are labeled or 91 | categorized. For purposes of this Public License, the rights 92 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 93 | Rights. 94 | d. Effective Technological Measures means those measures that, in the 95 | absence of proper authority, may not be circumvented under laws 96 | fulfilling obligations under Article 11 of the WIPO Copyright 97 | Treaty adopted on December 20, 1996, and/or similar international 98 | agreements. 99 | 100 | e. Exceptions and Limitations means fair use, fair dealing, and/or 101 | any other exception or limitation to Copyright and Similar Rights 102 | that applies to Your use of the Licensed Material. 103 | 104 | f. Licensed Material means the artistic or literary work, database, 105 | or other material to which the Licensor applied this Public 106 | License. 107 | 108 | g. Licensed Rights means the rights granted to You subject to the 109 | terms and conditions of this Public License, which are limited to 110 | all Copyright and Similar Rights that apply to Your use of the 111 | Licensed Material and that the Licensor has authority to license. 112 | 113 | h. Licensor means the individual(s) or entity(ies) granting rights 114 | under this Public License. 115 | 116 | i. NonCommercial means not primarily intended for or directed towards 117 | commercial advantage or monetary compensation. For purposes of 118 | this Public License, the exchange of the Licensed Material for 119 | other material subject to Copyright and Similar Rights by digital 120 | file-sharing or similar means is NonCommercial provided there is 121 | no payment of monetary compensation in connection with the 122 | exchange. 123 | 124 | j. Share means to provide material to the public by any means or 125 | process that requires permission under the Licensed Rights, such 126 | as reproduction, public display, public performance, distribution, 127 | dissemination, communication, or importation, and to make material 128 | available to the public including in ways that members of the 129 | public may access the material from a place and at a time 130 | individually chosen by them. 131 | 132 | k. Sui Generis Database Rights means rights other than copyright 133 | resulting from Directive 96/9/EC of the European Parliament and of 134 | the Council of 11 March 1996 on the legal protection of databases, 135 | as amended and/or succeeded, as well as other essentially 136 | equivalent rights anywhere in the world. 137 | 138 | l. You means the individual or entity exercising the Licensed Rights 139 | under this Public License. Your has a corresponding meaning. 140 | 141 | 142 | Section 2 -- Scope. 143 | 144 | a. License grant. 145 | 146 | 1. Subject to the terms and conditions of this Public License, 147 | the Licensor hereby grants You a worldwide, royalty-free, 148 | non-sublicensable, non-exclusive, irrevocable license to 149 | exercise the Licensed Rights in the Licensed Material to: 150 | 151 | a. reproduce and Share the Licensed Material, in whole or 152 | in part, for NonCommercial purposes only; and 153 | 154 | b. produce, reproduce, and Share Adapted Material for 155 | NonCommercial purposes only. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. No downstream restrictions. You may not offer or impose 186 | any additional or different terms or conditions on, or 187 | apply any Effective Technological Measures to, the 188 | Licensed Material if doing so restricts exercise of the 189 | Licensed Rights by any recipient of the Licensed 190 | Material. 191 | 192 | 6. No endorsement. Nothing in this Public License constitutes or 193 | may be construed as permission to assert or imply that You 194 | are, or that Your use of the Licensed Material is, connected 195 | with, or sponsored, endorsed, or granted official status by, 196 | the Licensor or others designated to receive attribution as 197 | provided in Section 3(a)(1)(A)(i). 198 | 199 | b. Other rights. 200 | 201 | 1. Moral rights, such as the right of integrity, are not 202 | licensed under this Public License, nor are publicity, 203 | privacy, and/or other similar personality rights; however, to 204 | the extent possible, the Licensor waives and/or agrees not to 205 | assert any such rights held by the Licensor to the limited 206 | extent necessary to allow You to exercise the Licensed 207 | Rights, but not otherwise. 208 | 209 | 2. Patent and trademark rights are not licensed under this 210 | Public License. 211 | 212 | 3. To the extent possible, the Licensor waives any right to 213 | collect royalties from You for the exercise of the Licensed 214 | Rights, whether directly or through a collecting society 215 | under any voluntary or waivable statutory or compulsory 216 | licensing scheme. In all other cases the Licensor expressly 217 | reserves any right to collect such royalties, including when 218 | the Licensed Material is used other than for NonCommercial 219 | purposes. 220 | 221 | 222 | Section 3 -- License Conditions. 223 | 224 | Your exercise of the Licensed Rights is expressly made subject to the 225 | following conditions. 226 | 227 | a. Attribution. 228 | 229 | 1. If You Share the Licensed Material (including in modified 230 | form), You must: 231 | 232 | a. retain the following if it is supplied by the Licensor 233 | with the Licensed Material: 234 | 235 | i. identification of the creator(s) of the Licensed 236 | Material and any others designated to receive 237 | attribution, in any reasonable manner requested by 238 | the Licensor (including by pseudonym if 239 | designated); 240 | 241 | ii. a copyright notice; 242 | 243 | iii. a notice that refers to this Public License; 244 | 245 | iv. a notice that refers to the disclaimer of 246 | warranties; 247 | 248 | v. a URI or hyperlink to the Licensed Material to the 249 | extent reasonably practicable; 250 | 251 | b. indicate if You modified the Licensed Material and 252 | retain an indication of any previous modifications; and 253 | 254 | c. indicate the Licensed Material is licensed under this 255 | Public License, and include the text of, or the URI or 256 | hyperlink to, this Public License. 257 | 258 | 2. You may satisfy the conditions in Section 3(a)(1) in any 259 | reasonable manner based on the medium, means, and context in 260 | which You Share the Licensed Material. For example, it may be 261 | reasonable to satisfy the conditions by providing a URI or 262 | hyperlink to a resource that includes the required 263 | information. 264 | 265 | 3. If requested by the Licensor, You must remove any of the 266 | information required by Section 3(a)(1)(A) to the extent 267 | reasonably practicable. 268 | 269 | 4. If You Share Adapted Material You produce, the Adapter's 270 | License You apply must not prevent recipients of the Adapted 271 | Material from complying with this Public License. 272 | 273 | 274 | Section 4 -- Sui Generis Database Rights. 275 | 276 | Where the Licensed Rights include Sui Generis Database Rights that 277 | apply to Your use of the Licensed Material: 278 | 279 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 280 | to extract, reuse, reproduce, and Share all or a substantial 281 | portion of the contents of the database for NonCommercial purposes 282 | only; 283 | 284 | b. if You include all or a substantial portion of the database 285 | contents in a database in which You have Sui Generis Database 286 | Rights, then the database in which You have Sui Generis Database 287 | Rights (but not its individual contents) is Adapted Material; and 288 | 289 | c. You must comply with the conditions in Section 3(a) if You Share 290 | all or a substantial portion of the contents of the database. 291 | 292 | For the avoidance of doubt, this Section 4 supplements and does not 293 | replace Your obligations under this Public License where the Licensed 294 | Rights include other Copyright and Similar Rights. 295 | 296 | 297 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 298 | 299 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 300 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 301 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 302 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 303 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 304 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 305 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 306 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 307 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 308 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 309 | 310 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 311 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 312 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 313 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 314 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 315 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 316 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 317 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 318 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 319 | 320 | c. The disclaimer of warranties and limitation of liability provided 321 | above shall be interpreted in a manner that, to the extent 322 | possible, most closely approximates an absolute disclaimer and 323 | waiver of all liability. 324 | 325 | 326 | Section 6 -- Term and Termination. 327 | 328 | a. This Public License applies for the term of the Copyright and 329 | Similar Rights licensed here. However, if You fail to comply with 330 | this Public License, then Your rights under this Public License 331 | terminate automatically. 332 | 333 | b. Where Your right to use the Licensed Material has terminated under 334 | Section 6(a), it reinstates: 335 | 336 | 1. automatically as of the date the violation is cured, provided 337 | it is cured within 30 days of Your discovery of the 338 | violation; or 339 | 340 | 2. upon express reinstatement by the Licensor. 341 | 342 | For the avoidance of doubt, this Section 6(b) does not affect any 343 | right the Licensor may have to seek remedies for Your violations 344 | of this Public License. 345 | 346 | c. For the avoidance of doubt, the Licensor may also offer the 347 | Licensed Material under separate terms or conditions or stop 348 | distributing the Licensed Material at any time; however, doing so 349 | will not terminate this Public License. 350 | 351 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 352 | License. 353 | 354 | 355 | Section 7 -- Other Terms and Conditions. 356 | 357 | a. The Licensor shall not be bound by any additional or different 358 | terms or conditions communicated by You unless expressly agreed. 359 | 360 | b. Any arrangements, understandings, or agreements regarding the 361 | Licensed Material not stated herein are separate from and 362 | independent of the terms and conditions of this Public License. 363 | 364 | 365 | Section 8 -- Interpretation. 366 | 367 | a. For the avoidance of doubt, this Public License does not, and 368 | shall not be interpreted to, reduce, limit, restrict, or impose 369 | conditions on any use of the Licensed Material that could lawfully 370 | be made without permission under this Public License. 371 | 372 | b. To the extent possible, if any provision of this Public License is 373 | deemed unenforceable, it shall be automatically reformed to the 374 | minimum extent necessary to make it enforceable. If the provision 375 | cannot be reformed, it shall be severed from this Public License 376 | without affecting the enforceability of the remaining terms and 377 | conditions. 378 | 379 | c. No term or condition of this Public License will be waived and no 380 | failure to comply consented to unless expressly agreed to by the 381 | Licensor. 382 | 383 | d. Nothing in this Public License constitutes or may be interpreted 384 | as a limitation upon, or waiver of, any privileges and immunities 385 | that apply to the Licensor or You, including from the legal 386 | processes of any jurisdiction or authority. 387 | 388 | ======================================================================= 389 | 390 | Creative Commons is not a party to its public 391 | licenses. Notwithstanding, Creative Commons may elect to apply one of 392 | its public licenses to material it publishes and in those instances 393 | will be considered the “Licensor.” The text of the Creative Commons 394 | public licenses is dedicated to the public domain under the CC0 Public 395 | Domain Dedication. Except for the limited purpose of indicating that 396 | material is shared under a Creative Commons public license or as 397 | otherwise permitted by the Creative Commons policies published at 398 | creativecommons.org/policies, Creative Commons does not authorize the 399 | use of the trademark "Creative Commons" or any other trademark or logo 400 | of Creative Commons without its prior written consent including, 401 | without limitation, in connection with any unauthorized modifications 402 | to any of its public licenses or any other arrangements, 403 | understandings, or agreements concerning use of licensed material. For 404 | the avoidance of doubt, this paragraph does not form part of the 405 | public licenses. 406 | 407 | Creative Commons may be contacted at creativecommons.org. 408 | -------------------------------------------------------------------------------- /data/README.md: -------------------------------------------------------------------------------- 1 | # Data 2 | 3 | This folder contains training data and results (rouge/raw model outputs/ChatGPT 4 | evals). 5 | 6 | - `alpaca_plus`: contains alpaca+ training and validation splits. See 7 | `README.md` in that folder to recreate Alpaca+ from the original Alpaca/Self 8 | Instruct data. 9 | - `results`: raw model outputs and chatgpt evaluation results. Also contains 10 | rouge results (`rouge.csv`). 11 | - `benchmarking`: benchmarking results with and without gist tokens. Note that 12 | `pytorch-llama-7b-benchmarking-prompt-human.csv` is the experiments using 13 | prompt caching. In that csv, the `gist` timings correspond not to gist 14 | caching but to caching the entire prompt. 15 | -------------------------------------------------------------------------------- /data/alpaca_plus/README.md: -------------------------------------------------------------------------------- 1 | # Alpaca Plus 2 | 3 | This data is called Alpaca Plus because it combines the Alpaca generated data 4 | with the Self Instruct data. 5 | 6 | 3 validation sets are included: 7 | 8 | 1. Validation seen: taking examples from Self Instruct whose instructions exist in the training data but have new inputs. 9 | 2. Validation unseen: taking examples from Alpaca whose instructions do not appear in the training data. 10 | 3. Validation human: human examples from Self Instruct. 11 | 12 | The license of this data inherits the licenses of the parent data, namely 13 | Alpaca's more restrictive academic license. 14 | 15 | To recreate the data, download the following files into the parent `data/` 16 | directory: 17 | 18 | - [`alpaca_data.json`](https://github.com/tatsu-lab/stanford_alpaca/blob/f134962/alpaca_data.json), the Stanford Alpaca data. 19 | - [`all_instances_82K.jsonl`](https://github.com/yizhongw/self-instruct/blob/a40887b/data/gpt3_generations/batch_221203/all_instances_82K.jsonl), the Self-Instruct data. 20 | - [`user_oriented_instructions.jsonl`](https://github.com/yizhongw/self-instruct/blob/a40887b/human_eval/user_oriented_instructions.jsonl), the Self-Instruct human eval data. 21 | 22 | Then run `python create_alpaca_plus_data.py`. 23 | -------------------------------------------------------------------------------- /data/create_alpaca_plus_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | Combines the alpaca and self instruct data, and splits into validation of seen 3 | and unseen tasks. 4 | """ 5 | 6 | 7 | import json 8 | from collections import defaultdict 9 | 10 | ALPACA_FILE = "alpaca_data.json" 11 | SELF_INSTRUCT_FILE = "all_instances_82K.jsonl" 12 | HUMAN_EVAL_FILE = "user_oriented_instructions.jsonl" 13 | 14 | 15 | NUM_VAL_EXAMPLES = 1000 16 | 17 | 18 | if __name__ == "__main__": 19 | with open(ALPACA_FILE, "r") as f: 20 | alpaca_data = json.load(f) 21 | 22 | with open(SELF_INSTRUCT_FILE, "r") as f: 23 | self_instruct_data = [json.loads(line) for line in f] 24 | 25 | # Add "source" field to each data point based on the source file. 26 | for data_point in alpaca_data: 27 | data_point["source"] = "alpaca" 28 | for data_point in self_instruct_data: 29 | data_point["source"] = "self_instruct" 30 | 31 | # ==== SPLITS ==== 32 | training_data = [] 33 | training_data_set = set() # Prevent duplicate examples. 34 | 35 | # Use the data from self instruct (same instruction but different inputs) as 36 | # a validation_seen split. 37 | 38 | # First, create dictionary mapping self instruct instructions to data points. 39 | self_instruct_data_dict = defaultdict(list) 40 | for data_point in self_instruct_data: 41 | self_instruct_data_dict[data_point["instruction"]].append(data_point) 42 | 43 | # Then, create a validation_seen split by taking the first data point for 44 | # each instruction in self instruct, for instructions with at least two data 45 | # points, to create a total of NUM_VAL_EXAMPLES examples. 46 | validation_seen_data = [] 47 | for instruction, data_points in self_instruct_data_dict.items(): 48 | if ( 49 | len(validation_seen_data) < NUM_VAL_EXAMPLES 50 | and len(data_points) > 1 51 | and data_points[0]["input"] 52 | ): 53 | validation_seen_data.append(data_points[0]) 54 | # Add this to training data set to prevent duplicates. 55 | training_data_set.add( 56 | (data_points[0]["instruction"], data_points[0]["input"]) 57 | ) 58 | extra_data = data_points[1:] 59 | else: 60 | extra_data = data_points 61 | 62 | # Add the rest of the data points to the training data, as long as it 63 | # doesn't overlap. 64 | for extra_data_point in extra_data: 65 | if ( 66 | extra_data_point["instruction"], 67 | extra_data_point["input"], 68 | ) not in training_data_set: 69 | training_data.append(extra_data_point) 70 | training_data_set.add( 71 | (extra_data_point["instruction"], extra_data_point["input"]) 72 | ) 73 | else: 74 | print("Duplicate examples for instruction:", data_points) 75 | 76 | # Create a validation_unseen split by taking NUM_VAL_EXAMPLES examples from 77 | # the alpaca data. 78 | training_data_instructions = set( 79 | data_point["instruction"] for data_point in training_data 80 | ) 81 | validation_unseen_data_instructions = set() 82 | validation_unseen_data = [] 83 | for data_point in alpaca_data: 84 | if ( 85 | len(validation_unseen_data) < NUM_VAL_EXAMPLES 86 | and data_point["input"] 87 | and data_point["instruction"] not in training_data_instructions 88 | ): 89 | validation_unseen_data.append(data_point) 90 | validation_unseen_data_instructions.add(data_point["instruction"]) 91 | else: 92 | if data_point["instruction"] in validation_unseen_data_instructions: 93 | raise RuntimeError() 94 | training_data.append(data_point) 95 | training_data_instructions.add(data_point["instruction"]) 96 | 97 | # Create a validation_human split by taking all examples from the human eval 98 | # data. 99 | validation_human_data = [] 100 | with open(HUMAN_EVAL_FILE, "r") as f: 101 | human_eval_data = [json.loads(line) for line in f] 102 | for data_point in human_eval_data: 103 | for io_pair in data_point["instances"]: 104 | validation_human_data.append( 105 | { 106 | "instruction": data_point["instruction"], 107 | "input": io_pair["input"], 108 | "output": io_pair["output"], 109 | "source": "self_instruct", 110 | } 111 | ) 112 | 113 | print("Final split sizes:") 114 | print("Training:", len(training_data)) 115 | print("Validation seen:", len(validation_seen_data)) 116 | print("Validation unseen:", len(validation_unseen_data)) 117 | print("Validation human:", len(validation_human_data)) 118 | 119 | with open("alpaca_plus/alpaca_plus_train.json", "w") as f: 120 | json.dump(training_data, f) 121 | 122 | with open("alpaca_plus/alpaca_plus_validation_seen.json", "w") as f: 123 | json.dump(validation_seen_data, f) 124 | 125 | with open("alpaca_plus/alpaca_plus_validation_unseen.json", "w") as f: 126 | json.dump(validation_unseen_data, f) 127 | 128 | with open("alpaca_plus/alpaca_plus_validation_human.json", "w") as f: 129 | json.dump(validation_human_data, f) 130 | 131 | # Verify that the splits have no example overlap, when considering 132 | # instruction AND input. 133 | training_examples = set( 134 | [ 135 | (data_point["instruction"], data_point["input"], data_point["source"]) 136 | for data_point in training_data 137 | ] 138 | ) 139 | validation_seen_examples = set( 140 | [ 141 | (data_point["instruction"], data_point["input"], data_point["source"]) 142 | for data_point in validation_seen_data 143 | ] 144 | ) 145 | validation_unseen_examples = set( 146 | [ 147 | (data_point["instruction"], data_point["input"], data_point["source"]) 148 | for data_point in validation_unseen_data 149 | ] 150 | ) 151 | assert len(training_examples.intersection(validation_seen_examples)) == 0 152 | assert len(training_examples.intersection(validation_unseen_examples)) == 0 153 | 154 | # Verify that the splits have the right instructions. 155 | training_instructions = set( 156 | [data_point["instruction"] for data_point in training_data] 157 | ) 158 | validation_seen_instructions = set( 159 | [data_point["instruction"] for data_point in validation_seen_data] 160 | ) 161 | validation_unseen_instructions = set( 162 | [data_point["instruction"] for data_point in validation_unseen_data] 163 | ) 164 | 165 | # Assert that every validation_seen instruction is in the training data. 166 | assert all( 167 | [ 168 | instruction in training_instructions 169 | for instruction in validation_seen_instructions 170 | ] 171 | ) 172 | # Assert that no validation_unseen instruction is in the training data. 173 | assert not any( 174 | [ 175 | instruction in training_instructions 176 | for instruction in validation_unseen_instructions 177 | ] 178 | ) 179 | assert not any( 180 | [ 181 | instruction in validation_seen_instructions 182 | for instruction in validation_unseen_instructions 183 | ] 184 | ) 185 | -------------------------------------------------------------------------------- /data/results/rouge.csv: -------------------------------------------------------------------------------- 1 | model,condition,num_gist_tokens,steps,value,split 2 | LLaMA,pos_control,1,3000,48.0998,unseen 3 | LLaMA,pos_control,1,3000,58.0104,seen 4 | LLaMA,pos_control,1,3000,27.0024,human 5 | LLaMA,neg_control,1,3000,31.4194,unseen 6 | LLaMA,neg_control,1,3000,31.5104,seen 7 | LLaMA,neg_control,1,3000,14.4014,human 8 | LLaMA,gist,1,3000,46.6212,unseen 9 | LLaMA,gist,1,3000,57.779,seen 10 | LLaMA,gist,1,3000,23.9176,human 11 | LLaMA,gist,2,3000,46.4711,unseen 12 | LLaMA,gist,2,3000,57.6075,seen 13 | LLaMA,gist,2,3000,24.8724,human 14 | LLaMA,gist,5,3000,46.4002,unseen 15 | LLaMA,gist,5,3000,57.5675,seen 16 | LLaMA,gist,5,3000,24.9192,human 17 | LLaMA,gist,10,3000,47.7459,unseen 18 | LLaMA,gist,10,3000,56.9077,seen 19 | LLaMA,gist,10,3000,24.8356,human 20 | FLAN-T5,pos_control,1,16000,45.7411,unseen 21 | FLAN-T5,pos_control,1,16000,50.5839,seen 22 | FLAN-T5,pos_control,1,16000,23.9329,human 23 | FLAN-T5,neg_control,1,16000,29.127,unseen 24 | FLAN-T5,neg_control,1,16000,25.4774,seen 25 | FLAN-T5,neg_control,1,16000,12.3652,human 26 | FLAN-T5,gist,1,16000,43.8152,unseen 27 | FLAN-T5,gist,1,16000,48.8645,seen 28 | FLAN-T5,gist,1,16000,21.7091,human 29 | FLAN-T5,gist,2,16000,44.0516,unseen 30 | FLAN-T5,gist,2,16000,48.5331,seen 31 | FLAN-T5,gist,2,16000,20.7524,human 32 | FLAN-T5,gist,5,16000,43.6741,unseen 33 | FLAN-T5,gist,5,16000,47.9804,seen 34 | FLAN-T5,gist,5,16000,21.242,human 35 | FLAN-T5,gist,10,16000,44.531,unseen 36 | FLAN-T5,gist,10,16000,49.1242,seen 37 | FLAN-T5,gist,10,16000,20.9442,human 38 | -------------------------------------------------------------------------------- /ds_configs/README.md: -------------------------------------------------------------------------------- 1 | # DeepSpeed Configs 2 | 3 | This folder contains deepspeed configs. All paper expts use `stage3.json`. 4 | -------------------------------------------------------------------------------- /ds_configs/stage3.json: -------------------------------------------------------------------------------- 1 | { 2 | "bf16": { 3 | "enabled": "auto" 4 | }, 5 | "optimizer": { 6 | "type": "AdamW", 7 | "params": { 8 | "lr": "auto", 9 | "betas": "auto", 10 | "eps": "auto", 11 | "weight_decay": "auto" 12 | } 13 | }, 14 | "scheduler": { 15 | "type": "WarmupLR", 16 | "params": { 17 | "warmup_min_lr": "auto", 18 | "warmup_max_lr": "auto", 19 | "warmup_num_steps": "auto" 20 | } 21 | }, 22 | "zero_optimization": { 23 | "stage": 3, 24 | "overlap_comm": true, 25 | "contiguous_gradients": true, 26 | "sub_group_size": 1e9, 27 | "reduce_bucket_size": "auto", 28 | "stage3_prefetch_bucket_size": "auto", 29 | "stage3_param_persistence_threshold": "auto", 30 | "stage3_max_live_parameters": 1e9, 31 | "stage3_max_reuse_distance": 1e9, 32 | "stage3_gather_16bit_weights_on_model_save": false 33 | }, 34 | "gradient_accumulation_steps": "auto", 35 | "gradient_clipping": "auto", 36 | "steps_per_print": 2000, 37 | "train_batch_size": "auto", 38 | "train_micro_batch_size_per_gpu": "auto", 39 | "wall_clock_breakdown": false 40 | } 41 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate==0.18.0 2 | datasets==2.10.0 3 | deepspeed==0.8.3 4 | pydantic==1.10.9 5 | evaluate==0.3.0 6 | fire==0.5.0 7 | hydra-core==1.2.0 8 | numpy==1.21.2 9 | omegaconf>=2.1.1 10 | openai==0.27.2 11 | rouge_score==0.1.2 12 | nltk==3.6.2 13 | sentencepiece==0.1.98 14 | torch==2.0.0 15 | git+https://github.com/huggingface/transformers@fb366b9a 16 | wandb==0.13.4 17 | -------------------------------------------------------------------------------- /run_deepspeed.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | #SBATCH --job-name=gist 3 | #SBATCH --ntasks=1 4 | #SBATCH --mem=480gb 5 | #SBATCH --time=26:00:00 6 | #SBATCH --output=gist.log 7 | #SBATCH --cpus-per-task=16 8 | #SBATCH --gres=gpu:4 9 | 10 | # This script can either be used interactively or submitted to SLURM with 11 | # sbatch. 12 | 13 | # NOTE: LLaMA runs typically take ~7 hours; FLAN-T5-XXL runs typically take ~26 14 | # hours. You can probably get away with training FLAN-T5-XXL less. 15 | 16 | 17 | TAG="test" 18 | 19 | port=$(shuf -i25000-30000 -n1) 20 | 21 | deepspeed --master_port $port --num_gpus=4 --no_local_rank \ 22 | --module src.train \ 23 | +model=llama-7b wandb.tag=$TAG \ 24 | training.deepspeed=ds_configs/stage3.json \ 25 | training.gist.condition=gist \ 26 | training.gist.num_gist_tokens=1 27 | -------------------------------------------------------------------------------- /scripts/eval_all.py: -------------------------------------------------------------------------------- 1 | """Eval all results with ChatGPT""" 2 | 3 | import json 4 | import os 5 | 6 | from tqdm import tqdm 7 | 8 | from eval_chatgpt import eval_chatgpt 9 | 10 | GLOBAL_N = None 11 | 12 | 13 | EXPECTED_TOTALS = { 14 | "validation_human": 252, 15 | "validation_unseen": 1000, 16 | "validation_seen": 1000, 17 | } 18 | 19 | 20 | def cfg( 21 | model: str, 22 | condition: str, 23 | num_gist_tokens: int, 24 | steps: int = 3000, 25 | split: str = "validation_human", 26 | ): 27 | assert model in {"LLaMA", "FLAN-T5"} 28 | return { 29 | "a": { 30 | "condition": condition, 31 | "num_gist_tokens": num_gist_tokens, 32 | }, 33 | "b": { 34 | "condition": "pos_control", 35 | "num_gist_tokens": "1", 36 | }, 37 | "model": model, 38 | "steps": steps, 39 | "split": split, 40 | } 41 | 42 | 43 | TO_COMPARE = [ 44 | cfg("LLaMA", "neg_control", 1, split="validation_human"), 45 | cfg("LLaMA", "gist", 1, split="validation_human"), 46 | cfg("LLaMA", "gist", 2, split="validation_human"), 47 | cfg("LLaMA", "gist", 5, split="validation_human"), 48 | cfg("LLaMA", "gist", 10, split="validation_human"), 49 | cfg("LLaMA", "neg_control", 1, split="validation_unseen"), 50 | cfg("LLaMA", "gist", 1, split="validation_unseen"), 51 | cfg("LLaMA", "gist", 2, split="validation_unseen"), 52 | cfg("LLaMA", "gist", 5, split="validation_unseen"), 53 | cfg("LLaMA", "gist", 10, split="validation_unseen"), 54 | cfg("LLaMA", "neg_control", 1, split="validation_seen"), 55 | cfg("LLaMA", "gist", 1, split="validation_seen"), 56 | cfg("LLaMA", "gist", 2, split="validation_seen"), 57 | cfg("LLaMA", "gist", 5, split="validation_seen"), 58 | cfg("LLaMA", "gist", 10, split="validation_seen"), 59 | cfg("FLAN-T5", "neg_control", 1, split="validation_human", steps=16000), 60 | cfg("FLAN-T5", "gist", 1, split="validation_human", steps=16000), 61 | cfg("FLAN-T5", "gist", 2, split="validation_human", steps=16000), 62 | cfg("FLAN-T5", "gist", 5, split="validation_human", steps=16000), 63 | cfg("FLAN-T5", "gist", 10, split="validation_human", steps=16000), 64 | cfg("FLAN-T5", "neg_control", 1, split="validation_unseen", steps=16000), 65 | cfg("FLAN-T5", "gist", 1, split="validation_unseen", steps=16000), 66 | cfg("FLAN-T5", "gist", 2, split="validation_unseen", steps=16000), 67 | cfg("FLAN-T5", "gist", 5, split="validation_unseen", steps=16000), 68 | cfg("FLAN-T5", "gist", 10, split="validation_unseen", steps=16000), 69 | cfg("FLAN-T5", "neg_control", 1, split="validation_seen", steps=16000), 70 | cfg("FLAN-T5", "gist", 1, split="validation_seen", steps=16000), 71 | cfg("FLAN-T5", "gist", 2, split="validation_seen", steps=16000), 72 | cfg("FLAN-T5", "gist", 5, split="validation_seen", steps=16000), 73 | cfg("FLAN-T5", "gist", 10, split="validation_seen", steps=16000), 74 | ] 75 | 76 | 77 | if __name__ == "__main__": 78 | import argparse 79 | 80 | parser = argparse.ArgumentParser() 81 | parser.add_argument("--folder", type=str, default="data/results") 82 | parser.add_argument("--seed", type=int, default=42) 83 | parser.add_argument("--overwrite", action="store_true") 84 | 85 | args = parser.parse_args() 86 | 87 | pbar = tqdm(TO_COMPARE) 88 | for comparison in pbar: 89 | a_name = f"{comparison['model']}-{comparison['a']['condition']}-{comparison['a']['num_gist_tokens']}" 90 | b_name = f"{comparison['model']}-{comparison['b']['condition']}-{comparison['b']['num_gist_tokens']}" 91 | pbar.set_description( 92 | f"{a_name} vs {b_name} {comparison['split']}@{comparison['steps']}" 93 | ) 94 | a = f"{args.folder}/{a_name}/outputs-{comparison['steps']}-{comparison['split']}.csv" 95 | b = f"{args.folder}/{b_name}/outputs-{comparison['steps']}-{comparison['split']}.csv" 96 | if not os.path.exists(a): 97 | tqdm.write(f"Skipping comparison {comparison} because {a} does not exist.") 98 | continue 99 | elif not os.path.exists(b): 100 | tqdm.write(f"Skipping comparison {comparison} because {b} does not exist.") 101 | continue 102 | 103 | results_file = f"{args.folder}/chatgpt-{a_name}-vs-{b_name}-{comparison['split']}-{comparison['steps']}.json" 104 | if os.path.exists(results_file): 105 | if args.overwrite: 106 | tqdm.write( 107 | f"WARNING: Found {results_file} but overwriting as --overwrite is set." 108 | ) 109 | else: 110 | with open(results_file, "r") as f: 111 | try: 112 | existing_results = json.load(f) 113 | existing_score = sum(existing_results["scores"].values()) 114 | if existing_score == EXPECTED_TOTALS[comparison["split"]]: 115 | tqdm.write( 116 | f"WARNING: Found {results_file} which looks complete (total score: {existing_score}) Skipping as --overwrite is not set." 117 | ) 118 | continue 119 | except json.JSONDecodeError: 120 | existing_score = "JSONDecodeError" 121 | tqdm.write( 122 | f"WARNING: Found {results_file} which looks incomplete (total score: {existing_score}). Rerunning." 123 | ) 124 | 125 | eval_chatgpt( 126 | a=a, 127 | a_name=a_name, 128 | b=b, 129 | b_name=b_name, 130 | n=GLOBAL_N, 131 | results_file=results_file, 132 | seed=args.seed, 133 | ) 134 | -------------------------------------------------------------------------------- /scripts/eval_chatgpt.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | """ChatGPT output evaluation.""" 3 | import json 4 | import random 5 | import time 6 | import warnings 7 | from collections import Counter 8 | 9 | import openai 10 | import pandas as pd 11 | from tqdm import tqdm, trange 12 | 13 | INSTRUCTION = """ 14 | {instruction} 15 | Assistant A: {a} 16 | Assistant B: {b} 17 | """.strip() 18 | 19 | SYSTEM = """ 20 | Given a user instruction and two AI assistant responses, your job is to select the response that is more helpful, and give reasons why. Judge responses holistically, paying special attention to whether the response (1) correctly follows the provided instruction and (2) is factually accurate. If both responses are equal, you may call a tie, but please use this response sparingly. 21 | 22 | Example 1: 23 | 24 | ``` 25 | Instruction: Given the name of a city, tell me the name of the state it is in. 26 | Input: Los Angeles 27 | Assistant A: California 28 | Assistant B: Wyoming 29 | ``` 30 | 31 | Your output should be: 32 | 33 | ``` 34 | {"reason": "Los Angeles is in California. Only Assistant A is correct.", "choice": "A"} 35 | ``` 36 | 37 | Example 2: 38 | 39 | ``` 40 | Instruction: Give me some examples of fun things to do with the kids on a weekend. 41 | Assistant A: For example, what should I do with my kids on a weekend? What if I'm in a city? What if I'm on the beach? 42 | Assistant B: You could try going to the zoo or a museum. If you want to stay at home, you could play board games or bake cookies. 43 | ``` 44 | 45 | Your output should be: 46 | 47 | ``` 48 | {"reason": "Assistant A doesn"t seem to be following the instruction. Assistant B provides helpful information with examples.", "choice": "B"} 49 | ``` 50 | 51 | Example 3: 52 | 53 | ``` 54 | Instruction: Write me a python function that prints "Hello, World". 55 | Assistant A: def hello_world(): print("Hello!") 56 | Assistant B: "Hello, World" 57 | ``` 58 | 59 | Your output should be: 60 | 61 | ``` 62 | {"reason": "Assistant B just wrote 'Hello, World'. Assistant A actually wrote a Python function, even if it doesn't exactly print the right thing, so overall Assistant A is better.", "choice": "A"} 63 | ``` 64 | 65 | Example 4: 66 | 67 | ``` 68 | Instruction: Translate the following sentence from English to French. 69 | Input: I like cats. 70 | Assistant A: Me gusta los gatos. 71 | Assistant B: 我喜欢猫. 72 | ``` 73 | 74 | Your output should be: 75 | 76 | ``` 77 | {"reason": "Both assistants got the language wrong.", "choice": "tie"} 78 | ``` 79 | 80 | Your response should only be in the JSON format above; THERE SHOULD BE NO OTHER CONTENT INCLUDED IN YOUR RESPONSE. Write the "reason" key *before* writing the "choice" key, so that you think step-by-step before making your decision. KEEP YOUR REASONING BRIEF. 81 | """.strip() 82 | 83 | 84 | def normalize(wins): 85 | total = sum(wins.values()) 86 | return {k: v / total for k, v in wins.items()} 87 | 88 | 89 | def round_counter(wins): 90 | return {k: round(v, 3) for k, v in wins.items()} 91 | 92 | 93 | def clean_instruction(instruction): 94 | # Clean the instruction. 95 | instruction = instruction.replace("⁇", "").strip() 96 | if "" in instruction: 97 | # Split on gist tokens, then recombine. 98 | pre_gist, *gist_pieces, post_gist = instruction.split("") 99 | 100 | # If any strings between gist tokens are nonempty (excl whitespace), raise 101 | # an error 102 | if any(gp.strip() for gp in gist_pieces): 103 | raise ValueError(f"Tokens detected in between gist: {gist_pieces}") 104 | 105 | instruction = f"{pre_gist.strip()}\n{post_gist.strip()}" 106 | 107 | # Remove trailing output if present. 108 | output_pieces = instruction.split("\nOutput: ") 109 | if len(output_pieces) > 2: 110 | warnings.warn(f"Too many output pieces: {instruction}, {output_pieces}") 111 | instruction = output_pieces[0].strip() 112 | return instruction 113 | 114 | 115 | def try_to_extract_json_objects(text, decoder=json.JSONDecoder()): 116 | """Find JSON objects in text, and yield the decoded JSON data 117 | 118 | Does not attempt to look for JSON arrays, text, or other JSON types outside 119 | of a parent JSON object. 120 | 121 | https://stackoverflow.com/questions/54235528/how-to-find-json-object-in-text-with-python 122 | """ 123 | text = text.strip() 124 | # Try to just parse the result alone. 125 | try: 126 | yield json.loads(text) 127 | except json.JSONDecodeError: 128 | pass 129 | 130 | # Sweep through the string. 131 | pos = 0 132 | while True: 133 | match = text.find("{", pos) 134 | if match == -1: 135 | break 136 | try: 137 | result, index = decoder.raw_decode(text[match:]) 138 | yield result 139 | pos = match + index 140 | except ValueError: 141 | pos = match + 1 142 | 143 | 144 | def query(instruction, a, b, max_num_retries=5): 145 | # Randomly select one assistant to be presented first. 146 | swapped = random.random() > 0.5 147 | if swapped: 148 | a, b = b, a 149 | 150 | instruction_formatted = INSTRUCTION.format(instruction=instruction, a=a, b=b) 151 | num_retries = 0 152 | # Repeat the query until we get a valid response. 153 | completion = None 154 | while num_retries < max_num_retries: 155 | try: 156 | completion = openai.ChatCompletion.create( 157 | model="gpt-3.5-turbo", 158 | messages=[ 159 | { 160 | "role": "system", 161 | "content": SYSTEM, 162 | }, 163 | { 164 | "role": "user", 165 | "content": instruction_formatted, 166 | }, 167 | ], 168 | temperature=0.0, 169 | ) 170 | break 171 | except: # noqa 172 | print("Retrying...") 173 | num_retries += 1 174 | time.sleep(10) 175 | 176 | if completion is None: 177 | raise RuntimeError(f"Could not get completion after {max_num_retries} retries.") 178 | 179 | result_txt = completion["choices"][0]["message"]["content"] 180 | result_txt = result_txt.replace("```", "").strip() 181 | maybe_jsons = list(try_to_extract_json_objects(result_txt)) 182 | result = None 183 | for maybe_json in maybe_jsons: 184 | # Does it have the right format? 185 | if "choice" in maybe_json and "reason" in maybe_json: 186 | result = maybe_json 187 | break 188 | else: 189 | # Either this was empty or we found no valid JSON. 190 | # Assume tie and just return the raw result. 191 | error_message = "Could not parse JSON: " + result_txt 192 | tqdm.write(error_message) 193 | result = {"reason": error_message, "choice": "tie"} 194 | assert result is not None 195 | 196 | # If swapped, swap the choice. 197 | if swapped: 198 | if result["choice"].lower() == "a": 199 | result["choice"] = "b" 200 | elif result["choice"].lower() == "b": 201 | result["choice"] = "a" 202 | elif result["choice"].lower() == "tie": 203 | pass 204 | 205 | # If invalid choice, mark as a parse error and call it a tie. 206 | if result["choice"].lower() not in {"a", "b", "tie"}: 207 | tqdm.write(f"Invalid choice: {result['choice']}, assuming tie") 208 | result[ 209 | "reason" 210 | ] = f"Could not parse JSON (choice: {result['choice']}): {result['reason']}" 211 | result["choice"] = "tie" 212 | 213 | tokens = completion["usage"]["total_tokens"] 214 | result["swapped"] = swapped 215 | return result, tokens 216 | 217 | 218 | def estimated_cost(total_tokens): 219 | return 0.002 * (total_tokens) / 1000 220 | 221 | 222 | def eval_chatgpt(a, a_name, b, b_name, n=None, results_file=None, seed=42): 223 | random.seed(seed) 224 | if results_file is None: 225 | results_file = f"data/{a_name}_vs_{b_name}.json" 226 | 227 | # Load assistant a and assistant b responses as csv. 228 | df_a = pd.read_csv(a) 229 | df_b = pd.read_csv(b) 230 | 231 | names = { 232 | "a": a_name, 233 | "b": b_name, 234 | } 235 | 236 | assert len(df_a) == len(df_b) 237 | if n is None: 238 | n = len(df_a) 239 | n = min(n, len(df_a)) 240 | 241 | pbar = trange(n) 242 | wins = Counter() 243 | results = [] 244 | total_tokens = 0 245 | for _, ((_, row_a), (_, row_b)) in zip(pbar, zip(df_a.iterrows(), df_b.iterrows())): 246 | # Remove gist tokens. 247 | # Assert that the instructions, up to gist tokens, are the same. 248 | a_instr = clean_instruction(row_a["x"]) 249 | b_instr = clean_instruction(row_b["x"]) 250 | if a_instr != b_instr: 251 | # Input could be truncated slightly differently due to differing # 252 | # of gist tokens. 253 | if a_instr.startswith(b_instr): 254 | # a_instr is longer. 255 | instr = a_instr 256 | elif b_instr.startswith(a_instr): 257 | # b_instr is longer. 258 | instr = b_instr 259 | else: 260 | raise ValueError( 261 | f"Got different instructions after cleaning: {a_instr}, {b_instr}" 262 | ) 263 | else: 264 | instr = a_instr 265 | 266 | # Get the predicted response. 267 | a_pred = row_a["y_pred"] 268 | b_pred = row_b["y_pred"] 269 | 270 | result, tokens = query(instr, a_pred, b_pred) 271 | if result["choice"] == "tie": 272 | wins[names["a"]] += 0.5 273 | wins[names["b"]] += 0.5 274 | else: 275 | wins[names[result["choice"].lower()]] += 1 276 | # Add some extra info to result. 277 | result["x"] = instr 278 | result[names["a"]] = a_pred 279 | result[names["b"]] = b_pred 280 | results.append(result) 281 | total_tokens += tokens 282 | cost = estimated_cost(total_tokens) 283 | pbar.set_description( 284 | f"Total tokens: {total_tokens} (${cost:.3f} USD) | Score: {round_counter(normalize(wins))})" 285 | ) 286 | combined_json = { 287 | "names": names, 288 | "scores": wins, 289 | "results": results, 290 | "estimated_cost": cost, 291 | } 292 | with open(results_file, "w") as f: 293 | json.dump(combined_json, f, indent=2) 294 | 295 | 296 | if __name__ == "__main__": 297 | import argparse 298 | 299 | parser = argparse.ArgumentParser() 300 | parser.add_argument( 301 | "--a", 302 | type=str, 303 | default="data/results/LLaMA-gist-1/outputs-3000-validation_human.csv", 304 | ) 305 | parser.add_argument("--a_name", type=str, default="LLaMA-gist-1") 306 | parser.add_argument( 307 | "--b", 308 | type=str, 309 | default="data/results/LLaMA-pos_control-1/outputs-3000-validation_human.csv", 310 | ) 311 | parser.add_argument("--b_name", type=str, default="LLaMA-pos_control-1") 312 | parser.add_argument( 313 | "--n", 314 | type=int, 315 | help="Number of examples to evaluate. If None, evaluate all.", 316 | default=256, 317 | ) 318 | parser.add_argument( 319 | "--results_file", 320 | type=str, 321 | default="data/results/chatgpt-LLaMA-gist-1-vs-LLaMA-pos_control-1-validation_human-3000.json", 322 | ) 323 | parser.add_argument( 324 | "--seed", 325 | type=int, 326 | default=42, 327 | ) 328 | 329 | args = parser.parse_args() 330 | 331 | eval_chatgpt( 332 | args.a, 333 | args.a_name, 334 | args.b, 335 | args.b_name, 336 | n=args.n, 337 | results_file=args.results_file, 338 | seed=args.seed, 339 | ) 340 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayelm/gisting/3be0d062b6bdfd3caf51843bbc60261a0855f876/src/__init__.py -------------------------------------------------------------------------------- /src/arguments.py: -------------------------------------------------------------------------------- 1 | """ 2 | Huggingface TrainingArguments + hydra = *chefs kiss* 3 | """ 4 | 5 | 6 | import logging 7 | import os 8 | import os.path as osp 9 | import socket 10 | import sys 11 | from dataclasses import dataclass, field 12 | from typing import Optional 13 | 14 | import datasets 15 | import torch # noqa 16 | import transformers 17 | from hydra.core.config_store import ConfigStore 18 | from omegaconf import DictConfig, OmegaConf 19 | from transformers import Seq2SeqTrainingArguments, TrainingArguments 20 | 21 | logger = logging.getLogger(__name__) 22 | 23 | 24 | def simple_basename(f): 25 | return osp.splitext(osp.basename(f))[0] 26 | 27 | 28 | OmegaConf.register_new_resolver("basename", simple_basename) 29 | 30 | 31 | @dataclass 32 | class GistArguments: 33 | """ 34 | Arguments for gist 35 | """ 36 | 37 | condition: str = field( 38 | default="gist", 39 | metadata={"help": "One of gist, pos_control (no masking), or neg_control."}, 40 | ) 41 | num_gist_tokens: int = field( 42 | default=1, 43 | metadata={ 44 | "help": ( 45 | "number of gist tokens to insert. successive gist tokens can attend " 46 | "to each other; post-gist-tokens can attend to all gist tokens prior." 47 | ) 48 | }, 49 | ) 50 | add_gist_token: bool = field( 51 | default=True, 52 | metadata={"help": ("Whether to add gist token or not.")}, 53 | ) 54 | 55 | 56 | @dataclass 57 | class WandBArguments: 58 | log: bool = field(default=False, metadata={"help": "log to wandb"}) 59 | entity: Optional[str] = field( 60 | default=os.environ.get("USERNAME") or os.environ.get("USER"), 61 | metadata={"help": "WandB entity"}, 62 | ) 63 | project: Optional[str] = field( 64 | default="alscratch", metadata={"help": "wandb project"} 65 | ) 66 | group: Optional[str] = field(default="debug", metadata={"help": "wandb group"}) 67 | name: Optional[str] = field(default="run", metadata={"help": "wandb run name"}) 68 | tag: Optional[str] = field( 69 | default="run", metadata={"help": "optional tag to prefix wandb group"} 70 | ) 71 | 72 | 73 | @dataclass 74 | class GistTrainingArguments(TrainingArguments): 75 | """ 76 | Fix some of the types of TrainingArguments so that OmegaConf typechecks 77 | okay, and control when _post_init happens. 78 | """ 79 | 80 | gist: GistArguments = GistArguments() 81 | 82 | # if True, benchmark the model with and without gist. 83 | do_benchmarking: bool = False 84 | # if True, do sanity checking on gist caching (verifying that 85 | # e.g. encoder representations look the same with and without gist caching). 86 | # NOTE: This will fail for very large models on bf16 due to floating point 87 | # errors. 88 | do_benchmarking_sanity_checks: bool = False 89 | # What path to save the benchmarking outputs to. 90 | benchmarking_output_file: str = "benchmarking-outputs.csv" 91 | # Use either deepspeed or pytorch profiler. Paper uses pytorch. 92 | benchmarking_profiler: str = "pytorch" 93 | 94 | # If `benchmarking_prompt_caching` is True, cache prompts rather than gists 95 | # for decoder-only models. 96 | benchmarking_prompt_caching: bool = False 97 | 98 | max_benchmarking_samples: Optional[int] = 256 99 | 100 | # Change these types to strs so that they typecheck with str configs 101 | evaluation_strategy: Optional[str] = "no" 102 | lr_scheduler_type: Optional[str] = "linear" 103 | logging_strategy: Optional[str] = "steps" 104 | save_strategy: Optional[str] = "steps" 105 | optim: Optional[str] = "adamw_hf" 106 | hub_strategy: Optional[str] = "every_save" 107 | report_to: str = "none" 108 | remove_unused_columns: bool = False 109 | include_inputs_for_metrics: bool = True 110 | 111 | write_outputs: bool = field( 112 | default=True, 113 | metadata={"help": ("If True, save outputs to .csv file in output dir.")}, 114 | ) 115 | evaluate_before_train: bool = False 116 | 117 | # Change these types to optional 118 | data_seed: Optional[int] = None 119 | tf32: Optional[bool] = None 120 | xpu_backend: Optional[str] = None 121 | eval_steps: Optional[int] = None 122 | hub_model_id: Optional[str] = None 123 | hub_token: Optional[str] = None 124 | push_to_hub_model_id: Optional[str] = None 125 | push_to_hub_organization: Optional[str] = None 126 | push_to_hub_token: Optional[str] = None 127 | 128 | _run_post_init: bool = False 129 | 130 | def __post_init__(self): 131 | # Don't run post-init until ready to convert to TrainingArgs 132 | if self._run_post_init: 133 | super().__post_init__() 134 | 135 | 136 | @dataclass 137 | class GistSeq2SeqTrainingArguments(GistTrainingArguments, Seq2SeqTrainingArguments): 138 | pass 139 | 140 | 141 | @dataclass 142 | class ModelArguments: 143 | """ 144 | Arguments pertaining to which model/config/tokenizer we are going to 145 | fine-tune, or train from scratch. 146 | """ 147 | 148 | model_name_or_path: str = field( 149 | default="google/flan-t5-base", 150 | metadata={ 151 | "help": ( 152 | "The model checkpoint for weights initialization. Don't set if you " 153 | "want to train a model from scratch." 154 | ) 155 | }, 156 | ) 157 | llama_debug: bool = field( 158 | default=False, 159 | metadata={"help": "If True, load a tiny LLama Model for debugging."}, 160 | ) 161 | pretrained: bool = field( 162 | default=True, 163 | metadata={ 164 | "help": ( 165 | "Use pretrained model. This replaces old run_clm.py script " 166 | "`model_type` argument." 167 | ) 168 | }, 169 | ) 170 | config_name: Optional[str] = field( 171 | default=None, 172 | metadata={ 173 | "help": "Pretrained config name or path if not the same as model_name" 174 | }, 175 | ) 176 | tokenizer_name: Optional[str] = field( 177 | default=None, 178 | metadata={ 179 | "help": "Pretrained tokenizer name or path if not the same as model_name" 180 | }, 181 | ) 182 | cache_dir: Optional[str] = field( 183 | default=None, 184 | metadata={ 185 | "help": ( 186 | "Where do you want to store the pretrained models downloaded from " 187 | "huggingface.co" 188 | ) 189 | }, 190 | ) 191 | use_fast_tokenizer: bool = field( 192 | default=True, 193 | metadata={ 194 | "help": ( 195 | "Whether to use one of the fast tokenizer (backed by the tokenizers " 196 | "library) or not." 197 | ) 198 | }, 199 | ) 200 | model_revision: str = field( 201 | default="main", 202 | metadata={ 203 | "help": ( 204 | "The specific model version to use (can be a branch name, tag name " 205 | "or commit id)." 206 | ) 207 | }, 208 | ) 209 | use_auth_token: bool = field( 210 | default=False, 211 | metadata={ 212 | "help": ( 213 | "Will use the token generated when running `huggingface-cli login` " 214 | "(necessary to use this script with private models)." 215 | ) 216 | }, 217 | ) 218 | 219 | 220 | @dataclass 221 | class DataTrainingArguments: 222 | """ 223 | Arguments pertaining to what data we are going to input our model for 224 | training and eval. 225 | """ 226 | 227 | dataset_name: Optional[str] = field( 228 | default="alpaca-plus", 229 | metadata={"help": "The name of the dataset to use (via the datasets library)."}, 230 | ) 231 | dataset_config_name: Optional[str] = field( 232 | default=None, 233 | metadata={ 234 | "help": ( 235 | "The configuration name of the dataset to use (via the datasets " 236 | "library)." 237 | ) 238 | }, 239 | ) 240 | train_file: Optional[str] = field( 241 | default=None, metadata={"help": "The input training data file (a text file)."} 242 | ) 243 | validation_file: Optional[str] = field( 244 | default=None, 245 | metadata={ 246 | "help": "An optional input evaluation data file to evaluate the perplexity " 247 | "on (a text file)." 248 | }, 249 | ) 250 | max_train_samples: Optional[int] = field( 251 | default=None, 252 | metadata={ 253 | "help": ( 254 | "For debugging purposes or quicker training, truncate the number of " 255 | "training examples to this value if set." 256 | ) 257 | }, 258 | ) 259 | max_eval_samples: Optional[int] = field( 260 | default=None, 261 | metadata={ 262 | "help": ( 263 | "For debugging purposes or quicker training, truncate the number of " 264 | "evaluation examples to this value if set." 265 | ) 266 | }, 267 | ) 268 | overwrite_cache: bool = field( 269 | default=False, 270 | metadata={"help": "Overwrite the cached training and evaluation sets"}, 271 | ) 272 | 273 | def __post_init__(self): 274 | if ( 275 | self.dataset_name is None 276 | and self.train_file is None 277 | and self.validation_file is None 278 | ): 279 | raise ValueError( 280 | "Need either a dataset name or a training/validation file." 281 | ) 282 | else: 283 | if self.train_file is not None: 284 | extension = self.train_file.split(".")[-1] 285 | assert extension in [ 286 | "csv", 287 | "json", 288 | "txt", 289 | ], "`train_file` should be a csv, a json or a txt file." 290 | if self.validation_file is not None: 291 | extension = self.validation_file.split(".")[-1] 292 | assert extension in [ 293 | "csv", 294 | "json", 295 | "txt", 296 | ], "`validation_file` should be a csv, a json or a txt file." 297 | 298 | 299 | @dataclass 300 | class Arguments: 301 | model: ModelArguments = ModelArguments() 302 | data: DataTrainingArguments = DataTrainingArguments() 303 | wandb: WandBArguments = WandBArguments() 304 | training: GistSeq2SeqTrainingArguments = GistSeq2SeqTrainingArguments("dummy") 305 | 306 | 307 | cs = ConfigStore.instance() 308 | cs.store(name="base_config", node=Arguments) 309 | 310 | 311 | def global_setup(args: DictConfig) -> Arguments: 312 | """Global setup of arguments.""" 313 | hostname = socket.gethostname() 314 | logger.info(f"Running on {hostname}") 315 | 316 | if args.training.report_to != "none": 317 | raise ValueError( 318 | "report_to is disabled; use training.wandb settings to " 319 | "configure wandb logging." 320 | ) 321 | 322 | # Setup logging 323 | logging.basicConfig( 324 | format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 325 | datefmt="%m/%d/%Y %H:%M:%S", 326 | handlers=[logging.StreamHandler(sys.stdout)], 327 | ) 328 | 329 | # Convert args to the actual dataclass object, to enable methods. Need to 330 | # delete _n_gpu, a property that TrainingArgs init doesn't expect. 331 | del args.training._n_gpu 332 | # Dirty hack: only run post init when we're ready to convert to TrainingArgs 333 | args.training._run_post_init = True 334 | args = OmegaConf.to_object(args) 335 | 336 | log_level = args.training.get_process_log_level() 337 | logger.setLevel(log_level) 338 | datasets.utils.logging.set_verbosity(log_level) 339 | transformers.utils.logging.set_verbosity(log_level) 340 | transformers.utils.logging.enable_default_handler() 341 | transformers.utils.logging.enable_explicit_format() 342 | 343 | # Log on each process the small summary: 344 | logger.warning( 345 | f"Process rank: {args.training.local_rank}, device: {args.training.device}, " 346 | f"n_gpu: {args.training.n_gpu}" 347 | f" distributed training: {bool(args.training.local_rank != -1)}, 16-bits " 348 | f"training: {args.training.fp16}, bf16 training: {args.training.bf16}" 349 | ) 350 | logger.info(f"Training/evaluation parameters {args.training}") 351 | 352 | return args 353 | -------------------------------------------------------------------------------- /src/benchmarking.py: -------------------------------------------------------------------------------- 1 | """Utilities for profling and benchmarking.""" 2 | 3 | 4 | from dataclasses import dataclass 5 | from typing import Any, Dict, Optional, Union 6 | 7 | from deepspeed.profiling.flops_profiler import FlopsProfiler 8 | from torch import nn 9 | from torch.autograd import DeviceType 10 | from torch.profiler import ProfilerActivity 11 | from torch.profiler import profile as torch_profile 12 | from torch.profiler import record_function 13 | 14 | 15 | @dataclass 16 | class ProfilerOutputs: 17 | profiler: Union[FlopsProfiler, torch_profile] 18 | _json: Optional[Dict[str, Any]] = None 19 | 20 | def to_json(self): 21 | raise NotImplementedError 22 | 23 | 24 | @dataclass 25 | class DeepspeedProfilerOutputs(ProfilerOutputs): 26 | def __post_init__(self): 27 | # Save profile info since end_profile cleans up. 28 | self._json = { 29 | "flops": self.profiler.get_total_flops(), 30 | "macs": self.profiler.get_total_macs(), 31 | "params": self.profiler.get_total_params(), 32 | "duration": self.profiler.get_total_duration(), 33 | } 34 | 35 | def to_json(self): 36 | return self._json 37 | 38 | 39 | class TorchProfilerOutputs(ProfilerOutputs): 40 | def to_json(self): 41 | events = self.profiler.key_averages() 42 | # https://github.com/pytorch/pytorch/blob/5b1cedacde7f3f93fd5b59e9a7a42ba13c8b5bfc/torch/autograd/profiler_util.py#L823-L832 # noqa 43 | total_cpu_time = sum([event.self_cpu_time_total for event in events]) 44 | total_flops = sum([event.flops for event in events]) 45 | total_cuda_time = 0 46 | for evt in events: 47 | if evt.device_type == DeviceType.CPU: 48 | # in legacy profiler, kernel info is stored in cpu events 49 | if evt.is_legacy: 50 | total_cuda_time += evt.self_cuda_time_total 51 | elif evt.device_type == DeviceType.CUDA: 52 | # in kineto profiler, there're events with the correct device 53 | # type (e.g. CUDA) 54 | total_cuda_time += evt.self_cuda_time_total 55 | 56 | return { 57 | "cpu_time": total_cpu_time, 58 | "cuda_time": total_cuda_time, 59 | "flops": total_flops, 60 | } 61 | 62 | 63 | def _ds_profile(func_to_profile): 64 | """Wrap any function that takes a model as first arg, and profile it.""" 65 | 66 | def profiled_func(model: nn.Module, *args, **kwargs): 67 | prof = FlopsProfiler(model) 68 | prof.start_profile() 69 | 70 | outputs = func_to_profile(model, *args, **kwargs) 71 | 72 | prof.stop_profile() 73 | 74 | profiler_outputs = DeepspeedProfilerOutputs(prof) 75 | 76 | prof.end_profile() 77 | 78 | return outputs, profiler_outputs 79 | 80 | return profiled_func 81 | 82 | 83 | def _pytorch_profile(func_to_profile): 84 | """Wrap any function that takes a model as first arg, and profile it.""" 85 | 86 | def profiled_func(*args, **kwargs): 87 | with torch_profile( 88 | activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], with_flops=True 89 | ) as prof: 90 | with record_function("model_inference"): 91 | outputs = func_to_profile(*args, **kwargs) 92 | profiler_outputs = TorchProfilerOutputs(prof) 93 | return outputs, profiler_outputs 94 | 95 | return profiled_func 96 | 97 | 98 | def profile(func_to_profile, profiler_type="deepspeed"): 99 | """Wrap any function that takes a model as first arg, and profile it.""" 100 | if profiler_type == "deepspeed": 101 | return _ds_profile(func_to_profile) 102 | elif profiler_type == "pytorch": 103 | return _pytorch_profile(func_to_profile) 104 | else: 105 | raise ValueError(f"Unknown profiler type {profiler_type})") 106 | -------------------------------------------------------------------------------- /src/compress.py: -------------------------------------------------------------------------------- 1 | """Gist compression demo.""" 2 | 3 | from typing import Optional 4 | 5 | import fire 6 | import torch 7 | from transformers import AutoConfig, AutoTokenizer, LlamaTokenizer 8 | 9 | from . import gist_llama, gist_t5, weight_diff 10 | from .gist_llama import GistLlamaForCausalLM 11 | from .gist_t5 import GistT5ForConditionalGeneration 12 | 13 | 14 | def humanbytes(B): 15 | """Return the given bytes as a human friendly KB, MB, GB, or TB string. 16 | 17 | https://stackoverflow.com/a/31631711/2980246 18 | """ 19 | B = float(B) 20 | KB = float(1024) 21 | MB = float(KB**2) # 1,048,576 22 | GB = float(KB**3) # 1,073,741,824 23 | TB = float(KB**4) # 1,099,511,627,776 24 | 25 | if B < KB: 26 | return "{0} {1}".format(B, "Bytes" if 0 == B > 1 else "Byte") 27 | elif KB <= B < MB: 28 | return "{0:.2f} KB".format(B / KB) 29 | elif MB <= B < GB: 30 | return "{0:.2f} MB".format(B / MB) 31 | elif GB <= B < TB: 32 | return "{0:.2f} GB".format(B / GB) 33 | elif TB <= B: 34 | return "{0:.2f} TB".format(B / TB) 35 | 36 | 37 | @torch.inference_mode() 38 | def main( 39 | model_name_or_path: str, 40 | instruction: str, 41 | input: str = "", 42 | num_gist_tokens: Optional[int] = 1, 43 | cache_dir: str = ".cache", 44 | precision: str = "fp32", 45 | max_new_tokens: int = 512, 46 | base_llama_path: Optional[str] = None, 47 | ) -> None: 48 | """Decode from a model with gist compression. 49 | 50 | Args: 51 | model_name_or_path: The model to load. MUST BE A GIST MODEL. 52 | instruction: The instruction to be compressed (required). 53 | input: The input for the instruction (optional). Will not be compressed 54 | or cached. 55 | num_gist_tokens: number of gist tokens to compress to. This should 56 | match the number of gist tokens the model was trained on. 57 | cache_dir: Hugging Face cache dir. 58 | precision: Precision to load the model in. Recommend fp32 or bf16 to 59 | save space (not fp16). 60 | max_new_tokens: Maximum number of new tokens to decode. 61 | base_llama_path: Any LLaMA model loaded from Hugging Face 62 | (jayelm/llama-7b-{gist,pos_control,neg_control}-1) is a weight 63 | diff, not the full model. If loading one of the Hugging Face LLaMA 64 | models, use this argument to specify the path to the raw LLaMA model. 65 | """ 66 | is_llama = "llama" in model_name_or_path.lower() 67 | is_t5 = "t5" in model_name_or_path.lower() 68 | 69 | # Load config 70 | config = AutoConfig.from_pretrained(model_name_or_path, cache_dir=cache_dir) 71 | 72 | # Load model 73 | print(f"Loading model {model_name_or_path}") 74 | if is_t5: 75 | model_cls = GistT5ForConditionalGeneration 76 | elif is_llama: 77 | model_cls = GistLlamaForCausalLM 78 | else: 79 | raise ValueError(f"Model type {model_name_or_path} not supported") 80 | 81 | if model_name_or_path in { 82 | "jayelm/llama-7b-gist-1", 83 | "jayelm/llama-7b-pos_control-1", 84 | "jayelm/llama-7b-neg_control-1", 85 | }: 86 | # Load with weight diff file 87 | if base_llama_path is None: 88 | raise ValueError( 89 | f"{model_name_or_path} is a weight diff huggingface repo. " 90 | "You must specify a `base_llama_path` for this to work." 91 | ) 92 | else: 93 | print("Weight diff detected. Applying to original model...") 94 | model, _ = weight_diff.recover( 95 | path_raw=base_llama_path, 96 | path_diff=model_name_or_path, 97 | test_inference=False, 98 | cache_dir=cache_dir, 99 | ) 100 | else: 101 | model = model_cls.from_pretrained( 102 | model_name_or_path, 103 | config=config, 104 | cache_dir=cache_dir, 105 | ) 106 | 107 | dtypes = { 108 | "bf16": torch.bfloat16, 109 | "fp16": torch.float16, 110 | "fp32": torch.float, 111 | } 112 | model = model.to(dtypes[precision]).cuda().eval() 113 | 114 | # Load tokenizer. It must already have gist token defined. 115 | print("Loading tokenizer") 116 | if is_llama: 117 | tokenizer = LlamaTokenizer.from_pretrained(model_name_or_path) 118 | tokenizer.pad_token = tokenizer.eos_token 119 | tokenizer.padding_side = "left" 120 | assert len(tokenizer) == gist_llama.PRETRAINED_VOCAB_SIZE + 1 121 | assert model.lm_head.weight.shape[0] == gist_llama.PRETRAINED_VOCAB_SIZE + 1 122 | else: 123 | tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) 124 | assert len(tokenizer) == gist_t5.PRETRAINED_VOCAB_SIZE + 1 125 | assert model.shared.weight.shape[0] == gist_t5.PRETRAINED_VOCAB_SIZE + 1 126 | gist_token = tokenizer.additional_special_tokens_ids[-1] 127 | 128 | # Compress instruction 129 | print("Compressing instruction") 130 | gist_str = "" * num_gist_tokens 131 | prepped_instruction = f"Instruction: {instruction}\n{gist_str}" 132 | instruction_input_ids = tokenizer.encode(prepped_instruction) 133 | if is_t5: 134 | instruction_input_ids = instruction_input_ids[:-1] # Remove eos token 135 | instruction_input_ids_tensor = ( 136 | torch.tensor(instruction_input_ids).unsqueeze(0).cuda() 137 | ) 138 | gist_kwargs = { 139 | "input_ids": instruction_input_ids_tensor, 140 | "attention_mask": torch.ones_like(instruction_input_ids_tensor), 141 | } 142 | if is_llama: 143 | gist_kwargs["attention_mask_gist"] = torch.ones_like( 144 | instruction_input_ids_tensor 145 | )[None, None] 146 | gist_activations = model.get_gist_activations( 147 | gist_token=gist_token, 148 | num_gist_tokens=num_gist_tokens, 149 | **gist_kwargs, 150 | ) 151 | 152 | # Prepare input. Input decoding must be done carefully: tokenizers will 153 | # tokenize things differently if the input is at the start of the string 154 | # (vs if it follows a gist token). The simplest thing to do to ensure 155 | # consistency is add a dummy gist token before the input, then remove it 156 | # from the input ids later. 157 | if is_t5: 158 | input_suffix = "" 159 | else: 160 | input_suffix = "\nOutput:" 161 | 162 | if input: 163 | prepped_input = f"\nInput: {input}{input_suffix}" 164 | full_prompt = ( 165 | f"Instruction: {instruction}\n{gist_str}\nInput: {input}{input_suffix}" 166 | ) 167 | else: 168 | prepped_input = f"{input_suffix}" 169 | full_prompt = f"Instruction: {instruction}\n{gist_str}{input_suffix}" 170 | 171 | input_ids = tokenizer.encode(prepped_input) 172 | # Trim off the gist token we added at the beginning. 173 | input_ids = input_ids[input_ids.index(gist_token) + 1 :] 174 | input_ids_tensor = torch.tensor(input_ids).unsqueeze(0).cuda() 175 | attention_mask_with_gist = ( 176 | torch.tensor([1] * (len(input_ids) + num_gist_tokens)).unsqueeze(0).cuda() 177 | ) 178 | 179 | # Sanity check that tokenizing the full prompt is the same as tokenizing the 180 | # prepped instruction and prepped input separately. 181 | full_prompt_input_ids = tokenizer.encode(full_prompt) 182 | assert ( 183 | full_prompt_input_ids == instruction_input_ids + input_ids 184 | ), "Got different results tokenizing the full prompt vs tokenizing instruction/input separately" 185 | 186 | print("Decoding from model") 187 | gen_kwargs = { 188 | "input_ids": input_ids_tensor, 189 | "attention_mask": attention_mask_with_gist, 190 | } 191 | if is_llama: 192 | gen_kwargs["attention_mask_gist"] = attention_mask_with_gist[None, None] 193 | gen_kwargs["past_key_values"] = gist_activations.past_key_values 194 | gen_kwargs["gist_offset"] = gist_activations.gist_indices 195 | else: 196 | gen_kwargs["gist_activations"] = gist_activations 197 | generated_tokens = model.generate( 198 | max_new_tokens=max_new_tokens, 199 | do_sample=False, 200 | **gen_kwargs, 201 | ) 202 | output = tokenizer.decode(generated_tokens[0], skip_special_tokens=True) 203 | if is_llama: 204 | output = output[len(prepped_input) - 5 :] 205 | 206 | num_layers = len(gist_activations.past_key_values) 207 | 208 | # Compute size of KV cache per token. 209 | kv_cache_tensor = gist_activations.past_key_values[0][0] 210 | single_token_kv_cache_tensor = kv_cache_tensor[:, :, 0] 211 | single_token_kv_cache_mem = ( 212 | single_token_kv_cache_tensor.element_size() 213 | * single_token_kv_cache_tensor.nelement() 214 | ) 215 | kv_cache_size_per_token = 2 * num_layers * single_token_kv_cache_mem 216 | 217 | # Compute sizes of original vs gisted kv caches. 218 | orig_kv_cache_mem = len(instruction_input_ids) * kv_cache_size_per_token 219 | gist_kv_cache_mem = num_gist_tokens * kv_cache_size_per_token 220 | 221 | print(f"Instruction: {instruction}") 222 | print( 223 | f">>> Compressed into {num_gist_tokens} gist tokens (compression factor: {len(instruction_input_ids) / num_gist_tokens}x)" 224 | ) 225 | print( 226 | f">>> {num_layers} layer KV cache, each layer has 2 tensors of shape {tuple(kv_cache_tensor.shape)}" 227 | ) 228 | print( 229 | f">>> {precision} KV cache size reduced from {humanbytes(orig_kv_cache_mem)} to {humanbytes(gist_kv_cache_mem)}" 230 | ) 231 | print(f"Input: {input}") 232 | print(f"Output: {output}") 233 | 234 | 235 | if __name__ == "__main__": 236 | fire.Fire(main) 237 | -------------------------------------------------------------------------------- /src/conf/config.yaml: -------------------------------------------------------------------------------- 1 | hydra: 2 | run: 3 | dir: . 4 | sweep: 5 | dir: . 6 | subdir: . 7 | job_logging: 8 | root: 9 | level: INFO 10 | job: 11 | env_set: 12 | TOKENIZERS_PARALLELISM: "false" 13 | 14 | 15 | defaults: 16 | - base_config # see src/arguments.py 17 | - _self_ 18 | 19 | 20 | wandb: 21 | log: true 22 | entity: jayelm # Change this to your wandb username. 23 | project: gist 24 | group: ${wandb.tag}-${training.gist.condition}-${training.gist.num_gist_tokens}tok-${basename:${model.model_name_or_path}}-${basename:${data.dataset_name}} 25 | name: ${wandb.group}-run-${training.seed} 26 | 27 | model: 28 | model_name_or_path: google/flan-t5-base 29 | pretrained: true 30 | # Recommend symlinking .cache to wherever you have space to store models, 31 | # datasets, etc. 32 | cache_dir: .cache/ 33 | 34 | training: 35 | predict_with_generate: true 36 | generation_max_length: 128 37 | 38 | do_train: true 39 | do_eval: true 40 | # Recommend symlinking exp to wherever you have space for experiment runs. 41 | output_dir: exp/${wandb.group}/${wandb.name} 42 | 43 | report_to: "none" # THIS MUST BE NONE. Use wandb args to control logging. 44 | 45 | dataloader_num_workers: 0 # If > 0, some weird process hanging might occur. 46 | 47 | # Default training params: effective batch size = 16 48 | num_train_epochs: 3 49 | fp16: false 50 | fp16_full_eval: false 51 | per_device_train_batch_size: 8 52 | per_device_eval_batch_size: 8 53 | gradient_accumulation_steps: 2 54 | 55 | # Save/eval every 1000 steps and track best model 56 | overwrite_output_dir: false # Resume training from checkpoint if it exists. 57 | evaluation_strategy: steps 58 | save_strategy: steps 59 | eval_steps: 1000 60 | save_steps: 1000 61 | save_total_limit: 1 62 | load_best_model_at_end: true 63 | 64 | metric_for_best_model: unseen_rougeL 65 | greater_is_better: true -------------------------------------------------------------------------------- /src/conf/experiment/debug.yaml: -------------------------------------------------------------------------------- 1 | # @package _global_ 2 | # A simple debug config. 3 | 4 | wandb: 5 | log: true 6 | group: debug-alpaca-plus 7 | 8 | model: 9 | model_name_or_path: google/flan-t5-small 10 | 11 | data: 12 | max_eval_samples: 10 13 | 14 | training: 15 | gist: 16 | num_gist_tokens: 2 17 | 18 | save_strategy: "no" # Don't save in debug mode. 19 | 20 | fp16: false 21 | fp16_full_eval: false 22 | bf16: false 23 | bf16_full_eval: false 24 | 25 | load_best_model_at_end: false 26 | 27 | max_steps: 100 # Overrides num_train_epochs 28 | eval_steps: 10 29 | per_device_train_batch_size: 2 30 | per_device_eval_batch_size: 2 31 | 32 | overwrite_output_dir: true 33 | -------------------------------------------------------------------------------- /src/conf/launcher/slurm.yaml: -------------------------------------------------------------------------------- 1 | # @package _global_ 2 | 3 | defaults: 4 | - override /hydra/launcher: submitit_slurm 5 | 6 | hydra: 7 | launcher: 8 | cpus_per_task: 16 9 | gres: gpu:1 10 | nodes: 1 11 | name: "${wandb.group}/${wandb.name}" 12 | mem_gb: 80 13 | timeout_min: 1440 14 | -------------------------------------------------------------------------------- /src/conf/model/README.md: -------------------------------------------------------------------------------- 1 | # Model configs 2 | 3 | These configs allow for easy switching of models, since switching models often 4 | requires changing batch sizes, etc to make things work reasonably. 5 | -------------------------------------------------------------------------------- /src/conf/model/flan-t5-base.yaml: -------------------------------------------------------------------------------- 1 | # @package _global_ 2 | # Uses tk-instruct finetuning params. 3 | 4 | model: 5 | model_name_or_path: google/flan-t5-base 6 | 7 | training: 8 | lr_scheduler_type: constant 9 | warmup_steps: 0 10 | 11 | per_device_train_batch_size: 8 12 | per_device_eval_batch_size: 8 13 | gradient_accumulation_steps: 2 14 | learning_rate: 0.00005 15 | 16 | save_steps: 8000 17 | eval_steps: 8000 18 | 19 | max_steps: 16000 # you may be able to get away with just 8k steps. -------------------------------------------------------------------------------- /src/conf/model/flan-t5-large.yaml: -------------------------------------------------------------------------------- 1 | # @package _global_ 2 | 3 | defaults: 4 | - flan-t5-base 5 | 6 | model: 7 | model_name_or_path: google/flan-t5-large 8 | 9 | training: 10 | per_device_train_batch_size: 2 11 | per_device_eval_batch_size: 2 12 | gradient_accumulation_steps: 8 13 | -------------------------------------------------------------------------------- /src/conf/model/flan-t5-xxl.yaml: -------------------------------------------------------------------------------- 1 | # @package _global_ 2 | # Check flan-t5-base.yaml for base config. 3 | 4 | defaults: 5 | - flan-t5-base 6 | 7 | model: 8 | model_name_or_path: google/flan-t5-xxl 9 | 10 | training: 11 | bf16: true 12 | bf16_full_eval: true 13 | # On 4 gpus, this gives total batch size of 16. 14 | per_device_train_batch_size: 1 15 | per_device_eval_batch_size: 1 16 | gradient_accumulation_steps: 4 17 | -------------------------------------------------------------------------------- /src/conf/model/llama-7b.yaml: -------------------------------------------------------------------------------- 1 | # @package _global_ 2 | # Hyperparams from https://github.com/tatsu-lab/stanford_alpaca#fine-tuning 3 | 4 | model: 5 | model_name_or_path: llama-7b 6 | 7 | training: 8 | bf16: true 9 | bf16_full_eval: true 10 | # 128 batch size. 11 | per_device_train_batch_size: 4 12 | per_device_eval_batch_size: 4 13 | gradient_checkpointing: false 14 | gradient_accumulation_steps: 8 15 | generation_max_length: 512 # This includes the prompt length. 16 | learning_rate: 2.0e-5 17 | weight_decay: 0.0 18 | warmup_ratio: 0.03 19 | lr_scheduler_type: cosine 20 | 21 | save_steps: 1500 22 | eval_steps: 1500 23 | -------------------------------------------------------------------------------- /src/conf/model/llama-debug.yaml: -------------------------------------------------------------------------------- 1 | # @package _global_ 2 | # A debug llama config 3 | 4 | defaults: 5 | - llama-7b 6 | 7 | model: 8 | llama_debug: true 9 | pretrained: false 10 | 11 | training: 12 | bf16: false 13 | bf16_full_eval: false 14 | per_device_train_batch_size: 4 15 | per_device_eval_batch_size: 4 16 | eval_steps: 2 -------------------------------------------------------------------------------- /src/data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jayelm/gisting/3be0d062b6bdfd3caf51843bbc60261a0855f876/src/data/__init__.py -------------------------------------------------------------------------------- /src/data/alpaca/__init__.py: -------------------------------------------------------------------------------- 1 | from . import alpaca, collator 2 | -------------------------------------------------------------------------------- /src/data/alpaca/alpaca.py: -------------------------------------------------------------------------------- 1 | """Combined Alpaca and Self-Instruct dataset.""" 2 | 3 | 4 | import json 5 | 6 | import datasets 7 | from datasets.splits import NamedSplit 8 | 9 | logger = datasets.logging.get_logger(__name__) 10 | 11 | 12 | class AlpacaConfig(datasets.BuilderConfig): 13 | def __init__( 14 | self, 15 | *args, 16 | train_file=None, 17 | validation_seen_file=None, 18 | validation_unseen_file=None, 19 | validation_human_file=None, 20 | **kwargs, 21 | ): 22 | super().__init__(*args, **kwargs) 23 | self.train_file: str = train_file 24 | self.validation_seen_file: str = validation_seen_file 25 | self.validation_unseen_file: str = validation_unseen_file 26 | self.validation_human_file: str = validation_human_file 27 | 28 | 29 | class AlpacaPlus(datasets.GeneratorBasedBuilder): 30 | """AlpacaPlus Dataset.""" 31 | 32 | VERSION = datasets.Version("1.0.1") 33 | BUILDER_CONFIG_CLASS = AlpacaConfig 34 | BUILDER_CONFIGS = [ 35 | AlpacaConfig( 36 | name="default", 37 | train_file="./data/alpaca_plus/alpaca_plus_train.json", 38 | validation_seen_file="./data/alpaca_plus/alpaca_plus_validation_seen.json", 39 | validation_unseen_file="./data/alpaca_plus/alpaca_plus_validation_unseen.json", # noqa 40 | validation_human_file="./data/alpaca_plus/alpaca_plus_validation_human.json", # noqa 41 | description="Default config for Alpaca", 42 | ), 43 | ] 44 | DEFAULT_CONFIG_NAME = "default" 45 | 46 | def _info(self): 47 | return datasets.DatasetInfo( 48 | description="Alpaca Data", 49 | features=datasets.Features( 50 | { 51 | "instruction": datasets.Value("string"), 52 | "input": datasets.Value("string"), 53 | "output": datasets.Value("string"), 54 | "source": datasets.Value("string"), 55 | "split": datasets.Value("string"), 56 | } 57 | ), 58 | supervised_keys=None, 59 | ) 60 | 61 | def _split_generators(self, dl_manager): 62 | """Returns SplitGenerators.""" 63 | del dl_manager 64 | return [ 65 | datasets.SplitGenerator( 66 | name=datasets.Split.TRAIN, 67 | gen_kwargs={ 68 | "path": self.config.train_file, 69 | "split": "train", 70 | }, 71 | ), 72 | datasets.SplitGenerator( 73 | name=NamedSplit("validation_seen"), 74 | gen_kwargs={ 75 | "path": self.config.validation_seen_file, 76 | "split": "validation_seen", 77 | }, 78 | ), 79 | datasets.SplitGenerator( 80 | name=NamedSplit("validation_human"), 81 | gen_kwargs={ 82 | "path": self.config.validation_human_file, 83 | "split": "validation_human", 84 | }, 85 | ), 86 | datasets.SplitGenerator( 87 | name=NamedSplit("validation_unseen"), 88 | gen_kwargs={ 89 | "path": self.config.validation_unseen_file, 90 | "split": "validation_unseen", 91 | }, 92 | ), 93 | ] 94 | 95 | def _generate_examples( 96 | self, 97 | path: str, 98 | split: str, 99 | ): 100 | """Yields examples.""" 101 | logger.info(f"Generating {split} tasks from = {path}") 102 | with open(path, encoding="utf-8") as split_f: 103 | task_json = json.load(split_f) 104 | for idx, instance in enumerate(task_json): 105 | instance["split"] = split 106 | yield f"alpaca_{split}_{idx}", instance 107 | -------------------------------------------------------------------------------- /src/data/alpaca/collator.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from collections import defaultdict 3 | from dataclasses import dataclass 4 | from typing import Any, Optional, Union 5 | 6 | import torch 7 | from torch.nn.utils.rnn import pad_sequence 8 | from transformers import PreTrainedTokenizerBase 9 | from transformers.data.data_collator import PaddingStrategy 10 | 11 | from ...utils import first_mismatch 12 | from .. import gist 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | @dataclass 18 | class DataCollatorForAlpaca: 19 | tokenizer: PreTrainedTokenizerBase 20 | model: Optional[Any] = None 21 | padding: Union[bool, str, PaddingStrategy] = True 22 | max_source_length: Optional[int] = None 23 | max_target_length: Optional[int] = None 24 | max_source_length_human: Optional[int] = None 25 | max_target_length_human: Optional[int] = None 26 | pad_to_multiple_of: Optional[int] = None 27 | label_pad_token_id: int = -100 28 | return_tensors: str = "pt" 29 | gist_token: int = 32100 30 | pad_token: int = 0 31 | add_gist_token: bool = True 32 | gist_condition: str = "gist" 33 | num_gist_tokens: int = 10 34 | 35 | def __post_init__(self): 36 | if self.max_source_length_human is None: 37 | self.max_source_length_human = self.max_source_length 38 | if self.max_target_length_human is None: 39 | self.max_target_length_human = self.max_target_length 40 | 41 | def __call__(self, batch, return_tensors=None): 42 | if any("human" in instance["split"] for instance in batch): 43 | # Use the human max lengths. 44 | max_source_length = self.max_source_length_human 45 | max_target_length = self.max_target_length_human 46 | else: 47 | max_source_length = self.max_source_length 48 | max_target_length = self.max_target_length 49 | 50 | if return_tensors is None: 51 | return_tensors = self.return_tensors 52 | 53 | sources = [] 54 | for instance in batch: 55 | if not self.add_gist_token: 56 | # Add gist tokens later, during tokenization. 57 | maybe_gist_str = "" 58 | else: 59 | maybe_gist_str = "" * self.num_gist_tokens 60 | 61 | if instance["input"]: 62 | source = f"Instruction: {instance['instruction']}\n{maybe_gist_str}\nInput: {instance['input']}" # noqa 63 | else: 64 | # No input, instruction only. 65 | source = f"Instruction: {instance['instruction']}\n{maybe_gist_str}" 66 | 67 | tokenized_source = self.tokenizer(source)["input_ids"] 68 | if len(tokenized_source) <= max_source_length: 69 | tokenized_source = tokenized_source[:-1] # Drop the token. 70 | else: 71 | tokenized_source = tokenized_source[:max_source_length] 72 | sources.append(self.tokenizer.decode(tokenized_source)) 73 | 74 | model_inputs = self.tokenizer( 75 | sources, 76 | max_length=max_source_length, 77 | padding=self.padding, 78 | return_tensors=self.return_tensors, 79 | truncation=True, 80 | pad_to_multiple_of=self.pad_to_multiple_of, 81 | ) 82 | 83 | # Tokenize labels. 84 | labels = [instance["output"] for instance in batch] 85 | with self.tokenizer.as_target_tokenizer(): 86 | labels = self.tokenizer( 87 | labels, 88 | max_length=max_target_length, 89 | padding=self.padding, 90 | return_tensors=self.return_tensors, 91 | truncation=True, 92 | pad_to_multiple_of=self.pad_to_multiple_of, 93 | ) 94 | label_mask = labels["attention_mask"].bool() 95 | model_inputs["labels"] = labels["input_ids"].masked_fill( 96 | ~label_mask, self.label_pad_token_id 97 | ) 98 | 99 | # prepare decoder_input_ids 100 | if self.model is not None and hasattr( 101 | self.model, "prepare_decoder_input_ids_from_labels" 102 | ): 103 | decoder_input_ids = self.model.prepare_decoder_input_ids_from_labels( 104 | labels=model_inputs["labels"] 105 | ) 106 | model_inputs["decoder_input_ids"] = decoder_input_ids 107 | 108 | # modify attention mask 109 | if self.gist_condition == "pos_control" or not self.add_gist_token: 110 | # Don't change anything, just set cross attention mask. 111 | model_inputs["cross_attention_mask"] = model_inputs["attention_mask"] 112 | elif self.gist_condition == "gist": 113 | model_inputs["attention_mask"] = gist.make_gist_mask( 114 | model_inputs["input_ids"], 115 | self.gist_token, 116 | pad_token=self.pad_token, 117 | ).squeeze( 118 | 1 119 | ) # Squeeze dim 1 as T5 codebase expects 3D mask. 120 | # Decoder cross attn cannot see prior to the first gist token. 121 | model_inputs["cross_attention_mask"] = gist.make_mask_pre_first_gist( 122 | model_inputs["input_ids"], 123 | self.gist_token, 124 | pad_token=self.pad_token, 125 | ) 126 | elif self.gist_condition == "neg_control": 127 | model_inputs["attention_mask"] = gist.make_neg_control_mask( 128 | model_inputs["input_ids"], 129 | self.gist_token, 130 | pad_token=self.pad_token, 131 | ).squeeze( 132 | 1 133 | ) # Squeeze dim 1 as T5 codebase expects 3D mask. 134 | # Decoder cross attn cannot see prior to (and including) *any* gist 135 | # token. 136 | model_inputs["cross_attention_mask"] = 1 - ( 137 | gist.make_mask_post_last_gist( 138 | model_inputs["input_ids"], 139 | self.gist_token, 140 | pad_token=self.pad_token, 141 | ) 142 | ) 143 | else: 144 | raise ValueError(f"Invalid gist_condition: {self.gist_condition}") 145 | 146 | return model_inputs 147 | 148 | 149 | @dataclass 150 | class DataCollatorForAlpacaCLM: 151 | """Data collator for decoder-only models. Does left padding.""" 152 | 153 | tokenizer: PreTrainedTokenizerBase 154 | max_length: Optional[int] = None 155 | max_length_human: Optional[int] = None 156 | label_pad_token_id: int = -100 157 | return_tensors: str = "pt" 158 | gist_token: int = 50257 159 | pad_token: int = 0 160 | add_gist_token: bool = True 161 | gist_condition: str = "gist" 162 | num_gist_tokens: int = 10 163 | check_correctness: bool = False 164 | 165 | def __post_init__(self): 166 | if self.max_length_human is None: 167 | self.max_length_human = self.max_length 168 | 169 | def __call__(self, batch, return_tensors=None): 170 | if any("human" in instance["split"] for instance in batch): 171 | # Use the human max lengths. 172 | max_length = self.max_length_human 173 | else: 174 | max_length = self.max_length 175 | 176 | if return_tensors is None: 177 | return_tensors = self.return_tensors 178 | 179 | model_inputs = defaultdict(list) 180 | for instance in batch: 181 | if not self.add_gist_token: 182 | # Add gist tokens later, during tokenization. 183 | maybe_gist_str = "" 184 | else: 185 | maybe_gist_str = " ".join( 186 | ["" for _ in range(self.num_gist_tokens)] 187 | ) 188 | 189 | if instance["input"]: 190 | prompt = f"Instruction: {instance['instruction']}\n{maybe_gist_str}\nInput: {instance['input']}\nOutput:" # noqa 191 | else: 192 | prompt = f"Instruction: {instance['instruction']}\n{maybe_gist_str}\nOutput:" # noqa 193 | completion = f"{instance['output']}" 194 | 195 | tokenized_prompt = self.tokenizer(prompt)["input_ids"] 196 | tokenized_completion = self.tokenizer(completion, add_special_tokens=False)[ 197 | "input_ids" 198 | ] + [self.tokenizer.eos_token_id] 199 | if self.check_correctness: 200 | # Check that combining the prompt + completion after 201 | # tokenization is the same as tokenizing the prompt + completion 202 | # together. 203 | combined = tokenized_prompt + tokenized_completion 204 | real = self.tokenizer(prompt + " " + completion)["input_ids"] + [ 205 | self.tokenizer.eos_token_id 206 | ] 207 | if combined != real: 208 | logger.warning( 209 | ( 210 | "Tokenizing prompt/completion separately gave different " 211 | "results. This is usually because the output is empty. " 212 | "First mismatch location: %s. Source: %s", 213 | ), 214 | str(first_mismatch(combined, real)), 215 | self.tokenizer.decode(combined), 216 | ) 217 | continue 218 | 219 | tokenized_source = tokenized_prompt + tokenized_completion 220 | labels = [self.label_pad_token_id] * len( 221 | tokenized_prompt 222 | ) + tokenized_completion 223 | if len(tokenized_source) > max_length: 224 | # Trim from the end of the source until it fits in the max length. 225 | to_trim = len(tokenized_source) - max_length 226 | tokenized_source = tokenized_source[:-to_trim] 227 | labels = labels[:-to_trim] 228 | logger.warning( 229 | "Truncating source on right from %d to %d tokens. Result: %s", 230 | max_length + to_trim, 231 | max_length, 232 | self.tokenizer.decode(tokenized_source), 233 | ) 234 | if to_trim >= len(tokenized_completion): 235 | logger.warning( 236 | "^^^ The above truncated the entire " 237 | "completion! Skipping loading this batch element." 238 | ) 239 | continue 240 | 241 | model_inputs["input_ids"].append(tokenized_source) 242 | model_inputs["labels"].append(labels) 243 | model_inputs["attention_mask"].append([1 for _ in tokenized_source]) 244 | 245 | model_inputs["prompt_input_ids"].append(tokenized_prompt) 246 | model_inputs["prompt_attention_mask"].append([1 for _ in tokenized_prompt]) 247 | 248 | model_inputs["completion_input_ids"].append(tokenized_completion) 249 | model_inputs["completion_attention_mask"].append( 250 | [1 for _ in tokenized_completion] 251 | ) 252 | 253 | # Left-pad inputs, convert to tensor. 254 | for key, value in model_inputs.items(): 255 | if key == "labels": 256 | pad_token_id = self.label_pad_token_id 257 | else: 258 | pad_token_id = self.tokenizer.pad_token_id 259 | # To left-pad inputs, reverse, then right-pad, then reverse. 260 | value_tensors = [torch.tensor(v[::-1]) for v in value] 261 | model_inputs[key] = torch.fliplr( 262 | pad_sequence( 263 | value_tensors, 264 | batch_first=True, 265 | padding_value=pad_token_id, 266 | ) 267 | ) 268 | 269 | # Construct gist mask. 270 | if self.gist_condition == "gist": 271 | gist_fn = gist.make_gist_mask 272 | elif self.gist_condition == "neg_control": 273 | gist_fn = gist.make_neg_control_mask 274 | elif self.gist_condition == "pos_control": 275 | gist_fn = gist.make_pos_control_mask 276 | else: 277 | raise ValueError(f"Unknown gist condition {self.gist_condition}") 278 | model_inputs["attention_mask_gist"] = gist_fn( 279 | model_inputs["input_ids"], 280 | self.gist_token, 281 | ) 282 | model_inputs["prompt_attention_mask_gist"] = gist_fn( 283 | model_inputs["prompt_input_ids"], 284 | self.gist_token, 285 | ) 286 | 287 | return model_inputs 288 | -------------------------------------------------------------------------------- /src/data/gist.py: -------------------------------------------------------------------------------- 1 | """Utilities for gist mask generation.""" 2 | 3 | 4 | from typing import Optional, Tuple 5 | 6 | import torch 7 | 8 | 9 | def reverse_cumsum(x: torch.Tensor) -> torch.Tensor: 10 | """Cumulative sum from right to left. 11 | 12 | See https://github.com/pytorch/pytorch/issues/33520. 13 | 14 | Args: 15 | x: a tensor of shape (batch_size, seq_len) 16 | Returns: 17 | A tensor of shape (batch_size, seq_len) where each element is the sum of 18 | all elements to the right of it. 19 | """ 20 | return x + torch.sum(x, dim=-1, keepdims=True) - torch.cumsum(x, dim=-1) 21 | 22 | 23 | def make_mask_pre_first_gist( 24 | inputs: torch.Tensor, 25 | gist_token: int, 26 | pad_token: Optional[int] = None, 27 | dtype=torch.int64, 28 | ) -> torch.Tensor: 29 | """Returns a mask where all tokens prior to the first gist token are masked out. 30 | Args: 31 | inputs: an array of input tokens where the last dimension is the 32 | sequence length. 33 | gist_token: the integer id of the gist token. 34 | pad_token: if supplied, mask out where inputs == pad_token. 35 | dtype: the dtype of the mask, default int64. 36 | Returns: 37 | The requested mask. 38 | """ 39 | mask = (inputs == gist_token).cumsum(-1) >= 1 40 | if pad_token is not None: 41 | mask = mask & (inputs != pad_token) 42 | return mask.type(dtype) 43 | 44 | 45 | def make_mask_post_last_gist( 46 | inputs: torch.Tensor, 47 | gist_token: int, 48 | pad_token: Optional[int] = None, 49 | dtype=torch.int64, 50 | ) -> torch.Tensor: 51 | """Returns a mask where all tokens after the last gist token are masked out. 52 | Computes the same as mask_pre_first_gist_token but reverses the 53 | sequence before and after the cumsum. 54 | Args: 55 | inputs: an array of input tokens where the last dimension is the 56 | sequence length. 57 | gist_token: the integer id of the gist token. 58 | pad_token: if supplied, mask out where inputs == pad_token. 59 | dtype: the dtype of the mask, default int64. 60 | Returns: 61 | The requested mask. 62 | """ 63 | mask = reverse_cumsum(inputs == gist_token) >= 1 64 | if pad_token is not None: 65 | mask = mask & (inputs != pad_token) 66 | return mask.type(dtype) 67 | 68 | 69 | def make_gist_mask( 70 | inputs: torch.Tensor, 71 | gist_token: int, 72 | pad_token: Optional[int] = None, 73 | dtype=torch.int64, 74 | ) -> torch.Tensor: 75 | """Creates a 4D gist mask. 76 | Here, tokens after the last gist cannot attend to tokens prior to the first 77 | gist. 78 | Additionally, tokens *before* the last gist cannot attend to tokens *after* 79 | the last gist. 80 | 81 | Example, where G is the gist token: 82 | 83 | a b c G d 84 | a 1 1 1 1 0 85 | b 1 1 1 1 0 86 | c 1 1 1 1 0 87 | G 1 1 1 1 0 88 | d 0 0 0 1 1 89 | 90 | Args: 91 | inputs: an array of shape (batch_size, seq_len) input tokens. 92 | gist_token: the integer id of the gist token. 93 | pad_token: if supplied, mask out where inputs == pad_token. 94 | dtype: the dtype of the mask, default int64. 95 | Returns: 96 | The requested mask of shape (batch_size, 1, seq_len, seq_len) 97 | """ 98 | # Attention mask for tokens before the last gist token. 99 | # Don't pass the pad token through for these first two masks, since we mask 100 | # out padding later. 101 | pre_gist_mask = make_mask_post_last_gist(inputs, gist_token, dtype=torch.bool)[ 102 | :, None, None 103 | ] 104 | # Attention mask for tokens after the last gist token. 105 | post_gist_mask = make_mask_pre_first_gist(inputs, gist_token, dtype=torch.bool)[ 106 | :, None, None 107 | ] 108 | # Construct time masks by permuting to time dimension. 109 | pre_gist_time_mask = pre_gist_mask.permute((0, 1, 3, 2)) 110 | 111 | mask = torch.where(pre_gist_time_mask, pre_gist_mask, post_gist_mask) 112 | # If there are no gist tokens in an example, don't modify the mask (return 113 | # all ones) 114 | has_gist = (inputs == gist_token).any(-1)[:, None, None, None] 115 | mask = torch.where(has_gist, mask, True) 116 | if pad_token is not None: 117 | mask = mask & (inputs != pad_token)[:, None, None] 118 | return mask.type(dtype) 119 | 120 | 121 | def make_neg_control_mask( 122 | inputs: torch.Tensor, 123 | gist_token: int, 124 | pad_token: Optional[int] = None, 125 | dtype=torch.int64, 126 | ): 127 | """Creates a 4D neg control mask. 128 | Here, tokens after the last gist cannot attend to any gist tokens (or prior). 129 | 130 | Example, where G is the gist token: 131 | 132 | a b c G d 133 | a 1 1 1 1 0 134 | b 1 1 1 1 0 135 | c 1 1 1 1 0 136 | G 1 1 1 1 0 137 | d 0 0 0 0 1 138 | 139 | Args: 140 | inputs: an array of shape (batch_size, seq_len) input tokens. 141 | gist_token: the integer id of the gist token. 142 | pad_token: if supplied, mask out where inputs == pad_token. 143 | dtype: the dtype of the mask, default int64. 144 | Returns: 145 | The requested mask of shape (batch_size, 1, seq_len, seq_len) 146 | """ 147 | # Attention mask for tokens before the last gist token. 148 | # Don't pass the pad token through for these first two masks, since we mask 149 | # out padding later. 150 | pre_gist_mask = make_mask_post_last_gist(inputs, gist_token, dtype=torch.bool)[ 151 | :, None, None 152 | ] 153 | # Attention mask for tokens after the last gist token. This creates a mask 154 | # that is zero for all tokens up to and including the last gist token. 155 | post_gist_mask = torch.logical_not(pre_gist_mask) 156 | # Construct time masks by permuting to time dimension. 157 | pre_gist_time_mask = pre_gist_mask.permute((0, 1, 3, 2)) 158 | 159 | mask = torch.where(pre_gist_time_mask, pre_gist_mask, post_gist_mask) 160 | # If there are no gist tokens in an example, don't modify the mask (return 161 | # all ones) 162 | has_gist = (inputs == gist_token).any(-1)[:, None, None, None] 163 | mask = torch.where(has_gist, mask, True) 164 | 165 | if pad_token is not None: 166 | mask = mask & (inputs != pad_token)[:, None, None] 167 | return mask.type(dtype) 168 | 169 | 170 | def make_pos_control_mask( 171 | inputs: torch.Tensor, 172 | gist_token: int, 173 | pad_token: Optional[int] = None, 174 | dtype=torch.int64, 175 | ): 176 | """Creates a 4D pos control mask. 177 | Returns all ones (unaffected mask). 178 | 179 | Args: 180 | inputs: an array of shape (batch_size, seq_len) input tokens. 181 | gist_token: the integer id of the gist token. 182 | pad_token: if supplied, mask out where inputs == pad_token. 183 | dtype: the dtype of the mask, default int64. 184 | Returns: 185 | The requested mask of shape (batch_size, 1, seq_len, seq_len) 186 | """ 187 | del gist_token 188 | batch_size, seq_len = inputs.shape 189 | mask = torch.ones((batch_size, 1, seq_len, seq_len), dtype=torch.bool) 190 | 191 | if pad_token is not None: 192 | mask = mask & (inputs != pad_token)[:, None, None] 193 | return mask.type(dtype) 194 | 195 | 196 | def get_gist_index( 197 | input_ids: torch.Tensor, gist_token: int, raise_if_no_tokens: bool = False 198 | ) -> Tuple[Optional[int], Optional[int]]: 199 | """Finds the start and end of the gist span in input_ids. 200 | 201 | Args: 202 | input_ids: tensor of input ids. 203 | gist_token: value of gist token. 204 | raise_if_no_tokens: raise an error if there are no gist tokens. 205 | 206 | Returns: 207 | (start, end) of gist token(s), with exclusive end, if they exist, 208 | otherwise (None, None) if raise_if_no_tokens is False (raises 209 | error if True). 210 | 211 | Raises: 212 | RuntimeError: If the gist tokens in the input are not a contiguous span. 213 | ValueError: If no gist tokens are found and raise_if_no_tokens is True. 214 | """ 215 | gist_indices = (input_ids == gist_token).nonzero().squeeze(-1) 216 | if len(gist_indices) == 0: 217 | if raise_if_no_tokens: 218 | raise ValueError(f"Could not find gist token {gist_token} in {input_ids}") 219 | return (None, None) 220 | # Assert that the gist indices are a single continuous sequence. 221 | _assert_continguous_span(gist_indices) 222 | return (gist_indices[0].item(), gist_indices[-1].item() + 1) 223 | 224 | 225 | def get_first_pad_index(input_ids: torch.Tensor, pad_token: int) -> int: 226 | """Finds the index of the first pad token in input_ids. 227 | 228 | Args: 229 | input_ids: tensor of input ids. 230 | pad_token: value of pad token. 231 | 232 | Returns: 233 | index of pad token if exists, otherwise len(input_ids). 234 | """ 235 | pad_indices = (input_ids == pad_token).nonzero() 236 | if len(pad_indices) == 0: 237 | return len(input_ids) 238 | return pad_indices[0].item() 239 | 240 | 241 | def _assert_continguous_span(gist_indices: torch.Tensor): 242 | """Assert that the gist indices form a contiguous span.""" 243 | gist_start = gist_indices[0] 244 | gist_indices_arange = torch.arange( 245 | start=gist_start, 246 | end=gist_start + len(gist_indices), 247 | device=gist_indices.device, 248 | ) 249 | if not (gist_indices == gist_indices_arange).all(): 250 | raise RuntimeError(f"gist tokens do not form a contiguous span: {gist_indices}") 251 | -------------------------------------------------------------------------------- /src/data/utils.py: -------------------------------------------------------------------------------- 1 | """Misc data utils.""" 2 | 3 | 4 | from datasets import DatasetDict 5 | 6 | 7 | def strip_special_tokens(s): 8 | """A way of getting rid of special tokens WITHOUT getting rid of the gist token.""" 9 | return ( 10 | s.replace(" ", "") 11 | .replace("", "") 12 | .replace("", "") 13 | .replace("⁇", "") 14 | .strip() 15 | ) 16 | 17 | 18 | def nested_select(datasets: DatasetDict, max_len: int, **kwargs): 19 | return DatasetDict( 20 | { 21 | k: v.select(range(min(max_len, len(v))), **kwargs) 22 | for k, v in datasets.items() 23 | } 24 | ) 25 | -------------------------------------------------------------------------------- /src/generation_utils.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | """Override GenerationMixin with Gist functionality.""" 3 | 4 | import inspect 5 | import warnings 6 | from typing import Any, Dict, List, Optional, Union 7 | 8 | import torch 9 | import torch.distributed as dist 10 | from transformers.generation.logits_process import LogitsProcessorList 11 | from transformers.generation.stopping_criteria import ( 12 | StoppingCriteriaList, validate_stopping_criteria) 13 | from transformers.generation.utils import (GenerationMixin, 14 | GreedySearchDecoderOnlyOutput, 15 | GreedySearchEncoderDecoderOutput, 16 | GreedySearchOutput) 17 | from transformers.utils import ModelOutput, logging 18 | 19 | logger = logging.get_logger(__name__) 20 | 21 | 22 | class GistGenerationMixin(GenerationMixin): 23 | """Overrides GenerationMixin with special handling for gist attention masks.""" 24 | 25 | def _prepare_encoder_decoder_kwargs_for_generation( 26 | self, 27 | inputs_tensor: torch.Tensor, 28 | model_kwargs, 29 | model_input_name: Optional[str] = None, 30 | ) -> Dict[str, Any]: 31 | # 1. get encoder 32 | encoder = self.get_encoder() 33 | 34 | # 2. Prepare encoder args and encoder kwargs from model kwargs. 35 | irrelevant_prefix = [ 36 | "decoder_", 37 | "cross_attn", 38 | "use_cache", 39 | "cross_attention_mask", 40 | ] 41 | encoder_kwargs = { 42 | argument: value 43 | for argument, value in model_kwargs.items() 44 | if not any(argument.startswith(p) for p in irrelevant_prefix) 45 | } 46 | encoder_signature = set(inspect.signature(encoder.forward).parameters) 47 | encoder_accepts_wildcard = ( 48 | "kwargs" in encoder_signature or "model_kwargs" in encoder_signature 49 | ) 50 | if not encoder_accepts_wildcard: 51 | encoder_kwargs = { 52 | argument: value 53 | for argument, value in encoder_kwargs.items() 54 | if argument in encoder_signature 55 | } 56 | 57 | # 3. make sure that encoder returns `ModelOutput` 58 | model_input_name = ( 59 | model_input_name if model_input_name is not None else self.main_input_name 60 | ) 61 | encoder_kwargs["return_dict"] = True 62 | encoder_kwargs[model_input_name] = inputs_tensor 63 | using_past_key_values = "past_key_values" in model_kwargs 64 | if using_past_key_values: 65 | warnings.warn( 66 | "past_key_values passed to encoder. " 67 | "This should only happen when reusing gist tokens." 68 | ) 69 | model_kwargs["encoder_outputs"]: ModelOutput = encoder(**encoder_kwargs) 70 | 71 | if using_past_key_values: 72 | # past_key_values should not be passed to decoder, it creates its own. 73 | del model_kwargs["past_key_values"] 74 | 75 | return model_kwargs 76 | 77 | def _update_model_kwargs_for_generation( 78 | self, 79 | outputs: ModelOutput, 80 | model_kwargs: Dict[str, Any], 81 | is_encoder_decoder: bool = False, 82 | standardize_cache_format: bool = False, 83 | ) -> Dict[str, Any]: 84 | """Update model inputs, especially attention_mask_gist, for gist generation. 85 | 86 | EXPLANATION OF HOW ATTENTION_MASK_GIST WORKS FOR DECODER ONLY MODELS: 87 | 88 | Normally, when gist model is forwarded over N tokens (e.g. a prompt), we 89 | broadcast the attention_mask_gist to 4D: (B, 1, N, N). This lets us 90 | encode the entire prompt, and lets us (1) learn the appropriate 91 | key/value representations for each past token, and (2) generate the 92 | next token (with masking correctly applied). 93 | 94 | For example, with N = 3 and a gist token in position 2/3, the attention 95 | mask might look like: (ignoring batch size and leading 1 dim) 96 | 97 | 1 1 1 98 | 0 1 1 <- GIST 99 | 0 1 1 100 | 101 | However, in subsequent decode steps in sequential generation, we cache 102 | the key/value representations learned in (1). Then, this function is 103 | called, and the default behavior is to encode only the SINGLE new input 104 | id that was sampled in the previous timestep. The FIRST TIME this 105 | function is called (after the first token post-prompt has been 106 | decoded), the attention mask is the (B, 1, N, N) 4D mask described 107 | above. However, in subsequent calls, we don't care about this 108 | attention mask anymore, since the cached key/values have already been 109 | computed (with masking already applied). 110 | 111 | Instead, since input_ids is only one token, what we need is a SINGLE 112 | attention_mask, of shape (B, 1, 1, N + 1), which tells the gist model 113 | what to attend to when decoding the next token. That is, we need 114 | 115 | 0 1 1 1 116 | 117 | where you are still prevented from attending pre-gist, but the new token 118 | you have decoded can be attended to. 119 | 120 | Given either a (B, 1, N, N) or (B, 1, 1, N) attention mask, this can be 121 | done by keeping just the last row of the 4D attention_mask_gist, then 122 | adding on a 1: 123 | 124 | (B, 1, N, N) 125 | 1 1 1 126 | 0 1 1 127 | 0 1 1 128 | 129 | (B, 1, 1, N) 130 | 0 1 1 131 | 132 | keep last row -> (B, 1, 1, N + 1) 133 | 0 1 1 1 134 | 135 | This preserves gist masking, since if there is a gist token, zero mask 136 | entries will persist for the rest of the decode sequence. 137 | """ 138 | # update past_key_values 139 | model_kwargs["past_key_values"] = self._extract_past_from_model_output( 140 | outputs, standardize_cache_format=standardize_cache_format 141 | ) 142 | 143 | # update token_type_ids with last value 144 | if "token_type_ids" in model_kwargs: 145 | token_type_ids = model_kwargs["token_type_ids"] 146 | model_kwargs["token_type_ids"] = torch.cat( 147 | [token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1 148 | ) 149 | 150 | if not is_encoder_decoder: 151 | # update attention mask 152 | if "attention_mask" in model_kwargs: 153 | attention_mask = model_kwargs["attention_mask"] 154 | assert attention_mask.ndim == 2, ( 155 | "Expected 2d attention mask. This code doesn't work " 156 | "with 3D attention masks" 157 | ) 158 | model_kwargs["attention_mask"] = torch.cat( 159 | [ 160 | attention_mask, 161 | attention_mask.new_ones((attention_mask.shape[0], 1)), 162 | ], 163 | dim=-1, 164 | ) 165 | if "attention_mask_gist" in model_kwargs: 166 | attention_mask_gist = model_kwargs["attention_mask_gist"] 167 | assert attention_mask_gist.ndim == 4, "Expected 4D attention mask gist." 168 | assert attention_mask_gist.shape[1] == 1 and ( 169 | # Attention mask should either be (B, 1, N, N) (at the 170 | # start of decoding) or (B, 1, 1, N) (midway through 171 | # decoding, since input ids only considers input for 172 | # the next token assuming other values are cached. 173 | attention_mask_gist.shape[2] == 1 174 | or attention_mask_gist.shape[2] == attention_mask_gist.shape[3] 175 | ), f"Got attention mask of shape {attention_mask_gist.shape}" 176 | # Here, M is either N or 1. 177 | last_row = attention_mask_gist[ 178 | :, :, -1: 179 | ] # (B, 1, M, N) -> (B, 1, 1, N) 180 | attention_mask_gist = torch.cat( 181 | [ 182 | last_row, # (B, 1, 1, N) 183 | last_row.new_ones((last_row.shape[0], 1, 1, 1)), # (B, 1, 1, 1) 184 | ], 185 | dim=-1, 186 | ) # (B, 1, 1, N) -> (B, 1, 1, N + 1) 187 | model_kwargs["attention_mask_gist"] = attention_mask_gist 188 | else: 189 | # update decoder attention mask 190 | if "decoder_attention_mask" in model_kwargs: 191 | decoder_attention_mask = model_kwargs["decoder_attention_mask"] 192 | model_kwargs["decoder_attention_mask"] = torch.cat( 193 | [ 194 | decoder_attention_mask, 195 | decoder_attention_mask.new_ones( 196 | (decoder_attention_mask.shape[0], 1) 197 | ), 198 | ], 199 | dim=-1, 200 | ) 201 | 202 | return model_kwargs 203 | 204 | def greedy_search( 205 | self, 206 | input_ids: torch.LongTensor, 207 | logits_processor: Optional[LogitsProcessorList] = None, 208 | stopping_criteria: Optional[StoppingCriteriaList] = None, 209 | max_length: Optional[int] = None, 210 | pad_token_id: Optional[int] = None, 211 | eos_token_id: Optional[Union[int, List[int]]] = None, 212 | output_attentions: Optional[bool] = None, 213 | output_hidden_states: Optional[bool] = None, 214 | output_scores: Optional[bool] = None, 215 | return_dict_in_generate: Optional[bool] = None, 216 | synced_gpus: Optional[bool] = False, 217 | **model_kwargs, 218 | ) -> Union[GreedySearchOutput, torch.LongTensor]: 219 | r""" 220 | NOTE: The only change between the huggingface greedy search and this 221 | function is the introduction of a "first_time" variable that doesn't 222 | truncate input ids when kv seqs are passed for the first time (for gist 223 | caching). 224 | 225 | Generates sequences of token ids for models with a language modeling head using **greedy decoding** and can be 226 | used for text-decoder, text-to-text, speech-to-text, and vision-to-text models. 227 | 228 | 229 | 230 | In most cases, you do not need to call [`~generation.GenerationMixin.greedy_search`] directly. Use generate() 231 | instead. For an overview of generation strategies and code examples, check the [following 232 | guide](../generation_strategies). 233 | 234 | 235 | 236 | 237 | Parameters: 238 | input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): 239 | The sequence used as a prompt for the generation. 240 | logits_processor (`LogitsProcessorList`, *optional*): 241 | An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`] 242 | used to modify the prediction scores of the language modeling head applied at each generation step. 243 | stopping_criteria (`StoppingCriteriaList`, *optional*): 244 | An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`] 245 | used to tell if the generation loop should stop. 246 | 247 | max_length (`int`, *optional*, defaults to 20): 248 | **DEPRECATED**. Use `logits_processor` or `stopping_criteria` directly to cap the number of generated 249 | tokens. The maximum length of the sequence to be generated. 250 | pad_token_id (`int`, *optional*): 251 | The id of the *padding* token. 252 | eos_token_id (`Union[int, List[int]]`, *optional*): 253 | The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. 254 | output_attentions (`bool`, *optional*, defaults to `False`): 255 | Whether or not to return the attentions tensors of all attention layers. See `attentions` under 256 | returned tensors for more details. 257 | output_hidden_states (`bool`, *optional*, defaults to `False`): 258 | Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors 259 | for more details. 260 | output_scores (`bool`, *optional*, defaults to `False`): 261 | Whether or not to return the prediction scores. See `scores` under returned tensors for more details. 262 | return_dict_in_generate (`bool`, *optional*, defaults to `False`): 263 | Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. 264 | synced_gpus (`bool`, *optional*, defaults to `False`): 265 | Whether to continue running the while loop until max_length (needed for ZeRO stage 3) 266 | model_kwargs: 267 | Additional model specific keyword arguments will be forwarded to the `forward` function of the model. 268 | If model is an encoder-decoder model the kwargs should include `encoder_outputs`. 269 | 270 | Return: 271 | [`~generation.GreedySearchDecoderOnlyOutput`], [`~generation.GreedySearchEncoderDecoderOutput`] or 272 | `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a 273 | [`~generation.GreedySearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and 274 | `return_dict_in_generate=True` or a [`~generation.GreedySearchEncoderDecoderOutput`] if 275 | `model.config.is_encoder_decoder=True`. 276 | 277 | Examples: 278 | 279 | ```python 280 | >>> from transformers import ( 281 | ... AutoTokenizer, 282 | ... AutoModelForCausalLM, 283 | ... LogitsProcessorList, 284 | ... MinLengthLogitsProcessor, 285 | ... StoppingCriteriaList, 286 | ... MaxLengthCriteria, 287 | ... ) 288 | 289 | >>> tokenizer = AutoTokenizer.from_pretrained("gpt2") 290 | >>> model = AutoModelForCausalLM.from_pretrained("gpt2") 291 | 292 | >>> # set pad_token_id to eos_token_id because GPT2 does not have a PAD token 293 | >>> model.generation_config.pad_token_id = model.generation_config.eos_token_id 294 | 295 | >>> input_prompt = "It might be possible to" 296 | >>> input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids 297 | 298 | >>> # instantiate logits processors 299 | >>> logits_processor = LogitsProcessorList( 300 | ... [ 301 | ... MinLengthLogitsProcessor(10, eos_token_id=model.generation_config.eos_token_id), 302 | ... ] 303 | ... ) 304 | >>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=20)]) 305 | 306 | >>> outputs = model.greedy_search( 307 | ... input_ids, logits_processor=logits_processor, stopping_criteria=stopping_criteria 308 | ... ) 309 | 310 | >>> tokenizer.batch_decode(outputs, skip_special_tokens=True) 311 | ["It might be possible to get a better understanding of the nature of the problem, but it's not"] 312 | ```""" 313 | # init values 314 | logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList() 315 | stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList() 316 | if max_length is not None: 317 | warnings.warn( 318 | "`max_length` is deprecated in this function, use" 319 | " `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.", 320 | UserWarning, 321 | ) 322 | stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length) 323 | pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id 324 | eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id 325 | if isinstance(eos_token_id, int): 326 | eos_token_id = [eos_token_id] 327 | eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None 328 | output_scores = output_scores if output_scores is not None else self.generation_config.output_scores 329 | output_attentions = ( 330 | output_attentions if output_attentions is not None else self.generation_config.output_attentions 331 | ) 332 | output_hidden_states = ( 333 | output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states 334 | ) 335 | return_dict_in_generate = ( 336 | return_dict_in_generate 337 | if return_dict_in_generate is not None 338 | else self.generation_config.return_dict_in_generate 339 | ) 340 | 341 | # init attention / hidden states / scores tuples 342 | scores = () if (return_dict_in_generate and output_scores) else None 343 | decoder_attentions = () if (return_dict_in_generate and output_attentions) else None 344 | cross_attentions = () if (return_dict_in_generate and output_attentions) else None 345 | decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None 346 | 347 | # if model is an encoder-decoder, retrieve encoder attention weights and hidden states 348 | if return_dict_in_generate and self.config.is_encoder_decoder: 349 | encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None 350 | encoder_hidden_states = ( 351 | model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None 352 | ) 353 | 354 | # keep track of which sequences are already finished 355 | unfinished_sequences = torch.ones(input_ids.shape[0], dtype=torch.long, device=input_ids.device) 356 | 357 | this_peer_finished = False # used by synced_gpus only 358 | first_time = True 359 | while True: 360 | if synced_gpus: 361 | # Under synced_gpus the `forward` call must continue until all gpus complete their sequence. 362 | # The following logic allows an early break if all peers finished generating their sequence 363 | this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(input_ids.device) 364 | # send 0.0 if we finished, 1.0 otherwise 365 | dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM) 366 | # did all peers finish? the reduced sum will be 0.0 then 367 | if this_peer_finished_flag.item() == 0.0: 368 | break 369 | 370 | # prepare model inputs 371 | model_inputs = self.prepare_inputs_for_generation(input_ids, first_time=first_time, **model_kwargs) 372 | first_time = False 373 | 374 | # forward pass to get next token 375 | outputs = self( 376 | **model_inputs, 377 | return_dict=True, 378 | output_attentions=output_attentions, 379 | output_hidden_states=output_hidden_states, 380 | ) 381 | 382 | if synced_gpus and this_peer_finished: 383 | continue # don't waste resources running the code we don't need 384 | 385 | next_token_logits = outputs.logits[:, -1, :] 386 | 387 | # pre-process distribution 388 | next_tokens_scores = logits_processor(input_ids, next_token_logits) 389 | 390 | # Store scores, attentions and hidden_states when required 391 | if return_dict_in_generate: 392 | if output_scores: 393 | scores += (next_tokens_scores,) 394 | if output_attentions: 395 | decoder_attentions += ( 396 | (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,) 397 | ) 398 | if self.config.is_encoder_decoder: 399 | cross_attentions += (outputs.cross_attentions,) 400 | 401 | if output_hidden_states: 402 | decoder_hidden_states += ( 403 | (outputs.decoder_hidden_states,) 404 | if self.config.is_encoder_decoder 405 | else (outputs.hidden_states,) 406 | ) 407 | 408 | # argmax 409 | next_tokens = torch.argmax(next_tokens_scores, dim=-1) 410 | 411 | # finished sentences should have their next token be a padding token 412 | if eos_token_id is not None: 413 | if pad_token_id is None: 414 | raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.") 415 | next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences) 416 | 417 | # update generated ids, model inputs, and length for next step 418 | input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1) 419 | model_kwargs = self._update_model_kwargs_for_generation( 420 | outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder 421 | ) 422 | 423 | # if eos_token was found in one sentence, set sentence to finished 424 | if eos_token_id_tensor is not None: 425 | unfinished_sequences = unfinished_sequences.mul( 426 | next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0) 427 | ) 428 | 429 | # stop when each sentence is finished, or if we exceed the maximum length 430 | if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores): 431 | if not synced_gpus: 432 | break 433 | else: 434 | this_peer_finished = True 435 | 436 | if return_dict_in_generate: 437 | if self.config.is_encoder_decoder: 438 | return GreedySearchEncoderDecoderOutput( 439 | sequences=input_ids, 440 | scores=scores, 441 | encoder_attentions=encoder_attentions, 442 | encoder_hidden_states=encoder_hidden_states, 443 | decoder_attentions=decoder_attentions, 444 | cross_attentions=cross_attentions, 445 | decoder_hidden_states=decoder_hidden_states, 446 | ) 447 | else: 448 | return GreedySearchDecoderOnlyOutput( 449 | sequences=input_ids, 450 | scores=scores, 451 | attentions=decoder_attentions, 452 | hidden_states=decoder_hidden_states, 453 | ) 454 | else: 455 | return input_ids 456 | -------------------------------------------------------------------------------- /src/gist_caching.py: -------------------------------------------------------------------------------- 1 | """Utilities for caching gist tokens.""" 2 | 3 | from __future__ import annotations 4 | 5 | from dataclasses import dataclass 6 | from typing import Optional, Tuple 7 | 8 | import torch 9 | from transformers.modeling_outputs import ModelOutput 10 | 11 | from .data.gist import get_gist_index 12 | 13 | 14 | @dataclass 15 | class GistActivations: 16 | last_hidden_state: torch.FloatTensor 17 | past_key_values: Tuple[Tuple[torch.FloatTensor]] 18 | # In case needed, e.g. for absolute position embeddings. 19 | gist_indices: Optional[torch.LongTensor] = None 20 | 21 | def get_single(self, batch_idx): 22 | # Return batch-size-1 version of each key. 23 | return GistActivations( 24 | last_hidden_state=self.last_hidden_state[batch_idx : batch_idx + 1], 25 | past_key_values=tuple( 26 | (k[batch_idx : batch_idx + 1], v[batch_idx : batch_idx + 1]) 27 | for k, v in self.past_key_values 28 | ), 29 | gist_indices=self.gist_indices[batch_idx : batch_idx + 1] 30 | if self.gist_indices is not None 31 | else None, 32 | ) 33 | 34 | @classmethod 35 | def from_model_outputs( 36 | cls, 37 | model_outputs: ModelOutput, 38 | input_ids: torch.LongTensor, 39 | gist_token: int, 40 | num_gist_tokens: int, 41 | cache_all: bool = False, 42 | ) -> GistActivations: 43 | """ 44 | Computes gist activations for the model. 45 | 46 | If cache_all is True, actually cache everything, not just the gist 47 | tokens. Useful for positive control decoder models, for example. 48 | 49 | Returns: 50 | GistActivations object containing the kv activations for the gist 51 | tokens of the encoder, and the start position of the first gist 52 | token (needed to correctly compute position embeddings). 53 | """ 54 | assert hasattr(model_outputs, "last_hidden_state") 55 | assert hasattr(model_outputs, "past_key_values") 56 | 57 | past_key_values = model_outputs.past_key_values 58 | batch_size, num_heads, seq_length, hidden_size = past_key_values[0][0].shape 59 | device = past_key_values[0][0].device 60 | 61 | if cache_all: 62 | assert batch_size == 1, "Can only cache all if batch size is 1 for now." 63 | _, gist_end = get_gist_index( 64 | input_ids[0], gist_token, raise_if_no_tokens=True 65 | ) 66 | num_gist_tokens = gist_end 67 | 68 | def kv(): 69 | return torch.zeros( 70 | (batch_size, num_heads, num_gist_tokens, hidden_size), 71 | dtype=past_key_values[0][0].dtype, 72 | device=device, 73 | ) 74 | 75 | # Save key/values and hidden states corresponding to gist tokens only. 76 | last_hidden_state = torch.zeros( 77 | (batch_size, num_gist_tokens, model_outputs.last_hidden_state.shape[-1]), 78 | dtype=model_outputs.last_hidden_state.dtype, 79 | device=device, 80 | ) 81 | # Same structure as past_key_values, but only has `num_gist_tokens` spots. 82 | gist_past_key_values = [(kv(), kv()) for _ in past_key_values] 83 | gist_starts = [] 84 | for batch_i, input_row in enumerate(input_ids): 85 | # Find start and end gist position. 86 | if cache_all: 87 | gist_start, gist_end = 0, num_gist_tokens 88 | else: 89 | gist_start, gist_end = get_gist_index( 90 | input_row, gist_token, raise_if_no_tokens=True 91 | ) 92 | 93 | # Compute # of observed gist tokens. 94 | obs_num_gist_tokens = gist_end - gist_start 95 | if obs_num_gist_tokens != num_gist_tokens: 96 | raise ValueError( 97 | f"Expected {num_gist_tokens} gist tokens, got " 98 | f"{obs_num_gist_tokens} " 99 | f"(input ids: {input_row}, start {gist_start} end {gist_end})" 100 | ) 101 | 102 | # For each hidden layer, save the activations corresponding to the 103 | # gist token. 104 | for layer_i, (past_k, past_v) in enumerate(past_key_values): 105 | gist_past_key_values[layer_i][0][batch_i] = past_k[ 106 | batch_i, :, gist_start:gist_end 107 | ] 108 | gist_past_key_values[layer_i][1][batch_i] = past_v[ 109 | batch_i, :, gist_start:gist_end 110 | ] 111 | 112 | # Keep track of gist starts for the batch. 113 | gist_starts.append(gist_start) 114 | 115 | # Save last hidden state corresponding to gist token. 116 | last_hidden_state[batch_i] = model_outputs.last_hidden_state[ 117 | batch_i, gist_start:gist_end 118 | ] 119 | 120 | return GistActivations( 121 | last_hidden_state=last_hidden_state, 122 | past_key_values=tuple(gist_past_key_values), 123 | gist_indices=torch.tensor(gist_starts, dtype=torch.int64, device=device), 124 | ) 125 | -------------------------------------------------------------------------------- /src/integrations.py: -------------------------------------------------------------------------------- 1 | """Custom wandb integrations""" 2 | 3 | 4 | import dataclasses 5 | import os 6 | 7 | import wandb 8 | from transformers.integrations import TrainerCallback, WandbCallback 9 | from transformers.utils import is_torch_tpu_available, logging 10 | 11 | from .arguments import Arguments 12 | 13 | logger = logging.get_logger(__name__) 14 | 15 | 16 | class CustomWandbCallback(WandbCallback): 17 | def __init__(self, wandb_args: Arguments, *args, **kwargs): 18 | """Just do standard wandb init, but save the arguments for setup.""" 19 | super().__init__(*args, **kwargs) 20 | self._wandb_args = wandb_args 21 | 22 | def setup(self, args, state, model, **kwargs): 23 | """ 24 | Setup the optional Weights & Biases (*wandb*) integration. 25 | One can subclass and override this method to customize the setup if 26 | needed. Find more information 27 | [here](https://docs.wandb.ai/integrations/huggingface). You can also 28 | override the following environment variables: 29 | Environment: 30 | WANDB_LOG_MODEL (`bool`, *optional*, defaults to `False`): 31 | Whether or not to log model as artifact at the end of training. 32 | Use along with 33 | *TrainingArguments.load_best_model_at_end* to upload best model. 34 | WANDB_WATCH (`str`, *optional* defaults to `"gradients"`): 35 | Can be `"gradients"`, `"all"` or `"false"`. Set to `"false"` to 36 | disable gradient logging or `"all"` to log gradients and 37 | parameters. 38 | """ 39 | del args # Use self._wandb_args instead. 40 | args = self._wandb_args 41 | 42 | if self._wandb is None: 43 | return 44 | self._initialized = True 45 | if state.is_world_process_zero: 46 | if self._wandb.run is None: 47 | self._wandb.init( 48 | entity=args.wandb.entity, 49 | project=args.wandb.project, 50 | group=args.wandb.group, 51 | name=args.wandb.name, 52 | config=dataclasses.asdict(args), 53 | settings=wandb.Settings(start_method="fork"), 54 | ) 55 | 56 | # define default x-axis (for latest wandb versions) 57 | if getattr(self._wandb, "define_metric", None): 58 | self._wandb.define_metric("train/global_step") 59 | self._wandb.define_metric( 60 | "*", step_metric="train/global_step", step_sync=True 61 | ) 62 | 63 | # keep track of model topology and gradients, unsupported on TPU 64 | if not is_torch_tpu_available() and os.getenv("WANDB_WATCH") != "false": 65 | self._wandb.watch( 66 | model, 67 | log=os.getenv("WANDB_WATCH", "gradients"), 68 | log_freq=max(100, args.training.logging_steps), 69 | ) 70 | 71 | 72 | class EvaluateFirstStepCallback(TrainerCallback): 73 | def on_step_end(self, args, state, control, **kwargs): 74 | if state.global_step == 1: 75 | control.should_evaluate = True 76 | -------------------------------------------------------------------------------- /src/metrics.py: -------------------------------------------------------------------------------- 1 | """ 2 | Metrics for gist token. 3 | """ 4 | 5 | 6 | import functools 7 | from typing import Callable, Dict, Optional, Tuple 8 | 9 | import nltk 10 | import numpy as np 11 | import pandas as pd 12 | import torch 13 | from transformers import PreTrainedTokenizer 14 | from transformers.trainer_utils import EvalPrediction 15 | 16 | from .arguments import Arguments 17 | from .data.utils import strip_special_tokens 18 | 19 | Metrics = Dict[str, float] 20 | PredAndLogprobsOutput = Tuple[torch.Tensor, torch.Tensor, torch.Tensor] 21 | 22 | # Must load after torch for some reason 23 | import evaluate # noqa 24 | 25 | 26 | def get_last_gist_indices( 27 | labels: np.ndarray, gist_token: int 28 | ) -> Tuple[np.ndarray, np.ndarray]: 29 | """Get the LAST occurrence of the gist token in each row. 30 | 31 | We do this by taking the argmax of the reverse view of the array that checks 32 | whether a token is equal to the gist token. This gives you the last 33 | occurrence of the gist token in each row, according to 34 | https://stackoverflow.com/questions/8768540/how-to-find-last-occurrence-of-maximum-value-in-a-numpy-ndarray 35 | 36 | """ 37 | equals_gist_token = labels == gist_token 38 | assert equals_gist_token.any(-1).all() 39 | 40 | last_gist_indices_rev = np.argmax(np.flip(equals_gist_token, axis=-1), -1) 41 | last_gist_indices = labels.shape[-1] - last_gist_indices_rev - 1 42 | return last_gist_indices 43 | 44 | 45 | def postprocess_text(preds, labels, remove_llama_padding=False): 46 | if remove_llama_padding: 47 | # XXX: This is a temporary hack because skip_special_tokens doesn't 48 | # seem to be working with the Llama SentencePiece tokenizer? 49 | preds = [pred.replace("⁇", "") for pred in preds] 50 | labels = [pred.replace("⁇", "") for pred in labels] 51 | 52 | preds = [pred.strip() for pred in preds] 53 | labels = [label.strip() for label in labels] 54 | 55 | # rougeLSum expects newline after each sentence 56 | preds = ["\n".join(nltk.sent_tokenize(pred)) for pred in preds] 57 | labels = ["\n".join(nltk.sent_tokenize(label)) for label in labels] 58 | 59 | return preds, labels 60 | 61 | 62 | def compute_metrics( 63 | eval_preds: EvalPrediction, 64 | gist_token: int, 65 | tokenizer: PreTrainedTokenizer, 66 | args: Arguments, 67 | output_file: Optional[str] = None, 68 | ) -> Metrics: 69 | del gist_token 70 | 71 | preds = eval_preds.predictions 72 | labels = eval_preds.label_ids 73 | if isinstance(preds, tuple): 74 | preds = preds[0] 75 | 76 | results = {} 77 | 78 | # Compute ROUGE-L by decoding 79 | decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) 80 | # Replace -100 in the labels as we can't decode them. 81 | labels = np.where(labels != -100, labels, tokenizer.pad_token_id) 82 | decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) 83 | 84 | # Some simple post-processing 85 | is_llama = any( 86 | t in args.model.model_name_or_path.lower() for t in ("llama", "alpaca") 87 | ) 88 | decoded_preds, decoded_labels = postprocess_text( 89 | decoded_preds, 90 | decoded_labels, 91 | remove_llama_padding=is_llama, 92 | ) 93 | 94 | rouge_results = evaluate.load("rouge").compute( 95 | predictions=decoded_preds, references=decoded_labels, use_stemmer=True 96 | ) 97 | rouge_results = {k: round(v * 100, 4) for k, v in rouge_results.items()} 98 | results.update(rouge_results) 99 | 100 | prediction_lens = [ 101 | np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds 102 | ] 103 | results["gen_len"] = np.mean(prediction_lens) 104 | 105 | if output_file is not None: 106 | if not hasattr(eval_preds, "inputs"): 107 | raise RuntimeError("If writing to output file, need inputs") 108 | inputs = np.where(eval_preds.inputs == -100, 0, eval_preds.inputs) 109 | decoded_inputs = tokenizer.batch_decode(inputs) 110 | decoded_inputs = list(map(strip_special_tokens, decoded_inputs)) 111 | decoded_preds = list(map(strip_special_tokens, decoded_preds)) 112 | decoded_labels = list(map(strip_special_tokens, decoded_labels)) 113 | pd.DataFrame( 114 | { 115 | "x": decoded_inputs, 116 | "y_pred": decoded_preds, 117 | "y_true": decoded_labels, 118 | } 119 | ).to_csv(output_file, index=False) 120 | 121 | return results 122 | 123 | 124 | def get_compute_metrics_fn( 125 | gist_token: int, tokenizer: PreTrainedTokenizer, args: Arguments 126 | ) -> Callable: 127 | return functools.partial( 128 | compute_metrics, gist_token=gist_token, tokenizer=tokenizer, args=args 129 | ) 130 | -------------------------------------------------------------------------------- /src/train.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2020 The HuggingFace Inc. team. All rights reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """ 16 | Gist training script, adapted from huggingface's run_clm.py example. 17 | """ 18 | 19 | import logging 20 | import os 21 | 22 | import hydra 23 | import torch # noqa 24 | from datasets import DatasetDict, load_dataset 25 | from omegaconf.dictconfig import DictConfig 26 | from transformers import ( 27 | AutoConfig, 28 | AutoTokenizer, 29 | LlamaTokenizer, 30 | is_torch_tpu_available, 31 | set_seed, 32 | ) 33 | from transformers.trainer_utils import get_last_checkpoint 34 | from transformers.utils import check_min_version 35 | from transformers.utils.versions import require_version 36 | 37 | from . import gist_llama, gist_t5 38 | from .arguments import Arguments, global_setup 39 | from .data import alpaca 40 | from .data.utils import nested_select 41 | from .gist_llama import DEBUG_LLAMA_CONFIG, GistLlamaForCausalLM 42 | from .gist_t5 import GistT5ForConditionalGeneration 43 | from .integrations import CustomWandbCallback, EvaluateFirstStepCallback 44 | from .metrics import get_compute_metrics_fn 45 | from .trainer_seq2seq import GistSeq2SeqTrainer 46 | 47 | # Will error if the minimal version of Transformers is not installed. Remove at 48 | # your own risks. 49 | check_min_version("4.28.0.dev0") 50 | 51 | require_version( 52 | "datasets>=1.8.0", 53 | "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt", 54 | ) 55 | 56 | logger = logging.getLogger(__name__) 57 | 58 | 59 | @hydra.main(config_path="conf", config_name="config") 60 | def main(args: DictConfig) -> None: 61 | args: Arguments = global_setup(args) 62 | 63 | # Detecting last checkpoint. 64 | last_checkpoint = None 65 | if ( 66 | os.path.isdir(args.training.output_dir) 67 | and args.training.do_train 68 | and not args.training.overwrite_output_dir 69 | ): 70 | last_checkpoint = get_last_checkpoint(args.training.output_dir) 71 | if last_checkpoint is None and len(os.listdir(args.training.output_dir)) > 0: 72 | existing_files = os.listdir(args.training.output_dir) 73 | logger.warning( 74 | ( 75 | "Output directory (%s) already exists and " 76 | "is not empty. Existing files: %s. " 77 | "Training anyways as these may just be output files." 78 | ), 79 | args.training.output_dir, 80 | str(existing_files), 81 | ) 82 | elif ( 83 | last_checkpoint is not None and args.training.resume_from_checkpoint is None 84 | ): 85 | logger.info( 86 | f"Checkpoint detected, resuming training at {last_checkpoint}. To " 87 | "avoid this behavior, change " 88 | "the `--output_dir` or add `--overwrite_output_dir` to train from " 89 | "scratch." 90 | ) 91 | 92 | # Set seed before initializing model. 93 | set_seed(args.training.seed) 94 | 95 | if args.data.dataset_name == "alpaca-plus": 96 | lm_datasets = load_dataset( 97 | "src/data/alpaca/alpaca.py", 98 | cache_dir=args.model.cache_dir, 99 | ) 100 | else: 101 | raise NotImplementedError(f"Unknown dataset name {args.data.dataset_name}") 102 | 103 | config_kwargs = { 104 | "cache_dir": args.model.cache_dir, 105 | "revision": args.model.model_revision, 106 | "use_auth_token": True if args.model.use_auth_token else None, 107 | } 108 | if args.model.llama_debug: 109 | if args.model.pretrained: 110 | raise RuntimeError("llama_debug requires pretrained set to False") 111 | config = DEBUG_LLAMA_CONFIG 112 | elif args.model.config_name: 113 | config = AutoConfig.from_pretrained(args.model.config_name, **config_kwargs) 114 | elif args.model.model_name_or_path: 115 | config = AutoConfig.from_pretrained( 116 | args.model.model_name_or_path, **config_kwargs 117 | ) 118 | else: 119 | raise ValueError( 120 | "Unlike run_clm.py, this script does not support specifying a model type " 121 | "from scratch. Specify args.model.model_name_or_path and set " 122 | "args.pretrained = False to train from scratch instead." 123 | ) 124 | 125 | is_t5 = any(t in args.model.model_name_or_path.lower() for t in ("t5", "tk")) 126 | is_llama = any(t in args.model.model_name_or_path.lower() for t in ("llama",)) 127 | 128 | tokenizer_kwargs = { 129 | "cache_dir": args.model.cache_dir, 130 | "use_fast": args.model.use_fast_tokenizer, 131 | "revision": args.model.model_revision, 132 | "use_auth_token": True if args.model.use_auth_token else None, 133 | } 134 | if args.model.tokenizer_name: 135 | tokenizer = AutoTokenizer.from_pretrained( 136 | args.model.tokenizer_name, **tokenizer_kwargs 137 | ) 138 | elif args.model.model_name_or_path: 139 | if is_llama: 140 | tokenizer = LlamaTokenizer.from_pretrained( 141 | args.model.model_name_or_path, **tokenizer_kwargs 142 | ) 143 | tokenizer.pad_token = tokenizer.eos_token 144 | tokenizer.padding_side = "left" 145 | else: 146 | tokenizer = AutoTokenizer.from_pretrained( 147 | args.model.model_name_or_path, **tokenizer_kwargs 148 | ) 149 | else: 150 | raise ValueError( 151 | "You are instantiating a new tokenizer from scratch. This is not supported " 152 | "by this script." 153 | "You can do it from another script, save it, and load it from here, using " 154 | "--tokenizer_name." 155 | ) 156 | 157 | if is_t5: 158 | model_cls = GistT5ForConditionalGeneration 159 | elif is_llama: 160 | model_cls = GistLlamaForCausalLM 161 | else: 162 | raise ValueError(f"Model type {args.model.model_name_or_path} not supported") 163 | if args.model.pretrained: 164 | model = model_cls.from_pretrained( 165 | args.model.model_name_or_path, 166 | from_tf=bool(".ckpt" in args.model.model_name_or_path), 167 | config=config, 168 | cache_dir=args.model.cache_dir, 169 | revision=args.model.model_revision, 170 | use_auth_token=True if args.model.use_auth_token else None, 171 | ) 172 | else: 173 | model = model_cls(config) 174 | 175 | # ==== BEGIN GIST CHANGES ==== 176 | # Check if gist token has already been added to the model (e.g. because 177 | # we're resuming from a checkpoint.) 178 | if is_t5 and len(tokenizer) == gist_t5.PRETRAINED_VOCAB_SIZE + 1: 179 | assert model.shared.weight.shape[0] == gist_t5.PRETRAINED_VOCAB_SIZE + 1 180 | elif is_llama and len(tokenizer) == gist_llama.PRETRAINED_VOCAB_SIZE + 1: 181 | assert ( 182 | model.model.embed_tokens.weight.shape[0] 183 | == gist_llama.PRETRAINED_VOCAB_SIZE + 1 184 | ) 185 | assert model.lm_head.weight.shape[0] == gist_llama.PRETRAINED_VOCAB_SIZE + 1 186 | else: 187 | # Initialize gist token 188 | tokenizer.add_special_tokens({"additional_special_tokens": [""]}) 189 | model.resize_token_embeddings(len(tokenizer)) 190 | # Set new word embedding to average of existing word embeddings. For why, 191 | # see https://nlp.stanford.edu/~johnhew/vocab-expansion.html 192 | if args.model.pretrained: 193 | with torch.no_grad(): 194 | if is_t5: 195 | model.shared.weight[-1] = model.shared.weight[:-1].mean(0) 196 | elif is_llama: 197 | model.model.embed_tokens.weight[ 198 | -1 199 | ] = model.model.embed_tokens.weight[:-1].mean(0) 200 | model.lm_head.weight[-1] = model.lm_head.weight[:-1].mean(0) 201 | else: 202 | raise ValueError( 203 | f"Model type {args.model.model_name_or_path} not supported" 204 | ) 205 | gist_token = tokenizer.additional_special_tokens_ids[-1] 206 | 207 | if args.training.do_train: 208 | if "train" not in lm_datasets: 209 | raise ValueError("--do_train requires a train dataset") 210 | train_dataset = lm_datasets["train"] 211 | if args.data.max_train_samples is not None: 212 | max_train_samples = min(len(train_dataset), args.data.max_train_samples) 213 | train_dataset = train_dataset.select(range(max_train_samples)) 214 | 215 | if args.training.do_eval: 216 | validation_splits = [ 217 | split for split in lm_datasets if split.startswith("validation") 218 | ] 219 | if not validation_splits: 220 | raise ValueError( 221 | "--do_eval requires at least one validation dataset " 222 | "that starts with `validation`" 223 | ) 224 | eval_dataset = DatasetDict( 225 | # Trim "validation-" prefix. 226 | {split[11:]: lm_datasets[split] for split in validation_splits} 227 | ) 228 | # (Deterministically) shuffle eval in case we are truncating. 229 | eval_dataset = eval_dataset.shuffle(seed=42) 230 | if args.data.max_eval_samples is not None: 231 | eval_dataset = nested_select( 232 | eval_dataset, 233 | args.data.max_eval_samples, 234 | ) 235 | 236 | compute_metrics = get_compute_metrics_fn( 237 | gist_token=gist_token, tokenizer=tokenizer, args=args 238 | ) 239 | 240 | if is_t5: 241 | data_collator = alpaca.collator.DataCollatorForAlpaca( 242 | tokenizer, 243 | model=model, 244 | padding="longest", 245 | # Chosen so that <1% of examples are truncated. 246 | # See data/alpaca_plus/length_stats.txt for length stats. 247 | max_source_length=128, 248 | max_target_length=256, 249 | # Human eval examples are longer. 250 | max_source_length_human=384, 251 | max_target_length_human=384, 252 | label_pad_token_id=-100, 253 | pad_to_multiple_of=8 if args.training.fp16 else None, 254 | gist_condition=args.training.gist.condition, 255 | num_gist_tokens=args.training.gist.num_gist_tokens, 256 | gist_token=gist_token, 257 | pad_token=tokenizer.pad_token_id, 258 | add_gist_token=args.training.gist.add_gist_token, 259 | ) 260 | elif is_llama: 261 | # This data collator variant does causal language modeling with left 262 | # padding. 263 | data_collator = alpaca.collator.DataCollatorForAlpacaCLM( 264 | tokenizer, 265 | # Chosen so that <1% of examples are truncated. 266 | # See data/alpaca_plus/length_stats.txt for length stats. 267 | max_length=256 + 256, # source=256; target=256 268 | # Human eval examples are longer. 269 | max_length_human=384 + 384, # source=384; target=384 270 | gist_condition=args.training.gist.condition, 271 | num_gist_tokens=args.training.gist.num_gist_tokens, 272 | gist_token=gist_token, 273 | pad_token=tokenizer.pad_token_id, 274 | check_correctness=True, 275 | ) 276 | else: 277 | assert False, "should be is_llama or is_t5" 278 | 279 | # Initialize our Trainer 280 | custom_callbacks = [] 281 | if args.wandb.log: 282 | custom_callbacks.append(CustomWandbCallback(args)) 283 | if args.training.evaluate_before_train: 284 | custom_callbacks.append(EvaluateFirstStepCallback()) 285 | 286 | trainer = GistSeq2SeqTrainer( 287 | model=model, 288 | args=args.training, 289 | train_dataset=train_dataset if args.training.do_train else None, 290 | eval_dataset=dict(eval_dataset) if args.training.do_eval else None, 291 | tokenizer=tokenizer, 292 | data_collator=data_collator, 293 | compute_metrics=compute_metrics 294 | if args.training.do_eval and not is_torch_tpu_available() 295 | else None, 296 | preprocess_logits_for_metrics=None, 297 | callbacks=custom_callbacks, 298 | ) 299 | 300 | # Training 301 | if args.training.do_train: 302 | checkpoint = None 303 | if args.training.resume_from_checkpoint is not None: 304 | checkpoint = args.training.resume_from_checkpoint 305 | elif last_checkpoint is not None: 306 | checkpoint = last_checkpoint 307 | train_result = trainer.train(resume_from_checkpoint=checkpoint) 308 | trainer.save_model() # Saves the tokenizer too for easy upload 309 | 310 | metrics = train_result.metrics 311 | 312 | max_train_samples = ( 313 | args.data.max_train_samples 314 | if args.data.max_train_samples is not None 315 | else len(train_dataset) 316 | ) 317 | metrics["train_samples"] = min(max_train_samples, len(train_dataset)) 318 | 319 | trainer.log_metrics("train", metrics) 320 | trainer.save_metrics("train", metrics) 321 | trainer.save_state() 322 | 323 | if args.training.do_benchmarking: 324 | if not args.training.do_eval: 325 | raise RuntimeError("do_benchmarking requires do_eval") 326 | trainer.benchmark( 327 | gist_token, 328 | eval_dataset["human"], 329 | output_file=args.training.benchmarking_output_file, 330 | ) 331 | logger.info("Only doing benchmarking. Exiting!") 332 | return 333 | 334 | # Do evaluation for each dataset. 335 | if args.training.do_eval: 336 | all_eval_metrics = {} 337 | for eval_name, to_eval in eval_dataset.items(): 338 | logger.info(f"*** Evaluate {eval_name} ***") 339 | 340 | metrics = trainer.evaluate(to_eval) 341 | 342 | max_eval_samples = ( 343 | args.data.max_eval_samples 344 | if args.data.max_eval_samples is not None 345 | else len(to_eval) 346 | ) 347 | metrics["eval_samples"] = min(max_eval_samples, len(to_eval)) 348 | 349 | metrics = { 350 | (f"{eval_name}_{k}" if k != "epoch" else k): v 351 | for k, v in metrics.items() 352 | } 353 | all_eval_metrics.update(metrics) 354 | 355 | trainer.log_metrics("eval", all_eval_metrics) 356 | trainer.save_metrics("eval", all_eval_metrics) 357 | 358 | 359 | if __name__ == "__main__": 360 | main() 361 | -------------------------------------------------------------------------------- /src/utils.py: -------------------------------------------------------------------------------- 1 | """Miscellaneous utils.""" 2 | 3 | 4 | import itertools 5 | from typing import Any, List 6 | 7 | 8 | def first_mismatch(a: List[Any], b: List[Any], window: int = 10): 9 | """Returns first mismatch as well as sublists for debugging.""" 10 | for i, (x, y) in enumerate(itertools.zip_longest(a, b)): 11 | if x != y: 12 | window_slice = slice(i - window, i + window) 13 | return (x, y), (a[window_slice], b[window_slice]) 14 | return None 15 | -------------------------------------------------------------------------------- /src/weight_diff.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """ 15 | This file is modified from Stanford Alpaca's weight diff file. 16 | https://github.com/tatsu-lab/stanford_alpaca/blob/main/weight_diff.py 17 | """ 18 | 19 | 20 | import warnings 21 | from typing import Optional 22 | 23 | import fire 24 | import torch 25 | import tqdm 26 | import transformers 27 | from torch import nn 28 | from transformers import LlamaTokenizer 29 | 30 | from .gist_llama import PRETRAINED_VOCAB_SIZE, GistLlamaForCausalLM 31 | 32 | WEIGHT_SUMS = { 33 | "gist": 50547.9570, 34 | "pos_control": 50596.9141, 35 | "neg_control": 50503.8789, 36 | } 37 | 38 | 39 | @torch.no_grad() 40 | def add_zero_embedding_(model: nn.Module, tokenizer: transformers.PreTrainedTokenizer): 41 | """Add an additional embedding to the model for gist tokens. 42 | 43 | Ensures that the embedding is zero, so that weight diff works 44 | correctly. 45 | """ 46 | model.resize_token_embeddings(len(tokenizer)) 47 | # Instead of setting new embedding to be average of existing 48 | # word embeddings, here, we set everything to 0, so this does 49 | # not interfere with the weight diff. 50 | model.model.embed_tokens.weight[-1] = 0 51 | model.lm_head.weight[-1] = 0 52 | 53 | 54 | @torch.inference_mode() 55 | def make_diff( 56 | path_raw: str, 57 | path_tuned: str, 58 | path_diff: str, 59 | device="cpu", # "cuda" or "cpu" 60 | ): 61 | """Make the weight diff. 62 | 63 | This function is given to present full transparency of how the weight diff was created. 64 | 65 | Run: 66 | python weight_diff.py make_diff --path_raw --path_tuned --path_diff 67 | """ 68 | model_tuned: transformers.PreTrainedModel = GistLlamaForCausalLM.from_pretrained( 69 | path_tuned, 70 | torch_dtype=torch.float32, 71 | # Requires Accelerate 72 | # device_map={"": torch.device(device)}, 73 | # low_cpu_mem_usage=True, 74 | ) 75 | model_raw: transformers.PreTrainedModel = GistLlamaForCausalLM.from_pretrained( 76 | path_raw, 77 | torch_dtype=torch.float32, 78 | # Requires Accelerate 79 | # device_map={"": torch.device(device)}, 80 | # low_cpu_mem_usage=True, 81 | ) 82 | 83 | tokenizer: transformers.PreTrainedTokenizer = LlamaTokenizer.from_pretrained( 84 | path_tuned 85 | ) 86 | tokenizer.pad_token = tokenizer.eos_token 87 | tokenizer.padding_side = "left" 88 | assert len(tokenizer) == PRETRAINED_VOCAB_SIZE + 1 89 | # Raw model should not have gist token, tuned model should. 90 | assert model_raw.lm_head.weight.shape[0] == PRETRAINED_VOCAB_SIZE 91 | assert model_tuned.lm_head.weight.shape[0] == PRETRAINED_VOCAB_SIZE + 1 92 | 93 | # Add 0 embedding to raw model to support weight diff 94 | add_zero_embedding_(model_raw, tokenizer) 95 | 96 | state_dict_tuned = model_tuned.state_dict() 97 | print("Weight sum:", sum(state_dict_tuned[key].sum() for key in state_dict_tuned)) 98 | state_dict_raw = model_raw.state_dict() 99 | for key in tqdm.tqdm(state_dict_tuned, desc="Weight diff"): 100 | state_dict_tuned[key].add_(-state_dict_raw[key]) 101 | 102 | model_tuned.save_pretrained(path_diff) 103 | tokenizer.save_pretrained(path_diff) 104 | 105 | 106 | @torch.inference_mode() 107 | def recover( 108 | path_raw, 109 | path_diff, 110 | path_tuned: Optional[str] = None, 111 | device="cpu", 112 | test_inference=True, 113 | check_integrity_naively=True, 114 | model_type: Optional[str] = None, 115 | **kwargs, 116 | ): 117 | """Recover the original weights from the released weight diff. 118 | 119 | This function is given for you to run. 120 | 121 | Things to do before running this: 122 | 1. Convert Meta's released weights into huggingface format. Follow this guide: 123 | https://huggingface.co/docs/transformers/main/model_doc/llama 124 | 2. Make sure you cloned the released weight diff into your local machine. The weight diff is located at: 125 | https://huggingface.co/tatsu-lab/alpaca-7b/tree/main 126 | 3. Run this function with the correct paths. E.g., 127 | python weight_diff.py recover --path_raw --path_diff 128 | 129 | Additional notes: 130 | - If things run too slowly, and you have an 80G GPU lying around, let GPU go brrr by setting `--device "cuda"`. 131 | - If you want to save the recovered weights, set `--path_tuned `. 132 | Next time you can load the recovered weights directly from ``. 133 | """ 134 | model_raw: transformers.PreTrainedModel = GistLlamaForCausalLM.from_pretrained( 135 | path_raw, 136 | torch_dtype=torch.float32, 137 | **kwargs, 138 | # Requires Accelerate 139 | # device_map={"": torch.device(device)}, 140 | # low_cpu_mem_usage=True, 141 | ) 142 | model_recovered: transformers.PreTrainedModel = GistLlamaForCausalLM.from_pretrained( 143 | path_diff, 144 | torch_dtype=torch.float32, 145 | **kwargs, 146 | # Requires Accelerate 147 | # device_map={"": torch.device(device)}, 148 | # low_cpu_mem_usage=True, 149 | ) 150 | 151 | tokenizer_recovered: transformers.PreTrainedTokenizer = ( 152 | LlamaTokenizer.from_pretrained( 153 | path_diff, 154 | **kwargs, 155 | ) 156 | ) 157 | 158 | add_zero_embedding_(model_raw, tokenizer_recovered) 159 | 160 | state_dict_recovered = model_recovered.state_dict() 161 | state_dict_raw = model_raw.state_dict() 162 | for key in tqdm.tqdm(state_dict_recovered, desc="Weight diff"): 163 | state_dict_recovered[key].add_(state_dict_raw[key]) 164 | 165 | if check_integrity_naively: 166 | # Guess what model we are loading. 167 | if model_type is None: 168 | if "pos_control" in path_diff: 169 | model_type = "pos_control" 170 | elif "neg_control" in path_diff: 171 | model_type = "neg_control" 172 | elif "gist" in path_diff: 173 | model_type = "gist" 174 | else: 175 | warnings.warn( 176 | f"Unable to guess model type from path: {path_diff}. " 177 | "Assuming gist model for naive integrity checks." 178 | ) 179 | model_type = "gist" 180 | 181 | # This is not a rigorous, cryptographically strong integrity check :) 182 | allsum = sum(state_dict_recovered[key].sum() for key in state_dict_recovered) 183 | refsum = WEIGHT_SUMS[model_type] 184 | assert torch.allclose( 185 | allsum, torch.full_like(allsum, fill_value=refsum), atol=1e-2, rtol=0 186 | ), ( 187 | "Naive integrity check failed. This could imply that some of the checkpoint " 188 | "files are corrupted, or that you are checking against the wrong model_type " 189 | f"({model_type})" 190 | ) 191 | 192 | if path_tuned is not None: 193 | model_recovered.save_pretrained(path_tuned) 194 | tokenizer_recovered.save_pretrained(path_tuned) 195 | 196 | if test_inference: 197 | input_text = "Instruction:\r\nList three technologies that make life easier. \r\nOutput:" 198 | inputs = tokenizer_recovered(input_text, return_tensors="pt") 199 | # Note: gist masking is not happening here. 200 | inputs["attention_mask_gist"] = inputs["attention_mask"][None, None] 201 | inputs = {k: v.cuda() for k, v in inputs.items()} 202 | model_recovered = model_recovered.cuda() 203 | out = model_recovered.generate(**inputs, max_new_tokens=100) 204 | output_text = tokenizer_recovered.batch_decode(out, skip_special_tokens=True)[0] 205 | print(output_text) 206 | 207 | return model_recovered, tokenizer_recovered 208 | 209 | 210 | def main(task, **kwargs): 211 | globals()[task](**kwargs) 212 | 213 | 214 | if __name__ == "__main__": 215 | fire.Fire(main) 216 | --------------------------------------------------------------------------------