Views
No views yet
1pip install -U transformers datasets accelerate peft trl bitsandbytes wandb
2pip install -qqq flash-attn
3pip install -qU transformers accelerate1
2"""
3wandb
4https://wandb.ai/wandb_account
5you need wb_token as well
6"""
7
8import gc
9import os
10
11import torch
12import wandb
13from datasets import load_dataset
14
15
16
17# Directly insert your Weights & Biases API key here
18wb_token = 'your_wb_token'
19wandb.login(key=wb_token)
20
21
22from peft import LoraConfig, PeftModel, prepare_model_for_kbit_training
23
24from transformers import (
25 AutoModelForCausalLM,
26 AutoTokenizer,
27 BitsAndBytesConfig,
28 TrainingArguments,
29 pipeline,)
30
31from trl import ORPOConfig, ORPOTrainer, setup_chat_format1
2if torch.cuda.get_device_capability()[0] >= 128:
3
4 attn_implementation = "flash_attention_2"
5 torch_dtype = torch.bfloat16
6else:
7 attn_implementation = "eager"
8 torch_dtype = torch.float16
9
10
11##################################
12
13import sys
14import os
15
16cwd = os.getcwd()
17# sys.path.append(cwd + '/my_directory')
18sys.path.append(cwd)
19
20
21def setting_directory(depth):
22 current_dir = os.path.abspath(os.getcwd())
23 root_dir = current_dir
24 for i in range(depth):
25 root_dir = os.path.abspath(os.path.join(root_dir, os.pardir))
26 sys.path.append(os.path.dirname(root_dir))
27 return root_dir
28
29# I load the model from local directory!
30model_path = "/data/bio-eng-llm/llm_repo/mlabonne/OrpoLlama-3-8B"1
2# QLoRA config
3bnb_config = BitsAndBytesConfig(
4 load_in_4bit=True,
5 bnb_4bit_quant_type="nf4",
6 bnb_4bit_compute_dtype= torch_dtype,
7 bnb_4bit_use_double_quant=True,
8)
9
10# LoRA config
11peft_config = LoraConfig(
12 r=16,
13 lora_alpha=32,
14 lora_dropout=0.05,
15 bias="none",
16 task_type="CAUSAL_LM",
17 target_modules=['up_proj', 'down_proj', 'gate_proj', 'k_proj', 'q_proj', 'v_proj', 'o_proj']
18)
19
20# Load tokenizer
21tokenizer = AutoTokenizer.from_pretrained(model_path)
22
23# Load model
24model = AutoModelForCausalLM.from_pretrained(
25 model_path,
26 quantization_config=bnb_config,
27 device_map="auto",
28 attn_implementation= attn_implementation
29)
30
31
32model, tokenizer = setup_chat_format(model, tokenizer)
33model = prepare_model_for_kbit_training(model)learning_rate: ORPO uses very low learning rates compared to traditional SFT or even DPO. This value of 8e-6 comes from the original paper, and roughly corresponds to an SFT learning rate of 1e-5 and a DPO learning rate of 5e-6. I would recommend increasing it around 1e-6 for a real fine-tune.
beta: It is the $\lambda$ parameter in the paper, with a default value of 0.1. An appendix from the original paper shows how it's been selected with an ablation study.
Other parameters, like max_length and batch size are set to use as much VRAM as available (~20 GB in this configuration). Ideally, we would train the model for 3-5 epochs, but we'll stick to 1 here.1# I saved the dataset in my local directory! but you may not
2dataset_name = "/data/bio-eng-llm/llm_repo/mlabonne/OrpoLlama-3-8B"
3
4dataset = load_dataset(dataset_name, split="all")
5dataset = dataset.shuffle(seed=42).select(range(1000))
6
7
8def format_chat_template(row):
9 row["chosen"] = tokenizer.apply_chat_template(row["chosen"], tokenize=False)
10 row["rejected"] = tokenizer.apply_chat_template(row["rejected"], tokenize=False)
11 return row
12
13dataset = dataset.map(
14 format_chat_template,
15 num_proc= os.cpu_count(),
16)
17dataset = dataset.train_test_split(test_size=0.01)
18
19epochs=20
20
21orpo_args = ORPOConfig(
22 learning_rate=8e-6,
23 beta=0.1,
24 lr_scheduler_type="linear",
25 max_length=1024,
26 max_prompt_length=512,
27 per_device_train_batch_size=2,
28 per_device_eval_batch_size=2,
29 gradient_accumulation_steps=4,
30 optim="paged_adamw_8bit",
31 num_train_epochs=epochs,
32 evaluation_strategy="steps",
33 eval_steps=0.2,
34 logging_steps=1,
35 warmup_steps=10,
36 report_to="wandb",
37 output_dir="./results/",
38)
39
40trainer = ORPOTrainer(
41 model=model,
42 args=orpo_args,
43 train_dataset=dataset["train"],
44 eval_dataset=dataset["test"],
45 peft_config=peft_config,
46 tokenizer=tokenizer,
47)
48trainer.train()
49
50import os
51
52# Define the directory where you want to save the model
53#
54
55root_dir = setting_directory(0)
56
57save_dir = root_dir + f"models/fine_tuned_models/OrpoLlama-3-8B_{epochs}e_qa_qa"
58#trainer.save_model(save_dir)
59
60
61# Create the directory if it doesn't exist
62os.makedirs(save_dir, exist_ok=True)
63
64# Combine the directory path with the model name
65#new_model_path = os.path.join(save_dir, "OrpoLlama-3-8B")
66
67# Save the model to the specified directory
68trainer.save_model(save_dir)
69
70
71#new_model = "OrpoLlama-3-8B"
72#trainer.save_model(new_model)1pip install -U transformers datasets accelerate peft trl bitsandbytes wandb
2pip install -qqq flash-attn
3pip install -qU transformers accelerate1import gc
2import os
3
4import torch
5import wandb
6from datasets import load_dataset
7
8
9
10# Directly insert your Weights & Biases API key here
11wb_token = 'your_wb_token'
12wandb.login(key=wb_token)
13
14
15from peft import LoraConfig, PeftModel, prepare_model_for_kbit_training
16
17from transformers import (
18 AutoModelForCausalLM,
19 AutoTokenizer,
20 BitsAndBytesConfig,
21 TrainingArguments,
22 pipeline,)
23
24from trl import ORPOConfig, ORPOTrainer, setup_chat_format
25
26
27
28if torch.cuda.get_device_capability()[0] >= 128:
29
30 attn_implementation = "flash_attention_2"
31 torch_dtype = torch.bfloat16
32else:
33 attn_implementation = "eager"
34 torch_dtype = torch.float16
35
36
37##################################
38
39import sys
40import os
41
42cwd = os.getcwd()
43# sys.path.append(cwd + '/my_directory')
44sys.path.append(cwd)
45
46
47def setting_directory(depth):
48 current_dir = os.path.abspath(os.getcwd())
49 root_dir = current_dir
50 for i in range(depth):
51 root_dir = os.path.abspath(os.path.join(root_dir, os.pardir))
52 sys.path.append(os.path.dirname(root_dir))
53 return root_dir
54
55# I loaded the base model form local directory but you may load it directy from huggingface
56model_path = "/data/bio-eng-llm/llm_repo/mlabonne/OrpoLlama-3-8B"
57
58
59###################################
60###################################
61
62"""
63# Model
64base_model = "meta-llama/Meta-Llama-3-8B"
65new_model = "OrpoLlama-3-8B"
66"""
67
68
69# QLoRA config
70bnb_config = BitsAndBytesConfig(
71 load_in_4bit=True,
72 bnb_4bit_quant_type="nf4",
73 bnb_4bit_compute_dtype= torch_dtype,
74 bnb_4bit_use_double_quant=True,
75)
76
77# LoRA config
78peft_config = LoraConfig(
79 r=16,
80 lora_alpha=32,
81 lora_dropout=0.05,
82 bias="none",
83 task_type="CAUSAL_LM",
84 target_modules=['up_proj', 'down_proj', 'gate_proj', 'k_proj', 'q_proj', 'v_proj', 'o_proj']
85)
86
87
88# Reload tokenizer and model
89tokenizer = AutoTokenizer.from_pretrained(model_path)
90model = AutoModelForCausalLM.from_pretrained(
91 model_path,
92 low_cpu_mem_usage=True,
93 return_dict=True,
94 torch_dtype=torch.float16,
95 device_map="auto",
96)
97model, tokenizer = setup_chat_format(model, tokenizer)
98
99
100
101root_dir = setting_directory(0)
102epochs = 20
103
104# I loaded the fine tuned model from my local directory but you may have it somewhere elese
105new_model_path = root_dir + f"models/fine_tuned_models/OrpoLlama-3-8B_{epochs}e_qa_qa"
106
107
108### Merge adapter with base model
109model = PeftModel.from_pretrained(model, new_model_path)
110model = model.merge_and_unload()
111
112print("#############################")
113print("#############################")
114print(model)
115
116
117
118
119# Pushing the model into the Huggingface hub
120
121from huggingface_hub import HfApi, login
122
123#########################################################
124#########################################################
125#########################################################
126######## Repo token
127# Login to Hugging Face
128login(token="your_huggingface_token")
129
130# Define your Hugging Face repository name
131repo_name = "your_name/OrpoLlama-3-8B_fine_tune_trl"
132
133
134
135# Push the model and tokenizer 2
136model.push_to_hub(repo_name, use_auth_token=True)
137tokenizer.push_to_hub(repo_name, use_auth_token=True)