Skip to content
Snippets Groups Projects
Commit 8754c8de authored by Atharva Jadhav's avatar Atharva Jadhav
Browse files

Add basic support for Llama fine-tuning

parent 1d668cd3
No related branches found
No related tags found
No related merge requests found
from datasets import load_dataset
from unsloth import FastLanguageModel
from unsloth.chat_templates import get_chat_template
def formatting_prompts_func(examples):
convos = examples["conversations"]
texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]
return { "text" : texts, }
pass
def format_to_conversations(examples):
conversations = []
codes = examples["code"]
refined_codes = examples["refined code"]
summaries = examples["summary"]
for i in range(len(refined_codes)):
user_content = f'''Refine the C# code enclosed within tags [C#] and [/C#].
[C#]
{codes[i]}
[/C#]
'''
assistant_content = f'''
[refined_C#]
{refined_codes[i]}
[/refined_C#]
[code_changes]
{summaries[i]}
[/code_changes]
'''
conversation = []
user_dict = {'content': user_content, 'role': 'user'}
assistant_dict = {'content': assistant_content, 'role': 'assistant'}
conversation.append(user_dict)
conversation.append(assistant_dict)
conversations.append(conversation)
return { "conversations" : conversations }
pass
max_seq_length = 32768 # Choose any! We auto support RoPE Scaling internally!
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Meta-Llama-3.1-8B-Instruct",
max_seq_length = max_seq_length,
dtype = dtype,
load_in_4bit = load_in_4bit,
)
tokenizer = get_chat_template(
tokenizer,
chat_template = "llama-3.1",
)
dataset = load_dataset("atharva2721/refined-train-aggregated", split = "train")
dataset = dataset.map(format_to_conversations, batched = True,)
dataset = dataset.map(formatting_prompts_func, batched = True,)
dataset.push_to_hub('llama-standardized-refined-test-aggregated')
print('Dataset pushed to hub')
\ No newline at end of file
...@@ -30,7 +30,7 @@ echo $VIRTUAL_ENV ...@@ -30,7 +30,7 @@ echo $VIRTUAL_ENV
python --version python --version
python dataset_standardization.py python llama_dataset_standardization.py
module unload CUDA module unload CUDA
module unload Python/3.11.5 module unload Python/3.11.5
......
from unsloth import FastLanguageModel, is_bfloat16_supported
from unsloth.chat_templates import get_chat_template, train_on_responses_only
from datasets import load_dataset
from trl import SFTTrainer
from transformers import TrainingArguments, DataCollatorForSeq2Seq
import wandb
import torch
import datetime
print(f'Started the script at {datetime.datetime.now()}', flush=True)
max_seq_length = 32768 # Choose any! We auto support RoPE Scaling internally!
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "unsloth/Meta-Llama-3.1-8B-Instruct",
max_seq_length = max_seq_length,
dtype = dtype,
load_in_4bit = load_in_4bit,
)
print(f'Model loaded successfully at {datetime.datetime.now()}', flush=True)
model = FastLanguageModel.get_peft_model(
model,
r = 64, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",],
lora_alpha = 64,
lora_dropout = 0, # Supports any, but = 0 is optimized
bias = "none", # Supports any, but = "none" is optimized
# [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
random_state = 3407,
use_rslora = False, # We support rank stabilized LoRA
loftq_config = None, # And LoftQ
)
tokenizer = get_chat_template(
tokenizer,
chat_template = "qwen-2.5",
)
dataset = load_dataset("atharva2721/standardized-refined-train-aggregated", split = "train")
validation_dataset = load_dataset("atharva2721/standardized-refined-val-test-aggregated", split = "train")
wandb.init(project="codebud")
trainer = SFTTrainer(
model = model,
tokenizer = tokenizer,
train_dataset = dataset,
eval_dataset=validation_dataset,
dataset_text_field = "text",
max_seq_length = max_seq_length,
data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer),
dataset_num_proc = 4,
packing = False, # Can make training 5x faster for short sequences.
args = TrainingArguments(
per_device_train_batch_size = 1,
gradient_accumulation_steps = 4, # Fixed major bug in latest Unsloth
warmup_ratio = 0.1,
num_train_epochs = 3, # Set this for 1 full training run.
#max_steps = 60,
learning_rate = 2e-5,
fp16 = not is_bfloat16_supported(),
bf16 = is_bfloat16_supported(),
eval_strategy="steps",
eval_steps=410,
per_device_eval_batch_size = 1,
fp16_full_eval = not is_bfloat16_supported(),
bf16_full_eval = is_bfloat16_supported(),
logging_steps = 10,
save_steps = 410,
optim = "paged_adamw_8bit", # Save more memory
weight_decay = 0.01,
lr_scheduler_type = "cosine",
seed = 3407,
output_dir = "outputs",
report_to = "wandb", # Use this for WandB etc
run_name = "run-name"
),
)
trainer = train_on_responses_only(
trainer,
instruction_part = "<|im_start|>user\n",
response_part = "<|im_start|>assistant\n",
)
tokenizer.decode(trainer.train_dataset[0]["input_ids"])
space = tokenizer(" ", add_special_tokens = False).input_ids[0]
tokenizer.decode([space if x == -100 else x for x in trainer.train_dataset[0]["labels"]])
gpu_stats = torch.cuda.get_device_properties(0)
start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.", flush=True)
print(f"{start_gpu_memory} GB of memory reserved.", flush=True)
print(f'Everything initialized. Starting the training at {datetime.datetime.now()}', flush=True)
trainer_stats = trainer.train()
print(f'Successfully completed training at {datetime.datetime.now()}', flush=True)
used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
used_percentage = round(used_memory / max_memory * 100, 3)
lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)
print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
print(
f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training."
)
print(f"Peak reserved memory = {used_memory} GB.")
print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
print(f"Peak reserved memory % of max memory = {used_percentage} %.")
print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
print(f'Pushing model and tokenizer at {datetime.datetime.now()}', flush=True)
model.save_pretrained("models/finetuned_model_with_three_epochs_eval") # Local saving
tokenizer.save_pretrained("models/finetuned_model_with_three_epochs_eval")
model.push_to_hub("finetuned_model_with_three_epochs_eval") # Online saving
tokenizer.push_to_hub("finetuned_model_with_three_epochs_eval") # Online saving
wandb.finish()
print(f'Run complete at {datetime.datetime.now()}', flush=True)
\ No newline at end of file
...@@ -4,8 +4,8 @@ dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for ...@@ -4,8 +4,8 @@ dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False. load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
model, tokenizer = FastLanguageModel.from_pretrained( model, tokenizer = FastLanguageModel.from_pretrained(
#model_name = "models/first_finetuned_model_one_epochs", model_name = "../fine-tuning/models/finetuned_model_with_three_epochs_eval",
model_name = "unsloth/Qwen2.5-Coder-7B-Instruct", #model_name = "unsloth/Qwen2.5-Coder-7B-Instruct",
max_seq_length = max_seq_length, max_seq_length = max_seq_length,
dtype = dtype, dtype = dtype,
load_in_4bit = load_in_4bit, load_in_4bit = load_in_4bit,
...@@ -13,11 +13,11 @@ model, tokenizer = FastLanguageModel.from_pretrained( ...@@ -13,11 +13,11 @@ model, tokenizer = FastLanguageModel.from_pretrained(
FastLanguageModel.for_inference(model) # Enable native 2x faster inference FastLanguageModel.for_inference(model) # Enable native 2x faster inference
code = """ code = """
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ConsignmentCompanyProject.com.app.dataobjects; using ConsignmentCompanyProject.com.app.model; namespace ConsignmentCompanyProject.com.app.business { class CustomerMainWindowHandler { OrderDBProcessHandler customerOrderDataHandler = new OrderDBProcessHandler(); public List<OrderProperties> getOrders(string vendorId,string orderStatus) { if (orderStatus==null) { return customerOrderDataHandler.getMultipleOrdersInfo(vendorId, null); } else { return customerOrderDataHandler.getMultipleOrdersInfo(vendorId, orderStatus); } } public bool cancelExistingOrder(OrderProperties cancelOrderProperties) { return customerOrderDataHandler.cancelOrder(cancelOrderProperties); } } }
""" """
content = f''' content = f'''
Refine the C# code enclosed within tags [C#] and [/C#]. Refine the C# code enclosed within tags [C#] and [/C#].
Provide the refined code enclosed within tags [refined_C#] and [/refined_C#] and summary of changes enclosed within tags [code_changes] and [/code_changes].
[C#] [C#]
{code} {code}
[/C#] [/C#]
...@@ -34,5 +34,8 @@ inputs = tokenizer.apply_chat_template( ...@@ -34,5 +34,8 @@ inputs = tokenizer.apply_chat_template(
from transformers import TextStreamer from transformers import TextStreamer
text_streamer = TextStreamer(tokenizer, skip_prompt = True) text_streamer = TextStreamer(tokenizer, skip_prompt = True)
_ = model.generate(input_ids = inputs, streamer = text_streamer, max_new_tokens = 10000, _ = model.generate(input_ids = inputs,
use_cache = True, temperature = 1.5, min_p = 0.1) streamer = text_streamer,
\ No newline at end of file max_new_tokens = 10000,
temperature = 0.2
)
\ No newline at end of file
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
### Add basic configuration for job ### Add basic configuration for job
#SBATCH --job-name=fine_tuning #SBATCH --job-name=inference
#SBATCH --output=logs/fine_tuning_%j.log #SBATCH --output=logs/inference_%j.log
#SBATCH --error=logs/fine_tuning_error_%j.log #SBATCH --error=logs/inference_%j.log
#SBATCH --nodes=1 #SBATCH --nodes=1
#SBATCH --ntasks=1 #SBATCH --ntasks=1
#SBATCH --cpus-per-task=3 #SBATCH --cpus-per-task=3
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
### Run the project in work directory of the cluster (configure based on need!! ### Run the project in work directory of the cluster (configure based on need!!
### RWTH File System : https://help.itc.rwth-aachen.de/en/service/rhr4fjjutttf/article/da307ec2c60940b29bd42ac483fc3ea7/ ### RWTH File System : https://help.itc.rwth-aachen.de/en/service/rhr4fjjutttf/article/da307ec2c60940b29bd42ac483fc3ea7/
cd $HPCWORK cd $HPCWORK
cd codebud/fine-tuning cd codebud/inference
###------------------------------------------------------------------------------------------------------------------------------ ###------------------------------------------------------------------------------------------------------------------------------
### JOB SCRIPT RUN ### JOB SCRIPT RUN
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment