Spaces:
Runtime error
Runtime error
daresearch
commited on
Update finetune_script.py
Browse files- finetune_script.py +196 -149
finetune_script.py
CHANGED
@@ -1,156 +1,203 @@
|
|
1 |
-
#
|
2 |
-
|
|
|
|
|
|
|
3 |
import torch
|
4 |
-
|
|
|
5 |
from datasets import load_dataset
|
6 |
from trl import SFTTrainer
|
7 |
-
from
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
)
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
)
|
|
|
74 |
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
max_steps=100,
|
89 |
-
learning_rate=2e-4,
|
90 |
-
fp16=not is_bfloat16_supported(),
|
91 |
-
bf16=is_bfloat16_supported(),
|
92 |
-
logging_steps=1,
|
93 |
-
evaluation_strategy="steps",
|
94 |
-
eval_steps=10,
|
95 |
-
optim="adamw_8bit",
|
96 |
-
weight_decay=0.01,
|
97 |
-
lr_scheduler_type="linear",
|
98 |
-
seed=3407,
|
99 |
-
output_dir="outputs",
|
100 |
-
),
|
101 |
-
)
|
102 |
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
|
107 |
-
print(f"{start_gpu_memory} GB of memory reserved.")
|
108 |
-
|
109 |
-
trainer_stats = trainer.train()
|
110 |
-
|
111 |
-
used_memory = round(torch.cuda.max_memory_reserved() / 1024**3, 3)
|
112 |
-
used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
|
113 |
-
used_percentage = round(used_memory / max_memory * 100, 3)
|
114 |
-
lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)
|
115 |
-
|
116 |
-
print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
|
117 |
-
print(f"{round(trainer_stats.metrics['train_runtime'] / 60, 2)} minutes used for training.")
|
118 |
-
print(f"Peak reserved memory = {used_memory} GB.")
|
119 |
-
print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
|
120 |
-
print(f"Peak reserved memory % of max memory = {used_percentage} %.")
|
121 |
-
print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
|
122 |
-
|
123 |
-
# Evaluation
|
124 |
-
eval_stats = trainer.evaluate(eval_dataset=valid_dataset)
|
125 |
-
print(f"Validation Loss: {eval_stats['eval_loss']}")
|
126 |
-
if "eval_accuracy" in eval_stats:
|
127 |
-
print(f"Validation Accuracy: {eval_stats['eval_accuracy']}")
|
128 |
-
|
129 |
-
# 5. After Training
|
130 |
-
FastLanguageModel.for_inference(model)
|
131 |
-
inputs = tokenizer(
|
132 |
-
[
|
133 |
-
alpaca_prompt.format(instruction, input, "")
|
134 |
-
], return_tensors="pt"
|
135 |
-
).to("cuda")
|
136 |
-
text_streamer = TextStreamer(tokenizer)
|
137 |
-
_ = model.generate(**inputs, streamer=text_streamer, max_new_tokens=1000)
|
138 |
-
|
139 |
-
# 6. Saving
|
140 |
-
model.save_pretrained("lora_model")
|
141 |
-
tokenizer.save_pretrained("lora_model")
|
142 |
-
model.push_to_hub(huggingface_model_name, token=os.getenv("HF_TOKEN"))
|
143 |
-
tokenizer.push_to_hub(huggingface_model_name, token=os.getenv("HF_TOKEN"))
|
144 |
-
if True:
|
145 |
-
model.save_pretrained_merged("model", tokenizer, save_method="merged_16bit")
|
146 |
-
if True:
|
147 |
-
model.push_to_hub_merged(huggingface_model_name, tokenizer, save_method="merged_16bit", token=os.getenv("HF_TOKEN"))
|
148 |
-
|
149 |
-
# # Merge to 4bit
|
150 |
-
# if True:
|
151 |
-
# model.save_pretrained_merged("model", tokenizer, save_method="merged_4bit")
|
152 |
-
# if True:
|
153 |
-
# model.push_to_hub_merged(huggingface_model_name, tokenizer, save_method="merged_4bit", token=os.getenv("HF_TOKEN")
|
154 |
-
|
155 |
-
# 0.4 Launch training inside this same script/notebook using multiple GPUs
|
156 |
-
notebook_launcher(train, num_processes=2) # or however many GPUs you have
|
|
|
1 |
+
#0.1 Install Dependencies
|
2 |
+
!pip install unsloth torch transformers datasets trl huggingface_hub
|
3 |
+
|
4 |
+
#0.2 Import Dependencies
|
5 |
+
from unsloth import FastLanguageModel
|
6 |
import torch
|
7 |
+
import os
|
8 |
+
from transformers import TextStreamer
|
9 |
from datasets import load_dataset
|
10 |
from trl import SFTTrainer
|
11 |
+
from transformers import TrainingArguments
|
12 |
+
from unsloth import is_bfloat16_supported
|
13 |
+
|
14 |
+
# 1. Configuration
|
15 |
+
max_seq_length = 2048
|
16 |
+
dtype = None
|
17 |
+
load_in_4bit = True
|
18 |
+
|
19 |
+
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
|
20 |
+
|
21 |
+
### Instruction:
|
22 |
+
{}
|
23 |
+
|
24 |
+
### Input:
|
25 |
+
{}
|
26 |
+
|
27 |
+
### Response:
|
28 |
+
{}"""
|
29 |
+
|
30 |
+
instruction = """This assistant is trained to code executive ranks and roles along the following categories with 1 or 0.
|
31 |
+
|
32 |
+
Ranks:
|
33 |
+
- VP: 1 if Vice President (VP), 0 otherwise
|
34 |
+
- SVP: 1 if Senior Vice President (SVP), 0 otherwise
|
35 |
+
- EVP: 1 if Executive Vice President (EVP), 0 otherwise
|
36 |
+
- SEVP: 1 if Senior Executive Vice President (SEVP), 0 otherwise
|
37 |
+
- Director: 1 if Director, 0 otherwise
|
38 |
+
- Senior Director: 1 if Senior Director, 0 otherwise
|
39 |
+
- MD: 1 if Managing Director (MD), 0 otherwise
|
40 |
+
- SMD: 1 if Senior Managing Director (SMD), 0 otherwise
|
41 |
+
- SE: 1 if Senior Executive, 0 otherwise
|
42 |
+
- VC: 1 if Vice Chair (VC), 0 otherwise
|
43 |
+
- SVC: 1 if Senior Vice Chair (SVC), 0 otherwise
|
44 |
+
- President: 1 if President of the parent company, 0 when President of subsidiary or division but not parent company.
|
45 |
+
|
46 |
+
Roles:
|
47 |
+
- Board: 1 when role suggests person is a member of the board of directors, 0 otherwise
|
48 |
+
- CEO: 1 when Chief Executive Officer of parent company, 0 when Chief Executive Officer of a subsidiary but not parent company.
|
49 |
+
- CXO: 1 when C-Suite title, i.e., Chief X Officer, where X can be any type of designation, 0 otherwise. Chief Executive Officer of the parent company. Not Chief AND Officer, e.g., only officer of a function.
|
50 |
+
- Primary: 1 when responsible for primary activity of value chain, i.e., Supply Chain, Manufacturing, Operations, Marketing & Sales, Customer Service and alike, 0 when not a primary value chain activity.
|
51 |
+
- Support: 1 when responsible for a support activity of the value chain, i.e., Procurement, IT, HR, Management, Strategy, HR, Finance, Legal, R&D, Investor Relations, Technology, General Counsel and alike, 0 when not support activity of the value.
|
52 |
+
- BU: 1 when involved with an entity/distinct unit responsible for Product, Customer, or Geographical domain/unit; or role is about a subsidiary, 0 when responsibility is not for a specific product/customer/geography area but, for example, for the entire parent company."""
|
53 |
+
input = "In 2015 the company 'cms' had an executive with the name david mengebier, whose official role title was: 'senior vice president, cms energy and consumers energy'."
|
54 |
+
huggingface_model_name = "daresearch/Llama-3.1"
|
55 |
+
|
56 |
+
|
57 |
+
# 2. Before Training
|
58 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
59 |
+
model_name = "unsloth/Meta-Llama-3.1-8B-bnb-4bit",
|
60 |
+
max_seq_length = max_seq_length,
|
61 |
+
dtype = dtype,
|
62 |
+
load_in_4bit = load_in_4bit,
|
63 |
+
token = os.getenv("HF_TOKEN")
|
64 |
+
)
|
65 |
+
|
66 |
+
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
|
67 |
+
inputs = tokenizer(
|
68 |
+
[
|
69 |
+
alpaca_prompt.format(
|
70 |
+
instruction, # instruction
|
71 |
+
input, # input
|
72 |
+
"", # output - leave this blank for generation!
|
73 |
)
|
74 |
+
], return_tensors = "pt").to("cuda")
|
75 |
+
|
76 |
+
text_streamer = TextStreamer(tokenizer)
|
77 |
+
_ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 1000)
|
78 |
+
|
79 |
+
# 3. Load data
|
80 |
+
|
81 |
+
EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
|
82 |
+
def formatting_prompts_func(examples):
|
83 |
+
instructions = examples["instruction"]
|
84 |
+
inputs = examples["input"]
|
85 |
+
outputs = examples["output"]
|
86 |
+
texts = []
|
87 |
+
for instruction, input, output in zip(instructions, inputs, outputs):
|
88 |
+
text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
|
89 |
+
texts.append(text)
|
90 |
+
return { "text" : texts, }
|
91 |
+
pass
|
92 |
+
#dataset = load_dataset("daresearch/orgdatabase-training0-data", split = "train")
|
93 |
+
#dataset = dataset.map(formatting_prompts_func, batched = True,)
|
94 |
+
|
95 |
+
|
96 |
+
# Load train and validation datasets
|
97 |
+
train_dataset = load_dataset("csv", data_files="train.csv", split="train")
|
98 |
+
valid_dataset = load_dataset("csv", data_files="valid.csv", split="train")
|
99 |
+
|
100 |
+
# Apply formatting to both datasets
|
101 |
+
train_dataset = train_dataset.map(formatting_prompts_func, batched=True)
|
102 |
+
valid_dataset = valid_dataset.map(formatting_prompts_func, batched=True)
|
103 |
+
|
104 |
+
|
105 |
+
# 4. Training
|
106 |
+
model = FastLanguageModel.get_peft_model(
|
107 |
+
model,
|
108 |
+
r=16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
|
109 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
|
110 |
+
"gate_proj", "up_proj", "down_proj"],
|
111 |
+
lora_alpha=16,
|
112 |
+
lora_dropout=0, # Supports any, but = 0 is optimized
|
113 |
+
bias="none", # Supports any, but = "none" is optimized
|
114 |
+
use_gradient_checkpointing="unsloth", # True or "unsloth" for very long context
|
115 |
+
random_state=3407,
|
116 |
+
use_rslora=False, # We support rank stabilized LoRA
|
117 |
+
loftq_config=None, # And LoftQ
|
118 |
+
)
|
119 |
+
|
120 |
+
trainer = SFTTrainer(
|
121 |
+
model=model,
|
122 |
+
tokenizer=tokenizer,
|
123 |
+
train_dataset=train_dataset, # Updated to use train_dataset
|
124 |
+
eval_dataset=valid_dataset, # Added eval_dataset for validation
|
125 |
+
dataset_text_field="text",
|
126 |
+
max_seq_length=max_seq_length,
|
127 |
+
dataset_num_proc=2,
|
128 |
+
packing=False, # Can make training 5x faster for short sequences.
|
129 |
+
args=TrainingArguments(
|
130 |
+
per_device_train_batch_size=2,
|
131 |
+
gradient_accumulation_steps=4,
|
132 |
+
warmup_steps=5,
|
133 |
+
max_steps=100,
|
134 |
+
learning_rate=2e-4,
|
135 |
+
fp16=not is_bfloat16_supported(),
|
136 |
+
bf16=is_bfloat16_supported(),
|
137 |
+
logging_steps=1,
|
138 |
+
evaluation_strategy="steps", # Enables evaluation during training
|
139 |
+
eval_steps=10, # Frequency of evaluation
|
140 |
+
optim="adamw_8bit",
|
141 |
+
weight_decay=0.01,
|
142 |
+
lr_scheduler_type="linear",
|
143 |
+
seed=3407,
|
144 |
+
output_dir="outputs",
|
145 |
+
),
|
146 |
+
)
|
147 |
+
|
148 |
+
# Show current memory stats
|
149 |
+
gpu_stats = torch.cuda.get_device_properties(0)
|
150 |
+
start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
|
151 |
+
max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
|
152 |
+
print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
|
153 |
+
print(f"{start_gpu_memory} GB of memory reserved.")
|
154 |
+
|
155 |
+
trainer_stats = trainer.train()
|
156 |
+
|
157 |
+
# Show final memory and time stats
|
158 |
+
used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
|
159 |
+
used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
|
160 |
+
used_percentage = round(used_memory / max_memory * 100, 3)
|
161 |
+
lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)
|
162 |
+
print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
|
163 |
+
print(f"{round(trainer_stats.metrics['train_runtime'] / 60, 2)} minutes used for training.")
|
164 |
+
print(f"Peak reserved memory = {used_memory} GB.")
|
165 |
+
print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
|
166 |
+
print(f"Peak reserved memory % of max memory = {used_percentage} %.")
|
167 |
+
print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
|
168 |
+
|
169 |
+
# Optionally evaluate after training if desired
|
170 |
+
eval_stats = trainer.evaluate(eval_dataset=valid_dataset)
|
171 |
+
print(f"Validation Loss: {eval_stats['eval_loss']}")
|
172 |
+
if "eval_accuracy" in eval_stats:
|
173 |
+
print(f"Validation Accuracy: {eval_stats['eval_accuracy']}")
|
174 |
+
|
175 |
+
|
176 |
+
# 5. After Training
|
177 |
+
FastLanguageModel.for_inference(model) # Enable native 2x faster inference
|
178 |
+
inputs = tokenizer(
|
179 |
+
[
|
180 |
+
alpaca_prompt.format(
|
181 |
+
instruction, # instruction
|
182 |
+
input, # input
|
183 |
+
"", # output - leave this blank for generation!
|
184 |
)
|
185 |
+
], return_tensors = "pt").to("cuda")
|
186 |
|
187 |
+
text_streamer = TextStreamer(tokenizer)
|
188 |
+
_ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 1000)
|
189 |
+
|
190 |
+
|
191 |
+
# 6. Saving
|
192 |
+
model.save_pretrained("lora_model") # Local saving
|
193 |
+
tokenizer.save_pretrained("lora_model")
|
194 |
+
model.push_to_hub(huggingface_model_name, token = os.getenv("HF_TOKEN"))
|
195 |
+
tokenizer.push_to_hub(huggingface_model_name, token = os.getenv("HF_TOKEN"))
|
196 |
+
|
197 |
+
# Merge to 16bit
|
198 |
+
if True: model.save_pretrained_merged("model", tokenizer, save_method = "merged_16bit",)
|
199 |
+
if True: model.push_to_hub_merged(huggingface_model_name, tokenizer, save_method = "merged_16bit", token = os.getenv("HF_TOKEN"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
|
201 |
+
# # Merge to 4bit
|
202 |
+
#if True: model.save_pretrained_merged("model", tokenizer, save_method = "merged_4bit",)
|
203 |
+
#if True: model.push_to_hub_merged(huggingface_model_name, tokenizer, save_method = "merged_4bit", token = os.getenv("HF_TOKEN"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|