English
naveensp commited on
Commit
cdcd0e2
·
verified ·
1 Parent(s): 98cfb8f

Delete folder train with huggingface_hub

Browse files
train/__pycache__/llava_trainer.cpython-310.pyc DELETED
Binary file (11.4 kB)
 
train/__pycache__/llava_trainer.cpython-312.pyc DELETED
Binary file (16.2 kB)
 
train/__pycache__/train.cpython-310.pyc DELETED
Binary file (27.3 kB)
 
train/__pycache__/train.cpython-312.pyc DELETED
Binary file (50 kB)
 
train/debug_run.py DELETED
@@ -1,4 +0,0 @@
1
- from llava.train.train_mem import train_mem
2
-
3
-
4
-
 
 
 
 
 
train/llama_flash_attn_monkey_patch.py DELETED
@@ -1,115 +0,0 @@
1
- from typing import Optional, Tuple
2
- import warnings
3
-
4
- import torch
5
-
6
- import transformers
7
- from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv
8
-
9
- try:
10
- from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func
11
- except ImportError:
12
- from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
13
- from flash_attn.bert_padding import unpad_input, pad_input
14
-
15
-
16
- def forward(
17
- self,
18
- hidden_states: torch.Tensor,
19
- attention_mask: Optional[torch.Tensor] = None,
20
- position_ids: Optional[torch.Tensor] = None,
21
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
22
- output_attentions: bool = False,
23
- use_cache: bool = False,
24
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
25
- if output_attentions:
26
- warnings.warn(
27
- "Output attentions is not supported for patched `LlamaAttention`, returning `None` instead."
28
- )
29
-
30
- bsz, q_len, _ = hidden_states.size()
31
-
32
- query_states = (
33
- self.q_proj(hidden_states)
34
- .view(bsz, q_len, self.num_heads, self.head_dim)
35
- .transpose(1, 2)
36
- )
37
- key_states = (
38
- self.k_proj(hidden_states)
39
- .view(bsz, q_len, self.num_key_value_heads, self.head_dim)
40
- .transpose(1, 2)
41
- )
42
- value_states = (
43
- self.v_proj(hidden_states)
44
- .view(bsz, q_len, self.num_key_value_heads, self.head_dim)
45
- .transpose(1, 2)
46
- ) # shape: (b, num_heads, s, head_dim)
47
-
48
- kv_seq_len = key_states.shape[-2]
49
- if past_key_value is not None:
50
- kv_seq_len += past_key_value[0].shape[-2]
51
-
52
- cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
53
- query_states, key_states = apply_rotary_pos_emb(
54
- query_states, key_states, cos, sin, position_ids
55
- )
56
-
57
- if past_key_value is not None:
58
- # reuse k, v
59
- key_states = torch.cat([past_key_value[0], key_states], dim=2)
60
- value_states = torch.cat([past_key_value[1], value_states], dim=2)
61
-
62
- past_key_value = (key_states, value_states) if use_cache else None
63
-
64
- # repeat k/v heads if n_kv_heads < n_heads
65
- key_states = repeat_kv(key_states, self.num_key_value_groups)
66
- value_states = repeat_kv(value_states, self.num_key_value_groups)
67
-
68
- # Transform the data into the format required by flash attention
69
- qkv = torch.stack([query_states, key_states, value_states], dim=2)
70
- qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim]
71
- key_padding_mask = attention_mask
72
-
73
- if key_padding_mask is None:
74
- qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim)
75
- cu_q_lens = torch.arange(
76
- 0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device
77
- )
78
- max_s = q_len
79
- output = flash_attn_unpadded_qkvpacked_func(
80
- qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
81
- )
82
- output = output.view(bsz, q_len, -1)
83
- else:
84
- qkv = qkv.reshape(bsz, q_len, -1)
85
- qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask)
86
- qkv = qkv.view(-1, 3, self.num_heads, self.head_dim)
87
- output_unpad = flash_attn_unpadded_qkvpacked_func(
88
- qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
89
- )
90
- output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim)
91
- output = pad_input(output_unpad, indices, bsz, q_len)
92
-
93
- return self.o_proj(output), None, past_key_value
94
-
95
-
96
- # Disable the transformation of the attention mask in LlamaModel as the flash attention
97
- # requires the attention mask to be the same as the key_padding_mask
98
- def _prepare_decoder_attention_mask(
99
- self, attention_mask, input_shape, inputs_embeds, past_key_values_length
100
- ):
101
- # [bsz, seq_len]
102
- return attention_mask
103
-
104
-
105
- def replace_llama_attn_with_flash_attn():
106
- cuda_major, cuda_minor = torch.cuda.get_device_capability()
107
- if cuda_major < 8:
108
- warnings.warn(
109
- "Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward."
110
- "ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593"
111
- )
112
- transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = (
113
- _prepare_decoder_attention_mask
114
- )
115
- transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
train/llama_xformers_attn_monkey_patch.py DELETED
@@ -1,129 +0,0 @@
1
- """
2
- Directly copied the code from https://raw.githubusercontent.com/oobabooga/text-generation-webui/main/modules/llama_attn_hijack.py and made some adjustments
3
- """
4
-
5
- import logging
6
- import math
7
- from typing import Optional, Tuple
8
-
9
- import torch
10
- import transformers.models.llama.modeling_llama
11
- from torch import nn
12
-
13
- try:
14
- import xformers.ops
15
- except ImportError:
16
- logging.error("xformers not found! Please install it before trying to use it.")
17
-
18
-
19
- def replace_llama_attn_with_xformers_attn():
20
- transformers.models.llama.modeling_llama.LlamaAttention.forward = xformers_forward
21
-
22
-
23
- def xformers_forward(
24
- self,
25
- hidden_states: torch.Tensor,
26
- attention_mask: Optional[torch.Tensor] = None,
27
- position_ids: Optional[torch.LongTensor] = None,
28
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
29
- output_attentions: bool = False,
30
- use_cache: bool = False,
31
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
32
- # pylint: disable=duplicate-code
33
- bsz, q_len, _ = hidden_states.size()
34
-
35
- query_states = (
36
- self.q_proj(hidden_states)
37
- .view(bsz, q_len, self.num_heads, self.head_dim)
38
- .transpose(1, 2)
39
- )
40
- key_states = (
41
- self.k_proj(hidden_states)
42
- .view(bsz, q_len, self.num_heads, self.head_dim)
43
- .transpose(1, 2)
44
- )
45
- value_states = (
46
- self.v_proj(hidden_states)
47
- .view(bsz, q_len, self.num_heads, self.head_dim)
48
- .transpose(1, 2)
49
- )
50
-
51
- kv_seq_len = key_states.shape[-2]
52
- if past_key_value is not None:
53
- kv_seq_len += past_key_value[0].shape[-2]
54
- cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
55
- (
56
- query_states,
57
- key_states,
58
- ) = transformers.models.llama.modeling_llama.apply_rotary_pos_emb(
59
- query_states, key_states, cos, sin, position_ids
60
- )
61
- # [bsz, nh, t, hd]
62
-
63
- if past_key_value is not None:
64
- # reuse k, v, self_attention
65
- key_states = torch.cat([past_key_value[0], key_states], dim=2)
66
- value_states = torch.cat([past_key_value[1], value_states], dim=2)
67
-
68
- past_key_value = (key_states, value_states) if use_cache else None
69
-
70
- # We only apply xformers optimizations if we don't need to output the whole attention matrix
71
- if not output_attentions:
72
- query_states = query_states.transpose(1, 2)
73
- key_states = key_states.transpose(1, 2)
74
- value_states = value_states.transpose(1, 2)
75
-
76
- # This is a nasty hack. We know attention_mask in transformers is either LowerTriangular or all Zeros.
77
- # We therefore check if one element in the upper triangular portion is zero. If it is, then the mask is all zeros.
78
- if attention_mask is None or attention_mask[0, 0, 0, 1] == 0:
79
- # input and output should be of form (bsz, q_len, num_heads, head_dim)
80
- attn_output = xformers.ops.memory_efficient_attention(
81
- query_states, key_states, value_states, attn_bias=None
82
- )
83
- else:
84
- # input and output should be of form (bsz, q_len, num_heads, head_dim)
85
- attn_output = xformers.ops.memory_efficient_attention(
86
- query_states,
87
- key_states,
88
- value_states,
89
- attn_bias=xformers.ops.LowerTriangularMask(),
90
- )
91
- attn_weights = None
92
- else:
93
- attn_weights = torch.matmul(
94
- query_states, key_states.transpose(2, 3)
95
- ) / math.sqrt(self.head_dim)
96
-
97
- if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
98
- raise ValueError(
99
- f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
100
- f" {attn_weights.size()}"
101
- )
102
-
103
- if attention_mask is not None:
104
- if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
105
- raise ValueError(
106
- f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
107
- )
108
- attn_weights = attn_weights + attention_mask
109
- attn_weights = torch.max(
110
- attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)
111
- )
112
-
113
- # upcast attention to fp32
114
- attn_weights = nn.functional.softmax(
115
- attn_weights, dim=-1, dtype=torch.float32
116
- ).to(query_states.dtype)
117
- attn_output = torch.matmul(attn_weights, value_states)
118
-
119
- if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
120
- raise ValueError(
121
- f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
122
- f" {attn_output.size()}"
123
- )
124
-
125
- attn_output = attn_output.transpose(1, 2)
126
-
127
- attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
128
- attn_output = self.o_proj(attn_output)
129
- return attn_output, attn_weights, past_key_value
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
train/llava_trainer.py DELETED
@@ -1,257 +0,0 @@
1
- import os
2
- import torch
3
- import torch.nn as nn
4
-
5
- from torch.utils.data import Sampler
6
-
7
- from transformers import Trainer
8
- from transformers.trainer import (
9
- is_sagemaker_mp_enabled,
10
- get_parameter_names,
11
- has_length,
12
- ALL_LAYERNORM_LAYERS,
13
- logger,
14
- )
15
- from typing import List, Optional
16
- from PIL import ImageFile
17
- ImageFile.LOAD_TRUNCATED_IMAGES = True
18
-
19
-
20
- def maybe_zero_3(param, ignore_status=False, name=None):
21
- from deepspeed import zero
22
- from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
23
- if hasattr(param, "ds_id"):
24
- if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
25
- if not ignore_status:
26
- print(name, 'no ignore status')
27
- with zero.GatheredParameters([param]):
28
- param = param.data.detach().cpu().clone()
29
- else:
30
- param = param.detach().cpu().clone()
31
- return param
32
-
33
-
34
- def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
35
- to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
36
- to_return = {k: maybe_zero_3(v, ignore_status=True, name=k).cpu() for k, v in to_return.items()}
37
- return to_return
38
-
39
-
40
- def split_to_even_chunks(indices, lengths, num_chunks):
41
- """
42
- Split a list of indices into `chunks` chunks of roughly equal lengths.
43
- """
44
-
45
- if len(indices) % num_chunks != 0:
46
- return [indices[i::num_chunks] for i in range(num_chunks)]
47
-
48
- num_indices_per_chunk = len(indices) // num_chunks
49
-
50
- chunks = [[] for _ in range(num_chunks)]
51
- chunks_lengths = [0 for _ in range(num_chunks)]
52
- for index in indices:
53
- shortest_chunk = chunks_lengths.index(min(chunks_lengths))
54
- chunks[shortest_chunk].append(index)
55
- chunks_lengths[shortest_chunk] += lengths[index]
56
- if len(chunks[shortest_chunk]) == num_indices_per_chunk:
57
- chunks_lengths[shortest_chunk] = float("inf")
58
-
59
- return chunks
60
-
61
-
62
- def get_modality_length_grouped_indices(lengths, batch_size, world_size, generator=None):
63
- # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
64
- assert all(l != 0 for l in lengths), "Should not have zero length."
65
- if all(l > 0 for l in lengths) or all(l < 0 for l in lengths):
66
- # all samples are in the same modality
67
- return get_length_grouped_indices(lengths, batch_size, world_size, generator=generator)
68
- mm_indices, mm_lengths = zip(*[(i, l) for i, l in enumerate(lengths) if l > 0])
69
- lang_indices, lang_lengths = zip(*[(i, -l) for i, l in enumerate(lengths) if l < 0])
70
-
71
- mm_shuffle = [mm_indices[i] for i in get_length_grouped_indices(mm_lengths, batch_size, world_size, generator=None)]
72
- lang_shuffle = [lang_indices[i] for i in get_length_grouped_indices(lang_lengths, batch_size, world_size, generator=None)]
73
- megabatch_size = world_size * batch_size
74
- mm_megabatches = [mm_shuffle[i : i + megabatch_size] for i in range(0, len(mm_shuffle), megabatch_size)]
75
- lang_megabatches = [lang_shuffle[i : i + megabatch_size] for i in range(0, len(lang_shuffle), megabatch_size)]
76
-
77
- last_mm = mm_megabatches[-1]
78
- last_lang = lang_megabatches[-1]
79
- additional_batch = last_mm + last_lang
80
- megabatches = mm_megabatches[:-1] + lang_megabatches[:-1]
81
- megabatch_indices = torch.randperm(len(megabatches), generator=generator)
82
- megabatches = [megabatches[i] for i in megabatch_indices]
83
-
84
- if len(additional_batch) > 0:
85
- megabatches.append(sorted(additional_batch))
86
-
87
- return [i for megabatch in megabatches for i in megabatch]
88
-
89
-
90
- def get_length_grouped_indices(lengths, batch_size, world_size, generator=None, merge=True):
91
- # We need to use torch for the random part as a distributed sampler will set the random seed for torch.
92
- indices = torch.randperm(len(lengths), generator=generator)
93
- megabatch_size = world_size * batch_size
94
- megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)]
95
- megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches]
96
- megabatches = [split_to_even_chunks(megabatch, lengths, world_size) for megabatch in megabatches]
97
-
98
- return [i for megabatch in megabatches for batch in megabatch for i in batch]
99
-
100
-
101
- class LengthGroupedSampler(Sampler):
102
- r"""
103
- Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
104
- keeping a bit of randomness.
105
- """
106
-
107
- def __init__(
108
- self,
109
- batch_size: int,
110
- world_size: int,
111
- lengths: Optional[List[int]] = None,
112
- generator=None,
113
- group_by_modality: bool = False,
114
- ):
115
- if lengths is None:
116
- raise ValueError("Lengths must be provided.")
117
-
118
- self.batch_size = batch_size
119
- self.world_size = world_size
120
- self.lengths = lengths
121
- self.generator = generator
122
- self.group_by_modality = group_by_modality
123
-
124
- def __len__(self):
125
- return len(self.lengths)
126
-
127
- def __iter__(self):
128
- if self.group_by_modality:
129
- indices = get_modality_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
130
- else:
131
- indices = get_length_grouped_indices(self.lengths, self.batch_size, self.world_size, generator=self.generator)
132
- return iter(indices)
133
-
134
-
135
- class LLaVATrainer(Trainer):
136
-
137
- def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:
138
- if self.train_dataset is None or not has_length(self.train_dataset):
139
- return None
140
-
141
- if self.args.group_by_modality_length:
142
- lengths = self.train_dataset.modality_lengths
143
- return LengthGroupedSampler(
144
- self.args.train_batch_size,
145
- world_size=self.args.world_size * self.args.gradient_accumulation_steps,
146
- lengths=lengths,
147
- group_by_modality=True,
148
- )
149
- else:
150
- return super()._get_train_sampler()
151
-
152
- def create_optimizer(self):
153
- """
154
- Setup the optimizer.
155
-
156
- We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
157
- Trainer's init through `optimizers`, or subclass and override this method in a subclass.
158
- """
159
- if is_sagemaker_mp_enabled():
160
- return super().create_optimizer()
161
-
162
- opt_model = self.model
163
-
164
- if self.optimizer is None:
165
- decay_parameters = get_parameter_names(opt_model, ALL_LAYERNORM_LAYERS)
166
- decay_parameters = [name for name in decay_parameters if "bias" not in name]
167
- if self.args.mm_projector_lr is not None:
168
- projector_parameters = [name for name, _ in opt_model.named_parameters() if "mm_projector" in name]
169
- optimizer_grouped_parameters = [
170
- {
171
- "params": [
172
- p for n, p in opt_model.named_parameters() if (n in decay_parameters and n not in projector_parameters and p.requires_grad)
173
- ],
174
- "weight_decay": self.args.weight_decay,
175
- },
176
- {
177
- "params": [
178
- p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n not in projector_parameters and p.requires_grad)
179
- ],
180
- "weight_decay": 0.0,
181
- },
182
- {
183
- "params": [
184
- p for n, p in opt_model.named_parameters() if (n in decay_parameters and n in projector_parameters and p.requires_grad)
185
- ],
186
- "weight_decay": self.args.weight_decay,
187
- "lr": self.args.mm_projector_lr,
188
- },
189
- {
190
- "params": [
191
- p for n, p in opt_model.named_parameters() if (n not in decay_parameters and n in projector_parameters and p.requires_grad)
192
- ],
193
- "weight_decay": 0.0,
194
- "lr": self.args.mm_projector_lr,
195
- },
196
- ]
197
- else:
198
- optimizer_grouped_parameters = [
199
- {
200
- "params": [
201
- p for n, p in opt_model.named_parameters() if (n in decay_parameters and p.requires_grad)
202
- ],
203
- "weight_decay": self.args.weight_decay,
204
- },
205
- {
206
- "params": [
207
- p for n, p in opt_model.named_parameters() if (n not in decay_parameters and p.requires_grad)
208
- ],
209
- "weight_decay": 0.0,
210
- },
211
- ]
212
-
213
- optimizer_cls, optimizer_kwargs = Trainer.get_optimizer_cls_and_kwargs(self.args)
214
-
215
- self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
216
- if optimizer_cls.__name__ == "Adam8bit":
217
- import bitsandbytes
218
-
219
- manager = bitsandbytes.optim.GlobalOptimManager.get_instance()
220
-
221
- skipped = 0
222
- for module in opt_model.modules():
223
- if isinstance(module, nn.Embedding):
224
- skipped += sum({p.data_ptr(): p.numel() for p in module.parameters()}.values())
225
- logger.info(f"skipped {module}: {skipped/2**20}M params")
226
- manager.register_module_override(module, "weight", {"optim_bits": 32})
227
- logger.debug(f"bitsandbytes: will optimize {module} in fp32")
228
- logger.info(f"skipped: {skipped/2**20}M params")
229
-
230
- return self.optimizer
231
-
232
- def _save_checkpoint(self, model, trial, metrics=None):
233
- if getattr(self.args, 'tune_mm_mlp_adapter', False):
234
- from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
235
- checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
236
-
237
- run_dir = self._get_output_dir(trial=trial)
238
- output_dir = os.path.join(run_dir, checkpoint_folder)
239
-
240
- # Only save Adapter
241
- keys_to_match = ['mm_projector', 'vision_resampler']
242
- if getattr(self.args, "use_im_start_end", False):
243
- keys_to_match.extend(['embed_tokens', 'embed_in'])
244
-
245
- weight_to_save = get_mm_adapter_state_maybe_zero_3(self.model.named_parameters(), keys_to_match)
246
-
247
- if self.args.local_rank == 0 or self.args.local_rank == -1:
248
- self.model.config.save_pretrained(output_dir)
249
- torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
250
- else:
251
- super(LLaVATrainer, self)._save_checkpoint(model, trial, metrics)
252
-
253
- def _save(self, output_dir: Optional[str] = None, state_dict=None):
254
- if getattr(self.args, 'tune_mm_mlp_adapter', False):
255
- pass
256
- else:
257
- super(LLaVATrainer, self)._save(output_dir, state_dict)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
train/train.py DELETED
@@ -1,1031 +0,0 @@
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
- import warnings
25
-
26
- import torch
27
-
28
- import transformers
29
- import tokenizers
30
-
31
- from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
32
- from torch.utils.data import Dataset
33
- from llava.train.llava_trainer import LLaVATrainer
34
-
35
- from llava import conversation as conversation_lib
36
- from llava.model import *
37
- from llava.mm_utils import tokenizer_image_token
38
- from PIL import Image
39
- from llava.model.language_model.llava_olmo1p58b import *
40
-
41
- local_rank = None
42
-
43
-
44
- def rank0_print(*args):
45
- if local_rank == 0:
46
- print(*args)
47
-
48
-
49
- from packaging import version
50
- IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse('0.14')
51
-
52
-
53
- @dataclass
54
- class ModelArguments:
55
- model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
56
- version: Optional[str] = field(default="v0")
57
- freeze_backbone: bool = field(default=False)
58
- tune_mm_mlp_adapter: bool = field(default=False)
59
- vision_tower: Optional[str] = field(default=None)
60
- mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer
61
- pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
62
- mm_projector_type: Optional[str] = field(default='linear')
63
- mm_use_im_start_end: bool = field(default=False)
64
- mm_use_im_patch_token: bool = field(default=True)
65
- mm_patch_merge_type: Optional[str] = field(default='flat')
66
- mm_vision_select_feature: Optional[str] = field(default="patch")
67
-
68
-
69
- @dataclass
70
- class DataArguments:
71
- data_path: str = field(default=None,
72
- metadata={"help": "Path to the training data."})
73
- lazy_preprocess: bool = False
74
- is_multimodal: bool = False
75
- image_folder: Optional[str] = field(default=None)
76
- image_aspect_ratio: str = 'square'
77
-
78
-
79
- @dataclass
80
- class TrainingArguments(transformers.TrainingArguments):
81
- cache_dir: Optional[str] = field(default=None)
82
- optim: str = field(default="adamw_torch")
83
- remove_unused_columns: bool = field(default=False)
84
- freeze_mm_mlp_adapter: bool = field(default=False)
85
- mpt_attn_impl: Optional[str] = field(default="triton")
86
- model_max_length: int = field(
87
- default=512,
88
- metadata={
89
- "help":
90
- "Maximum sequence length. Sequences will be right padded (and possibly truncated)."
91
- },
92
- )
93
- double_quant: bool = field(
94
- default=True,
95
- metadata={"help": "Compress the quantization statistics through double quantization."}
96
- )
97
- quant_type: str = field(
98
- default="nf4",
99
- metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}
100
- )
101
- bits: int = field(
102
- default=16,
103
- metadata={"help": "How many bits to use."}
104
- )
105
- lora_enable: bool = False
106
- lora_r: int = 64
107
- lora_alpha: int = 16
108
- lora_dropout: float = 0.05
109
- lora_weight_path: str = ""
110
- lora_bias: str = "none"
111
- mm_projector_lr: Optional[float] = None
112
- group_by_modality_length: bool = field(default=False)
113
-
114
-
115
- def maybe_zero_3(param, ignore_status=False, name=None):
116
- from deepspeed import zero
117
- from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
118
- if hasattr(param, "ds_id"):
119
- if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
120
- if not ignore_status:
121
- logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
122
- with zero.GatheredParameters([param]):
123
- param = param.data.detach().cpu().clone()
124
- else:
125
- param = param.detach().cpu().clone()
126
- return param
127
-
128
-
129
- # Borrowed from peft.utils.get_peft_model_state_dict
130
- def get_peft_state_maybe_zero_3(named_params, bias):
131
- if bias == "none":
132
- to_return = {k: t for k, t in named_params if "lora_" in k}
133
- elif bias == "all":
134
- to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
135
- elif bias == "lora_only":
136
- to_return = {}
137
- maybe_lora_bias = {}
138
- lora_bias_names = set()
139
- for k, t in named_params:
140
- if "lora_" in k:
141
- to_return[k] = t
142
- bias_name = k.split("lora_")[0] + "bias"
143
- lora_bias_names.add(bias_name)
144
- elif "bias" in k:
145
- maybe_lora_bias[k] = t
146
- for k, t in maybe_lora_bias:
147
- if bias_name in lora_bias_names:
148
- to_return[bias_name] = t
149
- else:
150
- raise NotImplementedError
151
- to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
152
- return to_return
153
-
154
-
155
- def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
156
- to_return = {k: t for k, t in named_params if "lora_" not in k}
157
- if require_grad_only:
158
- to_return = {k: t for k, t in to_return.items() if t.requires_grad}
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 get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
164
- to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)}
165
- to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
166
- return to_return
167
-
168
-
169
- def find_all_linear_names(model):
170
- cls = torch.nn.Linear
171
- lora_module_names = set()
172
- multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler']
173
- for name, module in model.named_modules():
174
- if any(mm_keyword in name for mm_keyword in multimodal_keywords):
175
- continue
176
- if isinstance(module, cls):
177
- names = name.split('.')
178
- lora_module_names.add(names[0] if len(names) == 1 else names[-1])
179
-
180
- if 'lm_head' in lora_module_names: # needed for 16-bit
181
- lora_module_names.remove('lm_head')
182
- return list(lora_module_names)
183
-
184
-
185
- def safe_save_model_for_hf_trainer(trainer: transformers.Trainer,
186
- output_dir: str):
187
- """Collects the state dict and dump to disk."""
188
-
189
- if getattr(trainer.args, "tune_mm_mlp_adapter", False):
190
- # Only save Adapter
191
- keys_to_match = ['mm_projector']
192
- if getattr(trainer.args, "use_im_start_end", False):
193
- keys_to_match.extend(['embed_tokens', 'embed_in'])
194
-
195
- weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match)
196
- trainer.model.config.save_pretrained(output_dir)
197
-
198
- current_folder = output_dir.split('/')[-1]
199
- parent_folder = os.path.dirname(output_dir)
200
- if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
201
- if current_folder.startswith('checkpoint-'):
202
- mm_projector_folder = os.path.join(parent_folder, "mm_projector")
203
- os.makedirs(mm_projector_folder, exist_ok=True)
204
- torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin'))
205
- else:
206
- torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin'))
207
- return
208
-
209
- if trainer.deepspeed:
210
- torch.cuda.synchronize()
211
- trainer.save_model(output_dir)
212
- return
213
-
214
- state_dict = trainer.model.state_dict()
215
- if trainer.args.should_save:
216
- cpu_state_dict = {
217
- key: value.cpu()
218
- for key, value in state_dict.items()
219
- }
220
- del state_dict
221
- trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
222
-
223
-
224
- def smart_tokenizer_and_embedding_resize(
225
- special_tokens_dict: Dict,
226
- tokenizer: transformers.PreTrainedTokenizer,
227
- model: transformers.PreTrainedModel,
228
- ):
229
- """Resize tokenizer and embedding.
230
-
231
- Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
232
- """
233
- num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
234
- model.resize_token_embeddings(len(tokenizer))
235
-
236
- if num_new_tokens > 0:
237
- input_embeddings = model.get_input_embeddings().weight.data
238
- output_embeddings = model.get_output_embeddings().weight.data
239
-
240
- input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
241
- dim=0, keepdim=True)
242
- output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
243
- dim=0, keepdim=True)
244
-
245
- input_embeddings[-num_new_tokens:] = input_embeddings_avg
246
- output_embeddings[-num_new_tokens:] = output_embeddings_avg
247
-
248
-
249
- def _tokenize_fn(strings: Sequence[str],
250
- tokenizer: transformers.PreTrainedTokenizer) -> Dict:
251
- """Tokenize a list of strings."""
252
- tokenized_list = [
253
- tokenizer(
254
- text,
255
- return_tensors="pt",
256
- padding="longest",
257
- max_length=tokenizer.model_max_length,
258
- truncation=True,
259
- ) for text in strings
260
- ]
261
- input_ids = labels = [
262
- tokenized.input_ids[0] for tokenized in tokenized_list
263
- ]
264
- input_ids_lens = labels_lens = [
265
- tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item()
266
- for tokenized in tokenized_list
267
- ]
268
- return dict(
269
- input_ids=input_ids,
270
- labels=labels,
271
- input_ids_lens=input_ids_lens,
272
- labels_lens=labels_lens,
273
- )
274
-
275
-
276
- def _mask_targets(target, tokenized_lens, speakers):
277
- # cur_idx = 0
278
- cur_idx = tokenized_lens[0]
279
- tokenized_lens = tokenized_lens[1:]
280
- target[:cur_idx] = IGNORE_INDEX
281
- for tokenized_len, speaker in zip(tokenized_lens, speakers):
282
- if speaker == "human":
283
- target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX
284
- cur_idx += tokenized_len
285
-
286
-
287
- def _add_speaker_and_signal(header, source, get_conversation=True):
288
- """Add speaker and start/end signal on each round."""
289
- BEGIN_SIGNAL = "### "
290
- END_SIGNAL = "\n"
291
- conversation = header
292
- for sentence in source:
293
- from_str = sentence["from"]
294
- if from_str.lower() == "human":
295
- from_str = conversation_lib.default_conversation.roles[0]
296
- elif from_str.lower() == "gpt":
297
- from_str = conversation_lib.default_conversation.roles[1]
298
- else:
299
- from_str = 'unknown'
300
- sentence["value"] = (BEGIN_SIGNAL + from_str + ": " +
301
- sentence["value"] + END_SIGNAL)
302
- if get_conversation:
303
- conversation += sentence["value"]
304
- conversation += BEGIN_SIGNAL
305
- return conversation
306
-
307
-
308
- def preprocess_multimodal(
309
- sources: Sequence[str],
310
- data_args: DataArguments
311
- ) -> Dict:
312
- is_multimodal = data_args.is_multimodal
313
- if not is_multimodal:
314
- return sources
315
-
316
- for source in sources:
317
- for sentence in source:
318
- if DEFAULT_IMAGE_TOKEN in sentence['value']:
319
- sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip()
320
- sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value']
321
- sentence['value'] = sentence['value'].strip()
322
- if "mmtag" in conversation_lib.default_conversation.version:
323
- sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '<Image>' + DEFAULT_IMAGE_TOKEN + '</Image>')
324
- replace_token = DEFAULT_IMAGE_TOKEN
325
- if data_args.mm_use_im_start_end:
326
- replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
327
- sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token)
328
-
329
- return sources
330
-
331
-
332
- def preprocess_llama_2(
333
- sources,
334
- tokenizer: transformers.PreTrainedTokenizer,
335
- has_image: bool = False
336
- ) -> Dict:
337
- conv = conversation_lib.default_conversation.copy()
338
- roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
339
-
340
- # Apply prompt templates
341
- conversations = []
342
- for i, source in enumerate(sources):
343
- if roles[source[0]["from"]] != conv.roles[0]:
344
- # Skip the first one if it is not from human
345
- source = source[1:]
346
-
347
- conv.messages = []
348
- for j, sentence in enumerate(source):
349
- role = roles[sentence["from"]]
350
- assert role == conv.roles[j % 2], f"{i}"
351
- conv.append_message(role, sentence["value"])
352
- conversations.append(conv.get_prompt())
353
-
354
- # Tokenize conversations
355
-
356
- if has_image:
357
- input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
358
- else:
359
- input_ids = tokenizer(
360
- conversations,
361
- return_tensors="pt",
362
- padding="longest",
363
- max_length=tokenizer.model_max_length,
364
- truncation=True,
365
- ).input_ids
366
-
367
- targets = input_ids.clone()
368
-
369
- assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
370
-
371
- # Mask targets
372
- sep = "[/INST] "
373
- for conversation, target in zip(conversations, targets):
374
- total_len = int(target.ne(tokenizer.pad_token_id).sum())
375
-
376
- rounds = conversation.split(conv.sep2)
377
- cur_len = 1
378
- target[:cur_len] = IGNORE_INDEX
379
- for i, rou in enumerate(rounds):
380
- if rou == "":
381
- break
382
-
383
- parts = rou.split(sep)
384
- if len(parts) != 2:
385
- break
386
- parts[0] += sep
387
-
388
- if has_image:
389
- round_len = len(tokenizer_image_token(rou, tokenizer))
390
- instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
391
- else:
392
- round_len = len(tokenizer(rou).input_ids)
393
- instruction_len = len(tokenizer(parts[0]).input_ids) - 2
394
-
395
- target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
396
-
397
- cur_len += round_len
398
- target[cur_len:] = IGNORE_INDEX
399
-
400
- if cur_len < tokenizer.model_max_length:
401
- if cur_len != total_len:
402
- target[:] = IGNORE_INDEX
403
- print(
404
- f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
405
- f" (ignored)"
406
- )
407
-
408
- return dict(
409
- input_ids=input_ids,
410
- labels=targets,
411
- )
412
-
413
-
414
- def preprocess_v1(
415
- sources,
416
- tokenizer: transformers.PreTrainedTokenizer,
417
- has_image: bool = False
418
- ) -> Dict:
419
- conv = conversation_lib.default_conversation.copy()
420
- roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
421
-
422
- # Apply prompt templates
423
- conversations = []
424
- for i, source in enumerate(sources):
425
- if roles[source[0]["from"]] != conv.roles[0]:
426
- # Skip the first one if it is not from human
427
- source = source[1:]
428
-
429
- conv.messages = []
430
- for j, sentence in enumerate(source):
431
- role = roles[sentence["from"]]
432
- assert role == conv.roles[j % 2], f"{i}"
433
- conv.append_message(role, sentence["value"])
434
- conversations.append(conv.get_prompt())
435
-
436
- # Tokenize conversations
437
-
438
- if has_image:
439
- # split the prompt along <image> token, insert -200 (IMAGE_TOKEN_ID) at <image> concat everything else and send back
440
- input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
441
- # input_ids should have N conversatios, each with len tokenizer(conv_len)-1 where -1 is for removing the <image> text and adding in a -200 token directly
442
- else:
443
- input_ids = tokenizer(
444
- conversations,
445
- return_tensors="pt",
446
- padding="longest",
447
- max_length=tokenizer.model_max_length,
448
- truncation=True,
449
- ).input_ids
450
-
451
- targets = input_ids.clone()
452
-
453
- assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
454
-
455
- # Mask targets
456
- sep = conv.sep + conv.roles[1] + ": "
457
- for conversation, target in zip(conversations, targets):
458
- total_len = int(target.ne(tokenizer.pad_token_id).sum())
459
-
460
- rounds = conversation.split(conv.sep2)
461
- cur_len = 0 # cur_len = 1 -> fix from https://github.com/haotian-liu/LLaVA/issues/661
462
- target[:cur_len] = IGNORE_INDEX
463
- for i, rou in enumerate(rounds):
464
- if rou == "":
465
- break
466
-
467
- parts = rou.split(sep)
468
- if len(parts) != 2:
469
- break
470
- parts[0] += sep
471
-
472
- # the total_len accounts for tokenization of round seperator </s>. But when it gets tokenized, the num of new tokens inserted differs based on if the last char is a full stop.
473
- # partly described in (https://github.com/haotian-liu/LLaVA/issues/661)
474
- if (rou[-1]=='.'): round_seperator_token_compensation =2
475
- else: round_seperator_token_compensation =3
476
-
477
- if has_image:
478
- # ideally I should add the <\s> token eq for round_len,
479
- # and subtract the ASSISTANT: token length from the instrucion len
480
- round_len = len(tokenizer_image_token(rou, tokenizer)) + round_seperator_token_compensation # adding a +2 to compensate for </s> which is part of conversations
481
- instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 5
482
- else:
483
- round_len = len(tokenizer(rou).input_ids) + round_seperator_token_compensation
484
- instruction_len = len(tokenizer(parts[0]).input_ids) - 5
485
-
486
- # Removing this as part of the new olmo tokenizer customaization
487
- # if i != 0 and not tokenizer.legacy and IS_TOKENIZER_GREATER_THAN_0_14:
488
- # round_len -= 1
489
- # instruction_len -= 1
490
-
491
- target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
492
-
493
- cur_len += round_len
494
- target[cur_len:] = IGNORE_INDEX
495
-
496
- if cur_len < tokenizer.model_max_length:
497
- if cur_len != total_len:
498
- target[:] = IGNORE_INDEX
499
- print(
500
- f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}. Round len: {len(rounds)-1}"
501
- f" (ignored)"
502
- )
503
-
504
- return dict(
505
- input_ids=input_ids,
506
- labels=targets,
507
- )
508
-
509
-
510
- def preprocess_mpt(
511
- sources,
512
- tokenizer: transformers.PreTrainedTokenizer,
513
- has_image: bool = False
514
- ) -> Dict:
515
- conv = conversation_lib.default_conversation.copy()
516
- roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
517
-
518
- # Apply prompt templates
519
- conversations = []
520
- for i, source in enumerate(sources):
521
- if roles[source[0]["from"]] != conv.roles[0]:
522
- # Skip the first one if it is not from human
523
- source = source[1:]
524
-
525
- conv.messages = []
526
- for j, sentence in enumerate(source):
527
- role = roles[sentence["from"]]
528
- assert role == conv.roles[j % 2], f"{i}"
529
- conv.append_message(role, sentence["value"])
530
- conversations.append(conv.get_prompt())
531
-
532
- # Tokenize conversations
533
-
534
- if has_image:
535
- input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0)
536
- else:
537
- input_ids = tokenizer(
538
- conversations,
539
- return_tensors="pt",
540
- padding="longest",
541
- max_length=tokenizer.model_max_length,
542
- truncation=True,
543
- ).input_ids
544
-
545
- targets = input_ids.clone()
546
- assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
547
-
548
- # Mask targets
549
- sep = conv.sep + conv.roles[1]
550
- for conversation, target in zip(conversations, targets):
551
- total_len = int(target.ne(tokenizer.pad_token_id).sum())
552
-
553
- rounds = conversation.split(conv.sep)
554
- re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
555
- for conv_idx in range(3, len(rounds), 2):
556
- re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt
557
- cur_len = 0
558
- target[:cur_len] = IGNORE_INDEX
559
- for i, rou in enumerate(re_rounds):
560
- if rou == "":
561
- break
562
-
563
- parts = rou.split(sep)
564
- if len(parts) != 2:
565
- break
566
- parts[0] += sep
567
-
568
- if has_image:
569
- round_len = len(tokenizer_image_token(rou, tokenizer))
570
- instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1
571
- else:
572
- round_len = len(tokenizer(rou).input_ids)
573
- instruction_len = len(tokenizer(parts[0]).input_ids) - 1
574
-
575
- if i != 0 and getattr(tokenizer, 'legacy', False) and IS_TOKENIZER_GREATER_THAN_0_14:
576
- round_len += 1
577
- instruction_len += 1
578
-
579
- target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
580
-
581
- cur_len += round_len
582
- target[cur_len:] = IGNORE_INDEX
583
-
584
- if cur_len < tokenizer.model_max_length:
585
- if cur_len != total_len:
586
- target[:] = IGNORE_INDEX
587
- print(
588
- f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
589
- f" (ignored)"
590
- )
591
-
592
- return dict(
593
- input_ids=input_ids,
594
- labels=targets,
595
- )
596
-
597
-
598
- def preprocess_plain(
599
- sources: Sequence[str],
600
- tokenizer: transformers.PreTrainedTokenizer,
601
- ) -> Dict:
602
- # add end signal and concatenate together
603
- conversations = []
604
- for source in sources:
605
- assert len(source) == 2
606
- assert DEFAULT_IMAGE_TOKEN in source[0]['value']
607
- source[0]['value'] = DEFAULT_IMAGE_TOKEN
608
- conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep
609
- conversations.append(conversation)
610
- # tokenize conversations
611
- input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations]
612
- targets = copy.deepcopy(input_ids)
613
- for target, source in zip(targets, sources):
614
- tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer))
615
- target[:tokenized_len] = IGNORE_INDEX
616
-
617
- return dict(input_ids=input_ids, labels=targets)
618
-
619
-
620
- def preprocess(
621
- sources: Sequence[str],
622
- tokenizer: transformers.PreTrainedTokenizer,
623
- has_image: bool = False
624
- ) -> Dict:
625
- """
626
- Given a list of sources, each is a conversation list. This transform:
627
- 1. Add signal '### ' at the beginning each sentence, with end signal '\n';
628
- 2. Concatenate conversations together;
629
- 3. Tokenize the concatenated conversation;
630
- 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
631
- """
632
- if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN:
633
- return preprocess_plain(sources, tokenizer)
634
- if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2:
635
- return preprocess_llama_2(sources, tokenizer, has_image=has_image)
636
- if conversation_lib.default_conversation.version.startswith("v1"):
637
- return preprocess_v1(sources, tokenizer, has_image=has_image)
638
- if conversation_lib.default_conversation.version == "mpt":
639
- return preprocess_mpt(sources, tokenizer, has_image=has_image)
640
- # add end signal and concatenate together
641
- conversations = []
642
- for source in sources:
643
- header = f"{conversation_lib.default_conversation.system}\n\n"
644
- conversation = _add_speaker_and_signal(header, source)
645
- conversations.append(conversation)
646
- # tokenize conversations
647
- def get_tokenize_len(prompts):
648
- return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
649
-
650
- if has_image:
651
- input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations]
652
- else:
653
- conversations_tokenized = _tokenize_fn(conversations, tokenizer)
654
- input_ids = conversations_tokenized["input_ids"]
655
-
656
- targets = copy.deepcopy(input_ids)
657
- for target, source in zip(targets, sources):
658
- if has_image:
659
- tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source])
660
- else:
661
- tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"]
662
- speakers = [sentence["from"] for sentence in source]
663
- _mask_targets(target, tokenized_lens, speakers)
664
-
665
- return dict(input_ids=input_ids, labels=targets)
666
-
667
-
668
- class LazySupervisedDataset(Dataset):
669
- """Dataset for supervised fine-tuning."""
670
-
671
- def __init__(self, data_path: str,
672
- tokenizer: transformers.PreTrainedTokenizer,
673
- data_args: DataArguments):
674
- super(LazySupervisedDataset, self).__init__()
675
- list_data_dict = json.load(open(data_path, "r"))
676
-
677
- rank0_print("Formatting inputs...Skip in lazy mode")
678
- self.tokenizer = tokenizer
679
- self.list_data_dict = list_data_dict
680
- self.data_args = data_args
681
-
682
- def __len__(self):
683
- return len(self.list_data_dict)
684
-
685
- @property
686
- def lengths(self):
687
- length_list = []
688
- for sample in self.list_data_dict:
689
- img_tokens = 128 if 'image' in sample else 0
690
- length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens)
691
- return length_list
692
-
693
- @property
694
- def modality_lengths(self):
695
- length_list = []
696
- for sample in self.list_data_dict:
697
- cur_len = sum(len(conv['value'].split()) for conv in sample['conversations'])
698
- cur_len = cur_len if 'image' in sample else -cur_len
699
- length_list.append(cur_len)
700
- return length_list
701
-
702
- def __getitem__(self, i) -> Dict[str, torch.Tensor]:
703
- sources = self.list_data_dict[i]
704
- if isinstance(i, int):
705
- sources = [sources]
706
- assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
707
- if 'image' in sources[0]:
708
- image_file = self.list_data_dict[i]['image']
709
- image_folder = self.data_args.image_folder
710
- processor = self.data_args.image_processor
711
- image = Image.open(os.path.join(image_folder, image_file)).convert('RGB')
712
- if self.data_args.image_aspect_ratio == 'pad':
713
- def expand2square(pil_img, background_color):
714
- width, height = pil_img.size
715
- if width == height:
716
- return pil_img
717
- elif width > height:
718
- result = Image.new(pil_img.mode, (width, width), background_color)
719
- result.paste(pil_img, (0, (width - height) // 2))
720
- return result
721
- else:
722
- result = Image.new(pil_img.mode, (height, height), background_color)
723
- result.paste(pil_img, ((height - width) // 2, 0))
724
- return result
725
- image = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
726
- image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
727
- else:
728
- image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
729
- sources = preprocess_multimodal(
730
- copy.deepcopy([e["conversations"] for e in sources]),
731
- self.data_args)
732
- else:
733
- sources = copy.deepcopy([e["conversations"] for e in sources])
734
- data_dict = preprocess(
735
- sources,
736
- self.tokenizer,
737
- has_image=('image' in self.list_data_dict[i]))
738
- if isinstance(i, int):
739
- data_dict = dict(input_ids=data_dict["input_ids"][0],
740
- labels=data_dict["labels"][0])
741
-
742
- # image exist in the data
743
- if 'image' in self.list_data_dict[i]:
744
- data_dict['image'] = image
745
- elif self.data_args.is_multimodal:
746
- # image does not exist in the data, but the model is multimodal
747
- crop_size = self.data_args.image_processor.crop_size
748
- data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width'])
749
- return data_dict
750
-
751
-
752
- @dataclass
753
- class DataCollatorForSupervisedDataset(object):
754
- """Collate examples for supervised fine-tuning."""
755
-
756
- tokenizer: transformers.PreTrainedTokenizer
757
-
758
- def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
759
- input_ids, labels = tuple([instance[key] for instance in instances]
760
- for key in ("input_ids", "labels"))
761
- input_ids = torch.nn.utils.rnn.pad_sequence(
762
- input_ids,
763
- batch_first=True,
764
- padding_value=self.tokenizer.pad_token_id)
765
- labels = torch.nn.utils.rnn.pad_sequence(labels,
766
- batch_first=True,
767
- padding_value=IGNORE_INDEX)
768
- input_ids = input_ids[:, :self.tokenizer.model_max_length]
769
- labels = labels[:, :self.tokenizer.model_max_length]
770
- batch = dict(
771
- input_ids=input_ids,
772
- labels=labels,
773
- attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
774
- )
775
-
776
- if 'image' in instances[0]:
777
- images = [instance['image'] for instance in instances]
778
- if all(x is not None and x.shape == images[0].shape for x in images):
779
- batch['images'] = torch.stack(images)
780
- else:
781
- batch['images'] = images
782
-
783
- return batch
784
-
785
-
786
- def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer,
787
- data_args) -> Dict:
788
- """Make dataset and collator for supervised fine-tuning."""
789
- train_dataset = LazySupervisedDataset(tokenizer=tokenizer,
790
- data_path=data_args.data_path,
791
- data_args=data_args)
792
- data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
793
- return dict(train_dataset=train_dataset,
794
- eval_dataset=None,
795
- data_collator=data_collator)
796
-
797
-
798
- def train(attn_implementation=None):
799
- global local_rank
800
- parser = transformers.HfArgumentParser(
801
- (ModelArguments, DataArguments, TrainingArguments))
802
- model_args, data_args, training_args = parser.parse_args_into_dataclasses()
803
- local_rank = training_args.local_rank
804
- compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
805
-
806
- bnb_model_from_pretrained_args = {}
807
- if training_args.bits in [4, 8]:
808
- from transformers import BitsAndBytesConfig
809
- bnb_model_from_pretrained_args.update(dict(
810
- device_map={"": training_args.device},
811
- load_in_4bit=training_args.bits == 4,
812
- load_in_8bit=training_args.bits == 8,
813
- quantization_config=BitsAndBytesConfig(
814
- load_in_4bit=training_args.bits == 4,
815
- load_in_8bit=training_args.bits == 8,
816
- llm_int8_skip_modules=["mm_projector"],
817
- llm_int8_threshold=6.0,
818
- llm_int8_has_fp16_weight=False,
819
- bnb_4bit_compute_dtype=compute_dtype,
820
- bnb_4bit_use_double_quant=training_args.double_quant,
821
- bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'}
822
- )
823
- ))
824
-
825
- if model_args.vision_tower is not None:
826
- if 'mpt' in model_args.model_name_or_path:
827
- config = transformers.AutoConfig.from_pretrained(model_args.model_name_or_path, trust_remote_code=True)
828
- config.attn_config['attn_impl'] = training_args.mpt_attn_impl
829
- model = LlavaMptForCausalLM.from_pretrained(
830
- model_args.model_name_or_path,
831
- config=config,
832
- cache_dir=training_args.cache_dir,
833
- **bnb_model_from_pretrained_args
834
- )
835
-
836
- elif 'OLMo' in model_args.model_name_or_path:
837
- print('Setting up OLMo model....')
838
- with open('llava/config.json') as json_file:
839
- data = json.load(json_file)
840
- config = LlavaOLMoBitnet1BConfig(**data)
841
- model = LlavaOLMoBitnet1BForCausalLM(config)
842
- model.load_state_dict(torch.load('OLMo_Bitnet_1B/pytorch_model.bin'), strict=False)
843
- training_args.save_safetensors = False # setting this as model saving is not happening due to shared tensors in the embed_token addition.
844
-
845
- else:
846
- model = LlavaLlamaForCausalLM.from_pretrained(
847
- model_args.model_name_or_path,
848
- cache_dir=training_args.cache_dir,
849
- attn_implementation=attn_implementation,
850
- torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
851
- **bnb_model_from_pretrained_args
852
- )
853
- else:
854
- model = transformers.LlamaForCausalLM.from_pretrained(
855
- model_args.model_name_or_path,
856
- cache_dir=training_args.cache_dir,
857
- attn_implementation=attn_implementation,
858
- torch_dtype=(torch.bfloat16 if training_args.bf16 else None),
859
- **bnb_model_from_pretrained_args
860
- )
861
- model.config.use_cache = False
862
-
863
- if model_args.freeze_backbone:
864
- model.model.requires_grad_(False)
865
-
866
- if training_args.bits in [4, 8]:
867
- from peft import prepare_model_for_kbit_training
868
- model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
869
- model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing)
870
-
871
- if training_args.gradient_checkpointing:
872
- if hasattr(model, "enable_input_require_grads"):
873
- model.enable_input_require_grads()
874
- else:
875
- def make_inputs_require_grad(module, input, output):
876
- output.requires_grad_(True)
877
- model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
878
-
879
- if training_args.lora_enable:
880
- from peft import LoraConfig, get_peft_model
881
- lora_config = LoraConfig(
882
- r=training_args.lora_r,
883
- lora_alpha=training_args.lora_alpha,
884
- target_modules=find_all_linear_names(model),
885
- lora_dropout=training_args.lora_dropout,
886
- bias=training_args.lora_bias,
887
- task_type="CAUSAL_LM",
888
- )
889
- if training_args.bits == 16:
890
- if training_args.bf16:
891
- model.to(torch.bfloat16)
892
- if training_args.fp16:
893
- model.to(torch.float16)
894
- rank0_print("Adding LoRA adapters...")
895
- model = get_peft_model(model, lora_config)
896
-
897
- if 'mpt' in model_args.model_name_or_path:
898
- tokenizer = transformers.AutoTokenizer.from_pretrained(
899
- model_args.model_name_or_path,
900
- cache_dir=training_args.cache_dir,
901
- model_max_length=training_args.model_max_length,
902
- padding_side="right"
903
- )
904
- elif 'OLMo' in model_args.model_name_or_path:
905
- print('Setting up OLMo tokenizer...')
906
- tokenizer = transformers.AutoTokenizer.from_pretrained(
907
- "NousResearch/OLMo-Bitnet-1B",
908
- cache_dir=training_args.cache_dir,
909
- model_max_length=training_args.model_max_length,
910
- padding_side="right",
911
- pad_token_id=1,
912
- use_fast=True,
913
- legacy=False,
914
- unk_token='<|padding|>',
915
- )
916
- tokenizer.legacy = False
917
- else:
918
- tokenizer = transformers.AutoTokenizer.from_pretrained(
919
- model_args.model_name_or_path,
920
- cache_dir=training_args.cache_dir,
921
- model_max_length=training_args.model_max_length,
922
- padding_side="right",
923
- use_fast=False,
924
- )
925
-
926
- if model_args.version == "v0":
927
- if tokenizer.pad_token is None:
928
- smart_tokenizer_and_embedding_resize(
929
- special_tokens_dict=dict(pad_token="[PAD]"),
930
- tokenizer=tokenizer,
931
- model=model,
932
- )
933
- elif model_args.version == "v0.5":
934
- tokenizer.pad_token = tokenizer.unk_token
935
- else:
936
- tokenizer.pad_token = tokenizer.unk_token
937
- if model_args.version in conversation_lib.conv_templates:
938
- conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version]
939
- else:
940
- conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"]
941
-
942
- if model_args.vision_tower is not None:
943
- model.get_model().initialize_vision_modules(
944
- model_args=model_args,
945
- fsdp=training_args.fsdp
946
- )
947
-
948
- vision_tower = model.get_vision_tower()
949
- vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device)
950
-
951
- data_args.image_processor = vision_tower.image_processor
952
- data_args.is_multimodal = True
953
-
954
- model.config.image_aspect_ratio = data_args.image_aspect_ratio
955
- model.config.tokenizer_padding_side = tokenizer.padding_side
956
- model.config.tokenizer_model_max_length = tokenizer.model_max_length
957
-
958
- model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter
959
- if model_args.tune_mm_mlp_adapter:
960
- model.requires_grad_(False)
961
- for p in model.get_model().mm_projector.parameters():
962
- p.requires_grad = True
963
-
964
- model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
965
- if training_args.freeze_mm_mlp_adapter:
966
- for p in model.get_model().mm_projector.parameters():
967
- p.requires_grad = False
968
-
969
- if training_args.bits in [4, 8]:
970
- model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device)
971
-
972
- model.config.mm_use_im_start_end = data_args.mm_use_im_start_end = model_args.mm_use_im_start_end
973
- model.config.mm_projector_lr = training_args.mm_projector_lr
974
- training_args.use_im_start_end = model_args.mm_use_im_start_end
975
- model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
976
- model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
977
-
978
- if training_args.bits in [4, 8]:
979
- from peft.tuners.lora import LoraLayer
980
- for name, module in model.named_modules():
981
- if isinstance(module, LoraLayer):
982
- if training_args.bf16:
983
- module = module.to(torch.bfloat16)
984
- if 'norm' in name:
985
- module = module.to(torch.float32)
986
- if 'lm_head' in name or 'embed_tokens' in name:
987
- if hasattr(module, 'weight'):
988
- if training_args.bf16 and module.weight.dtype == torch.float32:
989
- module = module.to(torch.bfloat16)
990
-
991
- data_module = make_supervised_data_module(tokenizer=tokenizer,
992
- data_args=data_args)
993
- trainer = LLaVATrainer(model=model,
994
- tokenizer=tokenizer,
995
- args=training_args,
996
- **data_module)
997
-
998
- # adding a warnings filter when training, as there is a token mismatch warnings always being displayed.
999
- # looks like this is a tokenizer version issue, I am not able to revert to the older tokenizer version without breaking a bunch of things
1000
- # link for the issue documented on llava page: https://github.com/haotian-liu/LLaVA/issues/661
1001
-
1002
- with warnings.catch_warnings():
1003
- warnings.filterwarnings("ignore", message="(ignored)*")
1004
-
1005
- if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
1006
- trainer.train(resume_from_checkpoint=True)
1007
- else:
1008
- trainer.train()
1009
-
1010
- trainer.save_state()
1011
-
1012
- model.config.use_cache = True
1013
-
1014
- if training_args.lora_enable:
1015
- state_dict = get_peft_state_maybe_zero_3(
1016
- model.named_parameters(), training_args.lora_bias
1017
- )
1018
- non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(
1019
- model.named_parameters()
1020
- )
1021
- if training_args.local_rank == 0 or training_args.local_rank == -1:
1022
- model.config.save_pretrained(training_args.output_dir)
1023
- model.save_pretrained(training_args.output_dir, state_dict=state_dict)
1024
- torch.save(non_lora_state_dict, os.path.join(training_args.output_dir, 'non_lora_trainables.bin'))
1025
- else:
1026
- safe_save_model_for_hf_trainer(trainer=trainer,
1027
- output_dir=training_args.output_dir)
1028
-
1029
-
1030
- if __name__ == "__main__":
1031
- train()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
train/train_mem.py DELETED
@@ -1,4 +0,0 @@
1
- from llava.train.train import train
2
-
3
- if __name__ == "__main__":
4
- train(attn_implementation="flash_attention_2")
 
 
 
 
 
train/train_xformers.py DELETED
@@ -1,13 +0,0 @@
1
- # Make it more memory efficient by monkey patching the LLaMA model with xformers attention.
2
-
3
- # Need to call this before importing transformers.
4
- from llava.train.llama_xformers_attn_monkey_patch import (
5
- replace_llama_attn_with_xformers_attn,
6
- )
7
-
8
- replace_llama_attn_with_xformers_attn()
9
-
10
- from llava.train.train import train
11
-
12
- if __name__ == "__main__":
13
- train()