daresearch commited on
Commit
6b0420b
·
verified ·
1 Parent(s): 2f9e79a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -0
app.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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=8,
131
+ gradient_accumulation_steps=4,
132
+ warmup_steps=5,
133
+ max_steps=-1,
134
+ num_train_epochs=3,
135
+ learning_rate=2e-4,
136
+ fp16=not is_bfloat16_supported(),
137
+ bf16=is_bfloat16_supported(),
138
+ logging_steps=1,
139
+ evaluation_strategy="steps", # Enables evaluation during training
140
+ eval_steps=10, # Frequency of evaluation
141
+ optim="adamw_8bit",
142
+ weight_decay=0.01,
143
+ lr_scheduler_type="linear",
144
+ seed=3407,
145
+ output_dir="outputs",
146
+ ),
147
+ )
148
+
149
+ # Show current memory stats
150
+ gpu_stats = torch.cuda.get_device_properties(0)
151
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
152
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
153
+ print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
154
+ print(f"{start_gpu_memory} GB of memory reserved.")
155
+
156
+ trainer_stats = trainer.train()
157
+
158
+ # Show final memory and time stats
159
+ used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
160
+ used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
161
+ used_percentage = round(used_memory / max_memory * 100, 3)
162
+ lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)
163
+ print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
164
+ print(f"{round(trainer_stats.metrics['train_runtime'] / 60, 2)} minutes used for training.")
165
+ print(f"Peak reserved memory = {used_memory} GB.")
166
+ print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
167
+ print(f"Peak reserved memory % of max memory = {used_percentage} %.")
168
+ print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
169
+
170
+ # Optionally evaluate after training if desired
171
+ eval_stats = trainer.evaluate(eval_dataset=valid_dataset)
172
+ print(f"Validation Loss: {eval_stats['eval_loss']}")
173
+ if "eval_accuracy" in eval_stats:
174
+ print(f"Validation Accuracy: {eval_stats['eval_accuracy']}")
175
+
176
+
177
+ # 5. After Training
178
+ FastLanguageModel.for_inference(model) # Enable native 2x faster inference
179
+ inputs = tokenizer(
180
+ [
181
+ alpaca_prompt.format(
182
+ instruction, # instruction
183
+ input, # input
184
+ "", # output - leave this blank for generation!
185
+ )
186
+ ], return_tensors = "pt").to("cuda")
187
+
188
+ text_streamer = TextStreamer(tokenizer)
189
+ _ = model.generate(**inputs, streamer = text_streamer, max_new_tokens = 1000)
190
+
191
+
192
+ # 6. Saving
193
+ #model.save_pretrained("lora_model") # Local saving
194
+ #tokenizer.save_pretrained("lora_model")
195
+
196
+ huggingface_model_name = "daresearch/Llama-3.1-8B-bnb-4bit-exec-roles"
197
+ model.push_to_hub(huggingface_model_name, token = os.getenv("HF_TOKEN"))
198
+ tokenizer.push_to_hub(huggingface_model_name, token = os.getenv("HF_TOKEN"))
199
+
200
+ merged_huggingface_model_name = "daresearch/Llama-3.1-8B-bnb-4bit-M-exec-roles"
201
+ # Merge to 16bit
202
+ if True: model.save_pretrained_merged("model", tokenizer, save_method = "merged_16bit",)
203
+ if True: model.push_to_hub_merged(merged_huggingface_model_name, tokenizer, save_method = "merged_16bit", token = os.getenv("HF_TOKEN"))
204
+
205
+ # # Merge to 4bit
206
+ #if True: model.save_pretrained_merged("model", tokenizer, save_method = "merged_4bit",)
207
+ #if True: model.push_to_hub_merged(huggingface_model_name, tokenizer, save_method = "merged_4bit", token = os.getenv("HF_TOKEN"))