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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 json
|
| 18 |
+
# filepath = "/kaggle/input/code-sim-try1/mutated_graph_all_lang_eq.json"
|
| 19 |
+
# examples = []
|
| 20 |
+
# with open(filepath, 'r') as file:
|
| 21 |
+
# for l in file:
|
| 22 |
+
# examples.append(json.loads(l))
|
| 23 |
+
|
| 24 |
+
# len(examples)
|
| 25 |
+
# examples[0]
|
| 26 |
+
|
| 27 |
+
# instruct_tune_dataset = load_dataset("mosaicml/instruct-v3",cache_dir = "/scratch/scai/mtech/aib222688/HF")
|
| 28 |
+
# instruct_tune_dataset = instruct_tune_dataset.filter(lambda x: x["source"] == "dolly_hhrlhf")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
traindataset_file = "./dataset_lfs/allpairs_data_large.json"
|
| 32 |
+
valdataset_file = "./dataset_lfs/allpairs_data_val.json"
|
| 33 |
+
testdataset_file = "./llm_for_code/datasets/codecontests/verified_iffp_1200.json"
|
| 34 |
+
traindata = []
|
| 35 |
+
initial_lr = 5e-6
|
| 36 |
+
checkpoint_store_dir_path = "./HPC_2_codellama_iffp_20k_4_lora_1200"
|
| 37 |
+
os.makedirs(checkpoint_store_dir_path, exist_ok=True)
|
| 38 |
+
num_epochs = 5
|
| 39 |
+
batch_size_train = 1
|
| 40 |
+
max_length = 2000
|
| 41 |
+
ckpnt_NUM = 2000
|
| 42 |
+
#ckpnt_NUM2 = 5000
|
| 43 |
+
SAVEALL = False #True
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
import os
|
| 50 |
+
import torch
|
| 51 |
+
from datasets import load_dataset
|
| 52 |
+
from transformers import (
|
| 53 |
+
AutoModelForCausalLM,
|
| 54 |
+
AutoTokenizer,
|
| 55 |
+
BitsAndBytesConfig,
|
| 56 |
+
HfArgumentParser,
|
| 57 |
+
TrainingArguments,
|
| 58 |
+
pipeline,
|
| 59 |
+
logging,
|
| 60 |
+
)
|
| 61 |
+
from peft import LoraConfig, PeftModel
|
| 62 |
+
from trl import SFTTrainer
|
| 63 |
+
|
| 64 |
+
nf4_config = BitsAndBytesConfig(
|
| 65 |
+
load_in_4bit=True,
|
| 66 |
+
bnb_4bit_quant_type="nf4",
|
| 67 |
+
bnb_4bit_use_double_quant=True,
|
| 68 |
+
bnb_4bit_compute_dtype=torch.bfloat16
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 72 |
+
model_name,
|
| 73 |
+
#device_map='auto',
|
| 74 |
+
#quantization_config=nf4_config,
|
| 75 |
+
use_cache=True,
|
| 76 |
+
cache_dir = "/scratch/scai/mtech/aib222688/HF",
|
| 77 |
+
attn_implementation="flash_attention_2",
|
| 78 |
+
torch_dtype=torch.float16,
|
| 79 |
+
trust_remote_code=True,
|
| 80 |
+
)
|
| 81 |
+
print(model)
|
| 82 |
+
# model = AutoModelForCausalLM.from_pretrained(
|
| 83 |
+
# "./HPC_2_codellama_iffp_20k_3_lora_900/checkpoint_0_99/",
|
| 84 |
+
# use_cache=True,
|
| 85 |
+
# cache_dir = "/scratch/scai/mtech/aib222688/HF",
|
| 86 |
+
# )
|
| 87 |
+
|
| 88 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 89 |
+
|
| 90 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 91 |
+
tokenizer.padding_side = "right"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
with open(traindataset_file, 'r') as file:
|
| 98 |
+
for l in file:
|
| 99 |
+
traindata.append(json.loads(l))
|
| 100 |
+
|
| 101 |
+
valdata = []
|
| 102 |
+
|
| 103 |
+
with open(valdataset_file, 'r') as file:
|
| 104 |
+
for l in file:
|
| 105 |
+
valdata.append(json.loads(l))
|
| 106 |
+
|
| 107 |
+
testdata = []
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
with open(testdataset_file, 'r') as file:
|
| 111 |
+
for l in file:
|
| 112 |
+
testdata.append(json.loads(l))
|
| 113 |
+
print(len(traindata), len(valdata), len(testdata))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
file_path = './prompt_file.txt'
|
| 119 |
+
file_content = ""
|
| 120 |
+
with open(file_path, 'r') as file:
|
| 121 |
+
file_content = file.read()
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def create_prompt(pair):
|
| 125 |
+
bos_token = "<s>"
|
| 126 |
+
eos_token = "</s>"
|
| 127 |
+
if pair['prog1']['probid'] == pair['prog2']['probid']:
|
| 128 |
+
response = "Yes"
|
| 129 |
+
else:
|
| 130 |
+
response = "No"
|
| 131 |
+
|
| 132 |
+
full_prompt = ""
|
| 133 |
+
full_prompt += bos_token
|
| 134 |
+
full_prompt += file_content + pair['prog1']['scode'] + "\nProgram 2:"
|
| 135 |
+
full_prompt += pair['prog2']['scode']+ "\n### Response:"
|
| 136 |
+
full_prompt += "\n" #+ response
|
| 137 |
+
full_prompt += eos_token
|
| 138 |
+
|
| 139 |
+
return full_prompt, response
|
| 140 |
+
#print(create_prompt(instruct_tune_dataset["train"][1]))
|
| 141 |
+
|
| 142 |
+
traindata1 = list(traindata) #[0:]
|
| 143 |
+
valdata1 = list( valdata)
|
| 144 |
+
testdata1 = list(testdata) #[0:]
|
| 145 |
+
|
| 146 |
+
traindata = []
|
| 147 |
+
|
| 148 |
+
for tdata in traindata1:
|
| 149 |
+
inp, trg = create_prompt(tdata)
|
| 150 |
+
traindata.append({
|
| 151 |
+
'inputs' : inp,
|
| 152 |
+
'targets' : trg
|
| 153 |
+
})
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
valdata = []
|
| 157 |
+
|
| 158 |
+
for tdata in valdata1:
|
| 159 |
+
inp, trg = create_prompt(tdata)
|
| 160 |
+
valdata.append({
|
| 161 |
+
'inputs' : inp,
|
| 162 |
+
'targets' : trg
|
| 163 |
+
})
|
| 164 |
+
|
| 165 |
+
testdata = []
|
| 166 |
+
|
| 167 |
+
for tdata in testdata1:
|
| 168 |
+
inp, trg = create_prompt(tdata)
|
| 169 |
+
testdata.append({
|
| 170 |
+
'inputs' : inp,
|
| 171 |
+
'targets' : trg
|
| 172 |
+
})
|
| 173 |
+
|
| 174 |
+
traindataset = Dataset.from_pandas(pd.DataFrame(traindata))
|
| 175 |
+
valdataset = Dataset.from_pandas(pd.DataFrame(valdata))
|
| 176 |
+
testdataset = Dataset.from_pandas(pd.DataFrame(testdata))
|
| 177 |
+
|
| 178 |
+
instruct_tune_dataset = {"train": traindataset,
|
| 179 |
+
"val" : valdataset,
|
| 180 |
+
"test" : testdataset}
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def preprocess_function(examples):
|
| 191 |
+
batch_size = len(examples['inputs'])
|
| 192 |
+
#inputs = [f"<s>[INST] Question : {x} [/INST] \\n Answer : " for x in examples[past_context_code]]
|
| 193 |
+
#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'])]
|
| 194 |
+
#targets = [str(x) for x in examples[label_column]]
|
| 195 |
+
#inputs, targets = get_examples_all_context(examples)
|
| 196 |
+
|
| 197 |
+
#inputs, targets = get_examples_all_context(examples)
|
| 198 |
+
#inputs, targets = get_examples_all_context_granite(examples, only_code=False)
|
| 199 |
+
inputs = []
|
| 200 |
+
targets = []
|
| 201 |
+
# for eg in examples:
|
| 202 |
+
# print(eg)
|
| 203 |
+
# #inp, trg = create_prompt(eg)
|
| 204 |
+
# #inputs.append(inp)
|
| 205 |
+
# #targets.append(trg)
|
| 206 |
+
inputs = examples['inputs']
|
| 207 |
+
targets = examples['targets']
|
| 208 |
+
model_inputs = tokenizer(inputs)
|
| 209 |
+
|
| 210 |
+
#print("Input example:\n{}".format(inputs[0]))
|
| 211 |
+
#print("Output example:\n{}".format(targets[0]))
|
| 212 |
+
|
| 213 |
+
input_sizes = [len(tokens) for tokens in model_inputs['input_ids']]
|
| 214 |
+
#print("Input sizes {}".format(input_sizes))
|
| 215 |
+
labels = tokenizer(targets, add_special_tokens=False) # don't add bos token because we concatenate with inputs
|
| 216 |
+
label_sizes = [len(tokens) for tokens in labels['input_ids']]
|
| 217 |
+
#print("Label sizes {}".format(label_sizes))
|
| 218 |
+
|
| 219 |
+
for i in range(batch_size):
|
| 220 |
+
sample_input_ids = model_inputs["input_ids"][i]
|
| 221 |
+
label_input_ids = labels["input_ids"][i] + [tokenizer.eos_token_id]
|
| 222 |
+
# print(i, sample_input_ids, label_input_ids)
|
| 223 |
+
model_inputs["input_ids"][i] = sample_input_ids + label_input_ids
|
| 224 |
+
labels["input_ids"][i] = [-100] * len(sample_input_ids) + label_input_ids
|
| 225 |
+
model_inputs["attention_mask"][i] = [1] * len(model_inputs["input_ids"][i])
|
| 226 |
+
# print(model_inputs)
|
| 227 |
+
for i in range(batch_size):
|
| 228 |
+
sample_input_ids = model_inputs["input_ids"][i]
|
| 229 |
+
label_input_ids = labels["input_ids"][i]
|
| 230 |
+
model_inputs["input_ids"][i] = [tokenizer.pad_token_id] * (
|
| 231 |
+
max_length - len(sample_input_ids)
|
| 232 |
+
) + sample_input_ids
|
| 233 |
+
model_inputs["attention_mask"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs["attention_mask"][i]
|
| 234 |
+
labels["input_ids"][i] = [-100] * (max_length - len(sample_input_ids)) + label_input_ids
|
| 235 |
+
model_inputs["input_ids"][i] = torch.tensor(model_inputs["input_ids"][i][:max_length])
|
| 236 |
+
model_inputs["attention_mask"][i] = torch.tensor(model_inputs["attention_mask"][i][:max_length])
|
| 237 |
+
labels["input_ids"][i] = torch.tensor(labels["input_ids"][i][:max_length])
|
| 238 |
+
model_inputs["labels"] = labels["input_ids"]
|
| 239 |
+
input_sizes = [len(tokens) for tokens in model_inputs['input_ids']]
|
| 240 |
+
#print("Input sizes {}".format(input_sizes))
|
| 241 |
+
return model_inputs
|
| 242 |
+
|
| 243 |
+
processed_datasets = traindataset.map(
|
| 244 |
+
preprocess_function,
|
| 245 |
+
batched=True,
|
| 246 |
+
num_proc=1,
|
| 247 |
+
remove_columns=traindataset.column_names,
|
| 248 |
+
load_from_cache_file=False,
|
| 249 |
+
desc="Running tokenizer on dataset",
|
| 250 |
+
)
|
| 251 |
+
train_dataset = processed_datasets
|
| 252 |
+
train_dataloader = DataLoader(
|
| 253 |
+
train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size_train, pin_memory=True
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
processed_datasets = valdataset.map(
|
| 258 |
+
preprocess_function,
|
| 259 |
+
batched=True,
|
| 260 |
+
num_proc=1,
|
| 261 |
+
remove_columns=valdataset.column_names,
|
| 262 |
+
load_from_cache_file=False,
|
| 263 |
+
desc="Running tokenizer on dataset",
|
| 264 |
+
)
|
| 265 |
+
val_dataset = processed_datasets
|
| 266 |
+
val_dataloader = DataLoader(
|
| 267 |
+
val_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size_train, pin_memory=True
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def test_preprocess_function(examples):
|
| 274 |
+
batch_size = len(examples['inputs'])
|
| 275 |
+
#inputs, targets = get_examples_all_context(examples)
|
| 276 |
+
#inputs, targets = get_examples_all_context_granite(examples)
|
| 277 |
+
#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'])]
|
| 278 |
+
model_inputs = tokenizer(examples['inputs'])
|
| 279 |
+
# print(model_inputs)
|
| 280 |
+
for i in range(batch_size):
|
| 281 |
+
sample_input_ids = model_inputs["input_ids"][i]
|
| 282 |
+
model_inputs["input_ids"][i] = [tokenizer.pad_token_id] * (
|
| 283 |
+
max_length - len(sample_input_ids)
|
| 284 |
+
) + sample_input_ids
|
| 285 |
+
model_inputs["attention_mask"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs["attention_mask"][i]
|
| 286 |
+
model_inputs["input_ids"][i] = torch.tensor(model_inputs["input_ids"][i][:max_length])
|
| 287 |
+
model_inputs["attention_mask"][i] = torch.tensor(model_inputs["attention_mask"][i][:max_length])
|
| 288 |
+
return model_inputs
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
processed_datasets = testdataset.map(
|
| 292 |
+
preprocess_function,
|
| 293 |
+
batched=True,
|
| 294 |
+
num_proc=1,
|
| 295 |
+
remove_columns=testdataset.column_names,
|
| 296 |
+
load_from_cache_file=False,
|
| 297 |
+
desc="Running tokenizer on dataset",
|
| 298 |
+
)
|
| 299 |
+
test_dataset = processed_datasets
|
| 300 |
+
test_dataloader = DataLoader(
|
| 301 |
+
test_dataset, shuffle=False, collate_fn=default_data_collator, batch_size=batch_size_train, pin_memory=True
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
peft_config = LoraConfig(
|
| 308 |
+
lora_alpha=16,
|
| 309 |
+
lora_dropout=0.1,
|
| 310 |
+
#target_modules = ['c_attn'],
|
| 311 |
+
target_modules = ['q_proj', 'kv_a_proj_with_mqa', 'o_proj'], #['q_proj', 'kv_a_proj_with_mqa', 'kv_b_proj', 'o_proj'],
|
| 312 |
+
r=64,
|
| 313 |
+
bias="none",
|
| 314 |
+
task_type="CAUSAL_LM"
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
# peft_config = LoraConfig(
|
| 318 |
+
# r=lora_r,
|
| 319 |
+
# lora_alpha=lora_alpha,
|
| 320 |
+
# lora_dropout=lora_dropout,
|
| 321 |
+
# target_modules= target_modules,
|
| 322 |
+
# bias="none",
|
| 323 |
+
# task_type="CAUSAL_LM"
|
| 324 |
+
# )
|
| 325 |
+
|
| 326 |
+
model = peft.get_peft_model(model, peft_config)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
print("Model loaded successfully!")
|
| 330 |
+
|
| 331 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 332 |
+
|
| 333 |
+
#optimizer = AdamW(model.parameters(), lr=3e-4)
|
| 334 |
+
optimizer = AdamW(model.parameters(), lr=initial_lr)
|
| 335 |
+
|
| 336 |
+
# Instantiate scheduler
|
| 337 |
+
lr_scheduler = get_cosine_schedule_with_warmup(
|
| 338 |
+
optimizer=optimizer,
|
| 339 |
+
num_warmup_steps=0.06 * (len(train_dataloader) * num_epochs),
|
| 340 |
+
num_training_steps=(len(train_dataloader) * num_epochs),
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
model.to(device)
|
| 344 |
+
|
| 345 |
+
#model = torch.nn.DataParallel(model)
|
| 346 |
+
#model = model.cuda()
|
| 347 |
+
|
| 348 |
+
for epoch in range(num_epochs):
|
| 349 |
+
try:
|
| 350 |
+
model.train()
|
| 351 |
+
total_loss = 0
|
| 352 |
+
best_eval_loss = 10000 #np.inf
|
| 353 |
+
|
| 354 |
+
for step, batch in enumerate(tqdm(train_dataloader)):
|
| 355 |
+
batch = {k: v.to(device) for k, v in batch.items()}
|
| 356 |
+
#batch = {k: v.cuda() for k, v in batch.items()}
|
| 357 |
+
# print(batch)
|
| 358 |
+
#print(batch["input_ids"].shape)
|
| 359 |
+
# if step > 5:
|
| 360 |
+
# break
|
| 361 |
+
#batch.to(device)
|
| 362 |
+
outputs = model(**batch)
|
| 363 |
+
loss = outputs.loss
|
| 364 |
+
total_loss += loss.detach().float()
|
| 365 |
+
if step % 100 == 0:
|
| 366 |
+
print(loss)
|
| 367 |
+
loss.backward()
|
| 368 |
+
#print("Loss {}".format(loss.item()))
|
| 369 |
+
optimizer.step()
|
| 370 |
+
lr_scheduler.step()
|
| 371 |
+
optimizer.zero_grad()
|
| 372 |
+
# if step % ckpnt_NUM2 == 0:
|
| 373 |
+
# checkpoint_dir = os.path.join(checkpoint_store_dir_path, f"checkpoint_{epoch}_{step}/")
|
| 374 |
+
# os.makedirs(checkpoint_dir, exist_ok=True)
|
| 375 |
+
# model.save_pretrained(checkpoint_dir)
|
| 376 |
+
|
| 377 |
+
if step % ckpnt_NUM == 0:
|
| 378 |
+
|
| 379 |
+
model.eval()
|
| 380 |
+
eval_loss = 0
|
| 381 |
+
eval_preds = []
|
| 382 |
+
eval_cnt = 1
|
| 383 |
+
for step1, batch_eval in enumerate(tqdm(val_dataloader)):
|
| 384 |
+
|
| 385 |
+
batch_eval = {k: v.to(device) for k, v in batch_eval.items()}
|
| 386 |
+
#batch_eval = {k: v.cuda() for k, v in batch_eval.items()}
|
| 387 |
+
|
| 388 |
+
#outputs = model.generate(**batch_eval, max_new_tokens=48)
|
| 389 |
+
#out = tokenizer.batch_decode(outputs, skip_special_tokens=True)
|
| 390 |
+
# for x in out:
|
| 391 |
+
# print(x)
|
| 392 |
+
# print("#" * 50)
|
| 393 |
+
with torch.no_grad():
|
| 394 |
+
outputs = model(**batch_eval)
|
| 395 |
+
loss = outputs.loss
|
| 396 |
+
if not math.isnan(loss.detach().float()) :
|
| 397 |
+
eval_loss += loss.detach().float()
|
| 398 |
+
eval_cnt += 1
|
| 399 |
+
# eval_preds.extend(
|
| 400 |
+
# tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(),
|
| 401 |
+
# skip_special_tokens=True)
|
| 402 |
+
# )
|
| 403 |
+
print(eval_loss)
|
| 404 |
+
eval_epoch_loss = eval_loss / len(val_dataloader)
|
| 405 |
+
if ((eval_loss/eval_cnt) < best_eval_loss) or SAVEALL:
|
| 406 |
+
|
| 407 |
+
best_eval_loss = eval_loss/eval_cnt
|
| 408 |
+
print(f"saving...{best_eval_loss} to checkpoint_{epoch}_{step}\n")
|
| 409 |
+
checkpoint_dir = os.path.join(checkpoint_store_dir_path, f"checkpoint_{epoch}_{step}/")
|
| 410 |
+
os.makedirs(checkpoint_dir, exist_ok=True)
|
| 411 |
+
model.save_pretrained(checkpoint_dir)
|
| 412 |
+
|
| 413 |
+
eval_ppl = torch.exp(eval_epoch_loss)
|
| 414 |
+
train_epoch_loss = total_loss #/ len(train_dataloader)
|
| 415 |
+
train_ppl = torch.exp(train_epoch_loss)
|
| 416 |
+
print(f"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=} {eval_loss/eval_cnt=} {eval_cnt=}")
|
| 417 |
+
#print(f"{epoch=}: {train_ppl=} {train_epoch_loss=}")
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
except KeyboardInterrupt:
|
| 421 |
+
|
| 422 |
+
checkpoint_dir = os.path.join(checkpoint_store_dir_path, f"checkpoint_{epoch}_interrupt/")
|
| 423 |
+
os.makedirs(checkpoint_dir, exist_ok=True)
|
| 424 |
+
model.save_pretrained(checkpoint_dir)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
print("Total Loss {}".format(total_loss.item()))
|
| 429 |
+
if ((epoch+1) % 1) == 0:
|
| 430 |
+
checkpoint_dir = os.path.join(checkpoint_store_dir_path, f"checkpoint_{epoch}/")
|
| 431 |
+
os.makedirs(checkpoint_dir, exist_ok=True)
|
| 432 |
+
model.save_pretrained(checkpoint_dir)
|
| 433 |
+
model.eval()
|
| 434 |
+
eval_loss = 0
|
| 435 |
+
eval_preds = []
|
| 436 |
+
for step1, batch_eval in enumerate(tqdm(test_dataloader)):
|
| 437 |
+
if step1 > 5:
|
| 438 |
+
break
|
| 439 |
+
batch_eval = {k: v.to(device) for k, v in batch_eval.items()}
|
| 440 |
+
#batch_eval = {k: v.cuda() for k, v in batch_eval.items()}
|
| 441 |
+
|
| 442 |
+
outputs = model.generate(**batch_eval, max_new_tokens=48)
|
| 443 |
+
out = tokenizer.batch_decode(outputs, skip_special_tokens=True)
|
| 444 |
+
for x in out:
|
| 445 |
+
print(x)
|
| 446 |
+
print("#" * 50)
|
| 447 |
+
# with torch.no_grad():
|
| 448 |
+
# outputs = model(**batch)
|
| 449 |
+
# loss = outputs.loss
|
| 450 |
+
# eval_loss += loss.detach().float()
|
| 451 |
+
# eval_preds.extend(
|
| 452 |
+
# tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(),
|
| 453 |
+
# skip_special_tokens=True)
|
| 454 |
+
# )
|
| 455 |
+
|
| 456 |
+
# eval_epoch_loss = eval_loss / len(test_dataloader)
|
| 457 |
+
# eval_ppl = torch.exp(eval_epoch_loss)
|
| 458 |
+
train_epoch_loss = total_loss / len(train_dataloader)
|
| 459 |
+
train_ppl = torch.exp(train_epoch_loss)
|
| 460 |
+
#print(f"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}")
|
| 461 |
+
print(f"{epoch=}: {train_ppl=} {train_epoch_loss=}")
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
sys.exit(0)
|
| 467 |
+
#model = peft.prepare_model_for_kbit_training(model)
|
| 468 |
+
#model = peft.get_peft_model(model, peft_config)
|
| 469 |
+
|
| 470 |
+
args = TrainingArguments(
|
| 471 |
+
output_dir = out_name,
|
| 472 |
+
num_train_epochs=5,
|
| 473 |
+
#max_steps = 100,
|
| 474 |
+
per_device_train_batch_size = 4,
|
| 475 |
+
warmup_steps = 0.03,
|
| 476 |
+
logging_steps=10,
|
| 477 |
+
save_strategy="epoch",
|
| 478 |
+
#evaluation_strategy="epoch",
|
| 479 |
+
evaluation_strategy="steps",
|
| 480 |
+
eval_steps=100,
|
| 481 |
+
learning_rate=2e-4,
|
| 482 |
+
bf16=True,
|
| 483 |
+
lr_scheduler_type='constant',
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
max_seq_length = 2048
|
| 487 |
+
|
| 488 |
+
trainer = SFTTrainer(
|
| 489 |
+
model=model,
|
| 490 |
+
peft_config=peft_config,
|
| 491 |
+
max_seq_length=max_seq_length,
|
| 492 |
+
tokenizer=tokenizer,
|
| 493 |
+
packing=True,
|
| 494 |
+
formatting_func=create_prompt,
|
| 495 |
+
args=args,
|
| 496 |
+
train_dataset=instruct_tune_dataset["train"],
|
| 497 |
+
eval_dataset=instruct_tune_dataset["val"]
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
# predictions, labels, _ = trainer.predict(instruct_tune_dataset["train"][1])
|
| 501 |
+
|
| 502 |
+
# # Convert predictions and labels to text
|
| 503 |
+
# predicted_texts = tokenizer.batch_decode(predictions.argmax(axis=-1), skip_special_tokens=True)
|
| 504 |
+
# true_texts = tokenizer.batch_decode(labels, skip_special_tokens=True)
|
| 505 |
+
# print(f" Pred {predicted_texts}, True {true_texts}")
|
| 506 |
+
|
| 507 |
+
import time
|
| 508 |
+
start = time.time()
|
| 509 |
+
try:
|
| 510 |
+
trainer.train()
|
| 511 |
+
except Exception as e:
|
| 512 |
+
print(f"ERRORR\n {e}")
|
| 513 |
+
traceback.print_exc()
|
| 514 |
+
|
| 515 |
+
print(time.time()- start)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def generate_response(prompt, model):
|
| 519 |
+
encoded_input = tokenizer(prompt, return_tensors="pt", add_special_tokens=True)
|
| 520 |
+
model_inputs = encoded_input.to('cuda')
|
| 521 |
+
|
| 522 |
+
generated_ids = model.generate(**model_inputs, max_new_tokens=1000, do_sample=True, pad_token_id=tokenizer.eos_token_id)
|
| 523 |
+
|
| 524 |
+
decoded_output = tokenizer.batch_decode(generated_ids)
|
| 525 |
+
|
| 526 |
+
return decoded_output[0].replace(prompt, "")
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
try:
|
| 531 |
+
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))
|
| 532 |
+
except Exception as e:
|
| 533 |
+
print(f"ERRORR\n {e}")
|
| 534 |
+
traceback.print_exc()
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
try:
|
| 538 |
+
trainer.save_model(out_name)
|
| 539 |
+
except Exception as e:
|
| 540 |
+
print(f"ERRORR\n {e}")
|
| 541 |
+
traceback.print_exc()
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
try:
|
| 545 |
+
tester = SFTTrainer(
|
| 546 |
+
model=trainer.model,
|
| 547 |
+
peft_config=peft_config,
|
| 548 |
+
max_seq_length=max_seq_length,
|
| 549 |
+
tokenizer=tokenizer,
|
| 550 |
+
packing=True,
|
| 551 |
+
formatting_func=create_prompt,
|
| 552 |
+
args=args,
|
| 553 |
+
train_dataset=instruct_tune_dataset["train"],
|
| 554 |
+
eval_dataset=instruct_tune_dataset["test"]
|
| 555 |
+
)
|
| 556 |
+
print(tester.evaluate())
|
| 557 |
+
|
| 558 |
+
except Exception as e:
|
| 559 |
+
print(f"ERRORR\n {e}")
|
| 560 |
+
traceback.print_exc()
|
| 561 |
+
|
| 562 |
+
trainer.push_to_hub("FT/mistral-instruct-generation")
|