ArunKr commited on
Commit
ba14f1f
1 Parent(s): 93ef792

Upload 2 files

Browse files
Copy_of_Alpaca_+_Llama_3_8b_full_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
copy_of_alpaca_+_llama_3_8b_full_example.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Copy of Alpaca + Llama-3 8b full example.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/12GTGPtaZvutZlE2GUHmeXVrvq2dgJdu6
8
+
9
+ ## To run this, press "*Runtime*" and press "*Run all*" on a **free** Tesla T4 Google Colab instance!
10
+
11
+ To install Unsloth on your own computer, follow the installation instructions on our Github page [here](https://github.com/unslothai/unsloth#installation-instructions---conda).
12
+
13
+ You will learn how to do [data prep](#Data), how to [train](#Train), how to [run the model](#Inference), & [how to save it](#Save) (eg for Llama.cpp).
14
+
15
+ **Llama-3 8b is trained on a crazy 15 trillion tokens! Llama-2 was 2 trillion.**
16
+ """
17
+
18
+ # Commented out IPython magic to ensure Python compatibility.
19
+ # %%capture
20
+ # # Installs Unsloth, Xformers (Flash Attention) and all other packages!
21
+ # !pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
22
+ # !pip install --no-deps "xformers<0.0.26" trl peft accelerate bitsandbytes
23
+
24
+ token = "" #HF Token
25
+
26
+ """* We support Llama, Mistral, CodeLlama, TinyLlama, Vicuna, Open Hermes etc
27
+ * And Yi, Qwen ([llamafied](https://huggingface.co/models?sort=trending&search=qwen+llama)), Deepseek, all Llama, Mistral derived archs.
28
+ * We support 16bit LoRA or 4bit QLoRA. Both 2x faster.
29
+ * `max_seq_length` can be set to anything, since we do automatic RoPE Scaling via [kaiokendev's](https://kaiokendev.github.io/til) method.
30
+ * [**NEW**] With [PR 26037](https://github.com/huggingface/transformers/pull/26037), we support downloading 4bit models **4x faster**! [Our repo](https://huggingface.co/unsloth) has Llama, Mistral 4bit models.
31
+ """
32
+
33
+ from unsloth import FastLanguageModel
34
+ import torch
35
+ max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
36
+ dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
37
+ load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
38
+
39
+ # 4bit pre quantized models we support for 4x faster downloading + no OOMs.
40
+ fourbit_models = [
41
+ "unsloth/mistral-7b-bnb-4bit",
42
+ "unsloth/mistral-7b-instruct-v0.2-bnb-4bit",
43
+ "unsloth/llama-2-7b-bnb-4bit",
44
+ "unsloth/gemma-7b-bnb-4bit",
45
+ "unsloth/gemma-7b-it-bnb-4bit", # Instruct version of Gemma 7b
46
+ "unsloth/gemma-2b-bnb-4bit",
47
+ "unsloth/gemma-2b-it-bnb-4bit", # Instruct version of Gemma 2b
48
+ "unsloth/llama-3-8b-bnb-4bit", # [NEW] 15 Trillion token Llama-3
49
+ ] # More models at https://huggingface.co/unsloth
50
+
51
+ model, tokenizer = FastLanguageModel.from_pretrained(
52
+ model_name = "unsloth/llama-3-8b-bnb-4bit",
53
+ max_seq_length = max_seq_length,
54
+ dtype = dtype,
55
+ load_in_4bit = load_in_4bit,
56
+ # token = token, # use one if using gated models like meta-llama/Llama-2-7b-hf
57
+ )
58
+
59
+ """We now add LoRA adapters so we only need to update 1 to 10% of all parameters!"""
60
+
61
+ model = FastLanguageModel.get_peft_model(
62
+ model,
63
+ r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
64
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
65
+ "gate_proj", "up_proj", "down_proj",],
66
+ lora_alpha = 16,
67
+ lora_dropout = 0, # Supports any, but = 0 is optimized
68
+ bias = "none", # Supports any, but = "none" is optimized
69
+ # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
70
+ use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
71
+ random_state = 3407,
72
+ use_rslora = False, # We support rank stabilized LoRA
73
+ loftq_config = None, # And LoftQ
74
+ )
75
+
76
+ """<a name="Data"></a>
77
+ ### Data Prep
78
+ We now use the Alpaca dataset from [yahma](https://huggingface.co/datasets/yahma/alpaca-cleaned), which is a filtered version of 52K of the original [Alpaca dataset](https://crfm.stanford.edu/2023/03/13/alpaca.html). You can replace this code section with your own data prep.
79
+
80
+ **[NOTE]** To train only on completions (ignoring the user's input) read TRL's docs [here](https://huggingface.co/docs/trl/sft_trainer#train-on-completions-only).
81
+
82
+ **[NOTE]** Remember to add the **EOS_TOKEN** to the tokenized output!! Otherwise you'll get infinite generations!
83
+
84
+ If you want to use the `ChatML` template for ShareGPT datasets, try our conversational [notebook](https://colab.research.google.com/drive/1Aau3lgPzeZKQ-98h69CCu1UJcvIBLmy2?usp=sharing).
85
+
86
+ For text completions like novel writing, try this [notebook](https://colab.research.google.com/drive/1ef-tab5bhkvWmBOObepl1WgJvfvSzn5Q?usp=sharing).
87
+ """
88
+
89
+ alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context.
90
+ Write a response that appropriately completes the request.
91
+
92
+ ### Instruction:
93
+ {}
94
+
95
+ ### Input:
96
+ {}
97
+
98
+ ### Response:
99
+ {}"""
100
+
101
+ EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
102
+ def formatting_prompts_func(examples):
103
+ instructions = examples["instruction"]
104
+ inputs = examples["input"]
105
+ outputs = examples["output"]
106
+ texts = []
107
+ for instruction, input, output in zip(instructions, inputs, outputs):
108
+ # Must add EOS_TOKEN, otherwise your generation will go on forever!
109
+ text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
110
+ texts.append(text)
111
+ return { "text" : texts, }
112
+ pass
113
+
114
+ from datasets import load_dataset
115
+ dataset = load_dataset("yahma/alpaca-cleaned", split = "train")
116
+ dataset = dataset.map(formatting_prompts_func, batched = True,)
117
+
118
+ """<a name="Train"></a>
119
+ ### Train the model
120
+ Now let's use Huggingface TRL's `SFTTrainer`! More docs here: [TRL SFT docs](https://huggingface.co/docs/trl/sft_trainer). We do 60 steps to speed things up, but you can set `num_train_epochs=1` for a full run, and turn off `max_steps=None`. We also support TRL's `DPOTrainer`!
121
+ """
122
+
123
+ from trl import SFTTrainer
124
+ from transformers import TrainingArguments
125
+
126
+ trainer = SFTTrainer(
127
+ model = model,
128
+ tokenizer = tokenizer,
129
+ train_dataset = dataset,
130
+ dataset_text_field = "text",
131
+ max_seq_length = max_seq_length,
132
+ dataset_num_proc = 2,
133
+ packing = False, # Can make training 5x faster for short sequences.
134
+ args = TrainingArguments(
135
+ per_device_train_batch_size = 2,
136
+ gradient_accumulation_steps = 4,
137
+ warmup_steps = 5,
138
+ max_steps = 60,
139
+ learning_rate = 2e-4,
140
+ fp16 = not torch.cuda.is_bf16_supported(),
141
+ bf16 = torch.cuda.is_bf16_supported(),
142
+ logging_steps = 1,
143
+ optim = "adamw_8bit",
144
+ weight_decay = 0.01,
145
+ lr_scheduler_type = "linear",
146
+ seed = 3407,
147
+ output_dir = "outputs",
148
+ ),
149
+ )
150
+
151
+ #@title Show current memory stats
152
+ gpu_stats = torch.cuda.get_device_properties(0)
153
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
154
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
155
+ print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
156
+ print(f"{start_gpu_memory} GB of memory reserved.")
157
+
158
+ trainer_stats = trainer.train()
159
+
160
+ #@title Show final memory and time stats
161
+ used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
162
+ used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
163
+ used_percentage = round(used_memory /max_memory*100, 3)
164
+ lora_percentage = round(used_memory_for_lora/max_memory*100, 3)
165
+ print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
166
+ print(f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training.")
167
+ print(f"Peak reserved memory = {used_memory} GB.")
168
+ print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
169
+ print(f"Peak reserved memory % of max memory = {used_percentage} %.")
170
+ print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
171
+
172
+ """<a name="Inference"></a>
173
+ ### Inference
174
+ Let's run the model! You can change the instruction and input - leave the output blank!
175
+ """
176
+
177
+ # alpaca_prompt = Copied from above
178
+ FastLanguageModel.for_inference(model) # Enable native 2x faster inference
179
+ inputs = tokenizer(
180
+ [
181
+ alpaca_prompt.format(
182
+ "Continue the fibonnaci sequence.", # instruction
183
+ "1, 1, 2, 3, 5, 8", # input
184
+ "", # output - leave this blank for generation!
185
+ )
186
+ ], return_tensors = "pt").to("cuda")
187
+
188
+ outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
189
+ tokenizer.batch_decode(outputs)
190
+
191
+ """ You can also use a `TextStreamer` for continuous inference - so you can see the generation token by token, instead of waiting the whole time!"""
192
+
193
+ # alpaca_prompt = Copied from above
194
+ FastLanguageModel.for_inference(model) # Enable native 2x faster inference
195
+ inputs = tokenizer(
196
+ [
197
+ alpaca_prompt.format(
198
+ "Continue the fibonnaci sequence.", # instruction
199
+ "1, 1, 2, 3, 5, 8", # input
200
+ "", # output - leave this blank for generation!
201
+ )
202
+ ], return_tensors = "pt").to("cuda")
203
+
204
+ from transformers import TextStreamer
205
+ text_streamer = TextStreamer(tokenizer)
206
+ _ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 128)
207
+
208
+ """<a name="Save"></a>
209
+ ### Saving, loading finetuned models
210
+ To save the final model as LoRA adapters, either use Huggingface's `push_to_hub` for an online save or `save_pretrained` for a local save.
211
+
212
+ **[NOTE]** This ONLY saves the LoRA adapters, and not the full model. To save to 16bit or GGUF, scroll down!
213
+ """
214
+
215
+ #model.save_pretrained("lora_model") # Local saving
216
+ #tokenizer.save_pretrained("lora_model")
217
+ model.push_to_hub("ArunKr/LLama3-LoRA", token = token) # Online saving
218
+ tokenizer.push_to_hub("ArunKr/LLama3-LoRA", token = token) # Online saving
219
+
220
+ """Now if you want to load the LoRA adapters we just saved for inference, set `False` to `True`:"""
221
+
222
+ if False:
223
+ from unsloth import FastLanguageModel
224
+ model, tokenizer = FastLanguageModel.from_pretrained(
225
+ model_name = "lora_model", # YOUR MODEL YOU USED FOR TRAINING
226
+ max_seq_length = max_seq_length,
227
+ dtype = dtype,
228
+ load_in_4bit = load_in_4bit,
229
+ )
230
+ FastLanguageModel.for_inference(model) # Enable native 2x faster inference
231
+
232
+ # alpaca_prompt = You MUST copy from above!
233
+
234
+ inputs = tokenizer(
235
+ [
236
+ alpaca_prompt.format(
237
+ "What is a famous tall tower in Paris?", # instruction
238
+ "", # input
239
+ "", # output - leave this blank for generation!
240
+ )
241
+ ], return_tensors = "pt").to("cuda")
242
+
243
+ outputs = model.generate(**inputs, max_new_tokens = 64, use_cache = True)
244
+ tokenizer.batch_decode(outputs)
245
+
246
+ """You can also use Hugging Face's `AutoModelForPeftCausalLM`. Only use this if you do not have `unsloth` installed. It can be hopelessly slow, since `4bit` model downloading is not supported, and Unsloth's **inference is 2x faster**."""
247
+
248
+ if False:
249
+ # I highly do NOT suggest - use Unsloth if possible
250
+ from peft import AutoPeftModelForCausalLM
251
+ from transformers import AutoTokenizer
252
+ model = AutoPeftModelForCausalLM.from_pretrained(
253
+ "lora_model", # YOUR MODEL YOU USED FOR TRAINING
254
+ load_in_4bit = load_in_4bit,
255
+ )
256
+ tokenizer = AutoTokenizer.from_pretrained("lora_model")
257
+
258
+ """### Saving to float16 for VLLM
259
+
260
+ We also support saving to `float16` directly. Select `merged_16bit` for float16 or `merged_4bit` for int4. We also allow `lora` adapters as a fallback. Use `push_to_hub_merged` to upload to your Hugging Face account! You can go to https://huggingface.co/settings/tokens for your personal tokens.
261
+ """
262
+
263
+ # Merge to 16bit
264
+ if False: model.save_pretrained_merged("model", tokenizer, save_method = "merged_16bit",)
265
+ if True: model.push_to_hub_merged("ArunKr/LLama3-LoRA", tokenizer, save_method = "merged_16bit", token = token)
266
+
267
+ # Merge to 4bit
268
+ if False: model.save_pretrained_merged("model", tokenizer, save_method = "merged_4bit",)
269
+ if True: model.push_to_hub_merged("ArunKr/LLama3-LoRA", tokenizer, save_method = "merged_4bit_forced", token = token)
270
+
271
+ # Just LoRA adapters
272
+ if False: model.save_pretrained_merged("model", tokenizer, save_method = "lora",)
273
+ if True: model.push_to_hub_merged("ArunKr/LLama3-LoRA", tokenizer, save_method = "lora", token = token)
274
+
275
+ """### GGUF / llama.cpp Conversion
276
+ To save to `GGUF` / `llama.cpp`, we support it natively now! We clone `llama.cpp` and we default save it to `q8_0`. We allow all methods like `q4_k_m`. Use `save_pretrained_gguf` for local saving and `push_to_hub_gguf` for uploading to HF.
277
+
278
+ Some supported quant methods (full list on our [Wiki page](https://github.com/unslothai/unsloth/wiki#gguf-quantization-options)):
279
+ * `q8_0` - Fast conversion. High resource use, but generally acceptable.
280
+ * `q4_k_m` - Recommended. Uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q4_K.
281
+ * `q5_k_m` - Recommended. Uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q5_K.
282
+ """
283
+
284
+ # Save to 8bit Q8_0
285
+ if False: model.save_pretrained_gguf("model", tokenizer,)
286
+ if True: model.push_to_hub_gguf("ArunKr/LLama3-LoRA", tokenizer, token = token)
287
+
288
+ # Save to 16bit GGUF
289
+ if False: model.save_pretrained_gguf("model", tokenizer, quantization_method = "f16")
290
+ if True: model.push_to_hub_gguf("ArunKr/LLama3-LoRA", tokenizer, quantization_method = "f16", token = token)
291
+
292
+ # Save to q4_k_m GGUF
293
+ if False: model.save_pretrained_gguf("model", tokenizer, quantization_method = "q4_k_m")
294
+ if True: model.push_to_hub_gguf("ArunKr/LLama3-LoRA", tokenizer, quantization_method = "q4_k_m", token = token)
295
+
296
+ """Now, use the `model-unsloth.gguf` file or `model-unsloth-Q4_K_M.gguf` file in `llama.cpp` or a UI based system like `GPT4All`. You can install GPT4All by going [here](https://gpt4all.io/index.html).
297
+
298
+ And we're done! If you have any questions on Unsloth, we have a [Discord](https://discord.gg/u54VK8m8tk) channel! If you find any bugs or want to keep updated with the latest LLM stuff, or need help, join projects etc, feel free to join our Discord!
299
+
300
+ Some other links:
301
+ 1. Zephyr DPO 2x faster [free Colab](https://colab.research.google.com/drive/15vttTpzzVXv_tJwEk-hIcQ0S9FcEWvwP?usp=sharing)
302
+ 2. Llama 7b 2x faster [free Colab](https://colab.research.google.com/drive/1lBzz5KeZJKXjvivbYvmGarix9Ao6Wxe5?usp=sharing)
303
+ 3. TinyLlama 4x faster full Alpaca 52K in 1 hour [free Colab](https://colab.research.google.com/drive/1AZghoNBQaMDgWJpi4RbffGM1h6raLUj9?usp=sharing)
304
+ 4. CodeLlama 34b 2x faster [A100 on Colab](https://colab.research.google.com/drive/1y7A0AxE3y8gdj4AVkl2aZX47Xu3P1wJT?usp=sharing)
305
+ 5. Mistral 7b [free Kaggle version](https://www.kaggle.com/code/danielhanchen/kaggle-mistral-7b-unsloth-notebook)
306
+ 6. We also did a [blog](https://huggingface.co/blog/unsloth-trl) with 🤗 HuggingFace, and we're in the TRL [docs](https://huggingface.co/docs/trl/main/en/sft_trainer#accelerate-fine-tuning-2x-using-unsloth)!
307
+ 7. `ChatML` for ShareGPT datasets, [conversational notebook](https://colab.research.google.com/drive/1Aau3lgPzeZKQ-98h69CCu1UJcvIBLmy2?usp=sharing)
308
+ 8. Text completions like novel writing [notebook](https://colab.research.google.com/drive/1ef-tab5bhkvWmBOObepl1WgJvfvSzn5Q?usp=sharing)
309
+ """
310
+