From 33c72145b98a166b503ceaaaa513d8f342801e79 Mon Sep 17 00:00:00 2001 From: ArmelRandy <76953833+ArmelRandy@users.noreply.github.com> Date: Fri, 5 May 2023 08:50:27 +0200 Subject: [PATCH 01/20] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7ca4eaf..973b5b5 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,7 @@ python finetune/finetune.py \ --weight_decay 0.05\ --output_dir="./checkpoints" \ ``` -The command is quite similar to the what we use on alpaca code. However, 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 +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 ```bash python -m torch.distributed.launch \ From ecd9a954eb8e1b5db0d411161590f74df00619de Mon Sep 17 00:00:00 2001 From: ArmelRandy <76953833+ArmelRandy@users.noreply.github.com> Date: Fri, 5 May 2023 11:17:23 +0200 Subject: [PATCH 02/20] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 973b5b5..9c4ced1 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,10 @@ # What is this about? 💫 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. +# Disclaimer + +Before you can use the model go to `hf.co/bigcode/starcoder` and accept the agreement and then use + # Table of Contents 1. [Quickstart](#quickstart) - [Installation](#installation) From 89c6c4280eb70a50347833c2ca8766a1a29a1d4c Mon Sep 17 00:00:00 2001 From: ArmelRandy Date: Fri, 5 May 2023 09:33:52 +0000 Subject: [PATCH 03/20] use authentification token when loading the model --- finetune/finetune.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/finetune/finetune.py b/finetune/finetune.py index 005b1bc..96ab961 100644 --- a/finetune/finetune.py +++ b/finetune/finetune.py @@ -239,7 +239,7 @@ def run_training(args, train_data, val_data): # disable caching mechanism when using gradient checkpointing model = AutoModelForCausalLM.from_pretrained( args.model_path, - trust_remote_code=True, + use_auth_token=True, use_cache=not args.no_gradient_checkpointing, load_in_8bit=True, device_map={"": Accelerator().process_index}, From 3839ae4b1fc443105d6e474c4db6aa1f9c76c8f6 Mon Sep 17 00:00:00 2001 From: ArmelRandy <76953833+ArmelRandy@users.noreply.github.com> Date: Fri, 5 May 2023 11:52:42 +0200 Subject: [PATCH 04/20] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c4ced1..98c66ff 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ # Disclaimer -Before you can use the model go to `hf.co/bigcode/starcoder` and accept the agreement and then use +Before you can use the model go to `hf.co/bigcode/starcoder` and accept the agreement. # Table of Contents 1. [Quickstart](#quickstart) From 97b2881c93c12c0a7caf6378146a8f979afdd7d7 Mon Sep 17 00:00:00 2001 From: Loubna Ben Allal <44069155+loubnabnl@users.noreply.github.com> Date: Sat, 6 May 2023 11:17:27 +0200 Subject: [PATCH 05/20] Update README.md - specify need to log to HF hub in disclaimer - mention use of fp16/bf16 to save memory when loading model - remove `trust_remote_code` when loading model --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 98c66ff..823f9d1 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,10 @@ # Disclaimer -Before you can use the model go to `hf.co/bigcode/starcoder` and accept the agreement. +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: +```bash +huggingface-cli login +``` # Table of Contents 1. [Quickstart](#quickstart) @@ -36,7 +39,8 @@ checkpoint = "bigcode/starcoder" device = "cuda" # for GPU usage or "cpu" for CPU usage tokenizer = AutoTokenizer.from_pretrained(checkpoint) -model = AutoModelForCausalLM.from_pretrained(checkpoint, trust_remote_code=True).to(device) +# to save memory consider using fp16 or bf16 by specifying torch.dtype=torch.float16 for example +model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device) inputs = tokenizer.encode("def print_hello_world():", return_tensors="pt").to(device) outputs = model.generate(inputs) From 80b46b1afbfd73a566d00879e046484be85bb6db Mon Sep 17 00:00:00 2001 From: Ikko Eltociear Ashimine Date: Sun, 7 May 2023 00:04:25 +0900 Subject: [PATCH 06/20] Update README.md github -> GitHub --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 98c66ff..87f0836 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # 💫 StarCoder # What is this about? -💫 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. +💫 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. # Disclaimer @@ -19,7 +19,7 @@ Before you can use the model go to `hf.co/bigcode/starcoder` and accept the agre - [Merging PEFT adapter layers](#merging-peft-adapter-layers) # Quickstart -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. +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. ## Installation First, we have to install all the libraries listed in `requirements.txt` From 6bc2a38ae7927e90760ce6a3c372f08a4383fde3 Mon Sep 17 00:00:00 2001 From: ArmelRandy <76953833+ArmelRandy@users.noreply.github.com> Date: Sun, 7 May 2023 10:33:13 +0200 Subject: [PATCH 07/20] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 98c66ff..9239491 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ checkpoint = "bigcode/starcoder" device = "cuda" # for GPU usage or "cpu" for CPU usage tokenizer = AutoTokenizer.from_pretrained(checkpoint) -model = AutoModelForCausalLM.from_pretrained(checkpoint, trust_remote_code=True).to(device) +model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device) inputs = tokenizer.encode("def print_hello_world():", return_tensors="pt").to(device) outputs = model.generate(inputs) @@ -45,10 +45,10 @@ print(tokenizer.decode(outputs[0])) or ```python from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline -model_ckpt = "bigcode/starcoder" +checkpoint = "bigcode/starcoder" -model = AutoModelForCausalLM.from_pretrained(model_ckpt) -tokenizer = AutoTokenizer.from_pretrained(model_ckpt) +model = AutoModelForCausalLM.from_pretrained(checkpoint) +tokenizer = AutoTokenizer.from_pretrained(checkpoint) pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0) print( pipe("def hello():") ) From 84fac591a9799067c5bb996e7407ae4a4cd88db5 Mon Sep 17 00:00:00 2001 From: Leandro von Werra Date: Sun, 7 May 2023 16:16:50 +0200 Subject: [PATCH 08/20] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 9239491..eba962c 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # 💫 StarCoder +[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/chat/?model=bigcode/starcoder) + # What is this about? 💫 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. From 54ba27e209a3d6ebf75387e9502d22dcec78e6fe Mon Sep 17 00:00:00 2001 From: lewtun Date: Tue, 9 May 2023 18:02:12 +0200 Subject: [PATCH 09/20] Add example to fine-tune StarCoder for chat-based applications (#17) * Add StarChat files * Clean up * Fix readme * Tweak * Clean up * Final polish * Fix steps * Final tweaks * Delete dead code * Fix typo --- .gitignore | 163 ++++++++++++++ README.md | 4 + chat/README.md | 111 ++++++++++ chat/config.py | 121 ++++++++++ chat/config.yaml | 42 ++++ chat/deepspeed_z3_config_bf16.json | 40 ++++ chat/dialogues.py | 241 ++++++++++++++++++++ chat/generate.py | 139 ++++++++++++ chat/requirements.txt | 6 + chat/train.py | 345 +++++++++++++++++++++++++++++ chat/utils.py | 65 ++++++ 11 files changed, 1277 insertions(+) create mode 100644 .gitignore create mode 100644 chat/README.md create mode 100644 chat/config.py create mode 100644 chat/config.yaml create mode 100644 chat/deepspeed_z3_config_bf16.json create mode 100644 chat/dialogues.py create mode 100644 chat/generate.py create mode 100644 chat/requirements.txt create mode 100644 chat/train.py create mode 100644 chat/utils.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..497d87e --- /dev/null +++ b/.gitignore @@ -0,0 +1,163 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +data/ +wandb/ \ No newline at end of file diff --git a/README.md b/README.md index dfdc8d0..fc0f85b 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,10 @@ # What is this about? 💫 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. +# News + +* **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). + # Disclaimer 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: diff --git a/chat/README.md b/chat/README.md new file mode 100644 index 0000000..8a0aedb --- /dev/null +++ b/chat/README.md @@ -0,0 +1,111 @@ +# Fine-tuning StarCoder for chat-based applications + +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: + +``` +Draw me a map of the world using geopandas. Make it so that only Germany and Spain are colored red. +``` + +the model will produce: + +```python +import pandas as pd +from matplotlib import pyplot as plt +import geopandas as gpd +from shapely.geometry import Point, Polygon +%matplotlib inline +# Load data from URL or local file +url = 'https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson' +df = gpd.read_file(url) + +# Create plot +fig, ax = plt.subplots() +ax.set_aspect('equal') +world = gpd.GeoDataFrame({'name': ['World'], + 'geometry': [Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])]}) +germany = df[df['ADMIN'] == "Germany"] +spain = df[df['ADMIN'] == "Spain"] +other = df[(df['ADMIN']!= "Germany") & (df['ADMIN']!= "Spain")] +world.plot(color='lightgrey', edgecolor='white', ax=ax) +germany.plot(color="red", ax=ax) +spain.plot(color="red", ax=ax) +other.plot(color="skyblue", ax=ax) +plt.title("European Countries") +plt.show() +``` + +Check out our [blog post](https://huggingface.co/blog/starchat-alpha) for more details. + +## Getting started + +To run the `train.py` script, first create a Python virtual environment using e.g. Conda: + +```shell +conda create -n chat python=3.10 && conda activate chat +``` + +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: + +```shell +pip install -r requirements.txt +``` + +You'll also need to be logged into both your Hugging Face account. To do so, run: + +```shell +huggingface-cli login +``` + +Finally, install Git LFS with: + +```shell +sudo apt-get install git-lfs +``` + +## Prepare your dataset + +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: + +```json +{ + "messages": [ + { + "content": "Is it possible to imagine a society without law?", + "role": "user"}, + { + "content": "It is difficult to imagine a society that is able to be maintained without any semblance of Law.", + "role": "assistant", + }, + { + "content": "It seems like you consider the absence of law equal to the absence of anything that could guide the behaviour of the individual.", + "role": "user", + }, + { + "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.", + "role": "assistant", + } + ] +} +``` + +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. + +## Launch training + +We use DeepSpeed ZeRO-3 to shard the model and optimizer across 8 x A100 (80GB) GPUs. To fine-tune run: + +``` +TRANSFORMERS_VERBOSITY=info torchrun --nproc_per_node=8 train.py config.yaml --deepspeed=deepspeed_z3_config_bf16.json +``` + +By default, this will save the model checkpoint in the `data/` directory and also push it to the Hugging Face Hub. + + +## Generate samples + +To generate a few coding examples from your model, run: + +```shell +python generate.py --model_id path/to/your/model +``` + diff --git a/chat/config.py b/chat/config.py new file mode 100644 index 0000000..fcdc569 --- /dev/null +++ b/chat/config.py @@ -0,0 +1,121 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass, field +from typing import List, Optional + +import transformers +from transformers import MODEL_FOR_CAUSAL_LM_MAPPING + +MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys()) +MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch. + """ + + model_name_or_path: Optional[str] = field( + default=None, + metadata={ + "help": ( + "The model checkpoint for weights initialization. Don't set if you want to train a model from scratch." + ) + }, + ) + model_revision: str = field( + default="main", + metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, + ) + torch_dtype: Optional[str] = field( + default=None, + metadata={ + "help": ( + "Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the " + "dtype will be automatically derived from the model's weights." + ), + "choices": ["auto", "bfloat16", "float16", "float32"], + }, + ) + use_fast_tokenizer: bool = field( + default=True, + metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, + ) + + +@dataclass +class DataArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + """ + + dataset_name: Optional[str] = field( + default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} + ) + max_train_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of training examples to this " + "value if set." + ) + }, + ) + max_eval_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of evaluation examples to this " + "value if set." + ) + }, + ) + block_size: Optional[int] = field( + default=None, + metadata={ + "help": ( + "Optional input sequence length after tokenization. " + "The training dataset will be truncated in block of this size for training. " + "Default to the model max input length for single sentence inputs (take into account special tokens)." + ) + }, + ) + overwrite_cache: bool = field( + default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} + ) + preprocessing_num_workers: Optional[int] = field( + default=None, + metadata={"help": "The number of processes to use for the preprocessing."}, + ) + dialogue_template: Optional[str] = field( + default="no_system", + metadata={ + "help": "The name of the dialogue template to use for conditioning the model. See h4.training.dialogues for choices." + }, + ) + + +@dataclass +class TrainingArguments(transformers.TrainingArguments): + """ + 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 + """ + + logging_first_step: Optional[bool] = field( + default=True, + metadata={"help": ("Whether to log and evaluate the first global_step or not.")}, + ) + optim: Optional[str] = field(default="adamw_torch") diff --git a/chat/config.yaml b/chat/config.yaml new file mode 100644 index 0000000..141565c --- /dev/null +++ b/chat/config.yaml @@ -0,0 +1,42 @@ +# Model arguments +model_name_or_path: bigcode/starcoderbase + +# Data training arguments +block_size: 1024 +dataset_name: HuggingFaceH4/oasst1_en +dialogue_template: no_system +preprocessing_num_workers: 12 + +# Training arguments with sensible defaults +# Add other options from here: https://huggingface.co/docs/transformers/v4.26.1/en/main_classes/trainer#transformers.TrainingArguments +bf16: true # Gives ~2x speed up in training time, but disable if you start seeing NaNs +do_eval: true +do_train: true +evaluation_strategy: epoch # One of ["no", "steps", "epoch"] +gradient_accumulation_steps: 8 +gradient_checkpointing: true +hub_model_id: lewtun/starchat-alpha +hub_private_repo: true +hub_strategy: every_save +learning_rate: 2.0e-05 +log_level: passive +logging_steps: 8 +logging_strategy: steps +lr_scheduler_type: cosine +max_steps: -1 +num_train_epochs: 3 +output_dir: data/starchat-alpha +overwrite_output_dir: true +per_device_eval_batch_size: 4 +per_device_train_batch_size: 4 +push_to_hub: true +remove_unused_columns: true +report_to: +- tensorboard +save_steps: 500 +save_strategy: steps +save_total_limit: null +seed: 42 +tf32: true +warmup_ratio: 0.03 +weight_decay: 0. \ No newline at end of file diff --git a/chat/deepspeed_z3_config_bf16.json b/chat/deepspeed_z3_config_bf16.json new file mode 100644 index 0000000..d067c66 --- /dev/null +++ b/chat/deepspeed_z3_config_bf16.json @@ -0,0 +1,40 @@ +{ + "bf16": { + "enabled": "auto" + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "betas": "auto", + "eps": "auto", + "weight_decay": "auto" + } + }, + "scheduler": { + "type": "WarmupLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto" + } + }, + "zero_optimization": { + "stage": 3, + "overlap_comm": true, + "contiguous_gradients": true, + "sub_group_size": 1e9, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": true + }, + "gradient_accumulation_steps": "auto", + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} \ No newline at end of file diff --git a/chat/dialogues.py b/chat/dialogues.py new file mode 100644 index 0000000..634c4a1 --- /dev/null +++ b/chat/dialogues.py @@ -0,0 +1,241 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional, Type, TypeVar, Union + +from huggingface_hub import ModelHubMixin, hf_hub_download + +# Generic variable that is either ModelHubMixin or a subclass thereof +T = TypeVar("T", bound="ModelHubMixin") + +TEMPLATE_FILENAME = "dialogue_template.json" +IGNORE_INDEX = -100 + + +@dataclass +class DialogueTemplate(ModelHubMixin): + """Converts all turns of a dialogue between a user and assistant to a standardized format. + + 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) + """ + + system: str + messages: List[Dict[str, str]] = None + system_token: str = "<|system|>" + user_token: str = "<|user|>" + assistant_token: str = "<|assistant|>" + end_token: str = "<|end|>" + + def get_training_prompt(self) -> str: + prompt = self.system_token + "\n" + self.system + self.end_token + "\n" + if self.messages is None: + raise ValueError("Dialogue template must have at least one message.") + for message in self.messages: + if message["role"] == "user": + prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n" + else: + prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n" + return prompt + + def get_inference_prompt(self) -> str: + prompt = self.system_token + "\n" + self.system + self.end_token + "\n" + if self.messages is None: + raise ValueError("Dialogue template must have at least one message.") + for message in self.messages: + if message["role"] == "user": + prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n" + else: + prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n" + prompt += self.assistant_token + return prompt + + def get_dialogue(self): + """Helper function to format the messages as an easy-to-read dialogue.""" + prompt = "" + if self.messages is None: + raise ValueError("Dialogue template must have at least one message.") + for message in self.messages: + if message["role"] == "user": + prompt += "\n\nHuman: " + message["content"] + else: + prompt += "\n\nAssistant: " + message["content"] + return prompt + + def get_special_tokens(self) -> List[str]: + return [self.system_token, self.user_token, self.assistant_token, self.end_token] + + def copy(self): + return DialogueTemplate( + system=self.system, + messages=self.messages, + system_token=self.system_token, + user_token=self.user_token, + assistant_token=self.assistant_token, + end_token=self.end_token, + ) + + def to_dict(self) -> Dict[str, Any]: + return {k: v for k, v in asdict(self).items()} + + @classmethod + def from_dict(cls, data): + return DialogueTemplate( + system=data["system"] if "system" in data else "", + messages=data["messages"] if "messages" in data else None, + system_token=data["system_token"] if "system_token" in data else "<|system|>", + user_token=data["user_token"] if "user_token" in data else "<|user|>", + assistant_token=data["assistant_token"] if "assistant_token" in data else "<|assistant|>", + end_token=data["end_token"] if "end_token" in data else "<|end|>", + ) + + def _save_pretrained(self, save_directory: Union[str, Path]) -> None: + save_directory = Path(save_directory) + save_directory.mkdir(exist_ok=True) + with open(save_directory / "dialogue_template.json", "w") as f: + json.dump(self.to_dict(), f, indent=2) + + @classmethod + def _from_pretrained( + cls: Type[T], + *, + model_id: str, + revision: Optional[str], + cache_dir: Optional[Union[str, Path]], + force_download: bool, + proxies: Optional[Dict], + resume_download: bool, + local_files_only: bool, + token: Optional[Union[str, bool]], + **model_kwargs, + ) -> T: + """Loads the dialogue template from a local directory or the Huggingface Hub. + + Args: + model_id (`str`): + ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`). + revision (`str`, *optional*): + Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the + latest commit on `main` branch. + force_download (`bool`, *optional*, defaults to `False`): + Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding + the existing cache. + resume_download (`bool`, *optional*, defaults to `False`): + Whether to delete incompletely received files. Will attempt to resume the download if such a file exists. + proxies (`Dict[str, str]`, *optional*): + A dictionary of proxy servers to use by protocol or endpoint (e.g., `{'http': 'foo.bar:3128', + 'http://hostname': 'foo.bar:4012'}`). + token (`str` or `bool`, *optional*): + The token to use as HTTP bearer authorization for remote files. By default, it will use the token + cached when running `huggingface-cli login`. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the local cached file if it exists. + model_kwargs: + Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method. + """ + if os.path.isdir(model_id): # Can either be a local directory + print("Loading dialogue template from local directory") + template_file = os.path.join(model_id, TEMPLATE_FILENAME) + else: # Or a template on the Hub + template_file = hf_hub_download( # Download from the hub, passing same input args + repo_id=model_id, + filename=TEMPLATE_FILENAME, + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + proxies=proxies, + resume_download=resume_download, + token=token, + local_files_only=local_files_only, + ) + + # Load template + with open(template_file, "r") as f: + data = json.load(f) + return cls.from_dict(data=data) + + +# A shortened version of the system message in Anthropic's HHH prompt: https://gist.github.com/jareddk/2509330f8ef3d787fc5aaac67aab5f11#file-hhh_prompt-txt +default_template = DialogueTemplate( + 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.", +) + +# OpenAI and OpenAssistant train on few to no system messages. +# TODO: consider defining this as the `default` template +no_system_template = DialogueTemplate( + system="", +) + +alpaca_template = DialogueTemplate( + system="Below is an instruction that describes a task. Write a response that appropriately completes the request.", + user_token="### Instruction:", + assistant_token="### Response:", +) + +SUPPORTED_DIALOGUE_TEMPLATES = { + "default": default_template, + "no_system": no_system_template, + "alpaca": alpaca_template, +} + + +def get_dialogue_template(template: str) -> DialogueTemplate: + if template not in SUPPORTED_DIALOGUE_TEMPLATES.keys(): + raise ValueError(f"Template {template} is not supported!") + return SUPPORTED_DIALOGUE_TEMPLATES[template].copy() + + +def prepare_dialogue(example, dialogue_template, is_train=True): + """Format example to single- or multi-turn dialogue.""" + # TODO: make this simpler by just ensuring every dataset has a messages column + if "messages" in example.keys() and example["messages"] is not None: + dialogue_template.messages = example["messages"] + elif all(k in example.keys() for k in ("prompt", "completion")): + # Construct single-turn dialogue from prompt and completion + dialogue_template.messages = [ + {"role": "user", "content": example["prompt"]}, + {"role": "assistant", "content": example["completion"]}, + ] + elif "prompt" in example.keys(): + # Construct single-turn dialogue from prompt (inference only) + dialogue_template.messages = [ + {"role": "user", "content": example["prompt"]}, + ] + else: + raise ValueError( + f"Could not format example as dialogue! Require either `messages` or `[prompt, completion]` or `[prompt]` keys but found {list(example.keys())}" + ) + if is_train: + example["text"] = dialogue_template.get_training_prompt() + else: + example["text"] = dialogue_template.get_inference_prompt() + return example + + +def mask_user_labels(tokenizer, dialogue_template, labels): + """Masks the user turns of a dialogue from the loss""" + user_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.user_token) + assistant_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.assistant_token) + for idx, label_id in enumerate(labels): + if label_id == user_token_id: + current_idx = idx + while labels[current_idx] != assistant_token_id and current_idx < len(labels): + labels[current_idx] = IGNORE_INDEX + current_idx += 1 diff --git a/chat/generate.py b/chat/generate.py new file mode 100644 index 0000000..64a3905 --- /dev/null +++ b/chat/generate.py @@ -0,0 +1,139 @@ +# coding=utf-8 +# Copyright 2023 The BigCode and HuggingFace teams. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""A simple script to quickly check the model outputs of a generative model""" +import argparse + +import torch +from dialogues import DialogueTemplate, get_dialogue_template +from transformers import (AutoModelForCausalLM, AutoTokenizer, + GenerationConfig, set_seed) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--model_id", + type=str, + help="Name of model to generate samples with", + ) + parser.add_argument( + "--revision", + type=str, + default=None, + help="The model repo's revision to use", + ) + parser.add_argument( + "--system_prompt", type=str, default=None, help="Overrides the dialogue template's system prompt" + ) + args = parser.parse_args() + + # Set seed for reproducibility + set_seed(42) + + prompts = [ + [ + { + "role": "user", + "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.", + } + ], + [ + { + "role": "user", + "content": "Implement a Python function to find the longest common subsequence of two input strings using dynamic programming.", + } + ], + [{"role": "user", "content": "Implement a regular expression in Python to validate an email address."}], + [ + { + "role": "user", + "content": "Write a program to find the nth Fibonacci number using dynamic programming.", + } + ], + [ + { + "role": "user", + "content": "Implement a binary search algorithm to find a specific element in a sorted array.", + } + ], + [{"role": "user", "content": "Implement a queue data structure using two stacks in Python."}], + [ + { + "role": "user", + "content": "Implement a program to find the common elements in two arrays without using any extra data structures.", + } + ], + ] + + try: + dialogue_template = DialogueTemplate.from_pretrained(args.model_id, revision=args.revision) + except Exception: + print("No dialogue template found in model repo. Defaulting to the `no_system` template.") + dialogue_template = get_dialogue_template("no_system") + + if args.system_prompt is not None: + dialogue_template.system = args.system_prompt + formatted_prompts = [] + for prompt in prompts: + dialogue_template.messages = [prompt] if isinstance(prompt, dict) else prompt + formatted_prompts.append(dialogue_template.get_inference_prompt()) + + print("=== SAMPLE PROMPT ===") + print(formatted_prompts[0]) + print("=====================") + + device = "cuda" if torch.cuda.is_available() else "cpu" + tokenizer = AutoTokenizer.from_pretrained(args.model_id, revision=args.revision) + print(f"Special tokens: {tokenizer.special_tokens_map}") + print(f"EOS token ID for generation: {tokenizer.convert_tokens_to_ids(dialogue_template.end_token)}") + generation_config = GenerationConfig( + temperature=0.2, + top_k=50, + top_p=0.95, + repetition_penalty=1.2, + do_sample=True, + pad_token_id=tokenizer.eos_token_id, + eos_token_id=tokenizer.convert_tokens_to_ids(dialogue_template.end_token), + min_new_tokens=32, + max_new_tokens=256, + ) + model = AutoModelForCausalLM.from_pretrained( + args.model_id, revision=args.revision, load_in_8bit=True, device_map="auto", torch_dtype=torch.float16 + ) + outputs = "" + for idx, prompt in enumerate(formatted_prompts): + batch = tokenizer(prompt, return_tensors="pt", return_token_type_ids=False).to(device) + generated_ids = model.generate(**batch, generation_config=generation_config) + generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=False).lstrip() + outputs += generated_text + "\n\n" + print(f"=== EXAMPLE {idx} ===") + print() + print(generated_text) + print() + print("======================") + print() + + raw_model_name = args.model_id.split("/")[-1] + model_name = f"{raw_model_name}-{args.prompt_type}" + if args.revision is not None: + model_name += f"-{args.revision}" + + with open(f"data/samples-{model_name}.txt", "w", encoding="utf-8") as f: + f.write(outputs) + + +if __name__ == "__main__": + main() diff --git a/chat/requirements.txt b/chat/requirements.txt new file mode 100644 index 0000000..da18df5 --- /dev/null +++ b/chat/requirements.txt @@ -0,0 +1,6 @@ +transformers>=4.28.1 +tokenizers>=0.13.3 +deepspeed==0.9.1 +datasets>=2.12.0 +accelerate>=0.18.0 +tensorboard \ No newline at end of file diff --git a/chat/train.py b/chat/train.py new file mode 100644 index 0000000..df383aa --- /dev/null +++ b/chat/train.py @@ -0,0 +1,345 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2023 The BigCode & HuggingFace Inc. teams. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Script to instruction fine-tune causal language models on a Hub dataset + +Adapted from huggingface/transformers: https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_clm.py +""" + +import logging +import math +import os +import random +import sys +from itertools import chain + +import datasets +import torch +import transformers +from config import DataArguments, ModelArguments, TrainingArguments +from datasets import load_dataset +from dialogues import get_dialogue_template, mask_user_labels, prepare_dialogue +from transformers import (AutoModelForCausalLM, AutoTokenizer, Trainer, + default_data_collator, set_seed) +from transformers.testing_utils import CaptureLogger +from transformers.trainer_utils import get_last_checkpoint +from utils import StarChatArgumentParser, hf_login + +logger = logging.getLogger(__name__) + + +def main(): + parser = StarChatArgumentParser((ModelArguments, DataArguments, TrainingArguments)) + if len(sys.argv) == 2 and sys.argv[1].endswith(".yaml"): + # If we pass only one argument to the script and it's the path to a YAML file, + # let's parse it to get our arguments. + model_args, data_args, training_args = parser.parse_yaml_file(os.path.abspath(sys.argv[1])) + # parse command line args and yaml file + elif len(sys.argv) > 2 and sys.argv[1].endswith(".yaml"): + model_args, data_args, training_args = parser.parse_yaml_and_args(os.path.abspath(sys.argv[1]), sys.argv[2:]) + # parse command line args only + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + # Set seed for reproducibility + set_seed(training_args.seed) + + ############### + # Setup logging + ############### + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + log_level = training_args.get_process_log_level() + logger.setLevel(log_level) + datasets.utils.logging.set_verbosity(log_level) + transformers.utils.logging.set_verbosity(log_level) + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + + # Log on each process a small summary + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + + f" distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" + ) + logger.info(f"Model parameters {model_args}") + logger.info(f"Data parameters {data_args}") + logger.info(f"Training/evaluation parameters {training_args}") + + # Login to HuggingFace Hub if needed + hf_login() + + ########################### + # Detecting last checkpoint + ########################### + last_checkpoint = None + if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: + last_checkpoint = get_last_checkpoint(training_args.output_dir) + if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: + raise ValueError( + f"Output directory ({training_args.output_dir}) already exists and is not empty. " + "Use --overwrite_output_dir to overcome." + ) + elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + + ############### + # Load datasets + ############### + raw_datasets = load_dataset(data_args.dataset_name) + logger.info( + f"Training on the following datasets and their proportions: {[split + ' : ' + str(dset.num_rows) for split, dset in raw_datasets.items()]}" + ) + with training_args.main_process_first(desc="Log a few random samples from the raw training set"): + for index in random.sample(range(len(raw_datasets["train"])), 3): + logger.info(f"Sample {index} of the raw training set:\n\n{raw_datasets['train'][index]['messages']}") + + ######################### + # Apply dialogue template + ######################### + dialogue_template = get_dialogue_template(data_args.dialogue_template) + logger.info(f"System prompt for dialogue template: {dialogue_template.system}") + raw_datasets = raw_datasets.map(prepare_dialogue, fn_kwargs={"dialogue_template": dialogue_template}) + + ##################################### + # Load tokenizer and process datasets + ##################################### + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + revision=model_args.model_revision, + ) + + # Note that we must call `add_tokens` before adding any special tokens + dialogue_tokens = dialogue_template.get_special_tokens() + num_added_tokens = tokenizer.add_special_tokens({"additional_special_tokens": dialogue_tokens}) + logger.info(f"Added {num_added_tokens} new tokens: {dialogue_tokens}") + + if training_args.do_train: + column_names = list(raw_datasets["train"].features) + else: + column_names = list(raw_datasets["test"].features) + text_column_name = "text" if "text" in column_names else column_names[0] + + with training_args.main_process_first(desc="Log a few random samples from the training set"): + for index in random.sample(range(len(raw_datasets["train"])), 3): + logger.info(f"Sample {index} of the raw training set:\n\n{raw_datasets['train'][index]['text']}") + + # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function + tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base") + + def tokenize_function(examples): + with CaptureLogger(tok_logger) as cl: + output = tokenizer(examples[text_column_name], return_token_type_ids=False) + # clm input could be much much longer than block_size + if "Token indices sequence length is longer than the" in cl.out: + tok_logger.warning( + "^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits" + " before being passed to the model." + ) + return output + + with training_args.main_process_first(desc="dataset map tokenization"): + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + num_proc=data_args.preprocessing_num_workers, + remove_columns=column_names, + load_from_cache_file=not data_args.overwrite_cache, + desc="Running tokenizer on dataset", + ) + + ############################## + # Concatenate and chunk corpus + ############################## + if data_args.block_size is None: + block_size = tokenizer.model_max_length + if block_size > 1024: + logger.warning( + "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" + " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" + " override this default with `--block_size xxx`." + ) + block_size = 1024 + else: + if data_args.block_size > tokenizer.model_max_length: + logger.warning( + f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model" + f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}." + ) + block_size = min(data_args.block_size, tokenizer.model_max_length) + + # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size. + def group_texts(examples): + # Concatenate all texts. + concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()} + total_length = len(concatenated_examples[list(examples.keys())[0]]) + # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can + # customize this part to your needs. + if total_length >= block_size: + total_length = (total_length // block_size) * block_size + # Split by chunks of max_len. + result = { + k: [t[i : i + block_size] for i in range(0, total_length, block_size)] + for k, t in concatenated_examples.items() + } + labels = result["input_ids"].copy() + mask_user_labels(tokenizer, dialogue_template, labels) + result["labels"] = labels + return result + + # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder + # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower + # to preprocess. + with training_args.main_process_first(desc="grouping texts together"): + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + num_proc=data_args.preprocessing_num_workers, + load_from_cache_file=not data_args.overwrite_cache, + desc=f"Grouping texts in chunks of {block_size}", + ) + + if training_args.do_train: + if "train" not in tokenized_datasets: + raise ValueError("--do_train requires a train dataset") + train_dataset = lm_datasets["train"] + if data_args.max_train_samples is not None: + max_train_samples = min(len(train_dataset), data_args.max_train_samples) + train_dataset = train_dataset.select(range(max_train_samples)) + + if training_args.do_eval: + if "test" not in tokenized_datasets: + raise ValueError("--do_eval requires a validation dataset") + eval_dataset = lm_datasets["test"] + if data_args.max_eval_samples is not None: + max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) + eval_dataset = eval_dataset.select(range(max_eval_samples)) + + ####################### + # Load pretrained model + ####################### + logger.info("*** Load pretrained model ***") + torch_dtype = ( + model_args.torch_dtype if model_args.torch_dtype in ["auto", None] else getattr(torch, model_args.torch_dtype) + ) + model = AutoModelForCausalLM.from_pretrained( + model_args.model_name_or_path, + revision=model_args.model_revision, + torch_dtype=torch_dtype, + use_cache=False if training_args.gradient_checkpointing else True, + ) + model.resize_token_embeddings(len(tokenizer)) + + ######################## + # Initialize the Trainer + ######################## + trainer = Trainer( + model=model, + args=training_args, + train_dataset=train_dataset if training_args.do_train else None, + eval_dataset=eval_dataset if training_args.do_eval else None, + tokenizer=tokenizer, + # Data collator defaults to DataCollatorWithPadding, so we change it + # since we've already chunked our corpus + data_collator=default_data_collator, + ) + + ############### + # Training loop + ############### + if training_args.do_train: + logger.info("*** Train ***") + checkpoint = None + if training_args.resume_from_checkpoint is not None: + checkpoint = training_args.resume_from_checkpoint + elif last_checkpoint is not None: + checkpoint = last_checkpoint + train_result = trainer.train(resume_from_checkpoint=checkpoint) + + metrics = train_result.metrics + + max_train_samples = ( + data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) + ) + metrics["train_samples"] = min(max_train_samples, len(train_dataset)) + + trainer.log_metrics("train", metrics) + trainer.save_metrics("train", metrics) + trainer.save_state() + + ########## + # Evaluate + ########## + if training_args.do_eval: + logger.info("*** Evaluate ***") + + metrics = trainer.evaluate() + + max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) + metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) + try: + perplexity = math.exp(metrics["eval_loss"]) + except OverflowError: + perplexity = float("inf") + metrics["perplexity"] = perplexity + + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + + ################################# + # Create model card & push to Hub + ################################# + kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"} + if data_args.dataset_name is not None: + kwargs["dataset_tags"] = data_args.dataset_name + if data_args.dataset_config_name is not None: + kwargs["dataset_args"] = data_args.dataset_config_name + kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" + else: + kwargs["dataset"] = data_args.dataset_name + kwargs["dataset_args"] = "default" + + # Store dialogue template so we can load it at deployment time + dialogue_template.save_pretrained(training_args.output_dir) + + if training_args.push_to_hub: + trainer.push_to_hub(**kwargs) + else: + trainer.save_model(training_args.output_dir) + trainer.create_model_card(**kwargs) + + with training_args.main_process_first(desc="Generate a sample from the model"): + inputs = tokenizer( + "<|system|>\n<|end|>\n<|user|>\nHow many helicopters can a human eat in one sitting?<|end|>\n<|assistant|>", + return_tensors="pt", + return_token_type_ids=False, + ).to(training_args.device) + outputs = model.generate( + **inputs, + max_new_tokens=256, + pad_token_id=tokenizer.eos_token_id, + eos_token_id=tokenizer.convert_tokens_to_ids(dialogue_template.end_token), + ) + logger.info(f"=== SAMPLE OUTPUT ==\n\n{tokenizer.decode(outputs[0], skip_special_tokens=False)}") + + +if __name__ == "__main__": + main() diff --git a/chat/utils.py b/chat/utils.py new file mode 100644 index 0000000..e17884d --- /dev/null +++ b/chat/utils.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import dataclasses +import os +from dataclasses import dataclass +from typing import List, Optional + +from huggingface_hub import login +from transformers import HfArgumentParser + + +class StarChatArgumentParser(HfArgumentParser): + def parse_yaml_and_args(self, yaml_arg: str, other_args: Optional[List[str]] = None) -> List[dataclass]: + arg_list = self.parse_yaml_file(os.path.abspath(yaml_arg)) + + outputs = [] + # strip other args list into dict of key-value pairs + other_args = {arg.split("=")[0].strip("-"): arg.split("=")[1] for arg in other_args} + used_args = {} + + # overwrite the default/loaded value with the value provided to the command line + # adapted from https://github.com/huggingface/transformers/blob/d0b5002378daabf62769159add3e7d66d3f83c3b/src/transformers/hf_argparser.py#L327 + for data_yaml, data_class in zip(arg_list, self.dataclass_types): + keys = {f.name for f in dataclasses.fields(data_yaml) if f.init} + inputs = {k: v for k, v in vars(data_yaml).items() if k in keys} + for arg, val in other_args.items(): + # add only if in keys + if arg in keys: + base_type = data_yaml.__dataclass_fields__[arg].type + inputs[arg] = val + + # cast type for ints, floats, and bools (default to strings) + if base_type in [int, float, bool]: + inputs[arg] = base_type(val) + + # add to used-args so we can check if double add + if arg not in used_args: + used_args[arg] = val + else: + raise ValueError(f"Duplicate argument provided: {arg}, may cause unexpected behavior") + + obj = data_class(**inputs) + outputs.append(obj) + + return outputs + + +def hf_login(): + """Login to HuggingFace Hub if HF_TOKEN is defined in the environment""" + hf_token = os.getenv("HF_TOKEN") + if hf_token is not None: + login(token=hf_token) From 118094fdbddb481281ca8862060df018acd843dc Mon Sep 17 00:00:00 2001 From: Leandro von Werra Date: Wed, 10 May 2023 17:13:47 +0200 Subject: [PATCH 10/20] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fc0f85b..e94f8b0 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ print( pipe("def hello():") ) ## Text-generation-inference ```bash -docker run --gpus '"device:0"' -p 8080:80 -v $PWD/data:/data -e HUGGING_FACE_HUB_TOKEN= -e HF_HUB_ENABLE_HF_TRANSFER=0 -d ghcr.io/huggingface/text-generation-inference:sha-880a76e --model-id bigcode/starcoder --max-total-tokens 8192 +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 ``` For more details, see [here](https://github.com/huggingface/text-generation-inference). From cb18f34289455ce3882408ef6a2f5093aaf8e62b Mon Sep 17 00:00:00 2001 From: ArmelRandy <76953833+ArmelRandy@users.noreply.github.com> Date: Mon, 15 May 2023 11:46:57 +0200 Subject: [PATCH 11/20] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e94f8b0..1c1c42a 100644 --- a/README.md +++ b/README.md @@ -178,10 +178,10 @@ python -m torch.distributed.launch \ ## Merging PEFT adapter layers 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: ```bash -python finetune/merge_peft_adapters.py --model_name_or_path model_to_merge --peft_model_path model_checkpoint +python finetune/merge_peft_adapters.py --base_model_name_or_path model_to_merge --peft_model_path model_checkpoint # Push merged model to the Hub -python finetune/merge_peft_adapters.py --model_name_or_path model_to_merge --peft_model_path model_checkpoint --push_to_hub +python finetune/merge_peft_adapters.py --base_model_name_or_path model_to_merge --peft_model_path model_checkpoint --push_to_hub ``` For example From da6e786ea0bd1ce29b0eb0b3dc109739d0dbacef Mon Sep 17 00:00:00 2001 From: lewtun Date: Tue, 16 May 2023 09:29:58 +0200 Subject: [PATCH 12/20] Switch chat link from HuggingChat to StarChat playground Since the prompted StarCoder is no longer hosted in HuggingChat, how about we direct users to StarChat? --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1c1c42a..32578fb 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 💫 StarCoder -[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/chat/?model=bigcode/starcoder) +[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) # What is this about? 💫 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. From 7a9f9dbab6dc60a001a07b05665e794ddee882de Mon Sep 17 00:00:00 2001 From: Loubna Ben Allal <44069155+loubnabnl@users.noreply.github.com> Date: Fri, 19 May 2023 14:18:24 +0200 Subject: [PATCH 13/20] add evaluation section --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 32578fb..cf1e22a 100644 --- a/README.md +++ b/README.md @@ -189,3 +189,5 @@ For example python finetune/merge_peft_adapters.py --model_name_or_path bigcode/starcoder --peft_model_path checkpoints/checkpoint-1000 --push_to_hub ``` +## Evaluation +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. From 652da2fa9ae74b9dd9da1f458d2bbee021be9e21 Mon Sep 17 00:00:00 2001 From: Loubna Ben Allal <44069155+loubnabnl@users.noreply.github.com> Date: Thu, 25 May 2023 18:50:20 +0200 Subject: [PATCH 14/20] Add hardware requirements section --- README.md | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cf1e22a..2deaf80 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,8 @@ huggingface-cli login - [Datasets](#datasets) - [Stack Exchange](#stack-exchange-se) - [Merging PEFT adapter layers](#merging-peft-adapter-layers) +3. [Evaluation](#evaluation) +4. [Inference hardware requirements](#inference-hardware-requirements) # Quickstart 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. @@ -63,6 +65,7 @@ tokenizer = AutoTokenizer.from_pretrained(checkpoint) pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0) print( pipe("def hello():") ) ``` +For hardware requirements, check the secyoon [Inference hardware requirements](#inference-hardware-requirements). ## Text-generation-inference @@ -189,5 +192,21 @@ For example python finetune/merge_peft_adapters.py --model_name_or_path bigcode/starcoder --peft_model_path checkpoints/checkpoint-1000 --push_to_hub ``` -## Evaluation +# Evaluation 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. + +# Inference hardware requirements +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 +```python +# make sure you have accelerate and bitsandbytes installed +from transformers import AutoModelForCausalLM, AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("bigcode/starcoder") +# for fp16 replace with `load_in_8bit=True` with `torch_dtype=torch.float16` +model = AutoModelForCausalLM.from_pretrained("bigcode/starcoder", device_map="auto", load_in_8bit=True) +print(f"Memory footprint: {model.get_memory_footprint() / 1e6:.2f} MB") +```` +``` +Memory footprint: 15939.61 MB +``` +You can also try [starcoder.cpp](https://github.com/bigcode-project/starcoder.cpp), a C++ implementation with [ggml](https://github.com/ggerganov/ggml) library. From 576502e8f8fb53207cea1cbc3f4fd157c81e04a7 Mon Sep 17 00:00:00 2001 From: Loubna Ben Allal <44069155+loubnabnl@users.noreply.github.com> Date: Thu, 25 May 2023 20:50:14 +0200 Subject: [PATCH 15/20] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2deaf80..47355f8 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ tokenizer = AutoTokenizer.from_pretrained(checkpoint) pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0) print( pipe("def hello():") ) ``` -For hardware requirements, check the secyoon [Inference hardware requirements](#inference-hardware-requirements). +For hardware requirements, check the section [Inference hardware requirements](#inference-hardware-requirements). ## Text-generation-inference From e25ab3ac73cef7c63c7fce6d7e54d4a705adda34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eryk=20Mazu=C5=9B?= Date: Wed, 31 May 2023 12:58:41 +0200 Subject: [PATCH 16/20] Update README.md (#48) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 47355f8..5e53236 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ checkpoint = "bigcode/starcoder" device = "cuda" # for GPU usage or "cpu" for CPU usage tokenizer = AutoTokenizer.from_pretrained(checkpoint) -# to save memory consider using fp16 or bf16 by specifying torch.dtype=torch.float16 for example +# to save memory consider using fp16 or bf16 by specifying torch_dtype=torch.float16 for example model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device) inputs = tokenizer.encode("def print_hello_world():", return_tensors="pt").to(device) From 80a39c2e0a0c064636df2d1e387b38086cd9c425 Mon Sep 17 00:00:00 2001 From: Arjun Guha Date: Wed, 31 May 2023 13:20:13 -0400 Subject: [PATCH 17/20] Removed unused line --- finetune/merge_peft_adapters.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/finetune/merge_peft_adapters.py b/finetune/merge_peft_adapters.py index 790b6fd..218728f 100644 --- a/finetune/merge_peft_adapters.py +++ b/finetune/merge_peft_adapters.py @@ -25,7 +25,6 @@ def main(): model = PeftModel.from_pretrained(base_model, args.peft_model_path) model = model.merge_and_unload() - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") tokenizer = AutoTokenizer.from_pretrained(args.base_model_name_or_path) if args.push_to_hub: @@ -38,4 +37,4 @@ def main(): print(f"Model saved to {args.base_model_name_or_path}-merged") if __name__ == "__main__" : - main() \ No newline at end of file + main() From 1f8b704981f046e240709db5256d5e5a268f3610 Mon Sep 17 00:00:00 2001 From: Daniel Fried Date: Wed, 7 Jun 2023 12:20:04 -0400 Subject: [PATCH 18/20] Update README.md Add `clean_up_tokenization_spaces=False` argument for `tokenizer.decode` to README. --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e53236..b800f42 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,8 @@ model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device) inputs = tokenizer.encode("def print_hello_world():", return_tensors="pt").to(device) outputs = model.generate(inputs) -print(tokenizer.decode(outputs[0])) +# clean_up_tokenization_spaces=False prevents a tokenizer edge case which can result in spaces being removed around punctuation +print(tokenizer.decode(outputs[0], clean_up_tokenization_spaces=False)) ``` or ```python From 0d275cddf7a63fc7c32851af5e1ebdb918bb61c0 Mon Sep 17 00:00:00 2001 From: ArmelRandy <76953833+ArmelRandy@users.noreply.github.com> Date: Wed, 28 Jun 2023 16:55:59 +0200 Subject: [PATCH 19/20] Removing argument prompt_type, which is not supported by the parser. --- chat/generate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chat/generate.py b/chat/generate.py index 64a3905..c67d7d8 100644 --- a/chat/generate.py +++ b/chat/generate.py @@ -127,7 +127,7 @@ def main(): print() raw_model_name = args.model_id.split("/")[-1] - model_name = f"{raw_model_name}-{args.prompt_type}" + model_name = f"{raw_model_name}" if args.revision is not None: model_name += f"-{args.revision}" From d72c7fe3dda81d47ad9b851f9567393fb6b551b9 Mon Sep 17 00:00:00 2001 From: ArmelRandy <76953833+ArmelRandy@users.noreply.github.com> Date: Thu, 29 Jun 2023 10:07:07 +0200 Subject: [PATCH 20/20] Add load_best_model_at_end=True --- finetune/finetune.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/finetune/finetune.py b/finetune/finetune.py index 96ab961..525b37f 100644 --- a/finetune/finetune.py +++ b/finetune/finetune.py @@ -267,6 +267,8 @@ def run_training(args, train_data, val_data): output_dir=args.output_dir, dataloader_drop_last=True, evaluation_strategy="steps", + save_strategy="steps", + load_best_model_at_end=True, max_steps=args.max_steps, eval_steps=args.eval_freq, save_steps=args.save_freq, @@ -309,4 +311,4 @@ def main(args): logging.set_verbosity_error() - main(args) \ No newline at end of file + main(args)