Fabrice-TIERCELIN
commited on
Commit
•
df25700
1
Parent(s):
f2d9681
Upload 3 files
Browse files- llava/train/llava_trainer.py +175 -0
- llava/train/train.py +952 -0
- llava/train/train_mem.py +13 -0
llava/train/llava_trainer.py
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
|
4 |
+
from torch.utils.data import Sampler
|
5 |
+
|
6 |
+
from transformers import Trainer
|
7 |
+
from transformers.trainer import (
|
8 |
+
has_length,
|
9 |
+
)
|
10 |
+
from typing import List, Optional
|
11 |
+
|
12 |
+
|
13 |
+
def maybe_zero_3(param, ignore_status=False, name=None):
|
14 |
+
from deepspeed import zero
|
15 |
+
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
|
16 |
+
if hasattr(param, "ds_id"):
|
17 |
+
if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
|
18 |
+
if not ignore_status:
|
19 |
+
print(name, 'no ignore status')
|
20 |
+
with zero.GatheredParameters([param]):
|
21 |
+
param = param.data.detach().cpu().clone()
|
22 |
+
else:
|
23 |
+
param = param.detach().cpu().clone()
|
24 |
+
return param
|
25 |
+
|
26 |
+
|
27 |
+
def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
|
28 |
+
to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
|
29 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()}
|
30 |
+
return to_return
|
31 |
+
|
32 |
+
|
33 |
+
def split_to_even_chunks(indices, lengths, num_chunks):
|
34 |
+
"""
|
35 |
+
Split a list of indices into `chunks` chunks of roughly equal lengths.
|
36 |
+
"""
|
37 |
+
|
38 |
+
if len(indices) % num_chunks != 0:
|
39 |
+
return [indices[i::num_chunks] for i in range(num_chunks)]
|
40 |
+
|
41 |
+
num_indices_per_chunk = len(indices) // num_chunks
|
42 |
+
|
43 |
+
chunks = [[] for _ in range(num_chunks)]
|
44 |
+
chunks_lengths = [0 for _ in range(num_chunks)]
|
45 |
+
for index in indices:
|
46 |
+
shortest_chunk = chunks_lengths.index(min(chunks_lengths))
|
47 |
+
chunks[shortest_chunk].append(index)
|
48 |
+
chunks_lengths[shortest_chunk] += lengths[index]
|
49 |
+
if len(chunks[shortest_chunk]) == num_indices_per_chunk:
|
50 |
+
chunks_lengths[shortest_chunk] = float("inf")
|
51 |
+
|
52 |
+
return chunks
|
53 |
+
|
54 |
+
|
55 |
+
def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None):
|
56 |
+
# We need to use torch for the random part as a distributed sampler will set the random seed for torch.
|
57 |
+
assert all(l != 0 for l in lengths), "Should not have zero length."
|
58 |
+
mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0])
|
59 |
+
lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0])
|
60 |
+
|
61 |
+
assert len(mm_indices) > 0, "Should have at least one multimodal sample."
|
62 |
+
assert len(lang_indices) > 0, "Should have at least one language sample."
|
63 |
+
|
64 |
+
mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)]
|
65 |
+
lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)]
|
66 |
+
megabatch_size = world_size * batch_size
|
67 |
+
mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)]
|
68 |
+
lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)]
|
69 |
+
|
70 |
+
last_mm = mm_megabatches[-1]
|
71 |
+
last_lang = lang_megabatches[-1]
|
72 |
+
additional_batch = last_mm + last_lang
|
73 |
+
megabatches = mm_megabatches[:-1] + lang_megabatches[:-1]
|
74 |
+
megabatch_indices = torch.randperm(len(megabatches), generator=generator)
|
75 |
+
megabatches = [megabatches[i] for i in megabatch_indices]
|
76 |
+
|
77 |
+
if len(additional_batch) >= megabatch_size:
|
78 |
+
megabatches = [additional_batch[:megabatch_size]] + megabatches
|
79 |
+
additional_batch = additional_batch[megabatch_size:]
|
80 |
+
|
81 |
+
if len(additional_batch) > 0:
|
82 |
+
megabatches.append(additional_batch)
|
83 |
+
|
84 |
+
return [i for megabatch in megabatches for i in megabatch]
|
85 |
+
|
86 |
+
|
87 |
+
def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True):
|
88 |
+
# We need to use torch for the random part as a distributed sampler will set the random seed for torch.
|
89 |
+
indices = torch.randperm(len(lengths), generator=generator)
|
90 |
+
megabatch_size = world_size * batch_size
|
91 |
+
megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)]
|
92 |
+
megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
|
93 |
+
megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
|
94 |
+
|
95 |
+
return [i for megabatch in megabatches for batch in megabatch for i in batch]
|
96 |
+
|
97 |
+
|
98 |
+
class LengthGroupedSampler(Sampler):
|
99 |
+
r"""
|
100 |
+
Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
|
101 |
+
keeping a bit of randomness.
|
102 |
+
"""
|
103 |
+
|
104 |
+
def __init__(
|
105 |
+
self,
|
106 |
+
batch_size: int,
|
107 |
+
world_size: int,
|
108 |
+
lengths: Optional[List[int]] = None,
|
109 |
+
generator=None,
|
110 |
+
group_by_modality: bool = False,
|
111 |
+
):
|
112 |
+
if lengths is None:
|
113 |
+
raise ValueError("Lengths must be provided.")
|
114 |
+
|
115 |
+
self.batch_size = batch_size
|
116 |
+
self.world_size = world_size
|
117 |
+
self.lengths = lengths
|
118 |
+
self.generator = generator
|
119 |
+
self.group_by_modality = group_by_modality
|
120 |
+
|
121 |
+
def __len__(self):
|
122 |
+
return len(self.lengths)
|
123 |
+
|
124 |
+
def __iter__(self):
|
125 |
+
if self.group_by_modality:
|
126 |
+
indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
|
127 |
+
else:
|
128 |
+
indices = get_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
|
129 |
+
return iter(indices)
|
130 |
+
|
131 |
+
|
132 |
+
class LLaVATrainer(Trainer):
|
133 |
+
|
134 |
+
def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
|
135 |
+
if self.train_dataset is None or not has_length(self.train_dataset):
|
136 |
+
return None
|
137 |
+
|
138 |
+
if self.args.group_by_modality_length:
|
139 |
+
lengths = self.train_dataset.modality_lengths
|
140 |
+
return LengthGroupedSampler(
|
141 |
+
# self.args.train_batch_size * self.args.gradient_accumulation_steps, # TODO: seems that we should not have gradient_accumulation_steps
|
142 |
+
self.args.train_batch_size,
|
143 |
+
world_size=self.args.world_size,
|
144 |
+
lengths=lengths,
|
145 |
+
group_by_modality=True,
|
146 |
+
)
|
147 |
+
else:
|
148 |
+
return super()._get_train_sampler()
|
149 |
+
|
150 |
+
def _save_checkpoint(self, model, trial, metrics=None):
|
151 |
+
if getattr(self.args, 'tune_mm_mlp_adapter', False):
|
152 |
+
from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
|
153 |
+
checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
|
154 |
+
|
155 |
+
run_dir = self._get_output_dir(trial=trial)
|
156 |
+
output_dir = os.path.join(run_dir, checkpoint_folder)
|
157 |
+
|
158 |
+
# Only save Adapter
|
159 |
+
keys_to_match = ['mm_projector', 'vision_resampler']
|
160 |
+
if getattr(self.args, "use_im_start_end", False):
|
161 |
+
keys_to_match.extend(['embed_tokens', 'embed_in'])
|
162 |
+
|
163 |
+
weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match)
|
164 |
+
|
165 |
+
if self.args.local_rank == 0 or self.args.local_rank == -1:
|
166 |
+
self.model.config.save_pretrained(output_dir)
|
167 |
+
torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
|
168 |
+
else:
|
169 |
+
super(LLaVATrainer, self)._save_checkpoint(model, trial, metrics)
|
170 |
+
|
171 |
+
def _save(self, output_dir: Optional[str] = None, state_dict=None):
|
172 |
+
if getattr(self.args, 'tune_mm_mlp_adapter', False):
|
173 |
+
pass
|
174 |
+
else:
|
175 |
+
super(LLaVATrainer, self)._save(output_dir, state_dict)
|
llava/train/train.py
ADDED
@@ -0,0 +1,952 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
|
2 |
+
# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
|
3 |
+
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
|
17 |
+
import os
|
18 |
+
import copy
|
19 |
+
from dataclasses import dataclass, field
|
20 |
+
import json
|
21 |
+
import logging
|
22 |
+
import pathlib
|
23 |
+
from typing import Dict, Optional, Sequence, List
|
24 |
+
|
25 |
+
import torch
|
26 |
+
|
27 |
+
import transformers
|
28 |
+
|
29 |
+
from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
30 |
+
from torch.utils.data import Dataset
|
31 |
+
from llava.train.llava_trainer import LLaVATrainer
|
32 |
+
|
33 |
+
from llava import conversation as conversation_lib
|
34 |
+
from llava.model import *
|
35 |
+
from llava.mm_utils import tokenizer_image_token
|
36 |
+
|
37 |
+
from PIL import Image
|
38 |
+
|
39 |
+
|
40 |
+
local_rank = None
|
41 |
+
|
42 |
+
|
43 |
+
def rank0_print(*args):
|
44 |
+
if local_rank == 0:
|
45 |
+
print(*args)
|
46 |
+
|
47 |
+
|
48 |
+
@dataclass
|
49 |
+
class ModelArguments:
|
50 |
+
model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
|
51 |
+
version: Optional[str] = field(default="v0")
|
52 |
+
freeze_backbone: bool = field(default=False)
|
53 |
+
tune_mm_mlp_adapter: bool = field(default=False)
|
54 |
+
vision_tower: Optional[str] = field(default=None)
|
55 |
+
mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer
|
56 |
+
pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
|
57 |
+
mm_projector_type: Optional[str] = field(default='linear')
|
58 |
+
mm_use_im_start_end: bool = field(default=False)
|
59 |
+
mm_use_im_patch_token: bool = field(default=True)
|
60 |
+
mm_vision_select_feature: Optional[str] = field(default="patch")
|
61 |
+
|
62 |
+
|
63 |
+
@dataclass
|
64 |
+
class DataArguments:
|
65 |
+
data_path: str = field(default=None,
|
66 |
+
metadata={"help": "Path to the training data."})
|
67 |
+
lazy_preprocess: bool = False
|
68 |
+
is_multimodal: bool = False
|
69 |
+
image_folder: Optional[str] = field(default=None)
|
70 |
+
image_aspect_ratio: str = 'square'
|
71 |
+
image_grid_pinpoints: Optional[str] = field(default=None)
|
72 |
+
|
73 |
+
|
74 |
+
@dataclass
|
75 |
+
class TrainingArguments(transformers.TrainingArguments):
|
76 |
+
cache_dir: Optional[str] = field(default=None)
|
77 |
+
optim: str = field(default="adamw_torch")
|
78 |
+
remove_unused_columns: bool = field(default=False)
|
79 |
+
freeze_mm_mlp_adapter: bool = field(default=False)
|
80 |
+
mpt_attn_impl: Optional[str] = field(default="triton")
|
81 |
+
model_max_length: int = field(
|
82 |
+
default=512,
|
83 |
+
metadata={
|
84 |
+
"help":
|
85 |
+
"Maximum sequence length. Sequences will be right padded (and possibly truncated)."
|
86 |
+
},
|
87 |
+
)
|
88 |
+
double_quant: bool = field(
|
89 |
+
default=True,
|
90 |
+
metadata={"help": "Compress the quantization statistics through double quantization."}
|
91 |
+
)
|
92 |
+
quant_type: str = field(
|
93 |
+
default="nf4",
|
94 |
+
metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}
|
95 |
+
)
|
96 |
+
bits: int = field(
|
97 |
+
default=16,
|
98 |
+
metadata={"help": "How many bits to use."}
|
99 |
+
)
|
100 |
+
lora_enable: bool = False
|
101 |
+
lora_r: int = 64
|
102 |
+
lora_alpha: int = 16
|
103 |
+
lora_dropout: float = 0.05
|
104 |
+
lora_weight_path: str = ""
|
105 |
+
lora_bias: str = "none"
|
106 |
+
group_by_modality_length: bool = field(default=False)
|
107 |
+
|
108 |
+
|
109 |
+
def maybe_zero_3(param, ignore_status=False, name=None):
|
110 |
+
from deepspeed import zero
|
111 |
+
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
|
112 |
+
if hasattr(param, "ds_id"):
|
113 |
+
if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
|
114 |
+
if not ignore_status:
|
115 |
+
logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
|
116 |
+
with zero.GatheredParameters([param]):
|
117 |
+
param = param.data.detach().cpu().clone()
|
118 |
+
else:
|
119 |
+
param = param.detach().cpu().clone()
|
120 |
+
return param
|
121 |
+
|
122 |
+
|
123 |
+
# Borrowed from peft.utils.get_peft_model_state_dict
|
124 |
+
def get_peft_state_maybe_zero_3(named_params, bias):
|
125 |
+
if bias == "none":
|
126 |
+
to_return = {k: t for k, t in named_params if "lora_" in k}
|
127 |
+
elif bias == "all":
|
128 |
+
to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
|
129 |
+
elif bias == "lora_only":
|
130 |
+
to_return = {}
|
131 |
+
maybe_lora_bias = {}
|
132 |
+
lora_bias_names = set()
|
133 |
+
for k, t in named_params:
|
134 |
+
if "lora_" in k:
|
135 |
+
to_return[k] = t
|
136 |
+
bias_name = k.split("lora_")[0] + "bias"
|
137 |
+
lora_bias_names.add(bias_name)
|
138 |
+
elif "bias" in k:
|
139 |
+
maybe_lora_bias[k] = t
|
140 |
+
for k, t in maybe_lora_bias:
|
141 |
+
if bias_name in lora_bias_names:
|
142 |
+
to_return[bias_name] = t
|
143 |
+
else:
|
144 |
+
raise NotImplementedError
|
145 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
|
146 |
+
return to_return
|
147 |
+
|
148 |
+
|
149 |
+
def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
|
150 |
+
to_return = {k: t for k, t in named_params if "lora_" not in k}
|
151 |
+
if require_grad_only:
|
152 |
+
to_return = {k: t for k, t in to_return.items() if t.requires_grad}
|
153 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
|
154 |
+
return to_return
|
155 |
+
|
156 |
+
|
157 |
+
def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
|
158 |
+
to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
|
159 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
|
160 |
+
return to_return
|
161 |
+
|
162 |
+
|
163 |
+
def find_all_linear_names(model):
|
164 |
+
cls = torch.nn.Linear
|
165 |
+
lora_module_names = set()
|
166 |
+
multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler']
|
167 |
+
for name, module in model.named_modules():
|
168 |
+
if any(mm_keyword in name for mm_keyword in multimodal_keywords):
|
169 |
+
continue
|
170 |
+
if isinstance(module, cls):
|
171 |
+
names = name.split('.')
|
172 |
+
lora_module_names.add(names[0] if len(names) == 1 else names[-1])
|
173 |
+
|
174 |
+
if 'lm_head' in lora_module_names: # needed for 16-bit
|
175 |
+
lora_module_names.remove('lm_head')
|
176 |
+
return list(lora_module_names)
|
177 |
+
|
178 |
+
|
179 |
+
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer,
|
180 |
+
output_dir: str):
|
181 |
+
"""Collects the state dict and dump to disk."""
|
182 |
+
|
183 |
+
if getattr(trainer.args, "tune_mm_mlp_adapter", False):
|
184 |
+
# Only save Adapter
|
185 |
+
keys_to_match = ['mm_projector']
|
186 |
+
if getattr(trainer.args, "use_im_start_end", False):
|
187 |
+
keys_to_match.extend(['embed_tokens', 'embed_in'])
|
188 |
+
|
189 |
+
weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
|
190 |
+
trainer.model.config.save_pretrained(output_dir)
|
191 |
+
|
192 |
+
current_folder = output_dir.split('/')[-1]
|
193 |
+
parent_folder = os.path.dirname(output_dir)
|
194 |
+
if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
|
195 |
+
if current_folder.startswith('checkpoint-'):
|
196 |
+
mm_projector_folder = os.path.join(parent_folder, "mm_projector")
|
197 |
+
os.makedirs(mm_projector_folder, exist_ok=True)
|
198 |
+
torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin'))
|
199 |
+
else:
|
200 |
+
torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
|
201 |
+
return
|
202 |
+
|
203 |
+
if trainer.deepspeed:
|
204 |
+
torch.cuda.synchronize()
|
205 |
+
trainer.save_model(output_dir)
|
206 |
+
return
|
207 |
+
|
208 |
+
state_dict = trainer.model.state_dict()
|
209 |
+
if trainer.args.should_save:
|
210 |
+
cpu_state_dict = {
|
211 |
+
key: value.cpu()
|
212 |
+
for key, value in state_dict.items()
|
213 |
+
}
|
214 |
+
del state_dict
|
215 |
+
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
|
216 |
+
|
217 |
+
|
218 |
+
def smart_tokenizer_and_embedding_resize(
|
219 |
+
special_tokens_dict: Dict,
|
220 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
221 |
+
model: transformers.PreTrainedModel,
|
222 |
+
):
|
223 |
+
"""Resize tokenizer and embedding.
|
224 |
+
|
225 |
+
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
|
226 |
+
"""
|
227 |
+
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
|
228 |
+
model.resize_token_embeddings(len(tokenizer))
|
229 |
+
|
230 |
+
if num_new_tokens > 0:
|
231 |
+
input_embeddings = model.get_input_embeddings().weight.data
|
232 |
+
output_embeddings = model.get_output_embeddings().weight.data
|
233 |
+
|
234 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
235 |
+
dim=0, keepdim=True)
|
236 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
237 |
+
dim=0, keepdim=True)
|
238 |
+
|
239 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
240 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
241 |
+
|
242 |
+
|
243 |
+
def _tokenize_fn(strings: Sequence[str],
|
244 |
+
tokenizer: transformers.PreTrainedTokenizer) -> Dict:
|
245 |
+
"""Tokenize a list of strings."""
|
246 |
+
tokenized_list = [
|
247 |
+
tokenizer(
|
248 |
+
text,
|
249 |
+
return_tensors="pt",
|
250 |
+
padding="longest",
|
251 |
+
max_length=tokenizer.model_max_length,
|
252 |
+
truncation=True,
|
253 |
+
) for text in strings
|
254 |
+
]
|
255 |
+
input_ids = labels = [
|
256 |
+
tokenized.input_ids[0] for tokenized in tokenized_list
|
257 |
+
]
|
258 |
+
input_ids_lens = labels_lens = [
|
259 |
+
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item()
|
260 |
+
for tokenized in tokenized_list
|
261 |
+
]
|
262 |
+
return dict(
|
263 |
+
input_ids=input_ids,
|
264 |
+
labels=labels,
|
265 |
+
input_ids_lens=input_ids_lens,
|
266 |
+
labels_lens=labels_lens,
|
267 |
+
)
|
268 |
+
|
269 |
+
|
270 |
+
def _mask_targets(target, tokenized_lens, speakers):
|
271 |
+
# cur_idx = 0
|
272 |
+
cur_idx = tokenized_lens[0]
|
273 |
+
tokenized_lens = tokenized_lens[1:]
|
274 |
+
target[:cur_idx] = IGNORE_INDEX
|
275 |
+
for tokenized_len, speaker in zip(tokenized_lens, speakers):
|
276 |
+
if speaker == "human":
|
277 |
+
target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX
|
278 |
+
cur_idx += tokenized_len
|
279 |
+
|
280 |
+
|
281 |
+
def _add_speaker_and_signal(header, source, get_conversation=True):
|
282 |
+
"""Add speaker and start/end signal on each round."""
|
283 |
+
BEGIN_SIGNAL = "### "
|
284 |
+
END_SIGNAL = "\n"
|
285 |
+
conversation = header
|
286 |
+
for sentence in source:
|
287 |
+
from_str = sentence["from"]
|
288 |
+
if from_str.lower() == "human":
|
289 |
+
from_str = conversation_lib.default_conversation.roles[0]
|
290 |
+
elif from_str.lower() == "gpt":
|
291 |
+
from_str = conversation_lib.default_conversation.roles[1]
|
292 |
+
else:
|
293 |
+
from_str = 'unknown'
|
294 |
+
sentence["value"] = (BEGIN_SIGNAL + from_str + ": " +
|
295 |
+
sentence["value"] + END_SIGNAL)
|
296 |
+
if get_conversation:
|
297 |
+
conversation += sentence["value"]
|
298 |
+
conversation += BEGIN_SIGNAL
|
299 |
+
return conversation
|
300 |
+
|
301 |
+
|
302 |
+
def preprocess_multimodal(
|
303 |
+
sources: Sequence[str],
|
304 |
+
data_args: DataArguments
|
305 |
+
) -> Dict:
|
306 |
+
is_multimodal = data_args.is_multimodal
|
307 |
+
if not is_multimodal:
|
308 |
+
return sources
|
309 |
+
|
310 |
+
for source in sources:
|
311 |
+
for sentence in source:
|
312 |
+
if DEFAULT_IMAGE_TOKEN in sentence['value']:
|
313 |
+
sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip()
|
314 |
+
sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value']
|
315 |
+
sentence['value'] = sentence['value'].strip()
|
316 |
+
if "mmtag" in conversation_lib.default_conversation.version:
|
317 |
+
sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '<Image>' + DEFAULT_IMAGE_TOKEN + '</Image>')
|
318 |
+
replace_token = DEFAULT_IMAGE_TOKEN
|
319 |
+
if data_args.mm_use_im_start_end:
|
320 |
+
replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
|
321 |
+
sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
322 |
+
|
323 |
+
return sources
|
324 |
+
|
325 |
+
|
326 |
+
def preprocess_llama_2(
|
327 |
+
sources,
|
328 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
329 |
+
has_image: bool = False
|
330 |
+
) -> Dict:
|
331 |
+
conv = conversation_lib.default_conversation.copy()
|
332 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
333 |
+
|
334 |
+
# Apply prompt templates
|
335 |
+
conversations = []
|
336 |
+
for i, source in enumerate(sources):
|
337 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
338 |
+
# Skip the first one if it is not from human
|
339 |
+
source = source[1:]
|
340 |
+
|
341 |
+
conv.messages = []
|
342 |
+
for j, sentence in enumerate(source):
|
343 |
+
role = roles[sentence["from"]]
|
344 |
+
assert role == conv.roles[j % 2], f"{i}"
|
345 |
+
conv.append_message(role, sentence["value"])
|
346 |
+
conversations.append(conv.get_prompt())
|
347 |
+
|
348 |
+
# Tokenize conversations
|
349 |
+
|
350 |
+
if has_image:
|
351 |
+
input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
|
352 |
+
else:
|
353 |
+
input_ids = tokenizer(
|
354 |
+
conversations,
|
355 |
+
return_tensors="pt",
|
356 |
+
padding="longest",
|
357 |
+
max_length=tokenizer.model_max_length,
|
358 |
+
truncation=True,
|
359 |
+
).input_ids
|
360 |
+
|
361 |
+
targets = input_ids.clone()
|
362 |
+
|
363 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
|
364 |
+
|
365 |
+
# Mask targets
|
366 |
+
sep = "[/INST] "
|
367 |
+
for conversation, target in zip(conversations, targets):
|
368 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
369 |
+
|
370 |
+
rounds = conversation.split(conv.sep2)
|
371 |
+
cur_len = 1
|
372 |
+
target[:cur_len] = IGNORE_INDEX
|
373 |
+
for i, rou in enumerate(rounds):
|
374 |
+
if rou == "":
|
375 |
+
break
|
376 |
+
|
377 |
+
parts = rou.split(sep)
|
378 |
+
if len(parts) != 2:
|
379 |
+
break
|
380 |
+
parts[0] += sep
|
381 |
+
|
382 |
+
if has_image:
|
383 |
+
round_len = len(tokenizer_image_token(rou, tokenizer))
|
384 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
|
385 |
+
else:
|
386 |
+
round_len = len(tokenizer(rou).input_ids)
|
387 |
+
instruction_len = len(tokenizer(parts[0]).input_ids) - 2
|
388 |
+
|
389 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
390 |
+
|
391 |
+
cur_len += round_len
|
392 |
+
target[cur_len:] = IGNORE_INDEX
|
393 |
+
|
394 |
+
if cur_len < tokenizer.model_max_length:
|
395 |
+
if cur_len != total_len:
|
396 |
+
target[:] = IGNORE_INDEX
|
397 |
+
print(
|
398 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
399 |
+
f" (ignored)"
|
400 |
+
)
|
401 |
+
|
402 |
+
return dict(
|
403 |
+
input_ids=input_ids,
|
404 |
+
labels=targets,
|
405 |
+
)
|
406 |
+
|
407 |
+
|
408 |
+
def preprocess_v1(
|
409 |
+
sources,
|
410 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
411 |
+
has_image: bool = False
|
412 |
+
) -> Dict:
|
413 |
+
conv = conversation_lib.default_conversation.copy()
|
414 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
415 |
+
|
416 |
+
# Apply prompt templates
|
417 |
+
conversations = []
|
418 |
+
for i, source in enumerate(sources):
|
419 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
420 |
+
# Skip the first one if it is not from human
|
421 |
+
source = source[1:]
|
422 |
+
|
423 |
+
conv.messages = []
|
424 |
+
for j, sentence in enumerate(source):
|
425 |
+
role = roles[sentence["from"]]
|
426 |
+
assert role == conv.roles[j % 2], f"{i}"
|
427 |
+
conv.append_message(role, sentence["value"])
|
428 |
+
conversations.append(conv.get_prompt())
|
429 |
+
|
430 |
+
# Tokenize conversations
|
431 |
+
|
432 |
+
if has_image:
|
433 |
+
input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
|
434 |
+
else:
|
435 |
+
input_ids = tokenizer(
|
436 |
+
conversations,
|
437 |
+
return_tensors="pt",
|
438 |
+
padding="longest",
|
439 |
+
max_length=tokenizer.model_max_length,
|
440 |
+
truncation=True,
|
441 |
+
).input_ids
|
442 |
+
|
443 |
+
targets = input_ids.clone()
|
444 |
+
|
445 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
|
446 |
+
|
447 |
+
# Mask targets
|
448 |
+
sep = conv.sep + conv.roles[1] + ": "
|
449 |
+
for conversation, target in zip(conversations, targets):
|
450 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
451 |
+
|
452 |
+
rounds = conversation.split(conv.sep2)
|
453 |
+
cur_len = 1
|
454 |
+
target[:cur_len] = IGNORE_INDEX
|
455 |
+
for i, rou in enumerate(rounds):
|
456 |
+
if rou == "":
|
457 |
+
break
|
458 |
+
|
459 |
+
parts = rou.split(sep)
|
460 |
+
if len(parts) != 2:
|
461 |
+
break
|
462 |
+
parts[0] += sep
|
463 |
+
|
464 |
+
if has_image:
|
465 |
+
round_len = len(tokenizer_image_token(rou, tokenizer))
|
466 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
|
467 |
+
else:
|
468 |
+
round_len = len(tokenizer(rou).input_ids)
|
469 |
+
instruction_len = len(tokenizer(parts[0]).input_ids) - 2
|
470 |
+
|
471 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
472 |
+
|
473 |
+
cur_len += round_len
|
474 |
+
target[cur_len:] = IGNORE_INDEX
|
475 |
+
|
476 |
+
if cur_len < tokenizer.model_max_length:
|
477 |
+
if cur_len != total_len:
|
478 |
+
target[:] = IGNORE_INDEX
|
479 |
+
print(
|
480 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
481 |
+
f" (ignored)"
|
482 |
+
)
|
483 |
+
|
484 |
+
return dict(
|
485 |
+
input_ids=input_ids,
|
486 |
+
labels=targets,
|
487 |
+
)
|
488 |
+
|
489 |
+
|
490 |
+
def preprocess_mpt(
|
491 |
+
sources,
|
492 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
493 |
+
) -> Dict:
|
494 |
+
conv = conversation_lib.default_conversation.copy()
|
495 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
496 |
+
|
497 |
+
# Apply prompt templates
|
498 |
+
conversations = []
|
499 |
+
for i, source in enumerate(sources):
|
500 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
501 |
+
# Skip the first one if it is not from human
|
502 |
+
source = source[1:]
|
503 |
+
|
504 |
+
conv.messages = []
|
505 |
+
for j, sentence in enumerate(source):
|
506 |
+
role = roles[sentence["from"]]
|
507 |
+
assert role == conv.roles[j % 2], f"{i}"
|
508 |
+
conv.append_message(role, sentence["value"])
|
509 |
+
conversations.append(conv.get_prompt())
|
510 |
+
|
511 |
+
# Tokenize conversations
|
512 |
+
input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
|
513 |
+
targets = input_ids.clone()
|
514 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
|
515 |
+
|
516 |
+
# Mask targets
|
517 |
+
sep = conv.sep + conv.roles[1]
|
518 |
+
for conversation, target in zip(conversations, targets):
|
519 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
520 |
+
|
521 |
+
rounds = conversation.split(conv.sep)
|
522 |
+
re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
|
523 |
+
for conv_idx in range(3, len(rounds), 2):
|
524 |
+
re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt
|
525 |
+
cur_len = 0
|
526 |
+
target[:cur_len] = IGNORE_INDEX
|
527 |
+
for i, rou in enumerate(re_rounds):
|
528 |
+
if rou == "":
|
529 |
+
break
|
530 |
+
|
531 |
+
parts = rou.split(sep)
|
532 |
+
if len(parts) != 2:
|
533 |
+
break
|
534 |
+
parts[0] += sep
|
535 |
+
round_len = len(tokenizer_image_token(rou, tokenizer)) + len(tokenizer_image_token(conv.sep, tokenizer))
|
536 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer))
|
537 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
538 |
+
|
539 |
+
cur_len += round_len
|
540 |
+
target[cur_len:] = IGNORE_INDEX
|
541 |
+
|
542 |
+
if cur_len < tokenizer.model_max_length:
|
543 |
+
if cur_len != total_len:
|
544 |
+
target[:] = IGNORE_INDEX
|
545 |
+
print(
|
546 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
547 |
+
f" (ignored)"
|
548 |
+
)
|
549 |
+
|
550 |
+
return dict(
|
551 |
+
input_ids=input_ids,
|
552 |
+
labels=targets,
|
553 |
+
)
|
554 |
+
|
555 |
+
|
556 |
+
def preprocess_plain(
|
557 |
+
sources: Sequence[str],
|
558 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
559 |
+
) -> Dict:
|
560 |
+
# add end signal and concatenate together
|
561 |
+
conversations = []
|
562 |
+
for source in sources:
|
563 |
+
assert len(source) == 2
|
564 |
+
assert DEFAULT_IMAGE_TOKEN in source[0]['value']
|
565 |
+
source[0]['value'] = DEFAULT_IMAGE_TOKEN
|
566 |
+
conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep
|
567 |
+
conversations.append(conversation)
|
568 |
+
# tokenize conversations
|
569 |
+
input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations]
|
570 |
+
targets = copy.deepcopy(input_ids)
|
571 |
+
for target, source in zip(targets, sources):
|
572 |
+
tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer))
|
573 |
+
target[:tokenized_len] = IGNORE_INDEX
|
574 |
+
|
575 |
+
return dict(input_ids=input_ids, labels=targets)
|
576 |
+
|
577 |
+
|
578 |
+
def preprocess(
|
579 |
+
sources: Sequence[str],
|
580 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
581 |
+
has_image: bool = False
|
582 |
+
) -> Dict:
|
583 |
+
"""
|
584 |
+
Given a list of sources, each is a conversation list. This transform:
|
585 |
+
1. Add signal '### ' at the beginning each sentence, with end signal '\n';
|
586 |
+
2. Concatenate conversations together;
|
587 |
+
3. Tokenize the concatenated conversation;
|
588 |
+
4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
|
589 |
+
"""
|
590 |
+
if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN:
|
591 |
+
return preprocess_plain(sources, tokenizer)
|
592 |
+
if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2:
|
593 |
+
return preprocess_llama_2(sources, tokenizer, has_image=has_image)
|
594 |
+
if conversation_lib.default_conversation.version.startswith("v1"):
|
595 |
+
return preprocess_v1(sources, tokenizer, has_image=has_image)
|
596 |
+
if conversation_lib.default_conversation.version == "mpt":
|
597 |
+
return preprocess_mpt(sources, tokenizer)
|
598 |
+
# add end signal and concatenate together
|
599 |
+
conversations = []
|
600 |
+
for source in sources:
|
601 |
+
header = f"{conversation_lib.default_conversation.system}\n\n"
|
602 |
+
conversation = _add_speaker_and_signal(header, source)
|
603 |
+
conversations.append(conversation)
|
604 |
+
# tokenize conversations
|
605 |
+
def get_tokenize_len(prompts):
|
606 |
+
return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
|
607 |
+
|
608 |
+
if has_image:
|
609 |
+
input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations]
|
610 |
+
else:
|
611 |
+
conversations_tokenized = _tokenize_fn(conversations, tokenizer)
|
612 |
+
input_ids = conversations_tokenized["input_ids"]
|
613 |
+
|
614 |
+
targets = copy.deepcopy(input_ids)
|
615 |
+
for target, source in zip(targets, sources):
|
616 |
+
if has_image:
|
617 |
+
tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source])
|
618 |
+
else:
|
619 |
+
tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"]
|
620 |
+
speakers = [sentence["from"] for sentence in source]
|
621 |
+
_mask_targets(target, tokenized_lens, speakers)
|
622 |
+
|
623 |
+
return dict(input_ids=input_ids, labels=targets)
|
624 |
+
|
625 |
+
|
626 |
+
class LazySupervisedDataset(Dataset):
|
627 |
+
"""Dataset for supervised fine-tuning."""
|
628 |
+
|
629 |
+
def __init__(self, data_path: str,
|
630 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
631 |
+
data_args: DataArguments):
|
632 |
+
super(LazySupervisedDataset, self).__init__()
|
633 |
+
list_data_dict = json.load(open(data_path, "r"))
|
634 |
+
|
635 |
+
rank0_print("Formatting inputs...Skip in lazy mode")
|
636 |
+
self.tokenizer = tokenizer
|
637 |
+
self.list_data_dict = list_data_dict
|
638 |
+
self.data_args = data_args
|
639 |
+
|
640 |
+
def __len__(self):
|
641 |
+
return len(self.list_data_dict)
|
642 |
+
|
643 |
+
@property
|
644 |
+
def lengths(self):
|
645 |
+
length_list = []
|
646 |
+
for sample in self.list_data_dict:
|
647 |
+
img_tokens = 128 if 'image' in sample else 0
|
648 |
+
length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens)
|
649 |
+
return length_list
|
650 |
+
|
651 |
+
@property
|
652 |
+
def modality_lengths(self):
|
653 |
+
length_list = []
|
654 |
+
for sample in self.list_data_dict:
|
655 |
+
cur_len = sum(len(conv['value'].split()) for conv in sample['conversations'])
|
656 |
+
cur_len = cur_len if 'image' in sample else -cur_len
|
657 |
+
length_list.append(cur_len)
|
658 |
+
return length_list
|
659 |
+
|
660 |
+
def __getitem__(self, i) -> Dict[str, torch.Tensor]:
|
661 |
+
sources = self.list_data_dict[i]
|
662 |
+
if isinstance(i, int):
|
663 |
+
sources = [sources]
|
664 |
+
assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
|
665 |
+
if 'image' in sources[0]:
|
666 |
+
image_file = self.list_data_dict[i]['image']
|
667 |
+
image_folder = self.data_args.image_folder
|
668 |
+
processor = self.data_args.image_processor
|
669 |
+
image = Image.open(os.path.join(image_folder, image_file)).convert('RGB')
|
670 |
+
if self.data_args.image_aspect_ratio == 'pad':
|
671 |
+
def expand2square(pil_img, background_color):
|
672 |
+
width, height = pil_img.size
|
673 |
+
if width == height:
|
674 |
+
return pil_img
|
675 |
+
elif width > height:
|
676 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
677 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
678 |
+
return result
|
679 |
+
else:
|
680 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
681 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
682 |
+
return result
|
683 |
+
image = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
|
684 |
+
image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
685 |
+
else:
|
686 |
+
image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
687 |
+
sources = preprocess_multimodal(
|
688 |
+
copy.deepcopy([e["conversations"] for e in sources]),
|
689 |
+
self.data_args)
|
690 |
+
else:
|
691 |
+
sources = copy.deepcopy([e["conversations"] for e in sources])
|
692 |
+
data_dict = preprocess(
|
693 |
+
sources,
|
694 |
+
self.tokenizer,
|
695 |
+
has_image=('image' in self.list_data_dict[i]))
|
696 |
+
if isinstance(i, int):
|
697 |
+
data_dict = dict(input_ids=data_dict["input_ids"][0],
|
698 |
+
labels=data_dict["labels"][0])
|
699 |
+
|
700 |
+
# image exist in the data
|
701 |
+
if 'image' in self.list_data_dict[i]:
|
702 |
+
data_dict['image'] = image
|
703 |
+
elif self.data_args.is_multimodal:
|
704 |
+
# image does not exist in the data, but the model is multimodal
|
705 |
+
crop_size = self.data_args.image_processor.crop_size
|
706 |
+
data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width'])
|
707 |
+
return data_dict
|
708 |
+
|
709 |
+
|
710 |
+
@dataclass
|
711 |
+
class DataCollatorForSupervisedDataset(object):
|
712 |
+
"""Collate examples for supervised fine-tuning."""
|
713 |
+
|
714 |
+
tokenizer: transformers.PreTrainedTokenizer
|
715 |
+
|
716 |
+
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
|
717 |
+
input_ids, labels = tuple([instance[key] for instance in instances]
|
718 |
+
for key in ("input_ids", "labels"))
|
719 |
+
input_ids = torch.nn.utils.rnn.pad_sequence(
|
720 |
+
input_ids,
|
721 |
+
batch_first=True,
|
722 |
+
padding_value=self.tokenizer.pad_token_id)
|
723 |
+
labels = torch.nn.utils.rnn.pad_sequence(labels,
|
724 |
+
batch_first=True,
|
725 |
+
padding_value=IGNORE_INDEX)
|
726 |
+
input_ids = input_ids[:, :self.tokenizer.model_max_length]
|
727 |
+
labels = labels[:, :self.tokenizer.model_max_length]
|
728 |
+
batch = dict(
|
729 |
+
input_ids=input_ids,
|
730 |
+
labels=labels,
|
731 |
+
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
|
732 |
+
)
|
733 |
+
|
734 |
+
if 'image' in instances[0]:
|
735 |
+
images = [instance['image'] for instance in instances]
|
736 |
+
if all(x is not None and x.shape == images[0].shape for x in images):
|
737 |
+
batch['images'] = torch.stack(images)
|
738 |
+
else:
|
739 |
+
batch['images'] = images
|
740 |
+
|
741 |
+
return batch
|
742 |
+
|
743 |
+
|
744 |
+
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer,
|
745 |
+
data_args) -> Dict:
|
746 |
+
"""Make dataset and collator for supervised fine-tuning."""
|
747 |
+
train_dataset = LazySupervisedDataset(tokenizer=tokenizer,
|
748 |
+
data_path=data_args.data_path,
|
749 |
+
data_args=data_args)
|
750 |
+
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
|
751 |
+
return dict(train_dataset=train_dataset,
|
752 |
+
eval_dataset=None,
|
753 |
+
data_collator=data_collator)
|
754 |
+
|
755 |
+
|
756 |
+
def train():
|
757 |
+
global local_rank
|
758 |
+
|
759 |
+
parser = transformers.HfArgumentParser(
|
760 |
+
(ModelArguments, DataArguments, TrainingArguments))
|
761 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
762 |
+
local_rank = training_args.local_rank
|
763 |
+
compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
|
764 |
+
|
765 |
+
bnb_model_from_pretrained_args = {}
|
766 |
+
if training_args.bits in [4, 8]:
|
767 |
+
from transformers import BitsAndBytesConfig
|
768 |
+
bnb_model_from_pretrained_args.update(dict(
|
769 |
+
device_map={"": training_args.device},
|
770 |
+
load_in_4bit=training_args.bits == 4,
|
771 |
+
load_in_8bit=training_args.bits == 8,
|
772 |
+
quantization_config=BitsAndBytesConfig(
|
773 |
+
load_in_4bit=training_args.bits == 4,
|
774 |
+
load_in_8bit=training_args.bits == 8,
|
775 |
+
llm_int8_threshold=6.0,
|
776 |
+
llm_int8_has_fp16_weight=False,
|
777 |
+
bnb_4bit_compute_dtype=compute_dtype,
|
778 |
+
bnb_4bit_use_double_quant=training_args.double_quant,
|
779 |
+
bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'}
|
780 |
+
)
|
781 |
+
))
|
782 |
+
|
783 |
+
if model_args.vision_tower is not None:
|
784 |
+
if 'mpt' in model_args.model_name_or_path:
|
785 |
+
config = transformers.AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True)
|
786 |
+
config.attn_config['attn_impl'] = training_args.mpt_attn_impl
|
787 |
+
model = LlavaMPTForCausalLM.from_pretrained(
|
788 |
+
model_args.model_name_or_path,
|
789 |
+
config=config,
|
790 |
+
cache_dir=training_args.cache_dir,
|
791 |
+
**bnb_model_from_pretrained_args
|
792 |
+
)
|
793 |
+
else:
|
794 |
+
model = LlavaLlamaForCausalLM.from_pretrained(
|
795 |
+
model_args.model_name_or_path,
|
796 |
+
cache_dir=training_args.cache_dir,
|
797 |
+
**bnb_model_from_pretrained_args
|
798 |
+
)
|
799 |
+
else:
|
800 |
+
model = transformers.LlamaForCausalLM.from_pretrained(
|
801 |
+
model_args.model_name_or_path,
|
802 |
+
cache_dir=training_args.cache_dir,
|
803 |
+
**bnb_model_from_pretrained_args
|
804 |
+
)
|
805 |
+
model.config.use_cache = False
|
806 |
+
|
807 |
+
if model_args.freeze_backbone:
|
808 |
+
model.model.requires_grad_(False)
|
809 |
+
|
810 |
+
if training_args.bits in [4, 8]:
|
811 |
+
from peft import prepare_model_for_kbit_training
|
812 |
+
model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
|
813 |
+
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
|
814 |
+
|
815 |
+
if training_args.gradient_checkpointing:
|
816 |
+
if hasattr(model, "enable_input_require_grads"):
|
817 |
+
model.enable_input_require_grads()
|
818 |
+
else:
|
819 |
+
def make_inputs_require_grad(module, input, output):
|
820 |
+
output.requires_grad_(True)
|
821 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
822 |
+
|
823 |
+
if training_args.lora_enable:
|
824 |
+
from peft import LoraConfig, get_peft_model
|
825 |
+
lora_config = LoraConfig(
|
826 |
+
r=training_args.lora_r,
|
827 |
+
lora_alpha=training_args.lora_alpha,
|
828 |
+
target_modules=find_all_linear_names(model),
|
829 |
+
lora_dropout=training_args.lora_dropout,
|
830 |
+
bias=training_args.lora_bias,
|
831 |
+
task_type="CAUSAL_LM",
|
832 |
+
)
|
833 |
+
if training_args.bits == 16:
|
834 |
+
if training_args.bf16:
|
835 |
+
model.to(torch.bfloat16)
|
836 |
+
if training_args.fp16:
|
837 |
+
model.to(torch.float16)
|
838 |
+
rank0_print("Adding LoRA adapters...")
|
839 |
+
model = get_peft_model(model, lora_config)
|
840 |
+
|
841 |
+
if 'mpt' in model_args.model_name_or_path:
|
842 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
843 |
+
model_args.model_name_or_path,
|
844 |
+
cache_dir=training_args.cache_dir,
|
845 |
+
model_max_length=training_args.model_max_length,
|
846 |
+
padding_side="right"
|
847 |
+
)
|
848 |
+
else:
|
849 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
850 |
+
model_args.model_name_or_path,
|
851 |
+
cache_dir=training_args.cache_dir,
|
852 |
+
model_max_length=training_args.model_max_length,
|
853 |
+
padding_side="right",
|
854 |
+
use_fast=False,
|
855 |
+
)
|
856 |
+
|
857 |
+
if model_args.version == "v0":
|
858 |
+
if tokenizer.pad_token is None:
|
859 |
+
smart_tokenizer_and_embedding_resize(
|
860 |
+
special_tokens_dict=dict(pad_token="[PAD]"),
|
861 |
+
tokenizer=tokenizer,
|
862 |
+
model=model,
|
863 |
+
)
|
864 |
+
elif model_args.version == "v0.5":
|
865 |
+
tokenizer.pad_token = tokenizer.unk_token
|
866 |
+
else:
|
867 |
+
tokenizer.pad_token = tokenizer.unk_token
|
868 |
+
if model_args.version in conversation_lib.conv_templates:
|
869 |
+
conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version]
|
870 |
+
else:
|
871 |
+
conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"]
|
872 |
+
|
873 |
+
if model_args.vision_tower is not None:
|
874 |
+
model.get_model().initialize_vision_modules(
|
875 |
+
model_args=model_args,
|
876 |
+
fsdp=training_args.fsdp
|
877 |
+
)
|
878 |
+
|
879 |
+
vision_tower = model.get_vision_tower()
|
880 |
+
vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
|
881 |
+
|
882 |
+
data_args.image_processor = vision_tower.image_processor
|
883 |
+
data_args.is_multimodal = True
|
884 |
+
|
885 |
+
model.config.image_aspect_ratio = data_args.image_aspect_ratio
|
886 |
+
model.config.image_grid_pinpoints = data_args.image_grid_pinpoints
|
887 |
+
|
888 |
+
model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
|
889 |
+
if model_args.tune_mm_mlp_adapter:
|
890 |
+
model.requires_grad_(False)
|
891 |
+
for p in model.get_model().mm_projector.parameters():
|
892 |
+
p.requires_grad = True
|
893 |
+
|
894 |
+
model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
|
895 |
+
if training_args.freeze_mm_mlp_adapter:
|
896 |
+
for p in model.get_model().mm_projector.parameters():
|
897 |
+
p.requires_grad = False
|
898 |
+
|
899 |
+
if training_args.bits in [4, 8]:
|
900 |
+
model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
|
901 |
+
|
902 |
+
model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end
|
903 |
+
training_args.use_im_start_end = model_args.mm_use_im_start_end
|
904 |
+
model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
|
905 |
+
model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
|
906 |
+
|
907 |
+
if training_args.bits in [4, 8]:
|
908 |
+
from peft.tuners.lora import LoraLayer
|
909 |
+
for name, module in model.named_modules():
|
910 |
+
if isinstance(module, LoraLayer):
|
911 |
+
if training_args.bf16:
|
912 |
+
module = module.to(torch.bfloat16)
|
913 |
+
if 'norm' in name:
|
914 |
+
module = module.to(torch.float32)
|
915 |
+
if 'lm_head' in name or 'embed_tokens' in name:
|
916 |
+
if hasattr(module, 'weight'):
|
917 |
+
if training_args.bf16 and module.weight.dtype == torch.float32:
|
918 |
+
module = module.to(torch.bfloat16)
|
919 |
+
|
920 |
+
data_module = make_supervised_data_module(tokenizer=tokenizer,
|
921 |
+
data_args=data_args)
|
922 |
+
trainer = LLaVATrainer(model=model,
|
923 |
+
tokenizer=tokenizer,
|
924 |
+
args=training_args,
|
925 |
+
**data_module)
|
926 |
+
|
927 |
+
if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
|
928 |
+
trainer.train(resume_from_checkpoint=True)
|
929 |
+
else:
|
930 |
+
trainer.train()
|
931 |
+
trainer.save_state()
|
932 |
+
|
933 |
+
model.config.use_cache = True
|
934 |
+
|
935 |
+
if training_args.lora_enable:
|
936 |
+
state_dict = get_peft_state_maybe_zero_3(
|
937 |
+
model.named_parameters(), training_args.lora_bias
|
938 |
+
)
|
939 |
+
non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(
|
940 |
+
model.named_parameters()
|
941 |
+
)
|
942 |
+
if training_args.local_rank == 0 or training_args.local_rank == -1:
|
943 |
+
model.config.save_pretrained(training_args.output_dir)
|
944 |
+
model.save_pretrained(training_args.output_dir, state_dict=state_dict)
|
945 |
+
torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin'))
|
946 |
+
else:
|
947 |
+
safe_save_model_for_hf_trainer(trainer=trainer,
|
948 |
+
output_dir=training_args.output_dir)
|
949 |
+
|
950 |
+
|
951 |
+
if __name__ == "__main__":
|
952 |
+
train()
|
llava/train/train_mem.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
|
2 |
+
# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
|
3 |
+
# Make it more memory efficient by monkey patching the LLaMA model with FlashAttn.
|
4 |
+
|
5 |
+
# Need to call this before importing transformers.
|
6 |
+
from llava.train.llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn
|
7 |
+
|
8 |
+
replace_llama_attn_with_flash_attn()
|
9 |
+
|
10 |
+
from llava.train.train import train
|
11 |
+
|
12 |
+
if __name__ == "__main__":
|
13 |
+
train()
|