1earner1 commited on
Commit
6244dc4
·
verified ·
1 Parent(s): a3da071

Upload run_lora_newchat.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. run_lora_newchat.py +643 -0
run_lora_newchat.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_5_lora" #"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 peft
10
+ import os
11
+ from tqdm import tqdm
12
+ import sys
13
+ import math
14
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, AdamW, default_data_collator, get_linear_schedule_with_warmup, get_cosine_schedule_with_warmup,set_seed
15
+ from torch.utils.data import DataLoader
16
+ import numpy as np
17
+ import os
18
+ import argparse
19
+ import torch
20
+ import datetime
21
+ from datasets import load_dataset
22
+ from transformers import (
23
+ AutoModelForCausalLM,
24
+ AutoTokenizer,
25
+ BitsAndBytesConfig,
26
+ HfArgumentParser,
27
+ TrainingArguments,
28
+ pipeline,
29
+ logging,
30
+ )
31
+ from peft import LoraConfig, PeftModel
32
+ from trl import SFTTrainer
33
+ import os
34
+ os.environ['WANDB_MODE'] = 'online'
35
+ import wandb
36
+ import socket
37
+ import random
38
+
39
+ def set_seed(seed: int = 42):
40
+ random.seed(seed) # Python’s built-in random module
41
+ np.random.seed(seed) # NumPy
42
+ torch.manual_seed(seed) # PyTorch CPU
43
+ torch.cuda.manual_seed(seed) # PyTorch GPU
44
+ torch.cuda.manual_seed_all(seed) # If using multi-GPU
45
+ torch.backends.cudnn.deterministic = True # Ensures deterministic behavior in CuDNN
46
+ torch.backends.cudnn.benchmark = False # Disables benchmarking to maintain consistency
47
+
48
+ # Example usage
49
+ set_seed(42)
50
+
51
+ # import json
52
+ # filepath = "/kaggle/input/code-sim-try1/mutated_graph_all_lang_eq.json"
53
+ # examples = []
54
+ # with open(filepath, 'r') as file:
55
+ # for l in file:
56
+ # examples.append(json.loads(l))
57
+
58
+ # len(examples)
59
+ # examples[0]
60
+
61
+ # instruct_tune_dataset = load_dataset("mosaicml/instruct-v3",cache_dir = "/scratch/scai/mtech/aib222688/HF")
62
+ # instruct_tune_dataset = instruct_tune_dataset.filter(lambda x: x["source"] == "dolly_hhrlhf")
63
+
64
+
65
+ # traindataset_file = "./dataset_lfs/allpairs_data_large_900_loop2.json"
66
+ # valdataset_file = "./dataset_lfs/allpairs_data_val_900_loop2.json"
67
+ # testdataset_file = "./llm_for_code/datasets/codecontests/verified_iffp_900_loop2.json"
68
+
69
+ # initial_lr = 5e-6
70
+ # checkpoint_store_dir_path = "./HPC_2_mistral_iffp_20k_3_lora_900_loop2"
71
+
72
+ # num_epochs = 5
73
+ # batch_size_train = 1
74
+ # max_length = 2000
75
+ # ckpnt_NUM = 2000
76
+ # SAVEALL = False #True
77
+
78
+
79
+ parser = argparse.ArgumentParser(description='Run lora finetuning..., NOTE: UPDATE PEFT CONFIG if needed')
80
+ parser.add_argument('--model_name', default="mistralai/Mistral-7B-Instruct-v0.3",type=str)
81
+ parser.add_argument('--traindataset_files', nargs='+', type=str, default="./dataset_lfs/allpairs_data_large_900_loop2.json")
82
+ parser.add_argument('--valdataset_file', type=str, default="./dataset_lfs/allpairs_data_val_900_loop2.json")
83
+ parser.add_argument('--testdataset_file', type=str, default="./llm_for_code/datasets/codecontests/verified_iffp_900_loop2.json")
84
+ parser.add_argument('--checkpoint_store_dir_path', type=str, default="./HPC_3_mistral_iffp_20k_3_lora_900_loop2")
85
+ parser.add_argument('--initial_lr', type=float, default=5e-6)
86
+ parser.add_argument('--num_epochs', type=int, default=5)
87
+ parser.add_argument('--batch_size_train', type=int, default=1)
88
+ parser.add_argument('--ckpnt_num', type=int, default=2000)
89
+ parser.add_argument('--saveall', type=int, default=0)
90
+ parser.add_argument('--prompt_file_path', type=str, default='./loop_prompt.txt')
91
+ parser.add_argument('--max_length', type=int, default=2000)
92
+ parser.add_argument('--max_new_tok', type=int, default=50)
93
+
94
+ args = parser.parse_args()
95
+ print(f"{len(vars(args))=}")
96
+
97
+ np.random.seed(40)
98
+ torch.manual_seed(40)
99
+ torch.cuda.manual_seed_all(40)
100
+
101
+
102
+
103
+ model_name = args.model_name.replace('\r', '')
104
+ traindataset_files = args.traindataset_files
105
+ for i in range(len(traindataset_files)):
106
+ traindataset_files[i] = traindataset_files[i].replace('\r', '')
107
+ #traindataset_file = args.traindataset_file.replace('\r', '')
108
+ valdataset_file = args.valdataset_file.replace('\r', '')
109
+ testdataset_file = args.testdataset_file.replace('\r', '')
110
+ checkpoint_store_dir_path = args.checkpoint_store_dir_path.replace('\r', '')
111
+ initial_lr = args.initial_lr
112
+ num_epochs = args.num_epochs
113
+ batch_size_train = args.batch_size_train
114
+ ckpnt_NUM = args.ckpnt_num
115
+ SAVEALL = args.saveall
116
+ prompt_file_path = args.prompt_file_path.replace('\r', '')
117
+ max_length = args.max_length
118
+ max_new_tok = args.max_new_tok
119
+
120
+
121
+
122
+ hostname = socket.gethostname()
123
+ ip_address = socket.gethostbyname(hostname)
124
+ node_name = os.uname().nodename
125
+ system_info = os.uname()
126
+ machine_info = {
127
+ "hostname": hostname,
128
+ "ip_address": ip_address,
129
+ "node_name": node_name,
130
+ "system_info": {
131
+ "sysname": system_info.sysname,
132
+ "nodename": system_info.nodename,
133
+ "release": system_info.release,
134
+ "version": system_info.version,
135
+ "machine": system_info.machine,
136
+ },
137
+ }
138
+
139
+ os.makedirs(checkpoint_store_dir_path, exist_ok=True)
140
+ current_time = datetime.datetime.now()
141
+
142
+ with open(checkpoint_store_dir_path+'/lora_logs.txt', 'a') as log_file:
143
+ log_file.write(f"{current_time}: running lora\n {vars(args)}\n")
144
+ log_file.write(f"{machine_info}-----\n")
145
+
146
+ traindata = []
147
+ nf4_config = BitsAndBytesConfig(
148
+ load_in_4bit=True,
149
+ bnb_4bit_quant_type="nf4",
150
+ bnb_4bit_use_double_quant=True,
151
+ bnb_4bit_compute_dtype=torch.bfloat16
152
+ )
153
+
154
+ mpath = './codellama'
155
+ # model = AutoModelForCausalLM.from_pretrained(
156
+ # model_name,
157
+ # #device_map='auto',
158
+ # #quantization_config=nf4_config,
159
+ # use_cache=True,
160
+ # #cache_dir = "../aib222688.scratch/HF/",
161
+ # attn_implementation="sdpa", #"flash_attention_2",
162
+ # torch_dtype=torch.float16,
163
+ # #trust_remote_code=True,
164
+ # )
165
+ model = AutoModelForCausalLM.from_pretrained(
166
+ #mpath,
167
+ model_name,
168
+ device_map='auto',
169
+ #use_cache=True,
170
+ #cache_dir = "../aib222688.scratch/HF/",
171
+ attn_implementation="flash_attention_2",
172
+ torch_dtype=torch.bfloat16,
173
+
174
+ #quantization_config=nf4_config,
175
+ #use_cache=False
176
+ )
177
+
178
+ print(f"Shards loaded for {model_name}")
179
+ # for name, module in model.named_modules():
180
+ # print(f"{name}: {module}")
181
+
182
+ # model = AutoModelForCausalLM.from_pretrained(
183
+ # "./HPC_2_mistral_iffp_20k_2_lora_1200/checkpoint_0_18000/"
184
+ # )
185
+
186
+ #tokenizer = AutoTokenizer.from_pretrained(model_name)
187
+ # tokenizer = AutoTokenizer.from_pretrained(mpath)
188
+
189
+ # tokenizer.pad_token = tokenizer.eos_token
190
+ # tokenizer.padding_side = "right"
191
+
192
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
193
+ #tokenizer = AutoTokenizer.from_pretrained(load_path)
194
+ tokenizer.pad_token = tokenizer.eos_token
195
+ tokenizer.padding_side = "right"
196
+
197
+ #wandb.login(key='e7fdeef2a423ceed55ae12d2c9f1bc530a9e9331')
198
+ wandb.init(project=checkpoint_store_dir_path[3:]+'_wandb', config={
199
+ 'args' : vars(args),
200
+ 'machine' : machine_info,
201
+ })
202
+
203
+ for traindataset_file in traindataset_files:
204
+ with open(traindataset_file, 'r') as file:
205
+ for l in file:
206
+ traindata.append(json.loads(l))
207
+
208
+ valdata = []
209
+
210
+ with open(valdataset_file, 'r') as file:
211
+ for l in file:
212
+ valdata.append(json.loads(l))
213
+
214
+ testdata = []
215
+
216
+
217
+ with open(testdataset_file, 'r') as file:
218
+ for l in file:
219
+ testdata.append(json.loads(l))
220
+ print(len(traindata), len(valdata), len(testdata))
221
+
222
+
223
+
224
+
225
+
226
+ file_content = ""
227
+ with open(prompt_file_path, 'r') as file:
228
+ file_content = file.read()
229
+
230
+
231
+ def create_prompt(pair):
232
+ #bos_token = "<|im_start|>system\n"+ "You are a helpful assistant.\n" + "<|im_end|>\n"+ "<|im_start|>user\n"
233
+ #eos_token = "<|im_end|>\n"+"<|im_start|>assistant\n"
234
+ bos_token = """<|im_start|>system
235
+ You are a helpful assistant.<|im_end|>
236
+ <|im_start|>user"""
237
+ eos_token = """<|im_end|>
238
+ <|im_start|>assistant"""
239
+
240
+ if pair['label'] == 1: # if pair['prog1']['probid'] == pair['prog2']['probid']: #
241
+ response = "Yes"
242
+ else:
243
+ response = "No"
244
+
245
+ full_prompt = ""
246
+ #full_prompt += bos_token
247
+ #print(f"{pair['prog1']['scode']=}")
248
+ full_prompt += file_content + pair['prog1']['scode'] + "\nProgram 2:"
249
+ full_prompt += pair['prog2']['scode']+ "\n" ### Response:"
250
+ full_prompt += "\n" #+ response
251
+ #full_prompt += eos_token
252
+ #response += "<|im_end|>"
253
+
254
+ messages = [ {"role": "system", "content": "You are a helpful assistant."},
255
+ {"role": "user", "content": full_prompt}, ]
256
+
257
+ return full_prompt, response #messages, response
258
+ #print(create_prompt(instruct_tune_dataset["train"][1]))
259
+
260
+
261
+ if "Qwen" not in model_name:
262
+ print("DSC!!!")
263
+ def create_prompt(pair):
264
+ bos_token = "<|begin▁of▁sentence|>You are a helpful assistant.### Instruction:\n"
265
+ eos_token = "\n### Response:\n"
266
+
267
+ """
268
+ if pair_label == 'true' or pair_label == True or pair_label==1:
269
+ #if category[2] == '1' and category[-1] == '1':
270
+ #if prog0["probid"] == prog1["probid"]:
271
+ correct_answer = True
272
+ else:
273
+ correct_answer = False
274
+ if 'ori' in out_file and category[2] == '1' :
275
+ correct_answer = True
276
+ elif 'ori' in out_file and category[2] == '0':
277
+ correct_answer = False
278
+ """
279
+
280
+
281
+ if pair['prog1']['probid'] == pair['prog2']['probid']: # if pair['label'] == 1: #
282
+ response = "Yes"
283
+ else:
284
+ response = "No"
285
+
286
+ full_prompt = ""
287
+ full_prompt += bos_token
288
+ #print(f"{pair['prog1']['scode']=}")
289
+ full_prompt += file_content + pair['prog1']['scode'] + "\nProgram 2:"
290
+ full_prompt += pair['prog2']['scode']+ "\n" ### Response:"
291
+ full_prompt += "\n" #+ response
292
+ full_prompt += eos_token
293
+ response += "\n"
294
+
295
+
296
+ return full_prompt, response
297
+
298
+
299
+ traindata1 = list(traindata) #[0:]
300
+ valdata1 = list( valdata)
301
+ testdata1 = list(testdata) #[0:]
302
+
303
+ traindata = []
304
+ pos_cnt = 0
305
+ for tdata in traindata1:
306
+ if tdata['prog1']['probid'] == tdata['prog2']['probid']: # if pair['label'] == 1: #
307
+ pos_cnt += 1
308
+ inp, trg = create_prompt(tdata)
309
+ traindata.append({
310
+ 'inputs' : inp,
311
+ 'targets' : trg
312
+ })
313
+
314
+ print("traindata[0] ", traindata[0], pos_cnt)
315
+ #exit(0)
316
+
317
+ valdata = []
318
+
319
+ for tdata in valdata1:
320
+ inp, trg = create_prompt(tdata)
321
+ valdata.append({
322
+ 'inputs' : inp,
323
+ 'targets' : trg
324
+ })
325
+
326
+ testdata = []
327
+
328
+ for tdata in testdata1:
329
+ inp, trg = create_prompt(tdata)
330
+ testdata.append({
331
+ 'inputs' : inp,
332
+ 'targets' : trg
333
+ })
334
+
335
+ traindataset = Dataset.from_pandas(pd.DataFrame(traindata))
336
+ valdataset = Dataset.from_pandas(pd.DataFrame(valdata))
337
+ testdataset = Dataset.from_pandas(pd.DataFrame(testdata))
338
+
339
+ instruct_tune_dataset = {"train": traindataset,
340
+ "val" : valdataset,
341
+ "test" : testdataset}
342
+
343
+
344
+
345
+
346
+
347
+
348
+
349
+
350
+
351
+ def preprocess_function(examples):
352
+ batch_size = len(examples['inputs'])
353
+ #inputs = [f"<s>[INST] Question : {x} [/INST] \\n Answer : " for x in examples[past_context_code]]
354
+ #inputs = [f"\n<|user|>\n You are given a set of APIs and previously generated Code as context. The task is given a new requirement from Bob modify or expand the given code using the provided APIs.\n\nAPIs:\n{apis}\n\nContext:\n{past_context}\n\nInput:\n{new_input} \n<|assistant|>\n " for apis, past_context, new_input in zip(examples['apis'], examples['past_context_code'], examples['new_input'])]
355
+ #targets = [str(x) for x in examples[label_column]]
356
+ #inputs, targets = get_examples_all_context(examples)
357
+
358
+ #inputs, targets = get_examples_all_context(examples)
359
+ #inputs, targets = get_examples_all_context_granite(examples, only_code=False)
360
+ inputs = []
361
+ targets = []
362
+ # for eg in examples:
363
+ # print(eg)
364
+ # #inp, trg = create_prompt(eg)
365
+ # #inputs.append(inp)
366
+ # #targets.append(trg)
367
+ inputs = examples['inputs']
368
+ targets = examples['targets']
369
+ # # tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt")
370
+ # model_input_ids = [tokenizer.apply_chat_template(convo, tokenize=True, add_generation_prompt=True) for convo in inputs]
371
+ # #model_inputs = [{'input_ids': lst} for lst in model_input_ids]
372
+ # model_inputs = {'input_ids': model_input_ids, 'attention_mask': [[1] * len(lst) for lst in model_input_ids]}
373
+ model_inputs = tokenizer(inputs, add_special_tokens=False)
374
+ #model_inputs = tokenizer(inputs)
375
+
376
+
377
+ #print("Input example:\n{}".format(inputs[0]))
378
+ #print("Output example:\n{}".format(targets[0]))
379
+ #print("model ip, tokeniszer of file ", "model_inputs", '\n', tokenizer([file_content, file_content]))
380
+ input_sizes = [len(tokens) for tokens in model_inputs['input_ids']]
381
+ #print("Input sizes {}".format(input_sizes))
382
+ labels = tokenizer(targets, add_special_tokens=False) # don't add bos token because we concatenate with inputs
383
+ label_sizes = [len(tokens) for tokens in labels['input_ids']]
384
+ #print("Label sizes {}".format(label_sizes))
385
+
386
+ for i in range(batch_size):
387
+ sample_input_ids = model_inputs["input_ids"][i]
388
+ label_input_ids = labels["input_ids"][i] + [tokenizer.eos_token_id]
389
+ # print(i, sample_input_ids, label_input_ids)
390
+ model_inputs["input_ids"][i] = sample_input_ids + label_input_ids
391
+ labels["input_ids"][i] = [-100] * len(sample_input_ids) + label_input_ids
392
+ model_inputs["attention_mask"][i] = [1] * len(model_inputs["input_ids"][i])
393
+ # print(model_inputs)
394
+ for i in range(batch_size):
395
+ sample_input_ids = model_inputs["input_ids"][i]
396
+ label_input_ids = labels["input_ids"][i]
397
+ model_inputs["input_ids"][i] = [tokenizer.pad_token_id] * (
398
+ max_length - len(sample_input_ids)
399
+ ) + sample_input_ids
400
+ model_inputs["attention_mask"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs["attention_mask"][i]
401
+ labels["input_ids"][i] = [-100] * (max_length - len(sample_input_ids)) + label_input_ids
402
+ model_inputs["input_ids"][i] = torch.tensor(model_inputs["input_ids"][i][:max_length])
403
+ model_inputs["attention_mask"][i] = torch.tensor(model_inputs["attention_mask"][i][:max_length])
404
+ labels["input_ids"][i] = torch.tensor(labels["input_ids"][i][:max_length])
405
+ model_inputs["labels"] = labels["input_ids"]
406
+ input_sizes = [len(tokens) for tokens in model_inputs['input_ids']]
407
+ #print("Input sizes {}".format(input_sizes))
408
+ return model_inputs
409
+
410
+ processed_datasets = traindataset.map(
411
+ preprocess_function,
412
+ batched=True,
413
+ num_proc=1,
414
+ remove_columns=traindataset.column_names,
415
+ load_from_cache_file=False,
416
+ desc="Running tokenizer on dataset",
417
+ )
418
+ train_dataset = processed_datasets
419
+ train_dataloader = DataLoader(
420
+ train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size_train, pin_memory=True
421
+ )
422
+
423
+
424
+ processed_datasets = valdataset.map(
425
+ preprocess_function,
426
+ batched=True,
427
+ num_proc=1,
428
+ remove_columns=valdataset.column_names,
429
+ load_from_cache_file=False,
430
+ desc="Running tokenizer on dataset",
431
+ )
432
+ val_dataset = processed_datasets
433
+ val_dataloader = DataLoader(
434
+ val_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size_train, pin_memory=True
435
+ )
436
+
437
+
438
+
439
+
440
+ def test_preprocess_function(examples):
441
+ batch_size = len(examples['inputs'])
442
+ #inputs, targets = get_examples_all_context(examples)
443
+ #inputs, targets = get_examples_all_context_granite(examples)
444
+ #inputs = [f"\n<|user|>\n You are given a set of APIs and previously generated Code as context. The task is given a new requirement from Bob modify or expand the given code using the provided APIs.\n\nAPIs:\n{apis}\n\nContext:\n{past_context}\n\nInput:\n{new_input} \n<|assistant|>\n " for apis, past_context, new_input in zip(examples['apis'], examples['past_context_code'], examples['new_input'])]
445
+ model_inputs = tokenizer(examples['inputs'])
446
+ # print(model_inputs)
447
+ for i in range(batch_size):
448
+ sample_input_ids = model_inputs["input_ids"][i]
449
+ model_inputs["input_ids"][i] = [tokenizer.pad_token_id] * (
450
+ max_length - len(sample_input_ids)
451
+ ) + sample_input_ids
452
+ model_inputs["attention_mask"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs["attention_mask"][i]
453
+ model_inputs["input_ids"][i] = torch.tensor(model_inputs["input_ids"][i][:max_length])
454
+ model_inputs["attention_mask"][i] = torch.tensor(model_inputs["attention_mask"][i][:max_length])
455
+ return model_inputs
456
+
457
+
458
+ processed_datasets = testdataset.map(
459
+ preprocess_function,
460
+ batched=True,
461
+ num_proc=1,
462
+ remove_columns=testdataset.column_names,
463
+ load_from_cache_file=False,
464
+ desc="Running tokenizer on dataset",
465
+ )
466
+ test_dataset = processed_datasets
467
+ test_dataloader = DataLoader(
468
+ test_dataset, shuffle=False, collate_fn=default_data_collator, batch_size=batch_size_train, pin_memory=True
469
+ )
470
+
471
+
472
+
473
+
474
+ peft_config = LoraConfig(
475
+ lora_alpha=16,
476
+ lora_dropout=0.1,
477
+ #target_modules = ['c_attn'],
478
+ target_modules = ['q_proj', 'k_proj', 'v_proj', 'o_proj'], #qwen
479
+ #target_modules = ['q_proj', 'v_proj'], #mistral
480
+ r=64,
481
+ bias="none",
482
+ task_type="CAUSAL_LM"
483
+ )
484
+
485
+ # peft_config = LoraConfig(
486
+ # r=lora_r,
487
+ # lora_alpha=lora_alpha,
488
+ # lora_dropout=lora_dropout,
489
+ # target_modules= target_modules,
490
+ # bias="none",
491
+ # task_type="CAUSAL_LM"
492
+ # )
493
+
494
+ model = peft.get_peft_model(model, peft_config)
495
+
496
+ wandb.watch(model, log='all')
497
+ print("Model loaded successfully!")
498
+
499
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
500
+
501
+ #optimizer = AdamW(model.parameters(), lr=3e-4)
502
+ optimizer = AdamW(model.parameters(), lr=initial_lr)
503
+
504
+ # Instantiate scheduler
505
+ lr_scheduler = get_cosine_schedule_with_warmup(
506
+ optimizer=optimizer,
507
+ num_warmup_steps=0.06 * (len(train_dataloader) * num_epochs),
508
+ num_training_steps=(len(train_dataloader) * num_epochs),
509
+ )
510
+
511
+ model.to(device)
512
+ model.to('cuda')
513
+
514
+ #model = torch.nn.DataParallel(model)
515
+ #model = model.cuda()
516
+ the_best_eval_loss = 10000
517
+ for epoch in range(num_epochs):
518
+ try:
519
+ model.train()
520
+ total_loss = 0
521
+ best_eval_loss = 10000 #np.inf
522
+
523
+ for step, batch in enumerate(tqdm(train_dataloader)):
524
+ batch = {k: v.to(device) for k, v in batch.items()}
525
+ #batch = {k: v.cuda() for k, v in batch.items()}
526
+ # print(batch)
527
+ #print(batch["input_ids"].shape)
528
+ # if step > 5:
529
+ # break
530
+ #batch.to(device)
531
+ outputs = model(**batch)
532
+ loss = outputs.loss
533
+ total_loss += loss.detach().float()
534
+ wandb.log({'train_loss': loss})
535
+ wandb.log({'lr': lr_scheduler.get_last_lr()[0], 'step': step})
536
+ if step % 100 == 0:
537
+ wandb.log({'train_step_loss': loss})
538
+ print(loss)
539
+ loss.backward()
540
+ #print("Loss {}".format(loss.item()))
541
+ optimizer.step()
542
+ lr_scheduler.step()
543
+ optimizer.zero_grad()
544
+ # if step % ckpnt_NUM == 0:
545
+ # checkpoint_dir = os.path.join(checkpoint_store_dir_path, f"checkpoint_{epoch}_{step}/")
546
+ # os.makedirs(checkpoint_dir, exist_ok=True)
547
+ # model.save_pretrained(checkpoint_dir)
548
+
549
+ if step % ckpnt_NUM == 0:
550
+
551
+ model.eval()
552
+ eval_loss = 0
553
+ eval_preds = []
554
+ eval_cnt = 1
555
+ for step1, batch_eval in enumerate(tqdm(val_dataloader)):
556
+
557
+ batch_eval = {k: v.to(device) for k, v in batch_eval.items()}
558
+ #batch_eval = {k: v.cuda() for k, v in batch_eval.items()}
559
+
560
+ #outputs = model.generate(**batch_eval, max_new_tokens=48)
561
+ #out = tokenizer.batch_decode(outputs, skip_special_tokens=True)
562
+ # for x in out:
563
+ # print(x)
564
+ # print("#" * 50)
565
+ with torch.no_grad():
566
+ outputs = model(**batch_eval)
567
+ loss = outputs.loss
568
+ if not math.isnan(loss.detach().float()) :
569
+ eval_loss += loss.detach().float()
570
+ eval_cnt += 1
571
+ # eval_preds.extend(
572
+ # tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(),
573
+ # skip_special_tokens=True)
574
+ # )
575
+ print(eval_loss)
576
+ wandb.log({'eval_loss': eval_loss})
577
+ eval_epoch_loss = eval_loss / len(val_dataloader)
578
+ if ((eval_loss/eval_cnt) < best_eval_loss) or SAVEALL==1:
579
+
580
+ best_eval_loss = eval_loss/eval_cnt
581
+ print(f"saving...{best_eval_loss} to checkpoint_{epoch}_{step}\n")
582
+ checkpoint_dir = os.path.join(checkpoint_store_dir_path, f"checkpoint_{epoch}_{step}/")
583
+ os.makedirs(checkpoint_dir, exist_ok=True)
584
+ model.save_pretrained(checkpoint_dir)
585
+
586
+ if ((eval_loss/eval_cnt) < the_best_eval_loss):
587
+ the_best_eval_loss = eval_loss/eval_cnt
588
+ print(f"saving...{best_eval_loss} to checkpoint_{epoch}_{step}_tb is best so far\n")
589
+
590
+
591
+ eval_ppl = torch.exp(eval_epoch_loss)
592
+ train_epoch_loss = total_loss #/ len(train_dataloader)
593
+ train_ppl = torch.exp(train_epoch_loss)
594
+ print(f"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=} {eval_loss/eval_cnt=} {eval_cnt=}")
595
+ #print(f"{epoch=}: {train_ppl=} {train_epoch_loss=}")
596
+
597
+ print("Total Loss {}".format(total_loss.item()))
598
+ if ((epoch+1) % 1) == 0:
599
+ checkpoint_dir = os.path.join(checkpoint_store_dir_path, f"checkpoint_{epoch}/")
600
+ os.makedirs(checkpoint_dir, exist_ok=True)
601
+ model.save_pretrained(checkpoint_dir)
602
+ model.eval()
603
+ eval_loss = 0
604
+ eval_preds = []
605
+ for step1, batch_eval in enumerate(tqdm(test_dataloader)):
606
+ if step1 > 5:
607
+ break
608
+ batch_eval = {k: v.to(device) for k, v in batch_eval.items()}
609
+ #batch_eval = {k: v.cuda() for k, v in batch_eval.items()}
610
+
611
+ outputs = model.generate(**batch_eval, max_new_tokens=max_new_tok)
612
+ out = tokenizer.batch_decode(outputs, skip_special_tokens=True)
613
+ for x in out:
614
+ print(x)
615
+ print("#" * 50)
616
+ # with torch.no_grad():
617
+ # outputs = model(**batch)
618
+ # loss = outputs.loss
619
+ # eval_loss += loss.detach().float()
620
+ # eval_preds.extend(
621
+ # tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(),
622
+ # skip_special_tokens=True)
623
+ # )
624
+
625
+ # eval_epoch_loss = eval_loss / len(test_dataloader)
626
+ # eval_ppl = torch.exp(eval_epoch_loss)
627
+ train_epoch_loss = total_loss / len(train_dataloader)
628
+ train_ppl = torch.exp(train_epoch_loss)
629
+ #print(f"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}")
630
+ print(f"{epoch=}: {train_ppl=} {train_epoch_loss=}")
631
+
632
+
633
+
634
+
635
+ except KeyboardInterrupt:
636
+
637
+ checkpoint_dir = os.path.join(checkpoint_store_dir_path, f"checkpoint_{epoch}_interrupt/")
638
+ os.makedirs(checkpoint_dir, exist_ok=True)
639
+ model.save_pretrained(checkpoint_dir)
640
+
641
+
642
+
643
+