a b/finetune.py
1
import os
2
import pickle
3
import random
4
import sys
5
from typing import List, Optional
6
7
import fire
8
import torch
9
import transformers
10
from datasets import load_dataset
11
import wandb
12
13
from torch import nn
14
from torch.utils.data import Sampler
15
from transformers.modeling_utils import unwrap_model
16
17
from local_config import WANDB_ENTITY
18
from utils.datacollator import MyDataCollatorForSeq2Seq
19
from model.lavis.models.blip2_models.modeling_llama_imgemb import LlamaForCausalLM
20
21
from peft import (
22
    LoraConfig,
23
    get_peft_model,
24
    get_peft_model_state_dict,
25
    prepare_model_for_int8_training,
26
    set_peft_model_state_dict,
27
)
28
from transformers import AutoTokenizer, PreTrainedModel
29
30
from utils.prompter import Prompter
31
32
import logging
33
logger = logging.getLogger(__name__)
34
35
#how are input and instruction put together:
36
'''
37
Below is an instruction that describes a task. Write a response that appropriately completes the request.
38
39
### Instruction:
40
{instruction}
41
42
### Response:
43
44
or
45
46
Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
47
48
### Instruction:
49
{instruction}
50
51
### Input:
52
{input}
53
54
### Response:
55
'''
56
57
class BalancedSampler(Sampler):
58
    def __init__(self, true_indices, false_indices):
59
        self.true_indices = true_indices
60
        self.false_indices = false_indices
61
        self.num_samples = 2 * min(len(self.true_indices), len(self.false_indices))
62
63
    def __iter__(self):
64
        # Randomly sample from true_indices
65
        sampled_true_indices = random.sample(self.true_indices, len(self.false_indices))
66
        # Merge and shuffle the two lists of indices
67
        indices = sampled_true_indices + self.false_indices
68
        random.shuffle(indices)
69
        return iter(indices)
70
71
    def __len__(self):
72
        return self.num_samples
73
74
class InstructTrainer(transformers.Trainer):
75
    def __init__(self, *args, rep_idxs=None, inst_idxs=None, **kwargs):
76
        super().__init__(*args, **kwargs)
77
        self.rep_idxs = rep_idxs
78
        self.inst_idxs = inst_idxs
79
80
    def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
81
        return BalancedSampler(self.rep_idxs, self.inst_idxs)
82
83
WEIGHTS_NAME = "pytorch_model.bin"
84
WEIGHTS_NAME_FINAL = "adapter_model.bin"
85
TRAINING_ARGS_NAME = "training_args.bin"
86
class ImgTrainer(transformers.Trainer): #also save img projector
87
    def _save(self, output_dir: Optional[str] = None, state_dict=None):
88
        # If we are executing this function, we are the process zero, so we don't check for that.
89
        output_dir = output_dir if output_dir is not None else self.args.output_dir
90
        os.makedirs(output_dir, exist_ok=True)
91
        logger.info(f"Saving model checkpoint to {output_dir}")
92
        # Save a trained model and configuration using `save_pretrained()`.
93
        # They can then be reloaded using `from_pretrained()`
94
        if not isinstance(self.model, PreTrainedModel):
95
            if state_dict is None:
96
                state_dict = self.model.state_dict()
97
                base_state_dict = self.model.base_model.state_dict()
98
                if 'model.model.img_proj_layer.weight' in base_state_dict:
99
                    state_dict['base_model.model.model.img_proj_layer.weight'] = base_state_dict['model.model.img_proj_layer.weight']
100
                    state_dict['base_model.model.model.img_proj_layer.bias'] = base_state_dict['model.model.img_proj_layer.bias']
101
102
            if isinstance(unwrap_model(self.model), PreTrainedModel):
103
                unwrap_model(self.model).save_pretrained(
104
                    output_dir, state_dict=state_dict, safe_serialization=self.args.save_safetensors
105
                )
106
            else:
107
                logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.")
108
                torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))
109
        else:
110
            self.model.save_pretrained(
111
                output_dir, state_dict=state_dict, safe_serialization=self.args.save_safetensors
112
            )
113
114
        if self.tokenizer is not None:
115
            self.tokenizer.save_pretrained(output_dir)
116
117
        # Good practice: save your training arguments together with the trained model
118
        torch.save(self.args, os.path.join(output_dir, TRAINING_ARGS_NAME))
119
120
121
def save_pretrained(model, save_directory, **kwargs):
122
    r"""
123
    This function saves the adapter model and the adapter configuration files to a directory, so that it can be
124
    reloaded using the [`LoraModel.from_pretrained`] class method, and also used by the [`LoraModel.push_to_hub`]
125
    method.
126
127
    Args:
128
        save_directory (`str`):
129
            Directory where the adapter model and configuration files will be saved (will be created if it does not
130
            exist).
131
        kwargs (additional keyword arguments, *optional*):
132
            Additional keyword arguments passed along to the `push_to_hub` method.
133
    """
134
    if os.path.isfile(save_directory):
135
        raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")
136
    os.makedirs(save_directory, exist_ok=True)
137
138
    # save only the trainable weights
139
    output_state_dict = get_peft_model_state_dict(model, kwargs.get("state_dict", None))
140
    base_state_dict = model.base_model.state_dict()
141
    if 'model.model.img_proj_layer.weight' in base_state_dict:
142
        output_state_dict['base_model.model.model.img_proj_layer.weight'] = base_state_dict['model.model.img_proj_layer.weight']
143
        output_state_dict['base_model.model.model.img_proj_layer.bias'] = base_state_dict['model.model.img_proj_layer.bias']
144
145
    torch.save(output_state_dict, os.path.join(save_directory, WEIGHTS_NAME_FINAL))
146
147
    inference_mode = model.peft_config.inference_mode
148
    model.peft_config.inference_mode = True
149
    model.peft_config.save_pretrained(save_directory)
150
    model.peft_config.inference_mode = inference_mode
151
152
153
def train(
154
    # model/data params
155
    base_model: str = "",  # the only required argument
156
    lora_weights: str = None,
157
    data_path: str = "yahma/alpaca-cleaned",
158
    output_dir: str = "./lora-cxr",
159
    # training hyperparams
160
    batch_size: int = 128,
161
    micro_batch_size: int = 2,
162
    num_epochs: int = 10,
163
    learning_rate: float = 3e-4,
164
    cutoff_len: int = 1024, #256 -> need much more with examples in prompt (1024), 512 for without examples but long IG labels
165
    val_set_size: int = 5,
166
    # lora hyperparams
167
    lora_r: int = 8,
168
    lora_alpha: int = 16,
169
    lora_dropout: float = 0.05,
170
    lora_target_modules: List[str] = [ #default is for llama models
171
        "q_proj",
172
        "v_proj",
173
    ],
174
    # llm hyperparams
175
    train_on_inputs: bool = False,  # if False, masks out inputs in loss
176
    add_eos_token: bool = False,
177
    group_by_length: bool = False,  # faster, but produces an odd training loss curve
178
    # wandb params
179
    wandb_project: str = "lora_training",
180
    wandb_run_name: str = "lora_mimic_cxr",
181
    wandb_entity: str = WANDB_ENTITY,
182
    wandb_watch: str = "",  # options: false | gradients | all
183
    wandb_log_model: str = "",  # options: false | true
184
    resume_from_checkpoint: str = None,  # either training checkpoint or final adapter
185
    prompt_template_name: str = "alpaca",  # The prompt template to use, will default to alpaca.
186
    use_embs=False,
187
    use_instruct_data=False
188
):
189
    if int(os.environ.get("LOCAL_RANK", 0)) == 0:
190
        print(
191
            f"Training Alpaca-LoRA model with params:\n"
192
            f"base_model: {base_model}\n"
193
            f"lora_weights: {lora_weights}\n"
194
            f"data_path: {data_path}\n"
195
            f"output_dir: {output_dir}\n"
196
            f"batch_size: {batch_size}\n"
197
            f"micro_batch_size: {micro_batch_size}\n"
198
            f"num_epochs: {num_epochs}\n"
199
            f"learning_rate: {learning_rate}\n"
200
            f"cutoff_len: {cutoff_len}\n"
201
            f"val_set_size: {val_set_size}\n"
202
            f"lora_r: {lora_r}\n"
203
            f"lora_alpha: {lora_alpha}\n"
204
            f"lora_dropout: {lora_dropout}\n"
205
            f"lora_target_modules: {lora_target_modules}\n"
206
            f"train_on_inputs: {train_on_inputs}\n"
207
            f"add_eos_token: {add_eos_token}\n"
208
            f"group_by_length: {group_by_length}\n"
209
            f"wandb_project: {wandb_project}\n"
210
            f"wandb_run_name: {wandb_run_name}\n"
211
            f"wandb_entity: {wandb_entity}\n"
212
            f"wandb_watch: {wandb_watch}\n"
213
            f"wandb_log_model: {wandb_log_model}\n"
214
            f"resume_from_checkpoint: {resume_from_checkpoint or False}\n"
215
            f"prompt template: {prompt_template_name}\n"
216
        )
217
    assert (
218
        base_model
219
    ), "Please specify a --base_model, e.g. --base_model='huggyllama/llama-7b'"
220
    gradient_accumulation_steps = batch_size // micro_batch_size
221
222
    prompter = Prompter(prompt_template_name)
223
224
    device_map = "auto"
225
    world_size = int(os.environ.get("WORLD_SIZE", 1))
226
    ddp = world_size != 1
227
    if ddp:
228
        device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)}
229
        gradient_accumulation_steps = gradient_accumulation_steps // world_size
230
231
    # Check if parameter passed or if set within environ
232
    use_wandb = len(wandb_project) > 0 or (
233
        "WANDB_PROJECT" in os.environ and len(os.environ["WANDB_PROJECT"]) > 0
234
    )
235
    # Only overwrite environ if wandb param passed
236
    if len(wandb_project) > 0:
237
        os.environ["WANDB_PROJECT"] = wandb_project
238
    if len(wandb_watch) > 0:
239
        os.environ["WANDB_WATCH"] = wandb_watch
240
    if len(wandb_log_model) > 0:
241
        os.environ["WANDB_LOG_MODEL"] = wandb_log_model
242
243
244
    if base_model == 'vicuna_v13':
245
        model = LlamaForCausalLM.from_pretrained("lmsys/vicuna-13b-v1.3", torch_dtype=torch.float16, device_map='auto', load_in_8bit=False)
246
        tokenizer = AutoTokenizer.from_pretrained("lmsys/vicuna-13b-v1.3", use_fast=False, truncation_side="right", padding_side="right")
247
    else: #7b
248
        model = LlamaForCausalLM.from_pretrained("lmsys/vicuna-7b-v1.3", torch_dtype=torch.float16, device_map='auto', load_in_8bit=False)
249
        tokenizer = AutoTokenizer.from_pretrained("lmsys/vicuna-7b-v1.3", use_fast=False, truncation_side="right", padding_side="right")
250
251
    tokenizer.pad_token = tokenizer.unk_token
252
253
    if use_embs:
254
        model.base_model.img_proj_layer = nn.Linear(768, model.base_model.config.hidden_size).to(model.base_model.device)
255
256
    # add special token to tokenizer
257
    tokenizer.add_special_tokens({"additional_special_tokens": ["<IMG>"]})
258
    model.resize_token_embeddings(len(tokenizer))
259
260
261
    def tokenize(prompt, add_eos_token=True):
262
        # there's probably a way to do this with the tokenizer settings
263
        # but again, gotta move fast
264
        result = tokenizer(
265
            prompt,
266
            truncation=True,
267
            max_length=cutoff_len,
268
            padding=False,
269
            return_tensors=None,
270
        )
271
        if (
272
            result["input_ids"][-1] != tokenizer.eos_token_id
273
            and len(result["input_ids"]) < cutoff_len
274
            and add_eos_token
275
        ):
276
            result["input_ids"].append(tokenizer.eos_token_id)
277
            result["attention_mask"].append(1)
278
279
        result["labels"] = result["input_ids"].copy()
280
281
        return result
282
283
    def generate_and_tokenize_prompt(data_point):
284
        full_prompt = prompter.generate_prompt(
285
            data_point["instruction"],
286
            data_point["input"],
287
            data_point["output"],
288
        )
289
        tokenized_full_prompt = tokenize(full_prompt)
290
        if not train_on_inputs:
291
            user_prompt = prompter.generate_prompt(
292
                data_point["instruction"], data_point["input"]
293
            )
294
            tokenized_user_prompt = tokenize(
295
                user_prompt, add_eos_token=add_eos_token
296
            )
297
            user_prompt_len = len(tokenized_user_prompt["input_ids"])
298
299
            if add_eos_token:
300
                user_prompt_len -= 1
301
302
            tokenized_full_prompt["labels"] = [
303
                -100
304
            ] * user_prompt_len + tokenized_full_prompt["labels"][
305
                user_prompt_len:
306
            ]  # could be sped up, probably
307
        return tokenized_full_prompt
308
309
    model = prepare_model_for_int8_training(model)
310
311
    config = LoraConfig(
312
        r=lora_r,
313
        lora_alpha=lora_alpha,
314
        target_modules=lora_target_modules,
315
        lora_dropout=lora_dropout,
316
        bias="none",
317
        task_type="CAUSAL_LM",
318
    )
319
320
    model = get_peft_model(model, config) #this sets requires_grad for all params to False
321
    # unfreeze the img_proj_layer
322
    model.model.base_model.img_proj_layer.weight.requires_grad = True
323
    model.model.base_model.img_proj_layer.bias.requires_grad = True
324
325
    print("Loading data from ", data_path)
326
    if data_path.endswith(".json") or data_path.endswith(".jsonl"):
327
        data = load_dataset("json", data_files=data_path)
328
    else:
329
        data = load_dataset(data_path)
330
331
    if resume_from_checkpoint:
332
        # Check the available weights and load them
333
        checkpoint_name = os.path.join(
334
            resume_from_checkpoint, "pytorch_model.bin"
335
        )  # Full checkpoint
336
        if not os.path.exists(checkpoint_name):
337
            checkpoint_name = os.path.join(
338
                resume_from_checkpoint, "adapter_model.bin"
339
            )  # only LoRA model - LoRA config above has to fit
340
            resume_from_checkpoint = (
341
                False  # So the trainer won't try loading its state
342
            )
343
        # The two files above have a different name depending on how they were saved, but are actually the same.
344
        if os.path.exists(checkpoint_name):
345
            print(f"Restarting from {checkpoint_name}")
346
            adapters_weights = torch.load(checkpoint_name)
347
            set_peft_model_state_dict(model, adapters_weights)
348
        else:
349
            print(f"Checkpoint {checkpoint_name} not found")
350
351
    model.print_trainable_parameters()  # Be more transparent about the % of trainable params.
352
353
    if val_set_size > 0:
354
        train_val = data["train"].train_test_split(
355
            test_size=val_set_size, shuffle=True, seed=42
356
        )
357
        train_data = (
358
            train_val["train"].shuffle().map(generate_and_tokenize_prompt)
359
        )
360
        val_data = (
361
            train_val["test"].shuffle().map(generate_and_tokenize_prompt)
362
        )
363
    else:
364
        train_data = data["train"].shuffle().map(generate_and_tokenize_prompt)
365
        val_data = None
366
367
    if use_instruct_data:
368
        report_indices = [i for i, item in enumerate(train_data) if item['is_report']][:5]
369
        instruct_indices = [i for i, item in enumerate(train_data) if not item['is_report']][:5]
370
371
    if not ddp and torch.cuda.device_count() > 1:
372
        # keeps Trainer from trying its own DataParallelism when more than 1 gpu is available
373
        model.is_parallelizable = True
374
        model.model_parallel = True
375
376
    wandb.init(
377
        project=wandb_project,
378
        entity=wandb_entity,
379
        name=wandb_run_name
380
    )
381
382
    if use_instruct_data:
383
        trainer = InstructTrainer(
384
            model=model,
385
            train_dataset=train_data,
386
            eval_dataset=val_data,
387
            rep_idxs = report_indices,
388
            inst_idxs = instruct_indices,
389
            args=transformers.TrainingArguments(
390
                per_device_train_batch_size=micro_batch_size,
391
                gradient_accumulation_steps=gradient_accumulation_steps,
392
                warmup_steps=100,
393
                num_train_epochs=num_epochs,
394
                learning_rate=learning_rate,
395
                fp16=True,
396
                logging_steps=10,
397
                optim="adamw_torch",
398
                evaluation_strategy="steps" if val_set_size > 0 else "no",
399
                save_strategy="steps",
400
                eval_steps=200 if val_set_size > 0 else None,
401
                save_steps=200,
402
                output_dir=output_dir,
403
                save_total_limit=None,
404
                load_best_model_at_end=True if val_set_size > 0 else False,
405
                ddp_find_unused_parameters=False if ddp else None,
406
                group_by_length=group_by_length,
407
                report_to="wandb" if use_wandb else None,
408
                run_name=wandb_run_name if use_wandb else None,
409
                max_steps=-1,
410
                dataloader_num_workers=8,
411
                remove_unused_columns=False if use_embs else True,
412
            ),
413
            data_collator=MyDataCollatorForSeq2Seq(
414
                tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
415
            ) if use_embs else
416
            transformers.DataCollatorForSeq2Seq(
417
                tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
418
            ),
419
        )
420
    else:
421
        trainer = ImgTrainer(
422
            model=model,
423
            train_dataset=train_data,
424
            eval_dataset=val_data,
425
            args=transformers.TrainingArguments(
426
                per_device_train_batch_size=micro_batch_size,
427
                gradient_accumulation_steps=gradient_accumulation_steps,
428
                warmup_steps=100,
429
                num_train_epochs=num_epochs,
430
                learning_rate=learning_rate,
431
                fp16=True,
432
                logging_steps=10,
433
                optim="adamw_torch",
434
                evaluation_strategy="steps" if val_set_size > 0 else "no",
435
                save_strategy="steps",
436
                eval_steps=400 if val_set_size > 0 else None,
437
                save_steps=400,
438
                output_dir=output_dir,
439
                save_total_limit=None,
440
                load_best_model_at_end=True if val_set_size > 0 else False,
441
                ddp_find_unused_parameters=False if ddp else None,
442
                group_by_length=group_by_length,
443
                report_to="wandb" if use_wandb else None,
444
                run_name=wandb_run_name if use_wandb else None,
445
                max_steps=-1,
446
                dataloader_num_workers=8,
447
                remove_unused_columns=False if use_embs else True
448
            ),
449
            data_collator=MyDataCollatorForSeq2Seq(
450
                tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
451
            ) if use_embs else
452
            transformers.DataCollatorForSeq2Seq(
453
                tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
454
            ),
455
        )
456
    model.config.use_cache = False
457
458
    old_state_dict = model.state_dict
459
    model.state_dict = (
460
        lambda self, *_, **__: get_peft_model_state_dict(
461
            self, old_state_dict()
462
        )
463
    ).__get__(model, type(model))
464
465
    if torch.__version__ >= "2" and sys.platform != "win32":
466
        model = torch.compile(model)
467
468
    trainer.train(resume_from_checkpoint=resume_from_checkpoint)
469
470
    save_pretrained(model, output_dir)
471
472
    print(
473
        "\n If there's a warning about missing keys above, please disregard :)"
474
    )
475
476
477
if __name__ == "__main__":
478
    fire.Fire(train)