PEFT
K00B404 commited on
Commit
a0db1c5
1 Parent(s): 3f22437

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +185 -0
README.md CHANGED
@@ -1,5 +1,8 @@
1
  ---
2
  library_name: peft
 
 
 
3
  ---
4
  ## Training procedure
5
 
@@ -19,3 +22,185 @@ The following `bitsandbytes` quantization config was used during training:
19
 
20
 
21
  - PEFT 0.6.0.dev0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  library_name: peft
3
+ license: afl-3.0
4
+ datasets:
5
+ - nickrosh/Evol-Instruct-Code-80k-v1
6
  ---
7
  ## Training procedure
8
 
 
22
 
23
 
24
  - PEFT 0.6.0.dev0
25
+
26
+ - # -*- coding: utf-8 -*-
27
+ """bf16_sharded_Fine_Tuning_using_QLora(1).ipynb
28
+
29
+ Automatically generated by Colaboratory.
30
+
31
+ Original file is located at
32
+ https://colab.research.google.com/drive/1yH0ov1ZDpun6yGi19zE07jkF_EUMI1Bf
33
+
34
+ **Code Credit: Hugging Face**
35
+
36
+ **Dataset Credit: https://twitter.com/Dorialexander/status/1681671177696161794 **
37
+
38
+ ## Finetune Llama-2-7b on a Google colab
39
+
40
+ Welcome to this Google Colab notebook that shows how to fine-tune the recent code Llama-2-7b model on a single Google colab and turn it into a chatbot
41
+
42
+ We will leverage PEFT library from Hugging Face ecosystem, as well as QLoRA for more memory efficient finetuning
43
+
44
+ ## Setup
45
+
46
+ Run the cells below to setup and install the required libraries. For our experiment we will need `accelerate`, `peft`, `transformers`, `datasets` and TRL to leverage the recent [`SFTTrainer`](https://huggingface.co/docs/trl/main/en/sft_trainer). We will use `bitsandbytes` to [quantize the base model into 4bit](https://huggingface.co/blog/4bit-transformers-bitsandbytes). We will also install `einops` as it is a requirement to load Falcon models.
47
+ """
48
+
49
+ !pip install -q -U trl transformers accelerate git+https://github.com/huggingface/peft.git
50
+ !pip install -q datasets bitsandbytes einops wandb
51
+
52
+ """## Dataset
53
+
54
+ login huggingface
55
+ """
56
+
57
+ import wandb
58
+
59
+ !wandb login
60
+
61
+ # Initialize WandB
62
+ wandb_key=["<API_KEY>"]
63
+ wandb.init(project="<project_name>",
64
+ name="<name>"
65
+ )
66
+ # login with API
67
+ from huggingface_hub import login
68
+ login()
69
+
70
+ from datasets import load_dataset
71
+
72
+ #dataset_name = "timdettmers/openassistant-guanaco" ###Human ,.,,,,,, ###Assistant
73
+ dataset_name = "nickrosh/Evol-Instruct-Code-80k-v1"
74
+ #dataset_name = 'AlexanderDoria/novel17_test' #french novels
75
+ dataset = load_dataset(dataset_name, split="train")
76
+
77
+ """## Loading the model"""
78
+
79
+ import torch
80
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, AutoTokenizer
81
+
82
+ #model_name = "TinyPixel/Llama-2-7B-bf16-sharded"
83
+ #model_name = "abhinand/Llama-2-7B-bf16-sharded-512MB"
84
+ model_name= "TinyPixel/CodeLlama-7B-Instruct-bf16-sharded"
85
+ bnb_config = BitsAndBytesConfig(
86
+ load_in_4bit=True,
87
+ bnb_4bit_quant_type="nf4",
88
+ bnb_4bit_compute_dtype=torch.float16,
89
+ )
90
+
91
+ model = AutoModelForCausalLM.from_pretrained(
92
+ model_name,
93
+ quantization_config=bnb_config,
94
+ trust_remote_code=True
95
+ )
96
+ model.config.use_cache = False
97
+
98
+ """Let's also load the tokenizer below"""
99
+
100
+ inputs = tokenizer(text, return_tensors="pt", padding="max_length", max_length=max_seq_length, truncation=True).to(device)
101
+
102
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
103
+ tokenizer.pad_token = tokenizer.eos_token
104
+
105
+ from peft import LoraConfig, get_peft_model
106
+
107
+ lora_alpha = 16
108
+ lora_dropout = 0.1
109
+ lora_r = 64
110
+
111
+ peft_config = LoraConfig(
112
+ lora_alpha=lora_alpha,
113
+ lora_dropout=lora_dropout,
114
+ r=lora_r,
115
+ bias="none",
116
+ task_type="CAUSAL_LM"
117
+ )
118
+
119
+ """## Loading the trainer
120
+
121
+ Here we will use the [`SFTTrainer` from TRL library](https://huggingface.co/docs/trl/main/en/sft_trainer) that gives a wrapper around transformers `Trainer` to easily fine-tune models on instruction based datasets using PEFT adapters. Let's first load the training arguments below.
122
+ """
123
+
124
+ from transformers import TrainingArguments
125
+
126
+ output_dir = "./results"
127
+ per_device_train_batch_size = 4
128
+ gradient_accumulation_steps = 4
129
+ optim = "paged_adamw_32bit"
130
+ save_steps = 10
131
+ logging_steps = 11
132
+ learning_rate = 2e-4
133
+ max_grad_norm = 0.3
134
+ max_steps = 10
135
+ warmup_ratio = 0.03
136
+ lr_scheduler_type = "constant"
137
+
138
+ training_arguments = TrainingArguments(
139
+ output_dir=output_dir,
140
+ per_device_train_batch_size=per_device_train_batch_size,
141
+ gradient_accumulation_steps=gradient_accumulation_steps,
142
+ optim=optim,
143
+ save_steps=save_steps,
144
+ logging_steps=logging_steps,
145
+ learning_rate=learning_rate,
146
+ fp16=True,
147
+ max_grad_norm=max_grad_norm,
148
+ max_steps=max_steps,
149
+ warmup_ratio=warmup_ratio,
150
+ group_by_length=True,
151
+ lr_scheduler_type=lr_scheduler_type,
152
+ )
153
+
154
+ """Then finally pass everthing to the trainer"""
155
+
156
+ from trl import SFTTrainer
157
+
158
+ max_seq_length = 512
159
+
160
+ trainer = SFTTrainer(
161
+ model=model,
162
+ train_dataset=dataset,
163
+ peft_config=peft_config,
164
+ dataset_text_field="output",
165
+ max_seq_length=max_seq_length,
166
+ tokenizer=tokenizer,
167
+ args=training_arguments,
168
+ )
169
+
170
+ """We will also pre-process the model by upcasting the layer norms in float 32 for more stable training"""
171
+
172
+ for name, module in trainer.model.named_modules():
173
+ if "norm" in name:
174
+ module = module.to(torch.float32)
175
+
176
+ """## Train the model
177
+ You're using a LlamaTokenizerFast tokenizer. Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding.
178
+
179
+ Now let's train the model! Simply call `trainer.train()`
180
+ """
181
+
182
+ trainer.train()
183
+
184
+ """During training, the model should converge nicely as follows:
185
+
186
+ ![image](https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/loss-falcon-7b.png)
187
+
188
+ The `SFTTrainer` also takes care of properly saving only the adapters during training instead of saving the entire model.
189
+ """
190
+
191
+ model_to_save = trainer.model.module if hasattr(trainer.model, 'module') else trainer.model # Take care of distributed/parallel training
192
+ model_to_save.save_pretrained("outputs")
193
+
194
+ lora_config = LoraConfig.from_pretrained('outputs')
195
+ model = get_peft_model(model, lora_config)
196
+
197
+ dataset['output']
198
+
199
+ text = "make a advanced python script to finetune a llama2-7b-bf16-sharded model with accelerator and qlora"
200
+ device = "cuda:0"
201
+ inputs = tokenizer(text, return_tensors="pt", padding="max_length", max_length=max_seq_length, truncation=True).to(device)
202
+ #inputs = tokenizer(text, return_tensors="pt").to(device)
203
+ outputs = model.generate(**inputs, max_new_tokens=150)
204
+ print(tokenizer.decode(outputs[0], skip_special_tokens=False))
205
+
206
+ model.push_to_hub("K00B404/CodeLlama-7B-Instruct-bf16-sharded-ft-v0_01", use_auth_token="<HUGGINGFACE_WRITE-api")