lxe commited on
Commit
e7ee027
0 Parent(s):

Initial commit

Browse files
Files changed (5) hide show
  1. .gitignore +9 -0
  2. README.md +66 -0
  3. main.py +424 -0
  4. requirements.txt +7 -0
  5. rlhf-mini-example.txt +0 -0
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ out/
2
+ 7B/
3
+ 13B/
4
+ __pycache__/
5
+ lora-*
6
+ checkpoint**
7
+ minimal-llama**
8
+ upload.py
9
+ models/
README.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Simple LLaMa FineTuner
2
+
3
+ Simple LLaMa FineTuner is a user-friendly interface designed to facilitate fine-tuning the LLaMa-7B language model using peft/LoRA method. With this intuitive UI, you can easily manage your dataset, customize parameters, train, and evaluate the model's inference capabilities.
4
+
5
+ ## Acknowledgements
6
+
7
+ - https://github.com/zphang/minimal-llama/
8
+ - https://github.com/tloen/alpaca-lora
9
+ - https://github.com/huggingface/peft
10
+ - https://huggingface.co/datasets/Anthropic/hh-rlhf
11
+
12
+ ## Features
13
+
14
+ - Fine-tuning LLaMa-7B on NVIDIA GTX 3090 (or similar hardware)
15
+ - Simply paste datasets in the UI, separated by double blank lines
16
+ - Adjustable parameters for fine-tuning and inference
17
+ - Begner-friendly UI with explanations for each parameter
18
+
19
+ ## Getting Started
20
+
21
+ ### Prerequisites
22
+
23
+ - Python 3.7 or later
24
+ - CUDA 11.0 or later
25
+ - NVIDIA 3090 GPU (or similar hardware) for optimal performance
26
+
27
+ ### Usage
28
+
29
+ 0. I recommend using a virtual environment to install the required packages. Conda preferred
30
+
31
+ ```
32
+ conda install -y cuda -c nvidia/label/cuda-11.7.0
33
+ conda install -y pytorch=1.13.1 pytorch-cuda=11.7 -c pytorch
34
+ ```
35
+
36
+ 1. Clone the repository and install the required packages.
37
+
38
+ ```
39
+ git clone https://github.com/lxe/simple-llama-finetuner.git
40
+ cd simple-llama-finetuner
41
+ pip install -r requirements.txt
42
+ ```
43
+
44
+ 2. Launch it
45
+
46
+ ```
47
+ python main.py
48
+ ```
49
+
50
+ 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.
51
+
52
+ After training is done, navigate to "Inference" tab, click "Reload Models", select your model, and play with it.
53
+
54
+ Have fun!
55
+
56
+ ## License
57
+
58
+ MIT License
59
+
60
+ Copyright (c) 2023 Aleksey Smolenchuk
61
+
62
+ 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:
63
+
64
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
65
+
66
+ 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.
main.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import gradio as gr
4
+ import transformers
5
+
6
+ from datasets import Dataset
7
+ from transformers import LlamaForCausalLM, LlamaTokenizer, GenerationConfig
8
+ from peft import prepare_model_for_int8_training, LoraConfig, get_peft_model, PeftModel
9
+
10
+ model = None
11
+ tokenizer = None
12
+ peft_model = None
13
+
14
+ def maybe_load_models():
15
+ global model
16
+ global tokenizer
17
+
18
+ if model is None:
19
+ model = LlamaForCausalLM.from_pretrained(
20
+ "decapoda-research/llama-7b-hf",
21
+ load_in_8bit=True,
22
+ torch_dtype=torch.float16,
23
+ device_map="auto",
24
+ )
25
+
26
+ if tokenizer is None:
27
+ tokenizer = LlamaTokenizer.from_pretrained(
28
+ "decapoda-research/llama-7b-hf",
29
+ )
30
+
31
+ return model, tokenizer
32
+
33
+ def reset_models():
34
+ global model
35
+ global tokenizer
36
+
37
+ del model
38
+ del tokenizer
39
+
40
+ model = None
41
+ tokenizer = None
42
+
43
+ def generate_text(
44
+ model_name,
45
+ text,
46
+ temperature,
47
+ top_p,
48
+ top_k,
49
+ repeat_penalty,
50
+ max_new_tokens,
51
+ progress=gr.Progress(track_tqdm=True)
52
+ ):
53
+ model, tokenizer = maybe_load_models()
54
+
55
+ if model_name and model_name != "None":
56
+ model = PeftModel.from_pretrained(
57
+ model, model_name,
58
+ torch_dtype=torch.float16
59
+ )
60
+
61
+ inputs = tokenizer(text, return_tensors="pt")
62
+ input_ids = inputs["input_ids"].to(model.device)
63
+ generation_config = GenerationConfig(
64
+ # Controls the 'temperature' of the softmax distribution during sampling.
65
+ # Higher values (e.g., 1.0) make the model generate more diverse and random outputs,
66
+ # while lower values (e.g., 0.1) make it more deterministic and
67
+ # focused on the highest probability tokens.
68
+ temperature=temperature,
69
+
70
+ # Sets the nucleus sampling threshold. In nucleus sampling,
71
+ # only the tokens whose cumulative probability exceeds 'top_p' are considered
72
+ # for sampling. This technique helps to reduce the number of low probability
73
+ # tokens considered during sampling, which can lead to more diverse and coherent outputs.
74
+ top_p=top_p,
75
+
76
+ # Sets the number of top tokens to consider during sampling.
77
+ # In top-k sampling, only the 'top_k' tokens with the highest probabilities
78
+ # are considered for sampling. This method can lead to more focused and coherent
79
+ # outputs by reducing the impact of low probability tokens.
80
+ top_k=top_k,
81
+
82
+ # Applies a penalty to the probability of tokens that have already been generated,
83
+ # discouraging the model from repeating the same words or phrases. The penalty is
84
+ # applied by dividing the token probability by a factor based on the number of times
85
+ # the token has appeared in the generated text.
86
+ repeat_penalty=repeat_penalty,
87
+
88
+ # Limits the maximum number of tokens generated in a single iteration.
89
+ # This can be useful to control the length of generated text, especially in tasks
90
+ # like text summarization or translation, where the output should not be excessively long.
91
+ max_new_tokens=max_new_tokens,
92
+ )
93
+
94
+
95
+ with torch.no_grad():
96
+ generation_output = model.generate(
97
+ input_ids=input_ids,
98
+ attention_mask=torch.ones_like(input_ids),
99
+ generation_config=generation_config,
100
+ return_dict_in_generate=True,
101
+ output_scores=True,
102
+ )
103
+
104
+ output = []
105
+ for token_id in generation_output[0]:
106
+ new = tokenizer.decode(token_id, skip_special_tokens=True)
107
+ output.append(new)
108
+ print(new, end=" ", flush=True)
109
+
110
+ return ''.join(output).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
+ model, tokenizer = maybe_load_models()
126
+
127
+ tokenizer.pad_token_id = 0
128
+
129
+ paragraphs = training_text.split("\n\n\n")
130
+ print("Number of samples: " + str(len(paragraphs)))
131
+
132
+ def tokenize(item):
133
+ result = tokenizer(
134
+ item["text"],
135
+ truncation=True,
136
+ max_length=max_seq_length,
137
+ padding="max_length",
138
+ )
139
+ return {
140
+ "input_ids": result["input_ids"][:-1],
141
+ "attention_mask": result["attention_mask"][:-1],
142
+ }
143
+
144
+ def to_dict(text):
145
+ return {"text": text}
146
+
147
+ paragraphs = [to_dict(x) for x in paragraphs]
148
+ data = Dataset.from_list(paragraphs)
149
+ data = data.shuffle().map(lambda x: tokenize(x))
150
+
151
+ model = prepare_model_for_int8_training(model)
152
+
153
+ model = get_peft_model(model, LoraConfig(
154
+ r=lora_r,
155
+ lora_alpha=lora_alpha,
156
+ target_modules=["q_proj", "v_proj"],
157
+ lora_dropout=lora_dropout,
158
+ bias="none",
159
+ task_type="CAUSAL_LM",
160
+ ))
161
+
162
+ output_dir = f"lora-{model_name}"
163
+
164
+ print("Training...")
165
+
166
+ training_args = transformers.TrainingArguments(
167
+ # Set the batch size for training on each device (GPU, CPU, or TPU).
168
+ per_device_train_batch_size=micro_batch_size,
169
+
170
+ # Number of steps for gradient accumulation. This is useful when the total
171
+ # batch size is too large to fit in GPU memory. The effective batch size
172
+ # will be the product of 'per_device_train_batch_size' and 'gradient_accumulation_steps'.
173
+ gradient_accumulation_steps=gradient_accumulation_steps,
174
+
175
+ # Number of warmup steps for the learning rate scheduler. During these steps,
176
+ # the learning rate increases linearly from 0 to its initial value. Warmup helps
177
+ # to reduce the risk of very large gradients at the beginning of training,
178
+ # which could destabilize the model.
179
+ # warmup_steps=100,
180
+
181
+ # The total number of training steps. The training process will end once this
182
+ # number is reached, even if not all the training epochs are completed.
183
+ # max_steps=1500,
184
+
185
+ # The total number of epochs (complete passes through the training data)
186
+ # to perform during the training process.
187
+ num_train_epochs=epochs,
188
+
189
+ # The initial learning rate to be used during training.
190
+ learning_rate=learning_rate,
191
+
192
+ # Enables mixed precision training using 16-bit floating point numbers (FP16).
193
+ # This can speed up training and reduce GPU memory consumption without
194
+ # sacrificing too much model accuracy.
195
+ fp16=True,
196
+
197
+ # The frequency (in terms of steps) of logging training metrics and statistics
198
+ # like loss, learning rate, etc. In this case, it logs after every 20 steps.
199
+ logging_steps=20,
200
+
201
+ # The output directory where the trained model, checkpoints,
202
+ # and other training artifacts will be saved.
203
+ output_dir=output_dir,
204
+
205
+ # The maximum number of checkpoints to keep. When this limit is reached,
206
+ # the oldest checkpoint will be deleted to save a new one. In this case,
207
+ # a maximum of 3 checkpoints will be kept.
208
+ save_total_limit=3,
209
+ )
210
+
211
+
212
+ trainer = transformers.Trainer(
213
+ # The pre-trained model that you want to fine-tune or train from scratch.
214
+ # 'model' should be an instance of a Hugging Face Transformer model, such as BERT, GPT-2, T5, etc.
215
+ model=model,
216
+
217
+ # The dataset to be used for training. 'data' should be a PyTorch Dataset or
218
+ # a compatible format, containing the input samples and labels or masks (if required).
219
+ train_dataset=data,
220
+
221
+ # The TrainingArguments instance created earlier, which contains various
222
+ # hyperparameters and configurations for the training process.
223
+ args=training_args,
224
+
225
+ # A callable that takes a batch of samples and returns a batch of inputs for the model.
226
+ # This is used to prepare the input samples for training by batching, padding, and possibly masking.
227
+ data_collator=transformers.DataCollatorForLanguageModeling(
228
+ tokenizer,
229
+ # Whether to use masked language modeling (MLM) during training.
230
+ # MLM is a training technique used in models like BERT, where some tokens in the
231
+ # input are replaced by a mask token, and the model tries to predict the
232
+ # original tokens. In this case, MLM is set to False, indicating that it will not be used.
233
+ mlm=False,
234
+ ),
235
+ )
236
+
237
+ result = trainer.train(resume_from_checkpoint=False)
238
+
239
+ model.save_pretrained(output_dir)
240
+
241
+ reset_models()
242
+
243
+ return result
244
+
245
+
246
+ with gr.Blocks(css="#refresh-button { max-width: 32px }") as demo:
247
+ with gr.Tab("Finetuning"):
248
+
249
+ with gr.Column():
250
+ training_text = gr.Textbox(lines=12, label="Training Data", info="Each sequence must be separated by a double newline")
251
+
252
+ max_seq_length = gr.Slider(
253
+ minimum=1, maximum=4096, value=512,
254
+ label="Max Sequence Length",
255
+ info="The maximum length of each sample text sequence. Sequences longer than this will be truncated."
256
+ )
257
+
258
+ with gr.Row():
259
+ with gr.Column():
260
+ micro_batch_size = gr.Slider(
261
+ minimum=1, maximum=100, value=1,
262
+ label="Micro Batch Size",
263
+ 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."
264
+ )
265
+
266
+ gradient_accumulation_steps = gr.Slider(
267
+ minimum=1, maximum=10, value=1,
268
+ label="Gradient Accumulation Steps",
269
+ 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."
270
+ )
271
+
272
+ epochs = gr.Slider(
273
+ minimum=1, maximum=100, value=1,
274
+ label="Epochs",
275
+ 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.")
276
+
277
+ learning_rate = gr.Slider(
278
+ minimum=0.00001, maximum=0.01, value=3e-4,
279
+ label="Learning Rate",
280
+ 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."
281
+ )
282
+
283
+ with gr.Column():
284
+ lora_r = gr.Slider(
285
+ minimum=1, maximum=16, value=8,
286
+ label="LoRA R",
287
+ 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."
288
+ )
289
+
290
+ lora_alpha = gr.Slider(
291
+ minimum=1, maximum=128, value=16,
292
+ label="LoRA Alpha",
293
+ 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."
294
+ )
295
+
296
+ lora_dropout = gr.Slider(
297
+ minimum=0, maximum=1, value=0.01,
298
+ label="LoRA Dropout",
299
+ 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."
300
+ )
301
+
302
+ with gr.Column():
303
+ model_name = gr.Textbox(
304
+ lines=1, label="LoRA Model Name", value=""
305
+ )
306
+
307
+ with gr.Row():
308
+ train_btn = gr.Button(
309
+ "Train", variant="primary", label="Train",
310
+ )
311
+
312
+ abort_button = gr.Button(
313
+ "Abort", label="Abort",
314
+ )
315
+
316
+ output_text = gr.Text("Training Status")
317
+
318
+ train_progress = train_btn.click(
319
+ fn=tokenize_and_train,
320
+ inputs=[
321
+ training_text,
322
+ max_seq_length,
323
+ micro_batch_size,
324
+ gradient_accumulation_steps,
325
+ epochs,
326
+ learning_rate,
327
+ lora_r,
328
+ lora_alpha,
329
+ lora_dropout,
330
+ model_name
331
+ ],
332
+ outputs=output_text
333
+ )
334
+
335
+ abort_button.click(None, None, None, cancels=[train_progress])
336
+
337
+ with gr.Tab("Inference"):
338
+ with gr.Row():
339
+ with gr.Column():
340
+ with gr.Row():
341
+ lora_model = gr.Dropdown(
342
+ label="LoRA Model",
343
+ )
344
+ refresh_models_list = gr.Button(
345
+ "Reload Models",
346
+ elem_id="refresh-button"
347
+ )
348
+ inference_text = gr.Textbox(lines=7, label="Input Text")
349
+ inference_output = gr.Textbox(lines=12, label="Output Text")
350
+ with gr.Row():
351
+ with gr.Column():
352
+ # temperature, top_p, top_k, repeat_penalty, max_new_tokens
353
+ temperature = gr.Slider(
354
+ minimum=0, maximum=2, value=0.7, step=0.1,
355
+ label="Temperature",
356
+ info=""
357
+ )
358
+
359
+ top_p = gr.Slider(
360
+ minimum=0, maximum=1, value=0.2, step=0.1,
361
+ label="Top P",
362
+ info=""
363
+ )
364
+
365
+ top_k = gr.Slider(
366
+ minimum=0, maximum=100, value=50, step=1,
367
+ label="Top K",
368
+ info=""
369
+ )
370
+
371
+ repeat_penalty = gr.Slider(
372
+ minimum=0, maximum=1, value=0.8, step=0.1,
373
+ label="Repeat Penalty",
374
+ info=""
375
+ )
376
+
377
+ max_new_tokens = gr.Slider(
378
+ minimum=0, maximum=4096, value=50, step=1,
379
+ label="Max New Tokens",
380
+ info=""
381
+ )
382
+ with gr.Column():
383
+ with gr.Row():
384
+ generate_btn = gr.Button(
385
+ "Generate", variant="primary", label="Generate",
386
+ )
387
+
388
+ inference_abort_button = gr.Button(
389
+ "Abort", label="Abort",
390
+ )
391
+
392
+ inference_progress = generate_btn.click(
393
+ fn=generate_text,
394
+ inputs=[
395
+ lora_model,
396
+ inference_text,
397
+ temperature,
398
+ top_p,
399
+ top_k,
400
+ repeat_penalty,
401
+ max_new_tokens
402
+ ],
403
+ outputs=inference_output,
404
+ )
405
+
406
+ lora_model.change(
407
+ fn=reset_models
408
+ )
409
+
410
+ def update_models_list():
411
+ return gr.Dropdown.update(choices=["None"] + [
412
+ d for d in os.listdir() if os.path.isdir(d) and d.startswith('lora-')
413
+ ], value="None")
414
+
415
+ refresh_models_list.click(
416
+ update_models_list,
417
+ inputs=None,
418
+ outputs=lora_model,
419
+ )
420
+
421
+
422
+
423
+ if __name__ == "__main__":
424
+ demo.queue().launch()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ datasets
2
+ loralib
3
+ sentencepiece
4
+ git+https://github.com/huggingface/transformers.git
5
+ accelerate
6
+ bitsandbytes
7
+ git+https://github.com/huggingface/peft.git
rlhf-mini-example.txt ADDED
The diff for this file is too large to render. See raw diff