-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
355 lines (300 loc) · 11.6 KB
/
main.py
1
2
3
4
5
6
7
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import argparse
import functools
import logging
import os
import torch
import wandb
from peft import AutoPeftModelForCausalLM, LoraConfig
from torch.utils.data import DataLoader
from transformers import (BitsAndBytesConfig, AutoModelForCausalLM, AutoTokenizer, TrainingArguments,
PreTrainedTokenizerBase)
from trl import DataCollatorForCompletionOnlyLM, SFTTrainer
from src.args_utils import init_args_llm_sota
from src.data_utils import data_collate_llm_dataset
from src.llm_classifier import llm_classify
from src.llm_sota_dataset import LLMSotaDataset
from src.templates.sota_templates import INSTRUCTIONS
from src.templates.sota_templates_few_shot import FEW_SHOT_PROMPTS_SOTA
def init_logging() -> None:
"""Initialize logging."""
logging.basicConfig(
format="%(asctime)s %(levelname)s: %(message)s",
level=logging.INFO,
datefmt="%Y-%m-%d %H:%M:%S",
)
def load_model_and_tokenizer_llm(
model_path: str,
load_in_8bits: bool,
token: str,
use_cpu: bool = False,
) -> tuple[AutoModelForCausalLM, PreTrainedTokenizerBase]:
"""Load model and tokenizer from path. Load model in 8-bit mode.
:param model_path: path to pre-trained model or shortcut name
:param load_in_8bits: if True, model is loaded in 8-bit mode
:param token: token
:param use_cpu: if True, CPU is used
:return: model and tokenizer
"""
bnb_config = None
if not use_cpu:
if load_in_8bits:
bnb_config = BitsAndBytesConfig(
load_in_8bit=True, # load model in 8-bit precision
low_cpu_mem_usage=True,
)
logging.info("Loading model in 8-bit mode")
else:
bnb_config = BitsAndBytesConfig(
load_in_4bit=True, # load model in 4-bit precision
bnb_4bit_quant_type="nf4", # pre-trained model should be quantized in 4-bit NF format
bnb_4bit_use_double_quant=True, # Using double quantization as mentioned in QLoRA paper
bnb_4bit_compute_dtype=torch.bfloat16,
)
logging.info("Loading model in 4-bit mode")
else:
logging.info("Using CPU")
model = AutoModelForCausalLM.from_pretrained(
model_path,
quantization_config=bnb_config,
token=token,
low_cpu_mem_usage=True if not use_cpu else False,
)
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False, token=token)
return model, tokenizer
def find_target_modules(model) -> list[str]:
# Initialize a Set to Store Unique Layers
unique_layers = set()
# Iterate Over All Named Modules in the Model
for name, module in model.named_modules():
# Check if the Module Type Contains 'Linear4bit'
if "Linear4bit" in str(type(module)):
# Extract the Type of the Layer
layer_type = name.split('.')[-1]
# Add the Layer Type to the Set of Unique Layers
unique_layers.add(layer_type)
# Return the Set of Unique Layers Converted to a List
return list(unique_layers)
def instruction_tuning(args: argparse.Namespace):
use_cpu = True if args.use_cpu else True if not torch.cuda.is_available() else False
device = torch.device("cpu" if use_cpu else "cuda" if torch.cuda.is_available() else "cpu")
bnb_config = BitsAndBytesConfig(
load_in_4bit=True, # load model in 4-bit precision
bnb_4bit_quant_type="nf4", # pre-trained model should be quantized in 4-bit NF format
bnb_4bit_use_double_quant=True, # Using double quantization as mentioned in QLoRA paper
bnb_4bit_compute_dtype=torch.bfloat16, # During computation, pre-trained model should be loaded in BF16 format
)
model = AutoModelForCausalLM.from_pretrained(
args.model,
quantization_config=bnb_config if not use_cpu else None,
device_map="auto" if not use_cpu else "cpu",
use_cache=False,
low_cpu_mem_usage=True,
token=args.token,
)
model.config.pretraining_tp = 1
tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=False, token=args.token)
tokenizer.padding_side = "right"
resized_embeddings = False
if tokenizer.pad_token is None:
tokenizer.pad_token = "[PAD]"
tokenizer.add_special_tokens({"pad_token": "[PAD]"})
model.resize_token_embeddings(len(tokenizer))
resized_embeddings = True
peft_config = LoraConfig(
lora_alpha=16,
lora_dropout=0.1,
r=64,
target_modules=find_target_modules(model),
modules_to_save=None if not resized_embeddings else ["lm_head", "embed_tokens"],
bias="none",
task_type="CAUSAL_LM",
)
if tokenizer.chat_template is None:
if "microsoft/Orca" in args.model:
tokenizer.chat_template = "{{ bos_token }} {% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
instruction = INSTRUCTIONS.get(args.data_path, None)
if instruction is None:
raise ValueError(f"Instruction not found for {args.data_path}")
data_path_train = os.path.join("data_sota", args.data_path, "train.txt")
train_dataset = LLMSotaDataset(
data_path=str(data_path_train),
tokenizer=tokenizer,
max_data=args.max_train_data,
instruction_tuning=True,
instruction=instruction,
testing=False,
)
data_path_dev = os.path.join("data_sota", args.data_path, "dev.txt")
dev_dataset = LLMSotaDataset(
data_path=str(data_path_dev),
tokenizer=tokenizer,
max_data=args.max_train_data,
instruction_tuning=True,
instruction=instruction,
testing=False,
)
data_path_test = os.path.join("data_sota", args.data_path, "test.txt")
test_dataset = LLMSotaDataset(
data_path=str(data_path_test),
tokenizer=tokenizer,
max_data=args.max_train_data,
instruction_tuning=True,
instruction=instruction,
testing=True,
)
output_dir = "output"
training_args = TrainingArguments(
output_dir=output_dir,
per_device_train_batch_size=8,
gradient_accumulation_steps=2,
learning_rate=2e-4,
logging_steps=10,
num_train_epochs=args.epochs,
optim="paged_adamw_32bit",
report_to=["wandb"] if not args.no_wandb else [],
lr_scheduler_type="constant",
max_grad_norm=0.3,
warmup_ratio=0.03,
bf16=True if not use_cpu else False,
tf32=True if not use_cpu else False,
save_strategy="epoch",
gradient_checkpointing=True,
gradient_checkpointing_kwargs={"use_reentrant": False},
evaluation_strategy="epoch",
use_cpu=use_cpu,
remove_unused_columns=True,
load_best_model_at_end=True,
save_total_limit=1,
metric_for_best_model="eval_loss",
disable_tqdm=True,
group_by_length=True,
dataloader_drop_last=False,
)
if "orca" in args.model.lower():
response_template = tokenizer.encode("\n<|im_start|>assistant\n", add_special_tokens=False)[2:]
assistant_text = "<|im_start|> assistant\n"
elif "llama" in args.model.lower():
response_template = tokenizer.encode(" [/INST]", add_special_tokens=False)[1:]
assistant_text = "[/INST]"
else:
raise ValueError("Response template not defined for this model.")
collator = DataCollatorForCompletionOnlyLM(response_template, tokenizer=tokenizer)
trainer = SFTTrainer(
train_dataset=train_dataset,
eval_dataset=dev_dataset,
model=model,
peft_config=peft_config,
tokenizer=tokenizer,
args=training_args,
packing=False,
dataset_text_field="input_ids",
max_seq_length=1024,
data_collator=collator,
)
best_model_dir = "best_model"
logging.info("Training...")
trainer.train()
trainer.save_model(best_model_dir)
logging.info("Training finished")
if args.load_in_8bits:
bnb_config = BitsAndBytesConfig(load_in_8bit=True)
# load best model
model = AutoPeftModelForCausalLM.from_pretrained(
best_model_dir,
quantization_config=bnb_config,
low_cpu_mem_usage=True,
)
tokenizer.padding_side = "left"
test_dataloader = DataLoader(
test_dataset,
batch_size=1,
collate_fn=functools.partial(data_collate_llm_dataset, tokenizer=tokenizer),
num_workers=0,
shuffle=False,
drop_last=False,
)
llm_classify(
model=model,
tokenizer=tokenizer,
data_loader=test_dataloader,
no_wandb=args.no_wandb,
assistant_text=assistant_text,
device=device,
)
def main():
init_logging()
args = init_args_llm_sota()
# Set system env variable HF_TOKEN to args.token
if args.token is not None:
os.environ["HF_TOKEN"] = args.token
if not args.no_wandb:
wandb.init(
project="absa",
entity="entity",
config=vars(args),
tags=[args.tag] if args.tag else [],
)
if args.instruction_tuning:
instruction_tuning(args)
wandb.finish()
logging.info("This is the end...")
else:
prompting(args)
def prompting(args: argparse.Namespace):
logging.info("Loading tokenizer and model...")
model, tokenizer = load_model_and_tokenizer_llm(
model_path=args.model,
load_in_8bits=args.load_in_8bits,
token=args.token,
use_cpu=args.use_cpu,
)
logging.info("Tokenizer and model loaded")
tokenizer.padding_side = "left"
if tokenizer.chat_template is None:
if "microsoft/Orca" in args.model:
tokenizer.chat_template = "{{ bos_token }} {% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
if "orca" in args.model.lower():
assistant_text = "<|im_start|> assistant\n"
elif "llama" in args.model.lower():
assistant_text = "[/INST]"
else:
raise ValueError("Response template not defined for this model.")
instruction = INSTRUCTIONS.get(args.data_path, None)
if instruction is None:
raise ValueError(f"Instruction not found for {args.data_path}")
if args.few_shot_prompt:
few_shot = FEW_SHOT_PROMPTS_SOTA.get(args.data_path, None)
if few_shot is None:
raise ValueError(f"Few shot prompt not found for {args.data_path}")
instruction += few_shot
data_path_test = os.path.join("data_sota", args.data_path, "test.txt")
test_dataset = LLMSotaDataset(
data_path=str(data_path_test),
tokenizer=tokenizer,
max_data=args.max_train_data,
instruction_tuning=True,
instruction=instruction,
testing=True,
)
test_dataloader = DataLoader(
test_dataset,
batch_size=1,
collate_fn=functools.partial(data_collate_llm_dataset, tokenizer=tokenizer),
num_workers=0,
shuffle=False,
drop_last=False,
)
device = torch.device("cpu" if args.use_cpu else "cuda" if torch.cuda.is_available() else "cpu")
llm_classify(
model=model,
tokenizer=tokenizer,
data_loader=test_dataloader,
no_wandb=args.no_wandb,
assistant_text=assistant_text,
device=device,
)
if not args.no_wandb:
wandb.finish()
logging.info("Finished!")
if __name__ == '__main__':
main()