ayuan0324 commited on
Commit
257f887
1 Parent(s): b842bf6

Delete finetune.py

Browse files
Files changed (1) hide show
  1. finetune.py +0 -283
finetune.py DELETED
@@ -1,283 +0,0 @@
1
- import os
2
- import sys
3
- from typing import List
4
-
5
- import fire
6
- import torch
7
- import transformers
8
- from datasets import load_dataset
9
-
10
- """
11
- Unused imports:
12
- import torch.nn as nn
13
- import bitsandbytes as bnb
14
- """
15
-
16
- from peft import (
17
- LoraConfig,
18
- get_peft_model,
19
- get_peft_model_state_dict,
20
- prepare_model_for_int8_training,
21
- set_peft_model_state_dict,
22
- )
23
- from transformers import LlamaForCausalLM, LlamaTokenizer
24
-
25
- from utils.prompter import Prompter
26
-
27
-
28
- def train(
29
- # model/data params
30
- base_model: str = "./hf_ckpt", # the only required argument
31
- data_path: str = "ayuan0324/ocean_only",
32
- output_dir: str = "./lora-alpaca",
33
- # training hyperparams
34
- batch_size: int = 128,
35
- micro_batch_size: int = 4,
36
- num_epochs: int = 3,
37
- learning_rate: float = 1e-4,
38
- cutoff_len: int = 512,
39
- val_set_size: int = 2000,
40
- # lora hyperparams
41
- lora_r: int = 8,
42
- lora_alpha: int = 16,
43
- lora_dropout: float = 0.05,
44
- lora_target_modules: List[str] = [
45
- "q_proj",
46
- "v_proj",
47
- ],
48
- # llm hyperparams
49
- train_on_inputs: bool = True, # if False, masks out inputs in loss
50
- add_eos_token: bool = False,
51
- group_by_length: bool = False, # faster, but produces an odd training loss curve
52
- # wandb params
53
- wandb_project: str = "",
54
- wandb_run_name: str = "",
55
- wandb_watch: str = "", # options: false | gradients | all
56
- wandb_log_model: str = "", # options: false | true
57
- resume_from_checkpoint: str = None, # either training checkpoint or final adapter
58
- prompt_template_name: str = "alpaca", # The prompt template to use, will default to alpaca.
59
- ):
60
- if int(os.environ.get("LOCAL_RANK", 0)) == 0:
61
- print(
62
- f"Training Alpaca-LoRA model with params:\n"
63
- f"base_model: {base_model}\n"
64
- f"data_path: {data_path}\n"
65
- f"output_dir: {output_dir}\n"
66
- f"batch_size: {batch_size}\n"
67
- f"micro_batch_size: {micro_batch_size}\n"
68
- f"num_epochs: {num_epochs}\n"
69
- f"learning_rate: {learning_rate}\n"
70
- f"cutoff_len: {cutoff_len}\n"
71
- f"val_set_size: {val_set_size}\n"
72
- f"lora_r: {lora_r}\n"
73
- f"lora_alpha: {lora_alpha}\n"
74
- f"lora_dropout: {lora_dropout}\n"
75
- f"lora_target_modules: {lora_target_modules}\n"
76
- f"train_on_inputs: {train_on_inputs}\n"
77
- f"add_eos_token: {add_eos_token}\n"
78
- f"group_by_length: {group_by_length}\n"
79
- f"wandb_project: {wandb_project}\n"
80
- f"wandb_run_name: {wandb_run_name}\n"
81
- f"wandb_watch: {wandb_watch}\n"
82
- f"wandb_log_model: {wandb_log_model}\n"
83
- f"resume_from_checkpoint: {resume_from_checkpoint or False}\n"
84
- f"prompt template: {prompt_template_name}\n"
85
- )
86
- assert (
87
- base_model
88
- ), "Please specify a --base_model, e.g. --base_model='huggyllama/llama-7b'"
89
- gradient_accumulation_steps = batch_size // micro_batch_size
90
-
91
- prompter = Prompter(prompt_template_name)
92
-
93
- device_map = "auto"
94
- world_size = int(os.environ.get("WORLD_SIZE", 1))
95
- ddp = world_size != 1
96
- if ddp:
97
- device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)}
98
- gradient_accumulation_steps = gradient_accumulation_steps // world_size
99
-
100
- # Check if parameter passed or if set within environ
101
- use_wandb = len(wandb_project) > 0 or (
102
- "WANDB_PROJECT" in os.environ and len(os.environ["WANDB_PROJECT"]) > 0
103
- )
104
- # Only overwrite environ if wandb param passed
105
- if len(wandb_project) > 0:
106
- os.environ["WANDB_PROJECT"] = wandb_project
107
- if len(wandb_watch) > 0:
108
- os.environ["WANDB_WATCH"] = wandb_watch
109
- if len(wandb_log_model) > 0:
110
- os.environ["WANDB_LOG_MODEL"] = wandb_log_model
111
-
112
- model = LlamaForCausalLM.from_pretrained(
113
- base_model,
114
- load_in_8bit=True,
115
- torch_dtype=torch.float16,
116
- device_map=device_map,
117
- )
118
-
119
- tokenizer = LlamaTokenizer.from_pretrained(base_model)
120
-
121
- tokenizer.pad_token_id = (
122
- 0 # unk. we want this to be different from the eos token
123
- )
124
- tokenizer.padding_side = "left" # Allow batched inference
125
-
126
- def tokenize(prompt, add_eos_token=True):
127
- # there's probably a way to do this with the tokenizer settings
128
- # but again, gotta move fast
129
- result = tokenizer(
130
- prompt,
131
- truncation=True,
132
- max_length=cutoff_len,
133
- padding=False,
134
- return_tensors=None,
135
- )
136
- if (
137
- result["input_ids"][-1] != tokenizer.eos_token_id
138
- and len(result["input_ids"]) < cutoff_len
139
- and add_eos_token
140
- ):
141
- result["input_ids"].append(tokenizer.eos_token_id)
142
- result["attention_mask"].append(1)
143
-
144
- result["labels"] = result["input_ids"].copy()
145
-
146
- return result
147
-
148
- def generate_and_tokenize_prompt(data_point):
149
- full_prompt = prompter.generate_prompt(
150
- data_point["instruction"],
151
- data_point["input"],
152
- data_point["output"],
153
- )
154
- tokenized_full_prompt = tokenize(full_prompt)
155
- if not train_on_inputs:
156
- user_prompt = prompter.generate_prompt(
157
- data_point["instruction"], data_point["input"]
158
- )
159
- tokenized_user_prompt = tokenize(
160
- user_prompt, add_eos_token=add_eos_token
161
- )
162
- user_prompt_len = len(tokenized_user_prompt["input_ids"])
163
-
164
- if add_eos_token:
165
- user_prompt_len -= 1
166
-
167
- tokenized_full_prompt["labels"] = [
168
- -100
169
- ] * user_prompt_len + tokenized_full_prompt["labels"][
170
- user_prompt_len:
171
- ] # could be sped up, probably
172
- return tokenized_full_prompt
173
-
174
- model = prepare_model_for_int8_training(model)
175
-
176
- config = LoraConfig(
177
- r=lora_r,
178
- lora_alpha=lora_alpha,
179
- target_modules=lora_target_modules,
180
- lora_dropout=lora_dropout,
181
- bias="none",
182
- task_type="CAUSAL_LM",
183
- )
184
- model = get_peft_model(model, config)
185
-
186
- if data_path.endswith(".json") or data_path.endswith(".jsonl"):
187
- data = load_dataset("json", data_files=data_path)
188
- else:
189
- data = load_dataset(data_path)
190
-
191
- if resume_from_checkpoint:
192
- # Check the available weights and load them
193
- checkpoint_name = os.path.join(
194
- resume_from_checkpoint, "pytorch_model.bin"
195
- ) # Full checkpoint
196
- if not os.path.exists(checkpoint_name):
197
- checkpoint_name = os.path.join(
198
- resume_from_checkpoint, "adapter_model.bin"
199
- ) # only LoRA model - LoRA config above has to fit
200
- resume_from_checkpoint = (
201
- False # So the trainer won't try loading its state
202
- )
203
- # The two files above have a different name depending on how they were saved, but are actually the same.
204
- if os.path.exists(checkpoint_name):
205
- print(f"Restarting from {checkpoint_name}")
206
- adapters_weights = torch.load(checkpoint_name)
207
- set_peft_model_state_dict(model, adapters_weights)
208
- else:
209
- print(f"Checkpoint {checkpoint_name} not found")
210
-
211
- model.print_trainable_parameters() # Be more transparent about the % of trainable params.
212
-
213
- if val_set_size > 0:
214
- train_val = data["train"].train_test_split(
215
- test_size=val_set_size, shuffle=True, seed=42
216
- )
217
- train_data = (
218
- train_val["train"].shuffle().map(generate_and_tokenize_prompt)
219
- )
220
- val_data = (
221
- train_val["test"].shuffle().map(generate_and_tokenize_prompt)
222
- )
223
- else:
224
- train_data = data["train"].shuffle().map(generate_and_tokenize_prompt)
225
- val_data = None
226
-
227
- if not ddp and torch.cuda.device_count() > 1:
228
- # keeps Trainer from trying its own DataParallelism when more than 1 gpu is available
229
- model.is_parallelizable = True
230
- model.model_parallel = True
231
-
232
- trainer = transformers.Trainer(
233
- model=model,
234
- train_dataset=train_data,
235
- eval_dataset=val_data,
236
- args=transformers.TrainingArguments(
237
- per_device_train_batch_size=micro_batch_size,
238
- gradient_accumulation_steps=gradient_accumulation_steps,
239
- warmup_steps=100,
240
- num_train_epochs=num_epochs,
241
- learning_rate=learning_rate,
242
- fp16=True,
243
- logging_steps=10,
244
- optim="adamw_torch",
245
- evaluation_strategy="steps" if val_set_size > 0 else "no",
246
- save_strategy="steps",
247
- eval_steps=200 if val_set_size > 0 else None,
248
- save_steps=200,
249
- output_dir=output_dir,
250
- save_total_limit=3,
251
- load_best_model_at_end=True if val_set_size > 0 else False,
252
- ddp_find_unused_parameters=False if ddp else None,
253
- group_by_length=group_by_length,
254
- report_to="wandb" if use_wandb else None,
255
- run_name=wandb_run_name if use_wandb else None,
256
- ),
257
- data_collator=transformers.DataCollatorForSeq2Seq(
258
- tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
259
- ),
260
- )
261
- model.config.use_cache = False
262
-
263
- old_state_dict = model.state_dict
264
- model.state_dict = (
265
- lambda self, *_, **__: get_peft_model_state_dict(
266
- self, old_state_dict()
267
- )
268
- ).__get__(model, type(model))
269
-
270
- if torch.__version__ >= "2" and sys.platform != "win32":
271
- model = torch.compile(model)
272
-
273
- trainer.train(resume_from_checkpoint=resume_from_checkpoint)
274
-
275
- model.save_pretrained(output_dir)
276
-
277
- print(
278
- "\n If there's a warning about missing keys above, please disregard :)"
279
- )
280
-
281
-
282
- if __name__ == "__main__":
283
- fire.Fire(train)