├── .gitignore ├── LICENSE ├── README.md ├── chat ├── README.md ├── config.py ├── config.yaml ├── deepspeed_z3_config_bf16.json ├── dialogues.py ├── generate.py ├── requirements.txt ├── train.py └── utils.py ├── finetune ├── finetune.py └── merge_peft_adapters.py └── requirements.txt /.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 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 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 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | data/ 163 | wandb/ -------------------------------------------------------------------------------- /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 | # 💫 StarCoder 2 | 3 | [Paper](https://drive.google.com/file/d/1cN-b9GnWtHzQRoE7M7gAEyivY0kl4BYs/view) | [Model](https://huggingface.co/bigcode/starcoder) | [Playground](https://huggingface.co/spaces/bigcode/bigcode-playground) | [VSCode](https://marketplace.visualstudio.com/items?itemName=HuggingFace.huggingface-vscode) | [Chat](https://huggingface.co/spaces/HuggingFaceH4/starchat-playground) 4 | 5 | # What is this about? 6 | 💫 StarCoder is a language model (LM) trained on source code and natural language text. Its training data incorporates more that 80 different programming languages as well as text extracted from GitHub issues and commits and from notebooks. This repository showcases how we get an overview of this LM's capabilities. 7 | 8 | # News 9 | 10 | * **May 9, 2023:** We've fine-tuned StarCoder to act as a helpful coding assistant 💬! Check out the `chat/` directory for the training code and play with the model [here](https://huggingface.co/spaces/HuggingFaceH4/starchat-playground). 11 | 12 | # Disclaimer 13 | 14 | Before you can use the model go to `hf.co/bigcode/starcoder` and accept the agreement. And make sure you are logged into the Hugging Face hub with: 15 | ```bash 16 | huggingface-cli login 17 | ``` 18 | 19 | # Table of Contents 20 | 1. [Quickstart](#quickstart) 21 | - [Installation](#installation) 22 | - [Code generation with StarCoder](#code-generation) 23 | - [Text-generation-inference code](#text-generation-inference) 24 | 2. [Fine-tuning](#fine-tuning) 25 | - [Step by step installation with conda](#step-by-step-installation-with-conda) 26 | - [Datasets](#datasets) 27 | - [Stack Exchange](#stack-exchange-se) 28 | - [Merging PEFT adapter layers](#merging-peft-adapter-layers) 29 | 3. [Evaluation](#evaluation) 30 | 4. [Inference hardware requirements](#inference-hardware-requirements) 31 | 32 | # Quickstart 33 | StarCoder was trained on GitHub code, thus it can be used to perform code generation. More precisely, the model can complete the implementation of a function or infer the following characters in a line of code. This can be done with the help of the 🤗's [transformers](https://github.com/huggingface/transformers) library. 34 | 35 | ## Installation 36 | First, we have to install all the libraries listed in `requirements.txt` 37 | ```bash 38 | pip install -r requirements.txt 39 | ``` 40 | ## Code generation 41 | The code generation pipeline is as follows 42 | 43 | ```python 44 | from transformers import AutoModelForCausalLM, AutoTokenizer 45 | 46 | checkpoint = "bigcode/starcoder" 47 | device = "cuda" # for GPU usage or "cpu" for CPU usage 48 | 49 | tokenizer = AutoTokenizer.from_pretrained(checkpoint) 50 | # to save memory consider using fp16 or bf16 by specifying torch_dtype=torch.float16 for example 51 | model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device) 52 | 53 | inputs = tokenizer.encode("def print_hello_world():", return_tensors="pt").to(device) 54 | outputs = model.generate(inputs) 55 | # clean_up_tokenization_spaces=False prevents a tokenizer edge case which can result in spaces being removed around punctuation 56 | print(tokenizer.decode(outputs[0], clean_up_tokenization_spaces=False)) 57 | ``` 58 | or 59 | ```python 60 | from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline 61 | checkpoint = "bigcode/starcoder" 62 | 63 | model = AutoModelForCausalLM.from_pretrained(checkpoint) 64 | tokenizer = AutoTokenizer.from_pretrained(checkpoint) 65 | 66 | pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0) 67 | print( pipe("def hello():") ) 68 | ``` 69 | For hardware requirements, check the section [Inference hardware requirements](#inference-hardware-requirements). 70 | 71 | ## Text-generation-inference 72 | 73 | ```bash 74 | docker run -p 8080:80 -v $PWD/data:/data -e HUGGING_FACE_HUB_TOKEN= -d ghcr.io/huggingface/text-generation-inference:latest --model-id bigcode/starcoder --max-total-tokens 8192 75 | ``` 76 | For more details, see [here](https://github.com/huggingface/text-generation-inference). 77 | 78 | # Fine-tuning 79 | 80 | Here, we showcase how we can fine-tune this LM on a specific downstream task. 81 | 82 | ## Step by step installation with conda 83 | 84 | Create a new conda environment and activate it 85 | ```bash 86 | conda create -n env 87 | conda activate env 88 | ``` 89 | Install the `pytorch` version compatible with your version of cuda [here](https://pytorch.org/get-started/previous-versions/), for example the following command works with cuda 11.6 90 | ```bash 91 | conda install pytorch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1 pytorch-cuda=11.6 -c pytorch -c nvidia 92 | ``` 93 | Install `transformers` and `peft` 94 | ```bash 95 | conda install -c huggingface transformers 96 | pip install git+https://github.com/huggingface/peft.git 97 | ``` 98 | Note that you can install the latest stable version of transformers by using 99 | 100 | ```bash 101 | pip install git+https://github.com/huggingface/transformers 102 | ``` 103 | 104 | Install `datasets`, `accelerate` and `huggingface_hub` 105 | 106 | ```bash 107 | conda install -c huggingface -c conda-forge datasets 108 | conda install -c conda-forge accelerate 109 | conda install -c conda-forge huggingface_hub 110 | ``` 111 | 112 | Finally, install `bitsandbytes` and `wandb` 113 | ```bash 114 | pip install bitsandbytes 115 | pip install wandb 116 | ``` 117 | To get the full list of arguments with descriptions you can run the following command on any script: 118 | ``` 119 | python scripts/some_script.py --help 120 | ``` 121 | Before you run any of the scripts make sure you are logged in and can push to the hub: 122 | ```bash 123 | huggingface-cli login 124 | ``` 125 | Make sure you are logged in `wandb`: 126 | ```bash 127 | wandb login 128 | ``` 129 | Now that everything is done, you can clone the repository and get into the corresponding directory. 130 | 131 | ## Datasets 132 | 💫 StarCoder can be fine-tuned to achieve multiple downstream tasks. Our interest here is to fine-tune StarCoder in order to make it follow instructions. [Instruction fine-tuning](https://arxiv.org/pdf/2109.01652.pdf) has gained a lot of attention recently as it proposes a simple framework that teaches language models to align their outputs with human needs. That procedure requires the availability of quality instruction datasets, which contain multiple `instruction - answer` pairs. Unfortunately such datasets are not ubiquitous but thanks to Hugging Face 🤗's [datasets](https://github.com/huggingface/datasets) library we can have access to some good proxies. To fine-tune cheaply and efficiently, we use Hugging Face 🤗's [PEFT](https://github.com/huggingface/peft) as well as Tim Dettmers' [bitsandbytes](https://github.com/TimDettmers/bitsandbytes). 133 | 134 | 135 | ### Stack Exchange SE 136 | [Stack Exchange](https://en.wikipedia.org/wiki/Stack_Exchange) is a well-known network of Q&A websites on topics in diverse fields. It is a place where a user can ask a question and obtain answers from other users. Those answers are scored and ranked based on their quality. [Stack exchange instruction](https://huggingface.co/datasets/ArmelR/stack-exchange-instruction) is a dataset that was obtained by scrapping the site in order to build a collection of Q&A pairs. A language model can then be fine-tuned on that dataset to make it elicit strong and diverse question-answering skills. 137 | 138 | To execute the fine-tuning script run the following command: 139 | ```bash 140 | python finetune/finetune.py \ 141 | --model_path="bigcode/starcoder"\ 142 | --dataset_name="ArmelR/stack-exchange-instruction"\ 143 | --subset="data/finetune"\ 144 | --split="train"\ 145 | --size_valid_set 10000\ 146 | --streaming\ 147 | --seq_length 2048\ 148 | --max_steps 1000\ 149 | --batch_size 1\ 150 | --input_column_name="question"\ 151 | --output_column_name="response"\ 152 | --gradient_accumulation_steps 16\ 153 | --learning_rate 1e-4\ 154 | --lr_scheduler_type="cosine"\ 155 | --num_warmup_steps 100\ 156 | --weight_decay 0.05\ 157 | --output_dir="./checkpoints" \ 158 | ``` 159 | The size of the SE dataset is better manageable when using streaming. We also have to precise the split of the dataset that is used. For more details, check the [dataset's page](https://huggingface.co/datasets/ArmelR/stack-exchange-instruction) on 🤗. Similarly we can modify the command to account for the availability of GPUs 160 | 161 | ```bash 162 | python -m torch.distributed.launch \ 163 | --nproc_per_node number_of_gpus finetune/finetune.py \ 164 | --model_path="bigcode/starcoder"\ 165 | --dataset_name="ArmelR/stack-exchange-instruction"\ 166 | --subset="data/finetune"\ 167 | --split="train"\ 168 | --size_valid_set 10000\ 169 | --streaming \ 170 | --seq_length 2048\ 171 | --max_steps 1000\ 172 | --batch_size 1\ 173 | --input_column_name="question"\ 174 | --output_column_name="response"\ 175 | --gradient_accumulation_steps 16\ 176 | --learning_rate 1e-4\ 177 | --lr_scheduler_type="cosine"\ 178 | --num_warmup_steps 100\ 179 | --weight_decay 0.05\ 180 | --output_dir="./checkpoints" \ 181 | ``` 182 | ## Merging PEFT adapter layers 183 | If you train a model with PEFT, you'll need to merge the adapter layers with the base model if you want to run inference / evaluation. To do so, run: 184 | ```bash 185 | python finetune/merge_peft_adapters.py --base_model_name_or_path model_to_merge --peft_model_path model_checkpoint 186 | 187 | # Push merged model to the Hub 188 | python finetune/merge_peft_adapters.py --base_model_name_or_path model_to_merge --peft_model_path model_checkpoint --push_to_hub 189 | ``` 190 | For example 191 | 192 | ```bash 193 | python finetune/merge_peft_adapters.py --model_name_or_path bigcode/starcoder --peft_model_path checkpoints/checkpoint-1000 --push_to_hub 194 | ``` 195 | 196 | # Evaluation 197 | To evaluate StarCoder and its derivatives, you can use the [BigCode-Evaluation-Harness](https://github.com/bigcode-project/bigcode-evaluation-harness) for evaluating Code LLMs. 198 | 199 | # Inference hardware requirements 200 | In FP32 the model requires more than 60GB of RAM, you can load it in FP16 or BF16 in ~30GB, or in 8bit under 20GB of RAM with 201 | ```python 202 | # make sure you have accelerate and bitsandbytes installed 203 | from transformers import AutoModelForCausalLM, AutoTokenizer 204 | 205 | tokenizer = AutoTokenizer.from_pretrained("bigcode/starcoder") 206 | # for fp16 replace with `load_in_8bit=True` with `torch_dtype=torch.float16` 207 | model = AutoModelForCausalLM.from_pretrained("bigcode/starcoder", device_map="auto", load_in_8bit=True) 208 | print(f"Memory footprint: {model.get_memory_footprint() / 1e6:.2f} MB") 209 | ```` 210 | ``` 211 | Memory footprint: 15939.61 MB 212 | ``` 213 | You can also try [starcoder.cpp](https://github.com/bigcode-project/starcoder.cpp), a C++ implementation with [ggml](https://github.com/ggerganov/ggml) library. 214 | -------------------------------------------------------------------------------- /chat/README.md: -------------------------------------------------------------------------------- 1 | # Fine-tuning StarCoder for chat-based applications 2 | 3 | This is a fully-working example to fine-tune `StarCoder` on a corpus of multi-turn dialogues and thus create a coding assistant that is chatty and helpful. The resulting model is quite good at generating code for plots and other programming tasks. For example, given the prompt: 4 | 5 | ``` 6 | Draw me a map of the world using geopandas. Make it so that only Germany and Spain are colored red. 7 | ``` 8 | 9 | the model will produce: 10 | 11 | ```python 12 | import pandas as pd 13 | from matplotlib import pyplot as plt 14 | import geopandas as gpd 15 | from shapely.geometry import Point, Polygon 16 | %matplotlib inline 17 | # Load data from URL or local file 18 | url = 'https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson' 19 | df = gpd.read_file(url) 20 | 21 | # Create plot 22 | fig, ax = plt.subplots() 23 | ax.set_aspect('equal') 24 | world = gpd.GeoDataFrame({'name': ['World'], 25 | 'geometry': [Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])]}) 26 | germany = df[df['ADMIN'] == "Germany"] 27 | spain = df[df['ADMIN'] == "Spain"] 28 | other = df[(df['ADMIN']!= "Germany") & (df['ADMIN']!= "Spain")] 29 | world.plot(color='lightgrey', edgecolor='white', ax=ax) 30 | germany.plot(color="red", ax=ax) 31 | spain.plot(color="red", ax=ax) 32 | other.plot(color="skyblue", ax=ax) 33 | plt.title("European Countries") 34 | plt.show() 35 | ``` 36 | 37 | Check out our [blog post](https://huggingface.co/blog/starchat-alpha) for more details. 38 | 39 | ## Getting started 40 | 41 | To run the `train.py` script, first create a Python virtual environment using e.g. Conda: 42 | 43 | ```shell 44 | conda create -n chat python=3.10 && conda activate chat 45 | ``` 46 | 47 | Next, install PyTorch v1.13.1. Since this is hardware-dependent, we direct you to the [PyTorch Installation Page](https://pytorch.org/get-started/previous-versions/#v1131) for this step. Next, install the rest of the project dependencies: 48 | 49 | ```shell 50 | pip install -r requirements.txt 51 | ``` 52 | 53 | You'll also need to be logged into both your Hugging Face account. To do so, run: 54 | 55 | ```shell 56 | huggingface-cli login 57 | ``` 58 | 59 | Finally, install Git LFS with: 60 | 61 | ```shell 62 | sudo apt-get install git-lfs 63 | ``` 64 | 65 | ## Prepare your dataset 66 | 67 | For training and inference, we use _dialogue templates_ to format each message in a conversation. For example, a typical dialogue between a human user and AI assistant takes the form: 68 | 69 | ```json 70 | { 71 | "messages": [ 72 | { 73 | "content": "Is it possible to imagine a society without law?", 74 | "role": "user"}, 75 | { 76 | "content": "It is difficult to imagine a society that is able to be maintained without any semblance of Law.", 77 | "role": "assistant", 78 | }, 79 | { 80 | "content": "It seems like you consider the absence of law equal to the absence of anything that could guide the behaviour of the individual.", 81 | "role": "user", 82 | }, 83 | { 84 | "content": "You are correct that there are other factors that can guide behavior in a society and play a role in shaping individuals' behavior and interactions with each other. However, even in societies where these factors are present, laws still serve an important role in maintaining social order and resolving conflicts.", 85 | "role": "assistant", 86 | } 87 | ] 88 | } 89 | ``` 90 | 91 | Make sure you convert your dataset according to this schema, in particular you need to include a `messages` column like the above. You can adjust the model, dataset, and hyperparamters in the `config.yaml` file. 92 | 93 | ## Launch training 94 | 95 | We use DeepSpeed ZeRO-3 to shard the model and optimizer across 8 x A100 (80GB) GPUs. To fine-tune run: 96 | 97 | ``` 98 | TRANSFORMERS_VERBOSITY=info torchrun --nproc_per_node=8 train.py config.yaml --deepspeed=deepspeed_z3_config_bf16.json 99 | ``` 100 | 101 | By default, this will save the model checkpoint in the `data/` directory and also push it to the Hugging Face Hub. 102 | 103 | 104 | ## Generate samples 105 | 106 | To generate a few coding examples from your model, run: 107 | 108 | ```shell 109 | python generate.py --model_id path/to/your/model 110 | ``` 111 | 112 | -------------------------------------------------------------------------------- /chat/config.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 The HuggingFace 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 | from dataclasses import dataclass, field 16 | from typing import List, Optional 17 | 18 | import transformers 19 | from transformers import MODEL_FOR_CAUSAL_LM_MAPPING 20 | 21 | MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys()) 22 | MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) 23 | 24 | 25 | @dataclass 26 | class ModelArguments: 27 | """ 28 | Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. 29 | """ 30 | 31 | model_name_or_path: Optional[str] = field( 32 | default=None, 33 | metadata={ 34 | "help": ( 35 | "The model checkpoint for weights initialization. Don't set if you want to train a model from scratch." 36 | ) 37 | }, 38 | ) 39 | model_revision: str = field( 40 | default="main", 41 | metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, 42 | ) 43 | torch_dtype: Optional[str] = field( 44 | default=None, 45 | metadata={ 46 | "help": ( 47 | "Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the " 48 | "dtype will be automatically derived from the model's weights." 49 | ), 50 | "choices": ["auto", "bfloat16", "float16", "float32"], 51 | }, 52 | ) 53 | use_fast_tokenizer: bool = field( 54 | default=True, 55 | metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, 56 | ) 57 | 58 | 59 | @dataclass 60 | class DataArguments: 61 | """ 62 | Arguments pertaining to what data we are going to input our model for training and eval. 63 | """ 64 | 65 | dataset_name: Optional[str] = field( 66 | default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} 67 | ) 68 | max_train_samples: Optional[int] = field( 69 | default=None, 70 | metadata={ 71 | "help": ( 72 | "For debugging purposes or quicker training, truncate the number of training examples to this " 73 | "value if set." 74 | ) 75 | }, 76 | ) 77 | max_eval_samples: Optional[int] = field( 78 | default=None, 79 | metadata={ 80 | "help": ( 81 | "For debugging purposes or quicker training, truncate the number of evaluation examples to this " 82 | "value if set." 83 | ) 84 | }, 85 | ) 86 | block_size: Optional[int] = field( 87 | default=None, 88 | metadata={ 89 | "help": ( 90 | "Optional input sequence length after tokenization. " 91 | "The training dataset will be truncated in block of this size for training. " 92 | "Default to the model max input length for single sentence inputs (take into account special tokens)." 93 | ) 94 | }, 95 | ) 96 | overwrite_cache: bool = field( 97 | default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} 98 | ) 99 | preprocessing_num_workers: Optional[int] = field( 100 | default=None, 101 | metadata={"help": "The number of processes to use for the preprocessing."}, 102 | ) 103 | dialogue_template: Optional[str] = field( 104 | default="no_system", 105 | metadata={ 106 | "help": "The name of the dialogue template to use for conditioning the model. See h4.training.dialogues for choices." 107 | }, 108 | ) 109 | 110 | 111 | @dataclass 112 | class TrainingArguments(transformers.TrainingArguments): 113 | """ 114 | Arguments related to the training process itself. For all parameters, see: https://huggingface.co/docs/transformers/v4.26.1/en/main_classes/trainer#transformers.TrainingArguments 115 | """ 116 | 117 | logging_first_step: Optional[bool] = field( 118 | default=True, 119 | metadata={"help": ("Whether to log and evaluate the first global_step or not.")}, 120 | ) 121 | optim: Optional[str] = field(default="adamw_torch") 122 | -------------------------------------------------------------------------------- /chat/config.yaml: -------------------------------------------------------------------------------- 1 | # Model arguments 2 | model_name_or_path: bigcode/starcoderbase 3 | 4 | # Data training arguments 5 | block_size: 1024 6 | dataset_name: HuggingFaceH4/oasst1_en 7 | dialogue_template: no_system 8 | preprocessing_num_workers: 12 9 | 10 | # Training arguments with sensible defaults 11 | # Add other options from here: https://huggingface.co/docs/transformers/v4.26.1/en/main_classes/trainer#transformers.TrainingArguments 12 | bf16: true # Gives ~2x speed up in training time, but disable if you start seeing NaNs 13 | do_eval: true 14 | do_train: true 15 | evaluation_strategy: epoch # One of ["no", "steps", "epoch"] 16 | gradient_accumulation_steps: 8 17 | gradient_checkpointing: true 18 | hub_model_id: lewtun/starchat-alpha 19 | hub_private_repo: true 20 | hub_strategy: every_save 21 | learning_rate: 2.0e-05 22 | log_level: passive 23 | logging_steps: 8 24 | logging_strategy: steps 25 | lr_scheduler_type: cosine 26 | max_steps: -1 27 | num_train_epochs: 3 28 | output_dir: data/starchat-alpha 29 | overwrite_output_dir: true 30 | per_device_eval_batch_size: 4 31 | per_device_train_batch_size: 4 32 | push_to_hub: true 33 | remove_unused_columns: true 34 | report_to: 35 | - tensorboard 36 | save_steps: 500 37 | save_strategy: steps 38 | save_total_limit: null 39 | seed: 42 40 | tf32: true 41 | warmup_ratio: 0.03 42 | weight_decay: 0. -------------------------------------------------------------------------------- /chat/deepspeed_z3_config_bf16.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": true 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 | } -------------------------------------------------------------------------------- /chat/dialogues.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 The HuggingFace 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 | import json 17 | import os 18 | from dataclasses import asdict, dataclass 19 | from pathlib import Path 20 | from typing import Any, Dict, List, Optional, Type, TypeVar, Union 21 | 22 | from huggingface_hub import ModelHubMixin, hf_hub_download 23 | 24 | # Generic variable that is either ModelHubMixin or a subclass thereof 25 | T = TypeVar("T", bound="ModelHubMixin") 26 | 27 | TEMPLATE_FILENAME = "dialogue_template.json" 28 | IGNORE_INDEX = -100 29 | 30 | 31 | @dataclass 32 | class DialogueTemplate(ModelHubMixin): 33 | """Converts all turns of a dialogue between a user and assistant to a standardized format. 34 | 35 | Adapted from OpenAI's ChatML (https://github.com/openai/openai-python/blob/main/chatml.md) and Vicuna (https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py) 36 | """ 37 | 38 | system: str 39 | messages: List[Dict[str, str]] = None 40 | system_token: str = "<|system|>" 41 | user_token: str = "<|user|>" 42 | assistant_token: str = "<|assistant|>" 43 | end_token: str = "<|end|>" 44 | 45 | def get_training_prompt(self) -> str: 46 | prompt = self.system_token + "\n" + self.system + self.end_token + "\n" 47 | if self.messages is None: 48 | raise ValueError("Dialogue template must have at least one message.") 49 | for message in self.messages: 50 | if message["role"] == "user": 51 | prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n" 52 | else: 53 | prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n" 54 | return prompt 55 | 56 | def get_inference_prompt(self) -> str: 57 | prompt = self.system_token + "\n" + self.system + self.end_token + "\n" 58 | if self.messages is None: 59 | raise ValueError("Dialogue template must have at least one message.") 60 | for message in self.messages: 61 | if message["role"] == "user": 62 | prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n" 63 | else: 64 | prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n" 65 | prompt += self.assistant_token 66 | return prompt 67 | 68 | def get_dialogue(self): 69 | """Helper function to format the messages as an easy-to-read dialogue.""" 70 | prompt = "" 71 | if self.messages is None: 72 | raise ValueError("Dialogue template must have at least one message.") 73 | for message in self.messages: 74 | if message["role"] == "user": 75 | prompt += "\n\nHuman: " + message["content"] 76 | else: 77 | prompt += "\n\nAssistant: " + message["content"] 78 | return prompt 79 | 80 | def get_special_tokens(self) -> List[str]: 81 | return [self.system_token, self.user_token, self.assistant_token, self.end_token] 82 | 83 | def copy(self): 84 | return DialogueTemplate( 85 | system=self.system, 86 | messages=self.messages, 87 | system_token=self.system_token, 88 | user_token=self.user_token, 89 | assistant_token=self.assistant_token, 90 | end_token=self.end_token, 91 | ) 92 | 93 | def to_dict(self) -> Dict[str, Any]: 94 | return {k: v for k, v in asdict(self).items()} 95 | 96 | @classmethod 97 | def from_dict(cls, data): 98 | return DialogueTemplate( 99 | system=data["system"] if "system" in data else "", 100 | messages=data["messages"] if "messages" in data else None, 101 | system_token=data["system_token"] if "system_token" in data else "<|system|>", 102 | user_token=data["user_token"] if "user_token" in data else "<|user|>", 103 | assistant_token=data["assistant_token"] if "assistant_token" in data else "<|assistant|>", 104 | end_token=data["end_token"] if "end_token" in data else "<|end|>", 105 | ) 106 | 107 | def _save_pretrained(self, save_directory: Union[str, Path]) -> None: 108 | save_directory = Path(save_directory) 109 | save_directory.mkdir(exist_ok=True) 110 | with open(save_directory / "dialogue_template.json", "w") as f: 111 | json.dump(self.to_dict(), f, indent=2) 112 | 113 | @classmethod 114 | def _from_pretrained( 115 | cls: Type[T], 116 | *, 117 | model_id: str, 118 | revision: Optional[str], 119 | cache_dir: Optional[Union[str, Path]], 120 | force_download: bool, 121 | proxies: Optional[Dict], 122 | resume_download: bool, 123 | local_files_only: bool, 124 | token: Optional[Union[str, bool]], 125 | **model_kwargs, 126 | ) -> T: 127 | """Loads the dialogue template from a local directory or the Huggingface Hub. 128 | 129 | Args: 130 | model_id (`str`): 131 | ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`). 132 | revision (`str`, *optional*): 133 | Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the 134 | latest commit on `main` branch. 135 | force_download (`bool`, *optional*, defaults to `False`): 136 | Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding 137 | the existing cache. 138 | resume_download (`bool`, *optional*, defaults to `False`): 139 | Whether to delete incompletely received files. Will attempt to resume the download if such a file exists. 140 | proxies (`Dict[str, str]`, *optional*): 141 | A dictionary of proxy servers to use by protocol or endpoint (e.g., `{'http': 'foo.bar:3128', 142 | 'http://hostname': 'foo.bar:4012'}`). 143 | token (`str` or `bool`, *optional*): 144 | The token to use as HTTP bearer authorization for remote files. By default, it will use the token 145 | cached when running `huggingface-cli login`. 146 | cache_dir (`str`, `Path`, *optional*): 147 | Path to the folder where cached files are stored. 148 | local_files_only (`bool`, *optional*, defaults to `False`): 149 | If `True`, avoid downloading the file and return the path to the local cached file if it exists. 150 | model_kwargs: 151 | Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method. 152 | """ 153 | if os.path.isdir(model_id): # Can either be a local directory 154 | print("Loading dialogue template from local directory") 155 | template_file = os.path.join(model_id, TEMPLATE_FILENAME) 156 | else: # Or a template on the Hub 157 | template_file = hf_hub_download( # Download from the hub, passing same input args 158 | repo_id=model_id, 159 | filename=TEMPLATE_FILENAME, 160 | revision=revision, 161 | cache_dir=cache_dir, 162 | force_download=force_download, 163 | proxies=proxies, 164 | resume_download=resume_download, 165 | token=token, 166 | local_files_only=local_files_only, 167 | ) 168 | 169 | # Load template 170 | with open(template_file, "r") as f: 171 | data = json.load(f) 172 | return cls.from_dict(data=data) 173 | 174 | 175 | # A shortened version of the system message in Anthropic's HHH prompt: https://gist.github.com/jareddk/2509330f8ef3d787fc5aaac67aab5f11#file-hhh_prompt-txt 176 | default_template = DialogueTemplate( 177 | system="Below is a dialogue between a human user and an AI assistant. The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.", 178 | ) 179 | 180 | # OpenAI and OpenAssistant train on few to no system messages. 181 | # TODO: consider defining this as the `default` template 182 | no_system_template = DialogueTemplate( 183 | system="", 184 | ) 185 | 186 | alpaca_template = DialogueTemplate( 187 | system="Below is an instruction that describes a task. Write a response that appropriately completes the request.", 188 | user_token="### Instruction:", 189 | assistant_token="### Response:", 190 | ) 191 | 192 | SUPPORTED_DIALOGUE_TEMPLATES = { 193 | "default": default_template, 194 | "no_system": no_system_template, 195 | "alpaca": alpaca_template, 196 | } 197 | 198 | 199 | def get_dialogue_template(template: str) -> DialogueTemplate: 200 | if template not in SUPPORTED_DIALOGUE_TEMPLATES.keys(): 201 | raise ValueError(f"Template {template} is not supported!") 202 | return SUPPORTED_DIALOGUE_TEMPLATES[template].copy() 203 | 204 | 205 | def prepare_dialogue(example, dialogue_template, is_train=True): 206 | """Format example to single- or multi-turn dialogue.""" 207 | # TODO: make this simpler by just ensuring every dataset has a messages column 208 | if "messages" in example.keys() and example["messages"] is not None: 209 | dialogue_template.messages = example["messages"] 210 | elif all(k in example.keys() for k in ("prompt", "completion")): 211 | # Construct single-turn dialogue from prompt and completion 212 | dialogue_template.messages = [ 213 | {"role": "user", "content": example["prompt"]}, 214 | {"role": "assistant", "content": example["completion"]}, 215 | ] 216 | elif "prompt" in example.keys(): 217 | # Construct single-turn dialogue from prompt (inference only) 218 | dialogue_template.messages = [ 219 | {"role": "user", "content": example["prompt"]}, 220 | ] 221 | else: 222 | raise ValueError( 223 | f"Could not format example as dialogue! Require either `messages` or `[prompt, completion]` or `[prompt]` keys but found {list(example.keys())}" 224 | ) 225 | if is_train: 226 | example["text"] = dialogue_template.get_training_prompt() 227 | else: 228 | example["text"] = dialogue_template.get_inference_prompt() 229 | return example 230 | 231 | 232 | def mask_user_labels(tokenizer, dialogue_template, labels): 233 | """Masks the user turns of a dialogue from the loss""" 234 | user_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.user_token) 235 | assistant_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.assistant_token) 236 | for idx, label_id in enumerate(labels): 237 | if label_id == user_token_id: 238 | current_idx = idx 239 | while labels[current_idx] != assistant_token_id and current_idx < len(labels): 240 | labels[current_idx] = IGNORE_INDEX 241 | current_idx += 1 242 | -------------------------------------------------------------------------------- /chat/generate.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 The BigCode and HuggingFace teams. 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 | """A simple script to quickly check the model outputs of a generative model""" 17 | import argparse 18 | 19 | import torch 20 | from dialogues import DialogueTemplate, get_dialogue_template 21 | from transformers import (AutoModelForCausalLM, AutoTokenizer, 22 | GenerationConfig, set_seed) 23 | 24 | 25 | def main(): 26 | parser = argparse.ArgumentParser() 27 | parser.add_argument( 28 | "--model_id", 29 | type=str, 30 | help="Name of model to generate samples with", 31 | ) 32 | parser.add_argument( 33 | "--revision", 34 | type=str, 35 | default=None, 36 | help="The model repo's revision to use", 37 | ) 38 | parser.add_argument( 39 | "--system_prompt", type=str, default=None, help="Overrides the dialogue template's system prompt" 40 | ) 41 | args = parser.parse_args() 42 | 43 | # Set seed for reproducibility 44 | set_seed(42) 45 | 46 | prompts = [ 47 | [ 48 | { 49 | "role": "user", 50 | "content": "Develop a C++ program that reads a text file line by line and counts the number of occurrences of a specific word in the file.", 51 | } 52 | ], 53 | [ 54 | { 55 | "role": "user", 56 | "content": "Implement a Python function to find the longest common subsequence of two input strings using dynamic programming.", 57 | } 58 | ], 59 | [{"role": "user", "content": "Implement a regular expression in Python to validate an email address."}], 60 | [ 61 | { 62 | "role": "user", 63 | "content": "Write a program to find the nth Fibonacci number using dynamic programming.", 64 | } 65 | ], 66 | [ 67 | { 68 | "role": "user", 69 | "content": "Implement a binary search algorithm to find a specific element in a sorted array.", 70 | } 71 | ], 72 | [{"role": "user", "content": "Implement a queue data structure using two stacks in Python."}], 73 | [ 74 | { 75 | "role": "user", 76 | "content": "Implement a program to find the common elements in two arrays without using any extra data structures.", 77 | } 78 | ], 79 | ] 80 | 81 | try: 82 | dialogue_template = DialogueTemplate.from_pretrained(args.model_id, revision=args.revision) 83 | except Exception: 84 | print("No dialogue template found in model repo. Defaulting to the `no_system` template.") 85 | dialogue_template = get_dialogue_template("no_system") 86 | 87 | if args.system_prompt is not None: 88 | dialogue_template.system = args.system_prompt 89 | formatted_prompts = [] 90 | for prompt in prompts: 91 | dialogue_template.messages = [prompt] if isinstance(prompt, dict) else prompt 92 | formatted_prompts.append(dialogue_template.get_inference_prompt()) 93 | 94 | print("=== SAMPLE PROMPT ===") 95 | print(formatted_prompts[0]) 96 | print("=====================") 97 | 98 | device = "cuda" if torch.cuda.is_available() else "cpu" 99 | tokenizer = AutoTokenizer.from_pretrained(args.model_id, revision=args.revision) 100 | print(f"Special tokens: {tokenizer.special_tokens_map}") 101 | print(f"EOS token ID for generation: {tokenizer.convert_tokens_to_ids(dialogue_template.end_token)}") 102 | generation_config = GenerationConfig( 103 | temperature=0.2, 104 | top_k=50, 105 | top_p=0.95, 106 | repetition_penalty=1.2, 107 | do_sample=True, 108 | pad_token_id=tokenizer.eos_token_id, 109 | eos_token_id=tokenizer.convert_tokens_to_ids(dialogue_template.end_token), 110 | min_new_tokens=32, 111 | max_new_tokens=256, 112 | ) 113 | model = AutoModelForCausalLM.from_pretrained( 114 | args.model_id, revision=args.revision, load_in_8bit=True, device_map="auto", torch_dtype=torch.float16 115 | ) 116 | outputs = "" 117 | for idx, prompt in enumerate(formatted_prompts): 118 | batch = tokenizer(prompt, return_tensors="pt", return_token_type_ids=False).to(device) 119 | generated_ids = model.generate(**batch, generation_config=generation_config) 120 | generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=False).lstrip() 121 | outputs += generated_text + "\n\n" 122 | print(f"=== EXAMPLE {idx} ===") 123 | print() 124 | print(generated_text) 125 | print() 126 | print("======================") 127 | print() 128 | 129 | raw_model_name = args.model_id.split("/")[-1] 130 | model_name = f"{raw_model_name}" 131 | if args.revision is not None: 132 | model_name += f"-{args.revision}" 133 | 134 | with open(f"data/samples-{model_name}.txt", "w", encoding="utf-8") as f: 135 | f.write(outputs) 136 | 137 | 138 | if __name__ == "__main__": 139 | main() 140 | -------------------------------------------------------------------------------- /chat/requirements.txt: -------------------------------------------------------------------------------- 1 | transformers>=4.28.1 2 | tokenizers>=0.13.3 3 | deepspeed==0.9.1 4 | datasets>=2.12.0 5 | accelerate>=0.18.0 6 | tensorboard -------------------------------------------------------------------------------- /chat/train.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | # Copyright 2023 The BigCode & HuggingFace Inc. teams. All rights reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | """ 17 | Script to instruction fine-tune causal language models on a Hub dataset 18 | 19 | Adapted from huggingface/transformers: https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_clm.py 20 | """ 21 | 22 | import logging 23 | import math 24 | import os 25 | import random 26 | import sys 27 | from itertools import chain 28 | 29 | import datasets 30 | import torch 31 | import transformers 32 | from config import DataArguments, ModelArguments, TrainingArguments 33 | from datasets import load_dataset 34 | from dialogues import get_dialogue_template, mask_user_labels, prepare_dialogue 35 | from transformers import (AutoModelForCausalLM, AutoTokenizer, Trainer, 36 | default_data_collator, set_seed) 37 | from transformers.testing_utils import CaptureLogger 38 | from transformers.trainer_utils import get_last_checkpoint 39 | from utils import StarChatArgumentParser, hf_login 40 | 41 | logger = logging.getLogger(__name__) 42 | 43 | 44 | def main(): 45 | parser = StarChatArgumentParser((ModelArguments, DataArguments, TrainingArguments)) 46 | if len(sys.argv) == 2 and sys.argv[1].endswith(".yaml"): 47 | # If we pass only one argument to the script and it's the path to a YAML file, 48 | # let's parse it to get our arguments. 49 | model_args, data_args, training_args = parser.parse_yaml_file(os.path.abspath(sys.argv[1])) 50 | # parse command line args and yaml file 51 | elif len(sys.argv) > 2 and sys.argv[1].endswith(".yaml"): 52 | model_args, data_args, training_args = parser.parse_yaml_and_args(os.path.abspath(sys.argv[1]), sys.argv[2:]) 53 | # parse command line args only 54 | else: 55 | model_args, data_args, training_args = parser.parse_args_into_dataclasses() 56 | 57 | # Set seed for reproducibility 58 | set_seed(training_args.seed) 59 | 60 | ############### 61 | # Setup logging 62 | ############### 63 | logging.basicConfig( 64 | format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 65 | datefmt="%Y-%m-%d %H:%M:%S", 66 | handlers=[logging.StreamHandler(sys.stdout)], 67 | ) 68 | log_level = training_args.get_process_log_level() 69 | logger.setLevel(log_level) 70 | datasets.utils.logging.set_verbosity(log_level) 71 | transformers.utils.logging.set_verbosity(log_level) 72 | transformers.utils.logging.enable_default_handler() 73 | transformers.utils.logging.enable_explicit_format() 74 | 75 | # Log on each process a small summary 76 | logger.warning( 77 | f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" 78 | + f" distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" 79 | ) 80 | logger.info(f"Model parameters {model_args}") 81 | logger.info(f"Data parameters {data_args}") 82 | logger.info(f"Training/evaluation parameters {training_args}") 83 | 84 | # Login to HuggingFace Hub if needed 85 | hf_login() 86 | 87 | ########################### 88 | # Detecting last checkpoint 89 | ########################### 90 | last_checkpoint = None 91 | if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: 92 | last_checkpoint = get_last_checkpoint(training_args.output_dir) 93 | if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: 94 | raise ValueError( 95 | f"Output directory ({training_args.output_dir}) already exists and is not empty. " 96 | "Use --overwrite_output_dir to overcome." 97 | ) 98 | elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: 99 | logger.info( 100 | f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " 101 | "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." 102 | ) 103 | 104 | ############### 105 | # Load datasets 106 | ############### 107 | raw_datasets = load_dataset(data_args.dataset_name) 108 | logger.info( 109 | f"Training on the following datasets and their proportions: {[split + ' : ' + str(dset.num_rows) for split, dset in raw_datasets.items()]}" 110 | ) 111 | with training_args.main_process_first(desc="Log a few random samples from the raw training set"): 112 | for index in random.sample(range(len(raw_datasets["train"])), 3): 113 | logger.info(f"Sample {index} of the raw training set:\n\n{raw_datasets['train'][index]['messages']}") 114 | 115 | ######################### 116 | # Apply dialogue template 117 | ######################### 118 | dialogue_template = get_dialogue_template(data_args.dialogue_template) 119 | logger.info(f"System prompt for dialogue template: {dialogue_template.system}") 120 | raw_datasets = raw_datasets.map(prepare_dialogue, fn_kwargs={"dialogue_template": dialogue_template}) 121 | 122 | ##################################### 123 | # Load tokenizer and process datasets 124 | ##################################### 125 | tokenizer = AutoTokenizer.from_pretrained( 126 | model_args.model_name_or_path, 127 | revision=model_args.model_revision, 128 | ) 129 | 130 | # Note that we must call `add_tokens` before adding any special tokens 131 | dialogue_tokens = dialogue_template.get_special_tokens() 132 | num_added_tokens = tokenizer.add_special_tokens({"additional_special_tokens": dialogue_tokens}) 133 | logger.info(f"Added {num_added_tokens} new tokens: {dialogue_tokens}") 134 | 135 | if training_args.do_train: 136 | column_names = list(raw_datasets["train"].features) 137 | else: 138 | column_names = list(raw_datasets["test"].features) 139 | text_column_name = "text" if "text" in column_names else column_names[0] 140 | 141 | with training_args.main_process_first(desc="Log a few random samples from the training set"): 142 | for index in random.sample(range(len(raw_datasets["train"])), 3): 143 | logger.info(f"Sample {index} of the raw training set:\n\n{raw_datasets['train'][index]['text']}") 144 | 145 | # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function 146 | tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base") 147 | 148 | def tokenize_function(examples): 149 | with CaptureLogger(tok_logger) as cl: 150 | output = tokenizer(examples[text_column_name], return_token_type_ids=False) 151 | # clm input could be much much longer than block_size 152 | if "Token indices sequence length is longer than the" in cl.out: 153 | tok_logger.warning( 154 | "^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits" 155 | " before being passed to the model." 156 | ) 157 | return output 158 | 159 | with training_args.main_process_first(desc="dataset map tokenization"): 160 | tokenized_datasets = raw_datasets.map( 161 | tokenize_function, 162 | batched=True, 163 | num_proc=data_args.preprocessing_num_workers, 164 | remove_columns=column_names, 165 | load_from_cache_file=not data_args.overwrite_cache, 166 | desc="Running tokenizer on dataset", 167 | ) 168 | 169 | ############################## 170 | # Concatenate and chunk corpus 171 | ############################## 172 | if data_args.block_size is None: 173 | block_size = tokenizer.model_max_length 174 | if block_size > 1024: 175 | logger.warning( 176 | "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" 177 | " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" 178 | " override this default with `--block_size xxx`." 179 | ) 180 | block_size = 1024 181 | else: 182 | if data_args.block_size > tokenizer.model_max_length: 183 | logger.warning( 184 | f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model" 185 | f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}." 186 | ) 187 | block_size = min(data_args.block_size, tokenizer.model_max_length) 188 | 189 | # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size. 190 | def group_texts(examples): 191 | # Concatenate all texts. 192 | concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()} 193 | total_length = len(concatenated_examples[list(examples.keys())[0]]) 194 | # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can 195 | # customize this part to your needs. 196 | if total_length >= block_size: 197 | total_length = (total_length // block_size) * block_size 198 | # Split by chunks of max_len. 199 | result = { 200 | k: [t[i : i + block_size] for i in range(0, total_length, block_size)] 201 | for k, t in concatenated_examples.items() 202 | } 203 | labels = result["input_ids"].copy() 204 | mask_user_labels(tokenizer, dialogue_template, labels) 205 | result["labels"] = labels 206 | return result 207 | 208 | # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder 209 | # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower 210 | # to preprocess. 211 | with training_args.main_process_first(desc="grouping texts together"): 212 | lm_datasets = tokenized_datasets.map( 213 | group_texts, 214 | batched=True, 215 | num_proc=data_args.preprocessing_num_workers, 216 | load_from_cache_file=not data_args.overwrite_cache, 217 | desc=f"Grouping texts in chunks of {block_size}", 218 | ) 219 | 220 | if training_args.do_train: 221 | if "train" not in tokenized_datasets: 222 | raise ValueError("--do_train requires a train dataset") 223 | train_dataset = lm_datasets["train"] 224 | if data_args.max_train_samples is not None: 225 | max_train_samples = min(len(train_dataset), data_args.max_train_samples) 226 | train_dataset = train_dataset.select(range(max_train_samples)) 227 | 228 | if training_args.do_eval: 229 | if "test" not in tokenized_datasets: 230 | raise ValueError("--do_eval requires a validation dataset") 231 | eval_dataset = lm_datasets["test"] 232 | if data_args.max_eval_samples is not None: 233 | max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) 234 | eval_dataset = eval_dataset.select(range(max_eval_samples)) 235 | 236 | ####################### 237 | # Load pretrained model 238 | ####################### 239 | logger.info("*** Load pretrained model ***") 240 | torch_dtype = ( 241 | model_args.torch_dtype if model_args.torch_dtype in ["auto", None] else getattr(torch, model_args.torch_dtype) 242 | ) 243 | model = AutoModelForCausalLM.from_pretrained( 244 | model_args.model_name_or_path, 245 | revision=model_args.model_revision, 246 | torch_dtype=torch_dtype, 247 | use_cache=False if training_args.gradient_checkpointing else True, 248 | ) 249 | model.resize_token_embeddings(len(tokenizer)) 250 | 251 | ######################## 252 | # Initialize the Trainer 253 | ######################## 254 | trainer = Trainer( 255 | model=model, 256 | args=training_args, 257 | train_dataset=train_dataset if training_args.do_train else None, 258 | eval_dataset=eval_dataset if training_args.do_eval else None, 259 | tokenizer=tokenizer, 260 | # Data collator defaults to DataCollatorWithPadding, so we change it 261 | # since we've already chunked our corpus 262 | data_collator=default_data_collator, 263 | ) 264 | 265 | ############### 266 | # Training loop 267 | ############### 268 | if training_args.do_train: 269 | logger.info("*** Train ***") 270 | checkpoint = None 271 | if training_args.resume_from_checkpoint is not None: 272 | checkpoint = training_args.resume_from_checkpoint 273 | elif last_checkpoint is not None: 274 | checkpoint = last_checkpoint 275 | train_result = trainer.train(resume_from_checkpoint=checkpoint) 276 | 277 | metrics = train_result.metrics 278 | 279 | max_train_samples = ( 280 | data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) 281 | ) 282 | metrics["train_samples"] = min(max_train_samples, len(train_dataset)) 283 | 284 | trainer.log_metrics("train", metrics) 285 | trainer.save_metrics("train", metrics) 286 | trainer.save_state() 287 | 288 | ########## 289 | # Evaluate 290 | ########## 291 | if training_args.do_eval: 292 | logger.info("*** Evaluate ***") 293 | 294 | metrics = trainer.evaluate() 295 | 296 | max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) 297 | metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) 298 | try: 299 | perplexity = math.exp(metrics["eval_loss"]) 300 | except OverflowError: 301 | perplexity = float("inf") 302 | metrics["perplexity"] = perplexity 303 | 304 | trainer.log_metrics("eval", metrics) 305 | trainer.save_metrics("eval", metrics) 306 | 307 | ################################# 308 | # Create model card & push to Hub 309 | ################################# 310 | kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"} 311 | if data_args.dataset_name is not None: 312 | kwargs["dataset_tags"] = data_args.dataset_name 313 | if data_args.dataset_config_name is not None: 314 | kwargs["dataset_args"] = data_args.dataset_config_name 315 | kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" 316 | else: 317 | kwargs["dataset"] = data_args.dataset_name 318 | kwargs["dataset_args"] = "default" 319 | 320 | # Store dialogue template so we can load it at deployment time 321 | dialogue_template.save_pretrained(training_args.output_dir) 322 | 323 | if training_args.push_to_hub: 324 | trainer.push_to_hub(**kwargs) 325 | else: 326 | trainer.save_model(training_args.output_dir) 327 | trainer.create_model_card(**kwargs) 328 | 329 | with training_args.main_process_first(desc="Generate a sample from the model"): 330 | inputs = tokenizer( 331 | "<|system|>\n<|end|>\n<|user|>\nHow many helicopters can a human eat in one sitting?<|end|>\n<|assistant|>", 332 | return_tensors="pt", 333 | return_token_type_ids=False, 334 | ).to(training_args.device) 335 | outputs = model.generate( 336 | **inputs, 337 | max_new_tokens=256, 338 | pad_token_id=tokenizer.eos_token_id, 339 | eos_token_id=tokenizer.convert_tokens_to_ids(dialogue_template.end_token), 340 | ) 341 | logger.info(f"=== SAMPLE OUTPUT ==\n\n{tokenizer.decode(outputs[0], skip_special_tokens=False)}") 342 | 343 | 344 | if __name__ == "__main__": 345 | main() 346 | -------------------------------------------------------------------------------- /chat/utils.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2023 The HuggingFace 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 | import dataclasses 17 | import os 18 | from dataclasses import dataclass 19 | from typing import List, Optional 20 | 21 | from huggingface_hub import login 22 | from transformers import HfArgumentParser 23 | 24 | 25 | class StarChatArgumentParser(HfArgumentParser): 26 | def parse_yaml_and_args(self, yaml_arg: str, other_args: Optional[List[str]] = None) -> List[dataclass]: 27 | arg_list = self.parse_yaml_file(os.path.abspath(yaml_arg)) 28 | 29 | outputs = [] 30 | # strip other args list into dict of key-value pairs 31 | other_args = {arg.split("=")[0].strip("-"): arg.split("=")[1] for arg in other_args} 32 | used_args = {} 33 | 34 | # overwrite the default/loaded value with the value provided to the command line 35 | # adapted from https://github.com/huggingface/transformers/blob/d0b5002378daabf62769159add3e7d66d3f83c3b/src/transformers/hf_argparser.py#L327 36 | for data_yaml, data_class in zip(arg_list, self.dataclass_types): 37 | keys = {f.name for f in dataclasses.fields(data_yaml) if f.init} 38 | inputs = {k: v for k, v in vars(data_yaml).items() if k in keys} 39 | for arg, val in other_args.items(): 40 | # add only if in keys 41 | if arg in keys: 42 | base_type = data_yaml.__dataclass_fields__[arg].type 43 | inputs[arg] = val 44 | 45 | # cast type for ints, floats, and bools (default to strings) 46 | if base_type in [int, float, bool]: 47 | inputs[arg] = base_type(val) 48 | 49 | # add to used-args so we can check if double add 50 | if arg not in used_args: 51 | used_args[arg] = val 52 | else: 53 | raise ValueError(f"Duplicate argument provided: {arg}, may cause unexpected behavior") 54 | 55 | obj = data_class(**inputs) 56 | outputs.append(obj) 57 | 58 | return outputs 59 | 60 | 61 | def hf_login(): 62 | """Login to HuggingFace Hub if HF_TOKEN is defined in the environment""" 63 | hf_token = os.getenv("HF_TOKEN") 64 | if hf_token is not None: 65 | login(token=hf_token) 66 | -------------------------------------------------------------------------------- /finetune/finetune.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | 4 | import torch 5 | from accelerate import Accelerator 6 | from datasets import load_dataset 7 | from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training, set_peft_model_state_dict 8 | from torch.utils.data import IterableDataset 9 | from tqdm import tqdm 10 | from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments, logging, set_seed 11 | from transformers import TrainerCallback, TrainingArguments, TrainerState, TrainerControl 12 | from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR 13 | 14 | """ 15 | Fine-Tune StarCoder on Code Alpaca/SE 16 | """ 17 | 18 | class SavePeftModelCallback(TrainerCallback): 19 | def on_save( 20 | self, 21 | args: TrainingArguments, 22 | state: TrainerState, 23 | control: TrainerControl, 24 | **kwargs, 25 | ): 26 | checkpoint_folder = os.path.join(args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}") 27 | 28 | kwargs["model"].save_pretrained(checkpoint_folder) 29 | 30 | pytorch_model_path = os.path.join(checkpoint_folder, "pytorch_model.bin") 31 | torch.save({}, pytorch_model_path) 32 | return control 33 | 34 | 35 | class LoadBestPeftModelCallback(TrainerCallback): 36 | def on_train_end( 37 | self, 38 | args: TrainingArguments, 39 | state: TrainerState, 40 | control: TrainerControl, 41 | **kwargs, 42 | ): 43 | print(f"Loading best peft model from {state.best_model_checkpoint} (score: {state.best_metric}).") 44 | best_model_path = os.path.join(state.best_model_checkpoint, "adapter_model.bin") 45 | adapters_weights = torch.load(best_model_path) 46 | model = kwargs["model"] 47 | set_peft_model_state_dict(model, adapters_weights) 48 | return control 49 | 50 | 51 | def get_args(): 52 | parser = argparse.ArgumentParser() 53 | parser.add_argument("--model_path", type=str, default="bigcode/large-model") 54 | parser.add_argument("--dataset_name", type=str, default="HuggingFaceH4/CodeAlpaca_20K") 55 | parser.add_argument("--subset", type=str) 56 | parser.add_argument("--split", type=str) 57 | parser.add_argument("--size_valid_set", type=int, default=10000) 58 | parser.add_argument("--streaming", action="store_true") 59 | parser.add_argument("--shuffle_buffer", type=int, default=5000) 60 | 61 | parser.add_argument("--input_column_name", type=str, default="prompt") 62 | parser.add_argument("--output_column_name", type=str, default="completion") 63 | 64 | parser.add_argument("--seq_length", type=int, default=2048) 65 | parser.add_argument("--max_steps", type=int, default=10000) 66 | parser.add_argument("--batch_size", type=int, default=1) 67 | parser.add_argument("--gradient_accumulation_steps", type=int, default=16) 68 | parser.add_argument("--eos_token_id", type=int, default=49152) 69 | 70 | parser.add_argument("--lora_r", type=int, default=16) 71 | parser.add_argument("--lora_alpha", type=int, default=32) 72 | parser.add_argument("--lora_dropout", type=float, default=0.05) 73 | 74 | parser.add_argument("--learning_rate", type=float, default=5e-6) 75 | parser.add_argument("--lr_scheduler_type", type=str, default="cosine") 76 | parser.add_argument("--num_warmup_steps", type=int, default=100) 77 | parser.add_argument("--weight_decay", type=float, default=0.05) 78 | 79 | parser.add_argument("--local_rank", type=int, default=0) 80 | parser.add_argument("--no_fp16", action="store_false") 81 | parser.add_argument("--bf16", action="store_true", default=True) 82 | parser.add_argument("--no_gradient_checkpointing", action="store_false", default=False) 83 | parser.add_argument("--seed", type=int, default=0) 84 | parser.add_argument("--num_workers", type=int, default=None) 85 | parser.add_argument("--output_dir", type=str, default="./checkpoints") 86 | parser.add_argument("--log_freq", default=100, type=int) 87 | parser.add_argument("--eval_freq", default=100, type=int) 88 | parser.add_argument("--save_freq", default=1000, type=int) 89 | 90 | return parser.parse_args() 91 | 92 | 93 | def chars_token_ratio(dataset, tokenizer, input_column_name="prompt", output_column_name="completion", nb_examples=400): 94 | """ 95 | Estimate the average number of characters per token in the dataset. 96 | """ 97 | total_characters, total_tokens = 0, 0 98 | for _, example in tqdm(zip(range(nb_examples), iter(dataset)), total=nb_examples): 99 | text = prepare_sample_text(example, input_column_name, output_column_name) 100 | total_characters += len(text) 101 | if tokenizer.is_fast: 102 | total_tokens += len(tokenizer(text).tokens()) 103 | else: 104 | total_tokens += len(tokenizer.tokenize(text)) 105 | 106 | return total_characters / total_tokens 107 | 108 | 109 | def print_trainable_parameters(model): 110 | """ 111 | Prints the number of trainable parameters in the model. 112 | """ 113 | trainable_params = 0 114 | all_param = 0 115 | for _, param in model.named_parameters(): 116 | all_param += param.numel() 117 | if param.requires_grad: 118 | trainable_params += param.numel() 119 | print( 120 | f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}" 121 | ) 122 | 123 | 124 | def prepare_sample_text(example, input_column_name="prompt", output_column_name="completion"): 125 | """Prepare the text from a sample of the dataset.""" 126 | text = f"Question: {example[input_column_name]}\n\nAnswer: {example[output_column_name]}" 127 | return text 128 | 129 | 130 | class ConstantLengthDataset(IterableDataset): 131 | """ 132 | Iterable dataset that returns constant length chunks of tokens from stream of text files. 133 | Args: 134 | tokenizer (Tokenizer): The processor used for proccessing the data. 135 | dataset (dataset.Dataset): Dataset with text files. 136 | infinite (bool): If True the iterator is reset after dataset reaches end else stops. 137 | seq_length (int): Length of token sequences to return. 138 | num_of_sequences (int): Number of token sequences to keep in buffer. 139 | chars_per_token (int): Number of characters per token used to estimate number of tokens in text buffer. 140 | """ 141 | 142 | def __init__( 143 | self, 144 | tokenizer, 145 | dataset, 146 | infinite=False, 147 | seq_length=1024, 148 | num_of_sequences=1024, 149 | chars_per_token=3.6, 150 | input_column_name="prompt", 151 | output_column_name="completion" 152 | ): 153 | self.tokenizer = tokenizer 154 | self.concat_token_id = tokenizer.eos_token_id if tokenizer.eos_token_id is not None else args.eos_token_id 155 | self.dataset = dataset 156 | self.seq_length = seq_length 157 | self.infinite = infinite 158 | self.current_size = 0 159 | self.max_buffer_size = seq_length * chars_per_token * num_of_sequences 160 | self.input_column_name = input_column_name 161 | self.output_column_name = output_column_name 162 | 163 | def __iter__(self): 164 | iterator = iter(self.dataset) 165 | more_examples = True 166 | while more_examples: 167 | buffer, buffer_len = [], 0 168 | while True: 169 | if buffer_len >= self.max_buffer_size: 170 | break 171 | try: 172 | buffer.append(prepare_sample_text(next(iterator), self.input_column_name, self.output_column_name)) 173 | buffer_len += len(buffer[-1]) 174 | except StopIteration: 175 | if self.infinite: 176 | iterator = iter(self.dataset) 177 | else: 178 | more_examples = False 179 | break 180 | tokenized_inputs = self.tokenizer(buffer, truncation=False)["input_ids"] 181 | all_token_ids = [] 182 | for tokenized_input in tokenized_inputs: 183 | all_token_ids.extend(tokenized_input + [self.concat_token_id]) 184 | for i in range(0, len(all_token_ids), self.seq_length): 185 | input_ids = all_token_ids[i : i + self.seq_length] 186 | if len(input_ids) == self.seq_length: 187 | self.current_size += 1 188 | yield { 189 | "input_ids": torch.LongTensor(input_ids), 190 | "labels": torch.LongTensor(input_ids), 191 | } 192 | 193 | 194 | def create_datasets(tokenizer, args): 195 | dataset = load_dataset( 196 | args.dataset_name, 197 | data_dir=args.subset, 198 | split=args.split, 199 | use_auth_token=True, 200 | num_proc=args.num_workers if not args.streaming else None, 201 | streaming=args.streaming, 202 | ) 203 | if args.streaming: 204 | print("Loading the dataset in streaming mode") 205 | valid_data = dataset.take(args.size_valid_set) 206 | train_data = dataset.skip(args.size_valid_set) 207 | train_data = train_data.shuffle(buffer_size=args.shuffle_buffer, seed=args.seed) 208 | else: 209 | train_data = dataset["train"] 210 | valid_data = dataset["test"] 211 | print(f"Size of the train set: {len(train_data)}. Size of the validation set: {len(valid_data)}") 212 | 213 | chars_per_token = chars_token_ratio(train_data, tokenizer, args.input_column_name, args.output_column_name) 214 | print(f"The character to token ratio of the dataset is: {chars_per_token:.2f}") 215 | 216 | train_dataset = ConstantLengthDataset( 217 | tokenizer, 218 | train_data, 219 | infinite=True, 220 | seq_length=args.seq_length, 221 | chars_per_token=chars_per_token, 222 | input_column_name=args.input_column_name, 223 | output_column_name=args.output_column_name 224 | ) 225 | valid_dataset = ConstantLengthDataset( 226 | tokenizer, 227 | valid_data, 228 | infinite=False, 229 | seq_length=args.seq_length, 230 | chars_per_token=chars_per_token, 231 | input_column_name=args.input_column_name, 232 | output_column_name=args.output_column_name 233 | ) 234 | return train_dataset, valid_dataset 235 | 236 | 237 | def run_training(args, train_data, val_data): 238 | print("Loading the model") 239 | # disable caching mechanism when using gradient checkpointing 240 | model = AutoModelForCausalLM.from_pretrained( 241 | args.model_path, 242 | use_auth_token=True, 243 | use_cache=not args.no_gradient_checkpointing, 244 | load_in_8bit=True, 245 | device_map={"": Accelerator().process_index}, 246 | ) 247 | model = prepare_model_for_int8_training(model) 248 | 249 | lora_config = LoraConfig( 250 | r=args.lora_r, 251 | lora_alpha=args.lora_alpha, 252 | lora_dropout=args.lora_dropout, 253 | bias="none", 254 | task_type="CAUSAL_LM", 255 | target_modules = ["c_proj", "c_attn", "q_attn"] 256 | ) 257 | 258 | model = get_peft_model(model, lora_config) 259 | 260 | print_trainable_parameters(model) 261 | 262 | train_data.start_iteration = 0 263 | 264 | print("Starting main loop") 265 | 266 | training_args = TrainingArguments( 267 | output_dir=args.output_dir, 268 | dataloader_drop_last=True, 269 | evaluation_strategy="steps", 270 | save_strategy="steps", 271 | load_best_model_at_end=True, 272 | max_steps=args.max_steps, 273 | eval_steps=args.eval_freq, 274 | save_steps=args.save_freq, 275 | logging_steps=args.log_freq, 276 | per_device_train_batch_size=args.batch_size, 277 | per_device_eval_batch_size=args.batch_size, 278 | learning_rate=args.learning_rate, 279 | lr_scheduler_type=args.lr_scheduler_type, 280 | warmup_steps=args.num_warmup_steps, 281 | gradient_accumulation_steps=args.gradient_accumulation_steps, 282 | gradient_checkpointing=not args.no_gradient_checkpointing, 283 | fp16=not args.no_fp16, 284 | bf16=args.bf16, 285 | weight_decay=args.weight_decay, 286 | run_name="StarCoder-finetuned", 287 | report_to="wandb", 288 | ddp_find_unused_parameters=False, 289 | ) 290 | 291 | trainer = Trainer(model=model, args=training_args, train_dataset=train_data, eval_dataset=val_data, callbacks=[SavePeftModelCallback, LoadBestPeftModelCallback]) 292 | 293 | print("Training...") 294 | trainer.train() 295 | 296 | print("Saving last checkpoint of the model") 297 | model.save_pretrained(os.path.join(args.output_dir, "final_checkpoint/")) 298 | 299 | 300 | def main(args): 301 | tokenizer = AutoTokenizer.from_pretrained(args.model_path, use_auth_token=True) 302 | train_dataset, eval_dataset = create_datasets(tokenizer, args) 303 | run_training(args, train_dataset, eval_dataset) 304 | 305 | 306 | if __name__ == "__main__": 307 | args = get_args() 308 | 309 | set_seed(args.seed) 310 | os.makedirs(args.output_dir, exist_ok=True) 311 | 312 | logging.set_verbosity_error() 313 | 314 | main(args) 315 | -------------------------------------------------------------------------------- /finetune/merge_peft_adapters.py: -------------------------------------------------------------------------------- 1 | from transformers import AutoModelForCausalLM, AutoTokenizer 2 | from peft import PeftModel 3 | import torch 4 | 5 | import os 6 | import argparse 7 | 8 | def get_args(): 9 | parser = argparse.ArgumentParser() 10 | parser.add_argument("--base_model_name_or_path", type=str, default="bigcode/large-model") 11 | parser.add_argument("--peft_model_path", type=str, default="/") 12 | parser.add_argument("--push_to_hub", action="store_true", default=True) 13 | 14 | return parser.parse_args() 15 | 16 | def main(): 17 | args = get_args() 18 | 19 | base_model = AutoModelForCausalLM.from_pretrained( 20 | args.base_model_name_or_path, 21 | return_dict=True, 22 | torch_dtype=torch.float16 23 | ) 24 | 25 | model = PeftModel.from_pretrained(base_model, args.peft_model_path) 26 | model = model.merge_and_unload() 27 | 28 | tokenizer = AutoTokenizer.from_pretrained(args.base_model_name_or_path) 29 | 30 | if args.push_to_hub: 31 | print(f"Saving to hub ...") 32 | model.push_to_hub(f"{args.base_model_name_or_path}-merged", use_temp_dir=False, private=True) 33 | tokenizer.push_to_hub(f"{args.base_model_name_or_path}-merged", use_temp_dir=False, private=True) 34 | else: 35 | model.save_pretrained(f"{args.base_model_name_or_path}-merged") 36 | tokenizer.save_pretrained(f"{args.base_model_name_or_path}-merged") 37 | print(f"Model saved to {args.base_model_name_or_path}-merged") 38 | 39 | if __name__ == "__main__" : 40 | main() 41 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | tqdm==4.65.0 2 | transformers==4.28.1 3 | datasets==2.11.0 4 | huggingface-hub==0.13.4 5 | accelerate==0.18.0 6 | --------------------------------------------------------------------------------