lxe commited on
Commit
806d367
β€’
1 Parent(s): d3bfed8

Full rework: Version 2 release (#37)

Browse files
Files changed (10) hide show
  1. .gitignore +1 -1
  2. LICENSE.txt +9 -0
  3. README.md +13 -29
  4. Simple_LLaMA_FineTuner.ipynb +34 -34
  5. app.py +337 -0
  6. config.py +64 -0
  7. Inference.ipynb β†’ inference.ipynb +60 -25
  8. main.py +0 -451
  9. requirements.txt +1 -1
  10. trainer.py +246 -0
.gitignore CHANGED
@@ -2,7 +2,7 @@ out/
2
  7B/
3
  13B/
4
  __pycache__/
5
- lora-*
6
  checkpoint**
7
  minimal-llama**
8
  upload.py
 
2
  7B/
3
  13B/
4
  __pycache__/
5
+ lora/
6
  checkpoint**
7
  minimal-llama**
8
  upload.py
LICENSE.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Aleksey Smolenchuk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
README.md CHANGED
@@ -1,21 +1,21 @@
1
  ---
2
- title: Simple LLaMA Finetuner
3
  emoji: πŸ¦™
4
  colorFrom: yellow
5
  colorTo: orange
6
  sdk: gradio
7
- app_file: main.py
8
  pinned: false
9
  ---
10
 
11
- # πŸ¦™ Simple LLaMA Finetuner
12
 
13
  [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/lxe/simple-llama-finetuner/blob/master/Simple_LLaMA_FineTuner.ipynb)
14
  [![Open In Spaces](https://img.shields.io/badge/πŸ€—-Open%20In%20Spaces-blue.svg)](https://huggingface.co/spaces/lxe/simple-llama-finetuner)
15
  [![](https://img.shields.io/badge/no-bugs-brightgreen.svg)](https://github.com/lxe/no-bugs)
16
  [![](https://img.shields.io/badge/coverage-%F0%9F%92%AF-green.svg)](https://github.com/lxe/onehundred/tree/master)
17
 
18
- Simple LLaMA Finetuner is a beginner-friendly interface designed to facilitate fine-tuning the [LLaMA-7B](https://github.com/facebookresearch/llama) language model using [LoRA](https://arxiv.org/abs/2106.09685) method via the [PEFT library](https://github.com/huggingface/peft) on commodity NVIDIA GPUs. With small dataset and sample lengths of 256, you can even run this on a regular Colab Tesla T4 instance.
19
 
20
  With this intuitive UI, you can easily manage your dataset, customize parameters, train, and evaluate the model's inference capabilities.
21
 
@@ -24,7 +24,6 @@ With this intuitive UI, you can easily manage your dataset, customize parameters
24
  - https://github.com/zphang/minimal-llama/
25
  - https://github.com/tloen/alpaca-lora
26
  - https://github.com/huggingface/peft
27
- - https://huggingface.co/datasets/Anthropic/hh-rlhf
28
 
29
  ## Features
30
 
@@ -32,12 +31,6 @@ With this intuitive UI, you can easily manage your dataset, customize parameters
32
  - Adjustable parameters for fine-tuning and inference
33
  - Beginner-friendly UI with explanations for each parameter
34
 
35
- ## TODO
36
-
37
- - [ ] Accelerate / DeepSpeed
38
- - [ ] Load other models
39
- - [ ] More dataset preparation tools
40
-
41
  ## Getting Started
42
 
43
  ### Prerequisites
@@ -50,10 +43,10 @@ With this intuitive UI, you can easily manage your dataset, customize parameters
50
  I recommend using a virtual environment to install the required packages. Conda preferred.
51
 
52
  ```
53
- conda create -n llama-finetuner python=3.10
54
- conda activate llama-finetuner
55
  conda install -y cuda -c nvidia/label/cuda-11.7.0
56
- conda install -y pytorch=1.13.1 pytorch-cuda=11.7 -c pytorch
57
  ```
58
 
59
  On WSL, you might need to install CUDA manually by following [these steps](https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&Distribution=WSL-Ubuntu&target_version=2.0&target_type=deb_local), then running the following before you launch:
@@ -65,8 +58,8 @@ export LD_LIBRARY_PATH=/usr/lib/wsl/lib
65
  Clone the repository and install the required packages.
66
 
67
  ```
68
- git clone https://github.com/lxe/simple-llama-finetuner.git
69
- cd simple-llama-finetuner
70
  pip install -r requirements.txt
71
  ```
72
 
@@ -76,25 +69,16 @@ Launch it
76
  python main.py
77
  ```
78
 
79
- Open http://127.0.0.1:7860/ in your browser. Prepare your training data by separating each sample with 2 blank lines. Paste the whole training dataset into the textbox. Specify the model name in the "LoRA Model Name" textbox, then click train. You might need to adjust the max sequence length and batch size to fit your GPU memory. The model will be saved in the `lora-{your model name}` directory.
80
 
81
- After training is done, navigate to "Inference" tab, click "Reload Models", select your model, and play with it.
82
 
83
  Have fun!
84
 
85
- ## Screenshots
86
 
87
- |![Image1](https://user-images.githubusercontent.com/1486609/226793136-84531388-4081-49bb-b982-3f47e6ec25cd.png) | ![Image2](https://user-images.githubusercontent.com/1486609/226809466-b1eb6f3f-4049-4a41-a2e3-52b06a6e1230.png) |
88
- |:---:|:---:|
89
 
90
  ## License
91
 
92
  MIT License
93
-
94
- Copyright (c) 2023 Aleksey Smolenchuk
95
-
96
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
97
-
98
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
99
-
100
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
1
  ---
2
+ title: Simple LLM Finetuner
3
  emoji: πŸ¦™
4
  colorFrom: yellow
5
  colorTo: orange
6
  sdk: gradio
7
+ app_file: app.py
8
  pinned: false
9
  ---
10
 
11
+ # πŸ¦™ Simple LLM Finetuner
12
 
13
  [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/lxe/simple-llama-finetuner/blob/master/Simple_LLaMA_FineTuner.ipynb)
14
  [![Open In Spaces](https://img.shields.io/badge/πŸ€—-Open%20In%20Spaces-blue.svg)](https://huggingface.co/spaces/lxe/simple-llama-finetuner)
15
  [![](https://img.shields.io/badge/no-bugs-brightgreen.svg)](https://github.com/lxe/no-bugs)
16
  [![](https://img.shields.io/badge/coverage-%F0%9F%92%AF-green.svg)](https://github.com/lxe/onehundred/tree/master)
17
 
18
+ Simple LLM Finetuner is a beginner-friendly interface designed to facilitate fine-tuning various language models using [LoRA](https://arxiv.org/abs/2106.09685) method via the [PEFT library](https://github.com/huggingface/peft) on commodity NVIDIA GPUs. With small dataset and sample lengths of 256, you can even run this on a regular Colab Tesla T4 instance.
19
 
20
  With this intuitive UI, you can easily manage your dataset, customize parameters, train, and evaluate the model's inference capabilities.
21
 
 
24
  - https://github.com/zphang/minimal-llama/
25
  - https://github.com/tloen/alpaca-lora
26
  - https://github.com/huggingface/peft
 
27
 
28
  ## Features
29
 
 
31
  - Adjustable parameters for fine-tuning and inference
32
  - Beginner-friendly UI with explanations for each parameter
33
 
 
 
 
 
 
 
34
  ## Getting Started
35
 
36
  ### Prerequisites
 
43
  I recommend using a virtual environment to install the required packages. Conda preferred.
44
 
45
  ```
46
+ conda create -n simple-llm-finetuner python=3.10
47
+ conda activate simple-llm-finetuner
48
  conda install -y cuda -c nvidia/label/cuda-11.7.0
49
+ conda install -y pytorch=2 pytorch-cuda=11.7 -c pytorch
50
  ```
51
 
52
  On WSL, you might need to install CUDA manually by following [these steps](https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&Distribution=WSL-Ubuntu&target_version=2.0&target_type=deb_local), then running the following before you launch:
 
58
  Clone the repository and install the required packages.
59
 
60
  ```
61
+ git clone https://github.com/lxe/simple-llm-finetuner.git
62
+ cd simple-llm-finetuner
63
  pip install -r requirements.txt
64
  ```
65
 
 
69
  python main.py
70
  ```
71
 
72
+ Open http://127.0.0.1:7860/ in your browser. Prepare your training data by separating each sample with 2 blank lines. Paste the whole training dataset into the textbox. Specify the new LoRA adapter name in the "New PEFT Adapter Name" textbox, then click train. You might need to adjust the max sequence length and batch size to fit your GPU memory. The model will be saved in the `lora/` directory.
73
 
74
+ After training is done, navigate to "Inference" tab, select your LoRA, and play with it.
75
 
76
  Have fun!
77
 
78
+ ## YouTube Walkthough
79
 
80
+ https://www.youtube.com/watch?v=yM1wanDkNz8
 
81
 
82
  ## License
83
 
84
  MIT License
 
 
 
 
 
 
 
 
Simple_LLaMA_FineTuner.ipynb CHANGED
@@ -1,20 +1,4 @@
1
  {
2
- "nbformat": 4,
3
- "nbformat_minor": 0,
4
- "metadata": {
5
- "colab": {
6
- "provenance": []
7
- },
8
- "kernelspec": {
9
- "name": "python3",
10
- "display_name": "Python 3"
11
- },
12
- "language_info": {
13
- "name": "python"
14
- },
15
- "accelerator": "GPU",
16
- "gpuClass": "standard"
17
- },
18
  "cells": [
19
  {
20
  "cell_type": "code",
@@ -28,8 +12,8 @@
28
  },
29
  "outputs": [
30
  {
31
- "output_type": "stream",
32
  "name": "stdout",
 
33
  "text": [
34
  "Wed Mar 22 03:47:25 2023 \n",
35
  "+-----------------------------------------------------------------------------+\n",
@@ -60,11 +44,7 @@
60
  },
61
  {
62
  "cell_type": "code",
63
- "source": [
64
- "![[ -d /content/simple-llama-finetuner ]] \\\n",
65
- " || git clone https://github.com/lxe/simple-llama-finetuner.git /content/simple-llama-finetuner\n",
66
- "!cd /content/simple-llama-finetuner && git pull && pip install -r requirements.txt"
67
- ],
68
  "metadata": {
69
  "colab": {
70
  "base_uri": "https://localhost:8080/"
@@ -72,11 +52,10 @@
72
  "id": "3PM_DilAZD8T",
73
  "outputId": "83c6ff7e-518f-4ceb-ac9d-df22660f5ce5"
74
  },
75
- "execution_count": 2,
76
  "outputs": [
77
  {
78
- "output_type": "stream",
79
  "name": "stdout",
 
80
  "text": [
81
  "Already up to date.\n",
82
  "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
@@ -174,13 +153,16 @@
174
  "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.9/dist-packages (from python-dateutil>=2.8.1->pandas->datasets->-r requirements.txt (line 1)) (1.16.0)\n"
175
  ]
176
  }
 
 
 
 
 
177
  ]
178
  },
179
  {
180
  "cell_type": "code",
181
- "source": [
182
- "!cd /content/simple-llama-finetuner && python main.py --share"
183
- ],
184
  "metadata": {
185
  "colab": {
186
  "base_uri": "https://localhost:8080/"
@@ -188,11 +170,10 @@
188
  "id": "BD693wIzZKUK",
189
  "outputId": "a392bff4-9a5b-4c8f-ecd1-6751517cd254"
190
  },
191
- "execution_count": null,
192
  "outputs": [
193
  {
194
- "output_type": "stream",
195
  "name": "stdout",
 
196
  "text": [
197
  "\n",
198
  "===================================BUG REPORT===================================\n",
@@ -219,16 +200,35 @@
219
  "This share link expires in 72 hours. For free permanent hosting and GPU upgrades (NEW!), check out Spaces: https://huggingface.co/spaces\n"
220
  ]
221
  }
 
 
 
222
  ]
223
  },
224
  {
225
  "cell_type": "code",
226
- "source": [],
227
  "metadata": {
228
  "id": "yhKSDrkKbYkG"
229
  },
230
- "execution_count": null,
231
- "outputs": []
232
  }
233
- ]
234
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  "cells": [
3
  {
4
  "cell_type": "code",
 
12
  },
13
  "outputs": [
14
  {
 
15
  "name": "stdout",
16
+ "output_type": "stream",
17
  "text": [
18
  "Wed Mar 22 03:47:25 2023 \n",
19
  "+-----------------------------------------------------------------------------+\n",
 
44
  },
45
  {
46
  "cell_type": "code",
47
+ "execution_count": 2,
 
 
 
 
48
  "metadata": {
49
  "colab": {
50
  "base_uri": "https://localhost:8080/"
 
52
  "id": "3PM_DilAZD8T",
53
  "outputId": "83c6ff7e-518f-4ceb-ac9d-df22660f5ce5"
54
  },
 
55
  "outputs": [
56
  {
 
57
  "name": "stdout",
58
+ "output_type": "stream",
59
  "text": [
60
  "Already up to date.\n",
61
  "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
 
153
  "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.9/dist-packages (from python-dateutil>=2.8.1->pandas->datasets->-r requirements.txt (line 1)) (1.16.0)\n"
154
  ]
155
  }
156
+ ],
157
+ "source": [
158
+ "![[ -d /content/simple-llama-finetuner ]] \\\n",
159
+ " || git clone https://github.com/lxe/simple-llama-finetuner.git /content/simple-llama-finetuner\n",
160
+ "!cd /content/simple-llama-finetuner && git pull && pip install -r requirements.txt"
161
  ]
162
  },
163
  {
164
  "cell_type": "code",
165
+ "execution_count": null,
 
 
166
  "metadata": {
167
  "colab": {
168
  "base_uri": "https://localhost:8080/"
 
170
  "id": "BD693wIzZKUK",
171
  "outputId": "a392bff4-9a5b-4c8f-ecd1-6751517cd254"
172
  },
 
173
  "outputs": [
174
  {
 
175
  "name": "stdout",
176
+ "output_type": "stream",
177
  "text": [
178
  "\n",
179
  "===================================BUG REPORT===================================\n",
 
200
  "This share link expires in 72 hours. For free permanent hosting and GPU upgrades (NEW!), check out Spaces: https://huggingface.co/spaces\n"
201
  ]
202
  }
203
+ ],
204
+ "source": [
205
+ "!cd /content/simple-llama-finetuner && python app.py --share"
206
  ]
207
  },
208
  {
209
  "cell_type": "code",
210
+ "execution_count": null,
211
  "metadata": {
212
  "id": "yhKSDrkKbYkG"
213
  },
214
+ "outputs": [],
215
+ "source": []
216
  }
217
+ ],
218
+ "metadata": {
219
+ "accelerator": "GPU",
220
+ "colab": {
221
+ "provenance": []
222
+ },
223
+ "gpuClass": "standard",
224
+ "kernelspec": {
225
+ "display_name": "Python 3",
226
+ "name": "python3"
227
+ },
228
+ "language_info": {
229
+ "name": "python"
230
+ }
231
+ },
232
+ "nbformat": 4,
233
+ "nbformat_minor": 0
234
+ }
app.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from config import SHARE, MODELS, TRAINING_PARAMS, LORA_TRAINING_PARAMS, GENERATION_PARAMS
2
+
3
+ import os
4
+ import gradio as gr
5
+ import random
6
+
7
+ from trainer import Trainer
8
+
9
+ LORA_DIR = 'lora'
10
+
11
+ def random_name():
12
+ fruits = [
13
+ "dragonfruit", "kiwano", "rambutan", "durian", "mangosteen",
14
+ "jabuticaba", "pitaya", "persimmon", "acai", "starfruit"
15
+ ]
16
+ return '-'.join(random.sample(fruits, 3))
17
+
18
+ class UI():
19
+ def __init__(self):
20
+ self.trainer = Trainer()
21
+
22
+ def load_loras(self):
23
+ loaded_model_name = self.trainer.model_name
24
+ if os.path.exists(LORA_DIR) and loaded_model_name is not None:
25
+ loras = [f for f in os.listdir(LORA_DIR)]
26
+ sanitized_model_name = loaded_model_name.replace('/', '_').replace('.', '_')
27
+ loras = [f for f in loras if f.startswith(sanitized_model_name)]
28
+ loras.insert(0, 'None')
29
+ return gr.Dropdown.update(choices=loras)
30
+ else:
31
+ return gr.Dropdown.update(choices=['None'], value='None')
32
+
33
+ def training_params_block(self):
34
+ with gr.Row():
35
+ with gr.Column():
36
+ self.max_seq_length = gr.Slider(
37
+ interactive=True,
38
+ minimum=1, maximum=4096, value=TRAINING_PARAMS['max_seq_length'],
39
+ label="Max Sequence Length",
40
+ )
41
+
42
+ self.micro_batch_size = gr.Slider(
43
+ minimum=1, maximum=100, step=1, value=TRAINING_PARAMS['micro_batch_size'],
44
+ label="Micro Batch Size",
45
+ )
46
+
47
+ self.gradient_accumulation_steps = gr.Slider(
48
+ minimum=1, maximum=128, step=1, value=TRAINING_PARAMS['gradient_accumulation_steps'],
49
+ label="Gradient Accumulation Steps",
50
+ )
51
+
52
+ self.epochs = gr.Slider(
53
+ minimum=1, maximum=100, step=1, value=TRAINING_PARAMS['epochs'],
54
+ label="Epochs",
55
+ )
56
+
57
+ self.learning_rate = gr.Slider(
58
+ minimum=0.00001, maximum=0.01, value=TRAINING_PARAMS['learning_rate'],
59
+ label="Learning Rate",
60
+ )
61
+
62
+ with gr.Column():
63
+ self.lora_r = gr.Slider(
64
+ minimum=1, maximum=64, step=1, value=LORA_TRAINING_PARAMS['lora_r'],
65
+ label="LoRA R",
66
+ )
67
+
68
+ self.lora_alpha = gr.Slider(
69
+ minimum=1, maximum=128, step=1, value=LORA_TRAINING_PARAMS['lora_alpha'],
70
+ label="LoRA Alpha",
71
+ )
72
+
73
+ self.lora_dropout = gr.Slider(
74
+ minimum=0, maximum=1, step=0.01, value=LORA_TRAINING_PARAMS['lora_dropout'],
75
+ label="LoRA Dropout",
76
+ )
77
+
78
+ def load_model(self, model_name, progress=gr.Progress(track_tqdm=True)):
79
+ if model_name == '': return ''
80
+ if model_name is None: return self.trainer.model_name
81
+ progress(0, desc=f'Loading {model_name}...')
82
+ self.trainer.load_model(model_name)
83
+ return self.trainer.model_name
84
+
85
+ def base_model_block(self):
86
+ self.model_name = gr.Dropdown(label='Base Model', choices=MODELS)
87
+
88
+ def training_data_block(self):
89
+ training_text = gr.TextArea(
90
+ lines=20,
91
+ label="Training Data",
92
+ info='Paste training data text here. Sequences must be separated with 2 blank lines'
93
+ )
94
+
95
+ examples_dir = os.path.join(os.getcwd(), 'example-datasets')
96
+
97
+ def load_example(filename):
98
+ with open(os.path.join(examples_dir, filename) , 'r', encoding='utf-8') as f:
99
+ return f.read()
100
+
101
+ example_filename = gr.Textbox(visible=False)
102
+ example_filename.change(fn=load_example, inputs=example_filename, outputs=training_text)
103
+
104
+ gr.Examples("./example-datasets", inputs=example_filename)
105
+
106
+ self.training_text = training_text
107
+
108
+ def training_launch_block(self):
109
+ with gr.Row():
110
+ with gr.Column():
111
+ self.new_lora_name = gr.Textbox(label='New PEFT Adapter Name', value=random_name())
112
+ with gr.Column():
113
+ train_button = gr.Button('Train', variant='primary')
114
+
115
+ def train(
116
+ training_text,
117
+ new_lora_name,
118
+ max_seq_length,
119
+ micro_batch_size,
120
+ gradient_accumulation_steps,
121
+ epochs,
122
+ learning_rate,
123
+ lora_r,
124
+ lora_alpha,
125
+ lora_dropout,
126
+ progress=gr.Progress(track_tqdm=True)
127
+ ):
128
+ self.trainer.unload_lora()
129
+
130
+ self.trainer.train(
131
+ training_text,
132
+ new_lora_name,
133
+ max_seq_length=max_seq_length,
134
+ micro_batch_size=micro_batch_size,
135
+ gradient_accumulation_steps=gradient_accumulation_steps,
136
+ epochs=epochs,
137
+ learning_rate=learning_rate,
138
+ lora_r=lora_r,
139
+ lora_alpha=lora_alpha,
140
+ lora_dropout=lora_dropout
141
+ )
142
+
143
+ return new_lora_name
144
+
145
+ train_button.click(
146
+ fn=train,
147
+ inputs=[
148
+ self.training_text,
149
+ self.new_lora_name,
150
+ self.max_seq_length,
151
+ self.micro_batch_size,
152
+ self.gradient_accumulation_steps,
153
+ self.epochs,
154
+ self.learning_rate,
155
+ self.lora_r,
156
+ self.lora_alpha,
157
+ self.lora_dropout,
158
+ ],
159
+ outputs=[self.new_lora_name]
160
+ ).then(
161
+ fn=lambda x: self.trainer.load_model(x, force=True),
162
+ inputs=[self.model_name],
163
+ outputs=[]
164
+ )
165
+
166
+ def inference_block(self):
167
+ with gr.Row():
168
+ with gr.Column():
169
+ self.lora_name = gr.Dropdown(
170
+ interactive=True,
171
+ choices=['None'],
172
+ value='None',
173
+ label='LoRA',
174
+ )
175
+
176
+ def load_lora(lora_name, progress=gr.Progress(track_tqdm=True)):
177
+ if lora_name == 'None':
178
+ self.trainer.unload_lora()
179
+ else:
180
+ self.trainer.load_lora(f'{LORA_DIR}/{lora_name}')
181
+
182
+ return lora_name
183
+
184
+ self.lora_name.change(
185
+ fn=load_lora,
186
+ inputs=self.lora_name,
187
+ outputs=self.lora_name
188
+ )
189
+
190
+ self.prompt = gr.Textbox(
191
+ interactive=True,
192
+ lines=5,
193
+ label="Prompt",
194
+ value="Human: How is cheese made?\nAssistant:"
195
+ )
196
+
197
+ self.generate_btn = gr.Button('Generate', variant='primary')
198
+
199
+ with gr.Row():
200
+ with gr.Column():
201
+ self.max_new_tokens = gr.Slider(
202
+ minimum=0, maximum=4096, step=1, value=GENERATION_PARAMS['max_new_tokens'],
203
+ label="Max New Tokens",
204
+ )
205
+ with gr.Column():
206
+ self.do_sample = gr.Checkbox(
207
+ interactive=True,
208
+ label="Enable Sampling (leave off for greedy search)",
209
+ value=True,
210
+ )
211
+
212
+
213
+ with gr.Row():
214
+ with gr.Column():
215
+ self.num_beams = gr.Slider(
216
+ minimum=1, maximum=10, step=1, value=GENERATION_PARAMS['num_beams'],
217
+ label="Num Beams",
218
+ )
219
+
220
+ with gr.Column():
221
+ self.repeat_penalty = gr.Slider(
222
+ minimum=0, maximum=4.5, step=0.01, value=GENERATION_PARAMS['repetition_penalty'],
223
+ label="Repetition Penalty",
224
+ )
225
+
226
+ with gr.Row():
227
+ with gr.Column():
228
+ self.temperature = gr.Slider(
229
+ minimum=0.01, maximum=1.99, step=0.01, value=GENERATION_PARAMS['temperature'],
230
+ label="Temperature",
231
+ )
232
+
233
+ self.top_p = gr.Slider(
234
+ minimum=0, maximum=1, step=0.01, value=GENERATION_PARAMS['top_p'],
235
+ label="Top P",
236
+ )
237
+
238
+ self.top_k = gr.Slider(
239
+ minimum=0, maximum=200, step=1, value=GENERATION_PARAMS['top_k'],
240
+ label="Top K",
241
+ )
242
+
243
+ with gr.Column():
244
+ self.output = gr.Textbox(
245
+ interactive=True,
246
+ lines=20,
247
+ label="Output"
248
+ )
249
+
250
+
251
+ def generate(
252
+ prompt,
253
+ do_sample,
254
+ max_new_tokens,
255
+ num_beams,
256
+ repeat_penalty,
257
+ temperature,
258
+ top_p,
259
+ top_k,
260
+ progress=gr.Progress(track_tqdm=True)
261
+ ):
262
+ return self.trainer.generate(
263
+ prompt,
264
+ do_sample=do_sample,
265
+ max_new_tokens=max_new_tokens,
266
+ num_beams=num_beams,
267
+ repetition_penalty=repeat_penalty,
268
+ temperature=temperature,
269
+ top_p=top_p,
270
+ top_k=top_k
271
+ )
272
+
273
+ self.generate_btn.click(
274
+ fn=generate,
275
+ inputs=[
276
+ self.prompt,
277
+ self.do_sample,
278
+ self.max_new_tokens,
279
+ self.num_beams,
280
+ self.repeat_penalty,
281
+ self.temperature,
282
+ self.top_p,
283
+ self.top_k
284
+ ],
285
+ outputs=[self.output]
286
+ )
287
+
288
+ def layout(self):
289
+ with gr.Blocks() as demo:
290
+ with gr.Row():
291
+ with gr.Column():
292
+ gr.HTML("""<h2>
293
+ <a style="text-decoration: none;" href="https://github.com/lxe/simple-llama-finetuner">πŸ¦™ Simple LLM Finetuner</a>&nbsp;<a href="https://huggingface.co/spaces/lxe/simple-llama-finetuner?duplicate=true"><img
294
+ src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&amp;style=flat&amp;logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&amp;logoWidth=14" style="display:inline">
295
+ </a></h2><p>Finetune an LLM on your own text. Duplicate this space onto a GPU-enabled space to run.</p>""")
296
+ with gr.Column():
297
+ self.base_model_block()
298
+ with gr.Tab('Finetuning'):
299
+ with gr.Row():
300
+ with gr.Column():
301
+ self.training_data_block()
302
+
303
+ with gr.Column():
304
+ self.training_params_block()
305
+ self.training_launch_block()
306
+
307
+ with gr.Tab('Inference') as inference_tab:
308
+ with gr.Row():
309
+ with gr.Column():
310
+ self.inference_block()
311
+
312
+ inference_tab.select(
313
+ fn=self.load_loras,
314
+ inputs=[],
315
+ outputs=[self.lora_name]
316
+ )
317
+
318
+ self.model_name.change(
319
+ fn=self.load_model,
320
+ inputs=[self.model_name],
321
+ outputs=[self.model_name]
322
+ ).then(
323
+ fn=self.load_loras,
324
+ inputs=[],
325
+ outputs=[self.lora_name]
326
+ )
327
+
328
+ return demo
329
+
330
+ def run(self):
331
+ self.ui = self.layout()
332
+ self.ui.queue().launch(show_error=True, share=SHARE)
333
+
334
+ if (__name__ == '__main__'):
335
+ ui = UI()
336
+ ui.run()
337
+
config.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+
4
+ HAS_CUDA = torch.cuda.is_available()
5
+ DEVICE = torch.device('cuda' if HAS_CUDA else 'cpu')
6
+
7
+ parser = argparse.ArgumentParser(description='Simple LLM Finetuner')
8
+ parser.add_argument('--models', nargs='+', default=[
9
+ 'decapoda-research/llama-7b-hf',
10
+ 'cerebras/Cerebras-GPT-2.7B',
11
+ 'cerebras/Cerebras-GPT-1.3B',
12
+ 'EleutherAI/gpt-neo-2.7B'
13
+ ], help='List of models to use')
14
+
15
+ parser.add_argument('--device-map', type=str, default='', help='Device map to use')
16
+ parser.add_argument('--model', type=str, default='cerebras/Cerebras-GPT-2.7B', help='Model to use')
17
+ parser.add_argument('--max-seq-length', type=int, default=256, help='Max sequence length')
18
+ parser.add_argument('--micro-batch-size', type=int, default=12, help='Micro batch size')
19
+ parser.add_argument('--gradient-accumulation-steps', type=int, default=8, help='Gradient accumulation steps')
20
+ parser.add_argument('--epochs', type=int, default=3, help='Number of epochs')
21
+ parser.add_argument('--learning-rate', type=float, default=3e-4, help='Learning rate')
22
+ parser.add_argument('--lora-r', type=int, default=8, help='LORA r')
23
+ parser.add_argument('--lora-alpha', type=int, default=32, help='LORA alpha')
24
+ parser.add_argument('--lora-dropout', type=float, default=0.01, help='LORA dropout')
25
+ parser.add_argument('--max-new-tokens', type=int, default=80, help='Max new tokens')
26
+ parser.add_argument('--temperature', type=float, default=0.1, help='Temperature')
27
+ parser.add_argument('--top-k', type=int, default=40, help='Top k')
28
+ parser.add_argument('--top-p', type=float, default=0.3, help='Top p')
29
+ parser.add_argument('--repetition-penalty', type=float, default=1.5, help='Repetition penalty')
30
+ parser.add_argument('--do-sample', action='store_true', help='Enable sampling')
31
+ parser.add_argument('--num-beams', type=int, default=1, help='Number of beams')
32
+ parser.add_argument('--share', action='store_true', default=False, help='Whether to deploy the interface with Gradio')
33
+
34
+ args = parser.parse_args()
35
+
36
+ MODELS = args.models
37
+ DEVICE_MAP = {'': 0} if not args.device_map else args.device_map
38
+ MODEL = args.model
39
+
40
+ TRAINING_PARAMS = {
41
+ 'max_seq_length': args.max_seq_length,
42
+ 'micro_batch_size': args.micro_batch_size,
43
+ 'gradient_accumulation_steps': args.gradient_accumulation_steps,
44
+ 'epochs': args.epochs,
45
+ 'learning_rate': args.learning_rate,
46
+ }
47
+
48
+ LORA_TRAINING_PARAMS = {
49
+ 'lora_r': args.lora_r,
50
+ 'lora_alpha': args.lora_alpha,
51
+ 'lora_dropout': args.lora_dropout,
52
+ }
53
+
54
+ GENERATION_PARAMS = {
55
+ 'max_new_tokens': args.max_new_tokens,
56
+ 'temperature': args.temperature,
57
+ 'top_k': args.top_k,
58
+ 'top_p': args.top_p,
59
+ 'repetition_penalty': args.repetition_penalty,
60
+ 'do_sample': args.do_sample,
61
+ 'num_beams': args.num_beams,
62
+ }
63
+
64
+ SHARE = args.share
Inference.ipynb β†’ inference.ipynb RENAMED
@@ -14,10 +14,10 @@
14
  "===================================BUG REPORT===================================\n",
15
  "Welcome to bitsandbytes. For bug reports, please submit your error trace to: https://github.com/TimDettmers/bitsandbytes/issues\n",
16
  "================================================================================\n",
17
- "CUDA SETUP: CUDA runtime path found: /root/miniconda3/envs/llama/lib/libcudart.so\n",
18
  "CUDA SETUP: Highest compute capability among GPUs detected: 8.6\n",
19
  "CUDA SETUP: Detected CUDA version 117\n",
20
- "CUDA SETUP: Loading binary /root/miniconda3/envs/llama/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda117.so...\n"
21
  ]
22
  }
23
  ],
@@ -29,32 +29,66 @@
29
  },
30
  {
31
  "cell_type": "code",
32
- "execution_count": 7,
33
  "id": "3c2f7268",
34
  "metadata": {},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  "outputs": [
36
  {
37
  "data": {
38
- "application/vnd.jupyter.widget-view+json": {
39
- "model_id": "a9779bdda9d54ce8adcfc3cf3c61b6ef",
40
- "version_major": 2,
41
- "version_minor": 0
42
- },
43
  "text/plain": [
44
- "Loading checkpoint shards: 0%| | 0/33 [00:00<?, ?it/s]"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  ]
46
  },
 
47
  "metadata": {},
48
- "output_type": "display_data"
49
  }
50
  ],
51
  "source": [
52
- "model = transformers.LlamaForCausalLM.from_pretrained(\n",
53
- " 'decapoda-research/llama-7b-hf', \n",
54
- " load_in_8bit=True,\n",
55
- " torch_dtype=torch.float16,\n",
56
- " device_map='auto'\n",
57
- ")"
58
  ]
59
  },
60
  {
@@ -74,8 +108,8 @@
74
  }
75
  ],
76
  "source": [
77
- "tokenizer = transformers.LlamaTokenizer.from_pretrained('decapoda-research/llama-7b-hf')\n",
78
- "tokenizer.pad_token_id = 0"
79
  ]
80
  },
81
  {
@@ -94,7 +128,7 @@
94
  },
95
  {
96
  "cell_type": "code",
97
- "execution_count": 10,
98
  "id": "4f944f46",
99
  "metadata": {},
100
  "outputs": [
@@ -102,20 +136,21 @@
102
  "name": "stdout",
103
  "output_type": "stream",
104
  "text": [
105
- " Human: What does the fox say?\n",
106
- "Assistant: The Fox says \\\"la la la\\\"!Human: That's not what it means. It is a song by Ylvis, and they are saying that this particular animal makes noises like these words when trying to communicate with humans in\n"
 
107
  ]
108
  }
109
  ],
110
  "source": [
111
- "inputs = tokenizer(\"Human: What does the fox say?\\nAssistant:\", return_tensors=\"pt\")\n",
112
  "input_ids = inputs[\"input_ids\"].to('cuda')\n",
113
  "\n",
114
  "generation_config = transformers.GenerationConfig(\n",
115
  " do_sample = True,\n",
116
  " temperature = 0.3,\n",
117
  " top_p = 0.1,\n",
118
- " top_k = 50,\n",
119
  " repetition_penalty = 1.5,\n",
120
  " max_new_tokens = 50\n",
121
  ")\n",
@@ -127,7 +162,7 @@
127
  " generation_config=generation_config,\n",
128
  " )\n",
129
  " \n",
130
- "output_text = tokenizer.decode(generation_output[0].cuda())\n",
131
  "print(output_text)"
132
  ]
133
  },
@@ -166,7 +201,7 @@
166
  "name": "python",
167
  "nbconvert_exporter": "python",
168
  "pygments_lexer": "ipython3",
169
- "version": "3.10.9"
170
  }
171
  },
172
  "nbformat": 4,
 
14
  "===================================BUG REPORT===================================\n",
15
  "Welcome to bitsandbytes. For bug reports, please submit your error trace to: https://github.com/TimDettmers/bitsandbytes/issues\n",
16
  "================================================================================\n",
17
+ "CUDA SETUP: CUDA runtime path found: /home/lxe/miniconda3/envs/llama-finetuner/lib/libcudart.so\n",
18
  "CUDA SETUP: Highest compute capability among GPUs detected: 8.6\n",
19
  "CUDA SETUP: Detected CUDA version 117\n",
20
+ "CUDA SETUP: Loading binary /home/lxe/miniconda3/envs/llama-finetuner/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda117.so...\n"
21
  ]
22
  }
23
  ],
 
29
  },
30
  {
31
  "cell_type": "code",
32
+ "execution_count": 4,
33
  "id": "3c2f7268",
34
  "metadata": {},
35
+ "outputs": [],
36
+ "source": [
37
+ "model = transformers.AutoModelForCausalLM.from_pretrained(\n",
38
+ " 'cerebras/Cerebras-GPT-2.7B', \n",
39
+ " load_in_8bit=True,\n",
40
+ " torch_dtype=torch.float16,\n",
41
+ " device_map='auto'\n",
42
+ ")"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": 5,
48
+ "id": "0dcc11cc",
49
+ "metadata": {},
50
  "outputs": [
51
  {
52
  "data": {
 
 
 
 
 
53
  "text/plain": [
54
+ "GPT2Config {\n",
55
+ " \"_name_or_path\": \"cerebras/Cerebras-GPT-2.7B\",\n",
56
+ " \"activation_function\": \"gelu\",\n",
57
+ " \"attn_pdrop\": 0.0,\n",
58
+ " \"bos_token_id\": 50256,\n",
59
+ " \"embd_pdrop\": 0.0,\n",
60
+ " \"eos_token_id\": 50256,\n",
61
+ " \"initializer_range\": 0.02,\n",
62
+ " \"layer_norm_epsilon\": 1e-05,\n",
63
+ " \"model_type\": \"gpt2\",\n",
64
+ " \"n_embd\": 2560,\n",
65
+ " \"n_head\": 32,\n",
66
+ " \"n_inner\": 10240,\n",
67
+ " \"n_layer\": 32,\n",
68
+ " \"n_positions\": 2048,\n",
69
+ " \"reorder_and_upcast_attn\": false,\n",
70
+ " \"resid_pdrop\": 0.0,\n",
71
+ " \"scale_attn_by_inverse_layer_idx\": false,\n",
72
+ " \"scale_attn_weights\": true,\n",
73
+ " \"summary_activation\": null,\n",
74
+ " \"summary_first_dropout\": 0.1,\n",
75
+ " \"summary_proj_to_labels\": true,\n",
76
+ " \"summary_type\": \"cls_index\",\n",
77
+ " \"summary_use_proj\": true,\n",
78
+ " \"torch_dtype\": \"float16\",\n",
79
+ " \"transformers_version\": \"4.28.0.dev0\",\n",
80
+ " \"use_cache\": true,\n",
81
+ " \"vocab_size\": 50257\n",
82
+ "}"
83
  ]
84
  },
85
+ "execution_count": 5,
86
  "metadata": {},
87
+ "output_type": "execute_result"
88
  }
89
  ],
90
  "source": [
91
+ "model.config"
 
 
 
 
 
92
  ]
93
  },
94
  {
 
108
  }
109
  ],
110
  "source": [
111
+ "tokenizer = transformers.AutoTokenizer.from_pretrained('decapoda-research/llama-7b-hf')\n",
112
+ "# tokenizer.pad_token_id = 0"
113
  ]
114
  },
115
  {
 
128
  },
129
  {
130
  "cell_type": "code",
131
+ "execution_count": 9,
132
  "id": "4f944f46",
133
  "metadata": {},
134
  "outputs": [
 
136
  "name": "stdout",
137
  "output_type": "stream",
138
  "text": [
139
+ "Human: How old is the sun?\n",
140
+ "Assistant: I'm not a member.\n",
141
+ "I am you, but it was and that he's.\n"
142
  ]
143
  }
144
  ],
145
  "source": [
146
+ "inputs = tokenizer(\"Human: How old is the sun?\\nAssistant:\", return_tensors=\"pt\")\n",
147
  "input_ids = inputs[\"input_ids\"].to('cuda')\n",
148
  "\n",
149
  "generation_config = transformers.GenerationConfig(\n",
150
  " do_sample = True,\n",
151
  " temperature = 0.3,\n",
152
  " top_p = 0.1,\n",
153
+ " top_k = 80,\n",
154
  " repetition_penalty = 1.5,\n",
155
  " max_new_tokens = 50\n",
156
  ")\n",
 
162
  " generation_config=generation_config,\n",
163
  " )\n",
164
  " \n",
165
+ "output_text = tokenizer.decode(generation_output[0].cuda(), skip_special_tokens=True).strip()\n",
166
  "print(output_text)"
167
  ]
168
  },
 
201
  "name": "python",
202
  "nbconvert_exporter": "python",
203
  "pygments_lexer": "ipython3",
204
+ "version": "3.10.10"
205
  }
206
  },
207
  "nbformat": 4,
main.py DELETED
@@ -1,451 +0,0 @@
1
- import os
2
- import gc
3
- import argparse
4
- import random
5
- import torch
6
- import transformers
7
- import peft
8
- import datasets
9
- import gradio as gr
10
-
11
- model = None
12
- tokenizer = None
13
- current_peft_model = None
14
-
15
- def load_base_model():
16
- global model
17
- print('Loading base model...')
18
- model = transformers.LlamaForCausalLM.from_pretrained(
19
- 'decapoda-research/llama-7b-hf',
20
- load_in_8bit=True,
21
- torch_dtype=torch.float16,
22
- device_map={'':0}
23
- )
24
-
25
- def load_tokenizer():
26
- global tokenizer
27
- print('Loading tokenizer...')
28
- tokenizer = transformers.LlamaTokenizer.from_pretrained(
29
- 'decapoda-research/llama-7b-hf',
30
- )
31
-
32
- def load_peft_model(model_name):
33
- global model
34
- print('Loading peft model ' + model_name + '...')
35
- model = peft.PeftModel.from_pretrained(
36
- model, model_name,
37
- torch_dtype=torch.float16
38
- )
39
-
40
- def reset_model():
41
- global model
42
- global tokenizer
43
- global current_peft_model
44
-
45
- del model
46
- del tokenizer
47
-
48
- gc.collect()
49
- with torch.no_grad():
50
- torch.cuda.empty_cache()
51
-
52
- model = None
53
- tokenizer = None
54
- current_peft_model = None
55
-
56
- def generate_text(
57
- peft_model,
58
- text,
59
- temperature,
60
- top_p,
61
- top_k,
62
- repetition_penalty,
63
- max_new_tokens,
64
- progress=gr.Progress(track_tqdm=True)
65
- ):
66
- global model
67
- global tokenizer
68
- global current_peft_model
69
-
70
- if (peft_model == 'None'): peft_model = None
71
-
72
- if (current_peft_model != peft_model):
73
- if (current_peft_model is None):
74
- if (model is None): load_base_model()
75
- else:
76
- reset_model()
77
- load_base_model()
78
- load_tokenizer()
79
-
80
- current_peft_model = peft_model
81
- if (peft_model is not None):
82
- load_peft_model(peft_model)
83
-
84
- if (model is None): load_base_model()
85
- if (tokenizer is None): load_tokenizer()
86
-
87
- assert model is not None
88
- assert tokenizer is not None
89
-
90
- inputs = tokenizer(text, return_tensors="pt")
91
- input_ids = inputs["input_ids"].to(model.device)
92
-
93
- generation_config = transformers.GenerationConfig(
94
- max_new_tokens=max_new_tokens,
95
- temperature=temperature,
96
- top_p=top_p,
97
- top_k=top_k,
98
- repetition_penalty=repetition_penalty,
99
- do_sample=True,
100
- num_beams=1,
101
- )
102
-
103
- with torch.no_grad():
104
- output = model.generate( # type: ignore
105
- input_ids=input_ids,
106
- attention_mask=torch.ones_like(input_ids),
107
- generation_config=generation_config
108
- )[0].cuda()
109
-
110
- return tokenizer.decode(output, skip_special_tokens=True).strip()
111
-
112
- def tokenize_and_train(
113
- training_text,
114
- max_seq_length,
115
- micro_batch_size,
116
- gradient_accumulation_steps,
117
- epochs,
118
- learning_rate,
119
- lora_r,
120
- lora_alpha,
121
- lora_dropout,
122
- model_name,
123
- progress=gr.Progress(track_tqdm=True)
124
- ):
125
- global model
126
- global tokenizer
127
-
128
- if (model is None): load_base_model()
129
- if (tokenizer is None):
130
- tokenizer = transformers.LlamaTokenizer.from_pretrained(
131
- "decapoda-research/llama-7b-hf", add_eos_token=True
132
- )
133
-
134
- assert model is not None
135
- assert tokenizer is not None
136
-
137
- tokenizer.pad_token_id = 0
138
-
139
- paragraphs = training_text.split("\n\n\n")
140
- paragraphs = [x.strip() for x in paragraphs]
141
-
142
- print("Number of samples: " + str(len(paragraphs)))
143
-
144
- def tokenize(item):
145
- assert tokenizer is not None
146
- result = tokenizer(
147
- item["text"],
148
- truncation=True,
149
- max_length=max_seq_length,
150
- padding="max_length",
151
- )
152
- return {
153
- "input_ids": result["input_ids"][:-1],
154
- "attention_mask": result["attention_mask"][:-1],
155
- }
156
-
157
- def to_dict(text):
158
- return {"text": text}
159
-
160
- paragraphs = [to_dict(x) for x in paragraphs]
161
- data = datasets.Dataset.from_list(paragraphs)
162
- data = data.shuffle().map(lambda x: tokenize(x))
163
-
164
- model = peft.prepare_model_for_int8_training(model)
165
-
166
- model = peft.get_peft_model(model, peft.LoraConfig(
167
- r=lora_r,
168
- lora_alpha=lora_alpha,
169
- target_modules=["q_proj", "v_proj"],
170
- lora_dropout=lora_dropout,
171
- bias="none",
172
- task_type="CAUSAL_LM",
173
- ))
174
-
175
- output_dir = f"lora-{model_name}"
176
-
177
- print("Training...")
178
-
179
- training_args = transformers.TrainingArguments(
180
- # Set the batch size for training on each device (GPU, CPU, or TPU).
181
- per_device_train_batch_size=micro_batch_size,
182
-
183
- # Number of steps for gradient accumulation. This is useful when the total
184
- # batch size is too large to fit in GPU memory. The effective batch size
185
- # will be the product of 'per_device_train_batch_size' and 'gradient_accumulation_steps'.
186
- gradient_accumulation_steps=gradient_accumulation_steps,
187
-
188
- # Number of warmup steps for the learning rate scheduler. During these steps,
189
- # the learning rate increases linearly from 0 to its initial value. Warmup helps
190
- # to reduce the risk of very large gradients at the beginning of training,
191
- # which could destabilize the model.
192
- # warmup_steps=100,
193
-
194
- # The total number of training steps. The training process will end once this
195
- # number is reached, even if not all the training epochs are completed.
196
- # max_steps=1500,
197
-
198
- # The total number of epochs (complete passes through the training data)
199
- # to perform during the training process.
200
- num_train_epochs=epochs,
201
-
202
- # The initial learning rate to be used during training.
203
- learning_rate=learning_rate,
204
-
205
- # Enables mixed precision training using 16-bit floating point numbers (FP16).
206
- # This can speed up training and reduce GPU memory consumption without
207
- # sacrificing too much model accuracy.
208
- fp16=True,
209
-
210
- # The frequency (in terms of steps) of logging training metrics and statistics
211
- # like loss, learning rate, etc. In this case, it logs after every 20 steps.
212
- logging_steps=20,
213
-
214
- # The output directory where the trained model, checkpoints,
215
- # and other training artifacts will be saved.
216
- output_dir=output_dir,
217
-
218
- # The maximum number of checkpoints to keep. When this limit is reached,
219
- # the oldest checkpoint will be deleted to save a new one. In this case,
220
- # a maximum of 3 checkpoints will be kept.
221
- save_total_limit=3,
222
- )
223
-
224
-
225
- trainer = transformers.Trainer(
226
- # The pre-trained model that you want to fine-tune or train from scratch.
227
- # 'model' should be an instance of a Hugging Face Transformer model, such as BERT, GPT-2, T5, etc.
228
- model=model,
229
-
230
- # The dataset to be used for training. 'data' should be a PyTorch Dataset or
231
- # a compatible format, containing the input samples and labels or masks (if required).
232
- train_dataset=data,
233
-
234
- # The TrainingArguments instance created earlier, which contains various
235
- # hyperparameters and configurations for the training process.
236
- args=training_args,
237
-
238
- # A callable that takes a batch of samples and returns a batch of inputs for the model.
239
- # This is used to prepare the input samples for training by batching, padding, and possibly masking.
240
- data_collator=transformers.DataCollatorForLanguageModeling(
241
- tokenizer,
242
- # Whether to use masked language modeling (MLM) during training.
243
- # MLM is a training technique used in models like BERT, where some tokens in the
244
- # input are replaced by a mask token, and the model tries to predict the
245
- # original tokens. In this case, MLM is set to False, indicating that it will not be used.
246
- mlm=False,
247
- ),
248
- )
249
-
250
- model.config.use_cache = False
251
- result = trainer.train(resume_from_checkpoint=False)
252
- model.save_pretrained(output_dir)
253
-
254
- del data
255
- reset_model()
256
-
257
- return result
258
-
259
- def random_hyphenated_word():
260
- word_list = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
261
- word1 = random.choice(word_list)
262
- word2 = random.choice(word_list)
263
- return word1 + '-' + word2
264
-
265
- def training_tab():
266
- with gr.Tab("Finetuning"):
267
-
268
- with gr.Column():
269
- training_text = gr.Textbox(lines=12, label="Training Data", info="Each sequence must be separated by 2 blank lines")
270
-
271
- max_seq_length = gr.Slider(
272
- minimum=1, maximum=4096, value=512,
273
- label="Max Sequence Length",
274
- info="The maximum length of each sample text sequence. Sequences longer than this will be truncated."
275
- )
276
-
277
- with gr.Row():
278
- with gr.Column():
279
- micro_batch_size = gr.Slider(
280
- minimum=1, maximum=100, value=1,
281
- label="Micro Batch Size",
282
- info="The number of examples in each mini-batch for gradient computation. A smaller micro_batch_size reduces memory usage but may increase training time."
283
- )
284
-
285
- gradient_accumulation_steps = gr.Slider(
286
- minimum=1, maximum=10, value=1,
287
- label="Gradient Accumulation Steps",
288
- info="The number of steps to accumulate gradients before updating model parameters. This can be used to simulate a larger effective batch size without increasing memory usage."
289
- )
290
-
291
- epochs = gr.Slider(
292
- minimum=1, maximum=100, value=1,
293
- label="Epochs",
294
- info="The number of times to iterate over the entire training dataset. A larger number of epochs may improve model performance but also increase the risk of overfitting.")
295
-
296
- learning_rate = gr.Slider(
297
- minimum=0.00001, maximum=0.01, value=3e-4,
298
- label="Learning Rate",
299
- info="The initial learning rate for the optimizer. A higher learning rate may speed up convergence but also cause instability or divergence. A lower learning rate may require more steps to reach optimal performance but also avoid overshooting or oscillating around local minima."
300
- )
301
-
302
- with gr.Column():
303
- lora_r = gr.Slider(
304
- minimum=1, maximum=16, value=8,
305
- label="LoRA R",
306
- info="The rank parameter for LoRA, which controls the dimensionality of the rank decomposition matrices. A larger lora_r increases the expressiveness and flexibility of LoRA but also increases the number of trainable parameters and memory usage."
307
- )
308
-
309
- lora_alpha = gr.Slider(
310
- minimum=1, maximum=128, value=16,
311
- label="LoRA Alpha",
312
- info="The scaling parameter for LoRA, which controls how much LoRA affects the original pre-trained model weights. A larger lora_alpha amplifies the impact of LoRA but may also distort or override the pre-trained knowledge."
313
- )
314
-
315
- lora_dropout = gr.Slider(
316
- minimum=0, maximum=1, value=0.01,
317
- label="LoRA Dropout",
318
- info="The dropout probability for LoRA, which controls the fraction of LoRA parameters that are set to zero during training. A larger lora_dropout increases the regularization effect of LoRA but also increases the risk of underfitting."
319
- )
320
-
321
- with gr.Column():
322
- model_name = gr.Textbox(
323
- lines=1, label="LoRA Model Name", value=random_hyphenated_word()
324
- )
325
-
326
- with gr.Row():
327
- train_btn = gr.Button(
328
- "Train", variant="primary", label="Train",
329
- )
330
-
331
- abort_button = gr.Button(
332
- "Abort", label="Abort",
333
- )
334
-
335
- output_text = gr.Text("Training Status")
336
-
337
- train_progress = train_btn.click(
338
- fn=tokenize_and_train,
339
- inputs=[
340
- training_text,
341
- max_seq_length,
342
- micro_batch_size,
343
- gradient_accumulation_steps,
344
- epochs,
345
- learning_rate,
346
- lora_r,
347
- lora_alpha,
348
- lora_dropout,
349
- model_name
350
- ],
351
- outputs=output_text
352
- )
353
-
354
- abort_button.click(None, None, None, cancels=[train_progress])
355
-
356
- def inference_tab():
357
- with gr.Tab("Inference"):
358
- with gr.Row():
359
- with gr.Column():
360
- with gr.Row():
361
- lora_model = gr.Dropdown(
362
- label="LoRA Model",
363
- )
364
- refresh_models_list = gr.Button(
365
- "Reload Models",
366
- elem_id="refresh-button"
367
- )
368
- inference_text = gr.Textbox(lines=7, label="Input Text")
369
- inference_output = gr.Textbox(lines=12, label="Output Text")
370
- with gr.Row():
371
- with gr.Column():
372
- # temperature, top_p, top_k, repeat_penalty, max_new_tokens
373
- temperature = gr.Slider(
374
- minimum=0.01, maximum=1.99, value=0.1, step=0.01,
375
- label="Temperature",
376
- info="Controls the 'temperature' of the softmax distribution during sampling. Higher values (e.g., 1.0) make the model generate more diverse and random outputs, while lower values (e.g., 0.1) make it more deterministic and focused on the highest probability tokens."
377
- )
378
-
379
- top_p = gr.Slider(
380
- minimum=0, maximum=1, value=0.75, step=0.01,
381
- label="Top P",
382
- info="Sets the nucleus sampling threshold. In nucleus sampling, only the tokens whose cumulative probability exceeds 'top_p' are considered for sampling. This technique helps to reduce the number of low probability tokens considered during sampling, which can lead to more diverse and coherent outputs."
383
- )
384
-
385
- top_k = gr.Slider(
386
- minimum=0, maximum=200, value=50, step=1,
387
- label="Top K",
388
- info="Sets the number of top tokens to consider during sampling. In top-k sampling, only the 'top_k' tokens with the highest probabilities are considered for sampling. This method can lead to more focused and coherent outputs by reducing the impact of low probability tokens."
389
- )
390
-
391
- repeat_penalty = gr.Slider(
392
- minimum=0, maximum=2.5, value=1.2, step=0.01,
393
- label="Repeat Penalty",
394
- info="Applies a penalty to the probability of tokens that have already been generated, discouraging the model from repeating the same words or phrases. The penalty is applied by dividing the token probability by a factor based on the number of times the token has appeared in the generated text."
395
- )
396
-
397
- max_new_tokens = gr.Slider(
398
- minimum=0, maximum=4096, value=50, step=1,
399
- label="Max New Tokens",
400
- info="Limits the maximum number of tokens generated in a single iteration."
401
- )
402
- with gr.Column():
403
- with gr.Row():
404
- generate_btn = gr.Button(
405
- "Generate", variant="primary", label="Generate",
406
- )
407
-
408
- generate_btn.click(
409
- fn=generate_text,
410
- inputs=[
411
- lora_model,
412
- inference_text,
413
- temperature,
414
- top_p,
415
- top_k,
416
- repeat_penalty,
417
- max_new_tokens
418
- ],
419
- outputs=inference_output,
420
- )
421
-
422
- def update_models_list():
423
- return gr.Dropdown.update(choices=["None"] + [
424
- d for d in os.listdir() if os.path.isdir(d) and d.startswith('lora-')
425
- ], value="None")
426
-
427
- refresh_models_list.click(
428
- update_models_list,
429
- inputs=None,
430
- outputs=lora_model,
431
- )
432
-
433
- with gr.Blocks(
434
- css="#refresh-button { max-width: 32px }",
435
- title="Simple LLaMA Finetuner") as demo:
436
- gr.Markdown("""
437
- ## πŸ¦™ Simple LLaMA Finetuner [<img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&amp;style=flat&amp;logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&amp;logoWidth=14" alt="" style="display: inline;">](https://huggingface.co/spaces/lxe/simple-llama-finetuner?duplicate=true)
438
- This tunes the [llama-7b](https://huggingface.co/decapoda-research/llama-7b-hf) model on your own text. Duplicate this space onto a GPU-enabled space to run.
439
- """)
440
- training_tab()
441
- inference_tab()
442
- gr.Markdown("""
443
- Enter your samples separated by two blank lines, then click "Train" to start training a new LoRA model. Once the model is trained, you can use it to generate new text by entering a prompt and clicking "Generate".
444
- """)
445
-
446
- if __name__ == '__main__':
447
- parser = argparse.ArgumentParser(description="Simple LLaMA Finetuner")
448
- parser.add_argument("-s", "--share", action="store_true", help="Enable sharing of the Gradio interface")
449
- args = parser.parse_args()
450
-
451
- demo.queue().launch(share=args.share)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -4,5 +4,5 @@ sentencepiece
4
  git+https://github.com/huggingface/transformers.git
5
  accelerate
6
  bitsandbytes
7
- git+https://github.com/huggingface/peft.git
8
  gradio
 
4
  git+https://github.com/huggingface/transformers.git
5
  accelerate
6
  bitsandbytes
7
+ git+https://github.com/huggingface/peft.git@smangrul/multi-lora-support
8
  gradio
trainer.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from config import HAS_CUDA, MODEL, DEVICE_MAP, TRAINING_PARAMS, LORA_TRAINING_PARAMS, GENERATION_PARAMS
2
+
3
+ import os
4
+ import gc
5
+ import torch
6
+ import transformers
7
+ import peft
8
+ import datasets
9
+ from contextlib import nullcontext
10
+
11
+ class Trainer():
12
+ def __init__(self):
13
+ self.model = None
14
+ self.model_name = None
15
+ self.lora_name = None
16
+ self.loras = {}
17
+
18
+ self.tokenizer = None
19
+ self.trainer = None
20
+
21
+ def unload_model(self):
22
+ del self.model
23
+ del self.tokenizer
24
+
25
+ self.model = None
26
+ self.model_name = None
27
+ self.tokenizer = None
28
+
29
+ if (HAS_CUDA):
30
+ with torch.no_grad():
31
+ torch.cuda.empty_cache()
32
+
33
+ gc.collect()
34
+
35
+ def load_model(self, model_name, force=False, **kwargs):
36
+ assert model_name is not None
37
+
38
+ if (model_name == self.model_name and not force):
39
+ return
40
+
41
+ if (self.model is not None):
42
+ self.unload_model()
43
+
44
+ self.model = transformers.AutoModelForCausalLM.from_pretrained(
45
+ model_name,
46
+ device_map=DEVICE_MAP,
47
+ load_in_8bit=True,
48
+ torch_dtype=torch.float16,
49
+ )
50
+
51
+ if model_name.startswith('decapoda-research/llama'):
52
+ self.tokenizer = transformers.LlamaTokenizer.from_pretrained(model_name)
53
+ else:
54
+ self.tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)
55
+
56
+ self.tokenizer.pad_token_id = 0
57
+ self.model_name = model_name
58
+
59
+ def load_lora(self, lora_name, replace_model=True):
60
+ assert self.model is not None
61
+ assert lora_name is not None
62
+
63
+ if (lora_name == self.lora_name):
64
+ return
65
+
66
+ if lora_name in self.loras:
67
+ self.lora_name = lora_name
68
+ self.model.set_adapter(lora_name)
69
+ return
70
+
71
+ peft_config = peft.PeftConfig.from_pretrained(lora_name)
72
+ if not replace_model:
73
+ assert peft_config.base_model_name_or_path == self.model_name
74
+
75
+ if peft_config.base_model_name_or_path != self.model_name:
76
+ self.load_model(peft_config.base_model_name_or_path)
77
+ self.loras = {}
78
+
79
+ assert self.model_name is not None
80
+ assert self.model is not None
81
+
82
+ if hasattr(self.model, 'load_adapter'):
83
+ self.model.load_adapter(lora_name, adapter_name=lora_name)
84
+ else:
85
+ self.model = peft.PeftModel.from_pretrained(self.model, lora_name, adapter_name=lora_name)
86
+
87
+ self.model.set_adapter(lora_name)
88
+ if (self.model_name.startswith('cerebras')):
89
+ self.model.half()
90
+
91
+ self.lora_name = lora_name
92
+ self.loras[lora_name] = True
93
+
94
+ def unload_lora(self):
95
+ self.lora_name = None
96
+
97
+ def generate(self, prompt, **kwargs):
98
+ assert self.model is not None
99
+ assert self.model_name is not None
100
+ assert self.tokenizer is not None
101
+
102
+ kwargs = { **GENERATION_PARAMS, **kwargs }
103
+
104
+ inputs = self.tokenizer(str(prompt), return_tensors="pt")
105
+ input_ids = inputs["input_ids"].to(self.model.device)
106
+
107
+ if self.model.config.pad_token_id is None:
108
+ kwargs['pad_token_id'] = self.model.config.eos_token_id
109
+
110
+ if (kwargs['do_sample']):
111
+ del kwargs['num_beams']
112
+
113
+ generation_config = transformers.GenerationConfig(
114
+ use_cache=False,
115
+ **kwargs
116
+ )
117
+
118
+ disable_lora = nullcontext()
119
+ if self.lora_name is None and hasattr(self.model, 'disable_adapter'):
120
+ disable_lora = self.model.disable_adapter()
121
+
122
+ with torch.no_grad(), disable_lora:
123
+ output = self.model.generate(
124
+ input_ids=input_ids,
125
+ attention_mask=torch.ones_like(input_ids),
126
+ generation_config=generation_config
127
+ )[0].to(self.model.device)
128
+
129
+ return self.tokenizer.decode(output, skip_special_tokens=True).strip()
130
+
131
+ def tokenize_sample(self, item, max_seq_length, add_eos_token=True):
132
+ assert self.tokenizer is not None
133
+ result = self.tokenizer(
134
+ item["text"],
135
+ truncation=True,
136
+ max_length=max_seq_length,
137
+ padding="max_length",
138
+ )
139
+
140
+ result = {
141
+ "input_ids": result["input_ids"][:-1],
142
+ "attention_mask": result["attention_mask"][:-1],
143
+ }
144
+
145
+ if (
146
+ result["input_ids"][-1] != self.tokenizer.eos_token_id
147
+ and len(result["input_ids"]) < max_seq_length
148
+ and add_eos_token
149
+ ):
150
+ result["input_ids"].append(self.tokenizer.eos_token_id)
151
+ result["attention_mask"].append(1)
152
+
153
+ return result
154
+
155
+ def tokenize_training_text(self, training_text, max_seq_length, separator="\n\n\n", **kwargs):
156
+ samples = training_text.split(separator)
157
+ samples = [x.strip() for x in samples]
158
+ def to_dict(text):
159
+ return { 'text': text }
160
+
161
+ samples = [to_dict(x) for x in samples]
162
+
163
+ training_dataset = datasets.Dataset.from_list(samples)
164
+ training_dataset = training_dataset.shuffle().map(
165
+ lambda x: self.tokenize_sample(x, max_seq_length),
166
+ batched=False
167
+ )
168
+
169
+ return training_dataset
170
+
171
+ def train(self, training_text=None, new_peft_model_name=None, **kwargs):
172
+ assert self.model is not None
173
+ assert self.model_name is not None
174
+ assert self.tokenizer is not None
175
+
176
+ kwargs = { **TRAINING_PARAMS, **LORA_TRAINING_PARAMS, **kwargs }
177
+
178
+ self.lora_name = None
179
+ self.loras = {}
180
+
181
+ train_dataset = self.tokenize_training_text(training_text, **kwargs)
182
+
183
+ if hasattr(self.model, 'disable_adapter'):
184
+ self.load_model(self.model_name, force=True)
185
+
186
+ self.model = peft.prepare_model_for_int8_training(self.model)
187
+ self.model = peft.get_peft_model(self.model, peft.LoraConfig(
188
+ r=kwargs['lora_r'],
189
+ lora_alpha=kwargs['lora_alpha'],
190
+ lora_dropout=kwargs['lora_dropout'],
191
+ bias="none",
192
+ task_type="CAUSAL_LM",
193
+ ))
194
+
195
+ if not os.path.exists('lora'):
196
+ os.makedirs('lora')
197
+
198
+ sanitized_model_name = self.model_name.replace('/', '_').replace('.', '_')
199
+ output_dir = f"lora/{sanitized_model_name}_{new_peft_model_name}"
200
+
201
+ training_args = transformers.TrainingArguments(
202
+ per_device_train_batch_size=kwargs['micro_batch_size'],
203
+ gradient_accumulation_steps=kwargs['gradient_accumulation_steps'],
204
+ num_train_epochs=kwargs['epochs'],
205
+ learning_rate=kwargs['learning_rate'],
206
+ fp16=True,
207
+ optim='adamw_torch',
208
+ logging_steps=20,
209
+ save_total_limit=3,
210
+ output_dir=output_dir,
211
+ )
212
+
213
+ # _trainer = self
214
+ # class LoggingCallback(transformers.TrainerCallback):
215
+ # def on_log(self, args, state, control, logs=None, **kwargs):
216
+ # _trainer.log += json.dumps(logs) + '\n'
217
+
218
+ self.trainer = transformers.Trainer(
219
+ model=self.model,
220
+ train_dataset=train_dataset,
221
+ args=training_args,
222
+ data_collator=transformers.DataCollatorForLanguageModeling(
223
+ self.tokenizer,
224
+ mlm=False,
225
+ ),
226
+ # callbacks=[LoggingCallback()]
227
+ )
228
+
229
+ self.model.config.use_cache = False
230
+ result = self.trainer.train(resume_from_checkpoint=False)
231
+ self.model.save_pretrained(output_dir)
232
+
233
+ return result
234
+
235
+ if __name__ == '__main__':
236
+ t = Trainer()
237
+ t.load_model(MODEL)
238
+
239
+ prompt = "Human: How is cheese made?\n\nAssistant:"
240
+ print(t.generate(prompt))
241
+
242
+ t.load_lora('lora/melon-mango-orange')
243
+ print(t.generate(prompt))
244
+
245
+ t.unload_lora()
246
+ print(t.generate(prompt))