1earner1 commited on
Commit
6460efa
·
verified ·
1 Parent(s): 5acc411

Upload mistral_ft.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. mistral_ft.py +254 -0
mistral_ft.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model_name = "mistralai/Mistral-7B-Instruct-v0.3"
2
+ #model_name = "bigcode/starcoder2-7b"
3
+ #model_name = "dorkai/codeX-1.0" #"Alibaba-NLP/gte-Qwen1.5-7B-instruct" #"google/flan-t5-small" #"microsoft/Phi-3-medium-128k-instruct" #"google/gemma-2-9b-it" # "meta-llama/CodeLlama-7b-hf" #"deepseek-ai/DeepSeek-Coder-V2-Instruct" #"deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct"
4
+ out_name = "HPC_2_mistral_iffp_20k_3" #"meta-llama/Meta-Llama-3-8B" #"tiiuae/falcon-40b" #"Phind/Phind-CodeLlama-34B-v2" # "deepseek-ai/DeepSeek-Coder-V2-Instruct" #
5
+ from datasets import load_dataset, Dataset
6
+ import pandas as pd
7
+ import json
8
+ import traceback
9
+ import torch
10
+ # import json
11
+ # filepath = "/kaggle/input/code-sim-try1/mutated_graph_all_lang_eq.json"
12
+ # examples = []
13
+ # with open(filepath, 'r') as file:
14
+ # for l in file:
15
+ # examples.append(json.loads(l))
16
+
17
+ # len(examples)
18
+ # examples[0]
19
+
20
+ # instruct_tune_dataset = load_dataset("mosaicml/instruct-v3",cache_dir = "/scratch/scai/mtech/aib222688/HF")
21
+ # instruct_tune_dataset = instruct_tune_dataset.filter(lambda x: x["source"] == "dolly_hhrlhf")
22
+
23
+ traindataset_file = "./dataset_lfs/allpairs_data_large.json"
24
+ valdataset_file = "./dataset_lfs/allpairs_data_val.json"
25
+ testdataset_file = "./llm_for_code/datasets/codecontests/verified_iffp_900.json"
26
+ traindata = []
27
+
28
+ with open(traindataset_file, 'r') as file:
29
+ for l in file:
30
+ traindata.append(json.loads(l))
31
+
32
+ valdata = []
33
+
34
+ with open(valdataset_file, 'r') as file:
35
+ for l in file:
36
+ valdata.append(json.loads(l))
37
+
38
+ testdata = []
39
+
40
+
41
+ with open(testdataset_file, 'r') as file:
42
+ for l in file:
43
+ testdata.append(json.loads(l))
44
+ print(len(traindata), len(valdata), len(testdata))
45
+
46
+ def create_prompt(sample):
47
+ bos_token = "<s>"
48
+ original_system_message = "Below is an instruction that describes a task. Write a response that appropriately completes the request."
49
+ system_message = "Use the provided input to create an instruction that could have been used to generate the response with an LLM."
50
+ #print(sample['prompt'])
51
+ response = sample["prompt"].replace(original_system_message, "").replace("\n\n### Instruction\n", "").replace("\n### Response\n", "").strip()
52
+ input = sample["response"]
53
+ eos_token = "</s>"
54
+
55
+ full_prompt = ""
56
+ full_prompt += bos_token
57
+ full_prompt += "### Instruction:"
58
+ full_prompt += "\n" + system_message
59
+ full_prompt += "\n\n### Input:"
60
+ full_prompt += "\n" + input
61
+ full_prompt += "\n\n### Response:"
62
+ full_prompt += "\n" + response
63
+ full_prompt += eos_token
64
+
65
+ return full_prompt
66
+
67
+
68
+ file_path = './prompt_file.txt'
69
+ file_content = ""
70
+ with open(file_path, 'r') as file:
71
+ file_content = file.read()
72
+
73
+
74
+ def create_prompt(pair):
75
+ bos_token = "<s>"
76
+ eos_token = "</s>"
77
+ if pair['prog1']['probid'] == pair['prog2']['probid']:
78
+ response = "Yes"
79
+ else:
80
+ response = "No"
81
+
82
+ full_prompt = ""
83
+ full_prompt += bos_token
84
+ full_prompt += file_content + pair['prog1']['scode'] + "\nProgram 2:"
85
+ full_prompt += pair['prog2']['scode']+ "\n### Response:"
86
+ full_prompt += "\n" + response
87
+ full_prompt += eos_token
88
+
89
+ return full_prompt
90
+
91
+
92
+
93
+ traindataset = Dataset.from_pandas(pd.DataFrame(traindata))
94
+ valdataset = Dataset.from_pandas(pd.DataFrame(valdata))
95
+ testdataset = Dataset.from_pandas(pd.DataFrame(testdata))
96
+
97
+ instruct_tune_dataset = {"train": traindataset,
98
+ "val" : valdataset,
99
+ "test" : testdataset}
100
+
101
+
102
+
103
+ print(create_prompt(instruct_tune_dataset["train"][1]))
104
+
105
+
106
+
107
+ import os
108
+ import torch
109
+ from datasets import load_dataset
110
+ from transformers import (
111
+ AutoModelForCausalLM,
112
+ AutoTokenizer,
113
+ BitsAndBytesConfig,
114
+ HfArgumentParser,
115
+ TrainingArguments,
116
+ pipeline,
117
+ logging,
118
+ )
119
+ from peft import LoraConfig, PeftModel
120
+ from trl import SFTTrainer
121
+
122
+ nf4_config = BitsAndBytesConfig(
123
+ load_in_4bit=True,
124
+ bnb_4bit_quant_type="nf4",
125
+ bnb_4bit_use_double_quant=True,
126
+ bnb_4bit_compute_dtype=torch.bfloat16
127
+ )
128
+
129
+ model = AutoModelForCausalLM.from_pretrained(
130
+ model_name,
131
+ device_map='auto',
132
+ quantization_config=nf4_config,
133
+ use_cache=True,
134
+ cache_dir = "/scratch/scai/mtech/aib222688/HF",
135
+ #trust_remote_code=True,
136
+ )
137
+
138
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
139
+
140
+ tokenizer.pad_token = tokenizer.eos_token
141
+ tokenizer.padding_side = "right"
142
+
143
+ peft_config = LoraConfig(
144
+ lora_alpha=16,
145
+ lora_dropout=0.1,
146
+ r=64,
147
+ bias="none",
148
+ task_type="CAUSAL_LM"
149
+ )
150
+
151
+ import peft
152
+ model = peft.prepare_model_for_kbit_training(model)
153
+ model = peft.get_peft_model(model, peft_config)
154
+
155
+ args = TrainingArguments(
156
+ output_dir = "./"+out_name+"/",
157
+ num_train_epochs=4,
158
+ #max_steps = 10,
159
+ per_device_train_batch_size = 4,
160
+ warmup_steps = 0.03,
161
+ logging_steps=10,
162
+ #save_strategy="epoch",
163
+ #evaluation_strategy="epoch",
164
+ evaluation_strategy="steps",
165
+ eval_steps=100,
166
+ save_steps=500,
167
+ learning_rate=2e-4,
168
+ bf16=True,
169
+ lr_scheduler_type='constant',
170
+ )
171
+
172
+ max_seq_length = 2048
173
+
174
+ trainer = SFTTrainer(
175
+ model=model,
176
+ peft_config=peft_config,
177
+ max_seq_length=max_seq_length,
178
+ tokenizer=tokenizer,
179
+ packing=True,
180
+ formatting_func=create_prompt,
181
+ args=args,
182
+ train_dataset=instruct_tune_dataset["train"],
183
+ eval_dataset=instruct_tune_dataset["val"]
184
+ )
185
+
186
+ # predictions, labels, _ = trainer.predict(instruct_tune_dataset["train"][1])
187
+
188
+ # # Convert predictions and labels to text
189
+ # predicted_texts = tokenizer.batch_decode(predictions.argmax(axis=-1), skip_special_tokens=True)
190
+ # true_texts = tokenizer.batch_decode(labels, skip_special_tokens=True)
191
+ # print(f" Pred {predicted_texts}, True {true_texts}")
192
+
193
+ import time
194
+ start = time.time()
195
+ try:
196
+ trainer.train()
197
+ except Exception as e:
198
+ print(f"ERRORR\n {e}")
199
+ traceback.print_exc()
200
+
201
+ print(time.time()- start)
202
+
203
+
204
+ def generate_response(prompt, model):
205
+ encoded_input = tokenizer(prompt, return_tensors="pt", add_special_tokens=True)
206
+ model_inputs = encoded_input.to('cuda')
207
+
208
+ generated_ids = model.generate(**model_inputs, max_new_tokens=1000, do_sample=True, pad_token_id=tokenizer.eos_token_id)
209
+
210
+ decoded_output = tokenizer.batch_decode(generated_ids)
211
+
212
+ return decoded_output[0].replace(prompt, "")
213
+
214
+
215
+
216
+ try:
217
+ print(generate_response("### Instruction:\nUse the provided input to create an instruction that could have been used to generate the response with an LLM.### Input:\nThere are more than 12,000 species of grass. The most common is Kentucky Bluegrass, because it grows quickly, easily, and is soft to the touch. Rygrass is shiny and bright green colored. Fescues are dark green and shiny. Bermuda grass is harder but can grow in drier soil.\n\n### Response:", trainer.model))
218
+ except Exception as e:
219
+ print(f"ERRORR\n {e}")
220
+ traceback.print_exc()
221
+
222
+
223
+ try:
224
+ trainer.save_model("./"+out_name)
225
+ except Exception as e:
226
+ print(f"ERRORR\n {e}")
227
+ traceback.print_exc()
228
+
229
+
230
+ try:
231
+ torch.save(model.state_dict(), "./"+out_name+"/"+'model_state_dict.pkl')
232
+ except Exception as e:
233
+ print(f"ERRORR\n {e}")
234
+ traceback.print_exc()
235
+
236
+ try:
237
+ tester = SFTTrainer(
238
+ model=trainer.model,
239
+ peft_config=peft_config,
240
+ max_seq_length=max_seq_length,
241
+ tokenizer=tokenizer,
242
+ packing=True,
243
+ formatting_func=create_prompt,
244
+ args=args,
245
+ train_dataset=instruct_tune_dataset["train"],
246
+ eval_dataset=instruct_tune_dataset["test"]
247
+ )
248
+ print(tester.evaluate())
249
+
250
+ except Exception as e:
251
+ print(f"ERRORR\n {e}")
252
+ traceback.print_exc()
253
+
254
+ trainer.push_to_hub("FT/mistral-instruct-generation")