benchang1110 commited on
Commit
26371b7
1 Parent(s): ce7c6e1

Upload TaiVisionForCausalLM

Browse files
config.json CHANGED
@@ -1,6 +1,10 @@
1
  {
 
 
 
2
  "auto_map": {
3
- "AutoConfig": "configuration_taivisionlm.TaiVisionLMConfig"
 
4
  },
5
  "hidden_size": 2048,
6
  "ignore_index": -100,
@@ -21,6 +25,7 @@
21
  "torch_dtype": "bfloat16",
22
  "vocab_size": 32001
23
  },
 
24
  "transformers_version": "4.44.0",
25
  "vision_config": {
26
  "model_type": "siglip_vision_model",
 
1
  {
2
+ "architectures": [
3
+ "TaiVisionForCausalLM"
4
+ ],
5
  "auto_map": {
6
+ "AutoConfig": "configuration_taivisionlm.TaiVisionLMConfig",
7
+ "AutoModelForCausalLM": "modeling_taivisionlm.TaiVisionForCausalLM"
8
  },
9
  "hidden_size": 2048,
10
  "ignore_index": -100,
 
25
  "torch_dtype": "bfloat16",
26
  "vocab_size": 32001
27
  },
28
+ "torch_dtype": "float32",
29
  "transformers_version": "4.44.0",
30
  "vision_config": {
31
  "model_type": "siglip_vision_model",
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.44.0"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e3c91245701f070448659cda849d90ef35ea419ad8aa53c459b20a7d516df00
3
+ size 4806424752
modeling_taivisionlm.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch TaiVisionLM"""
2
+ import torch
3
+ from transformers import PreTrainedModel, AutoModel, AutoModelForCausalLM
4
+ from transformers.utils import logging, add_start_docstrings, ModelOutput
5
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask_for_sdpa
6
+ from dataclasses import dataclass
7
+ from typing import List, Optional, Tuple, Union
8
+ from torch import nn
9
+ from transformers.cache_utils import Cache, StaticCache
10
+
11
+ logger = logging.get_logger(__name__)
12
+
13
+ from .configuration_taivisionlm import TaiVisionLMConfig
14
+
15
+ _CONFIG_FOR_DOC = "TaiVisionLMConfig"
16
+
17
+ @dataclass
18
+ class TaiVisionCausalLMOutputWithPast(ModelOutput):
19
+ """
20
+ Base class for TaiVision language model (or autoregressive) outputs.
21
+
22
+ Args:
23
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
24
+ Language modeling loss (for next-token prediction).
25
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
26
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
27
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
28
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
29
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
30
+
31
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
32
+ `past_key_values` input) to speed up sequential decoding.
33
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
34
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
35
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
36
+
37
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
38
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
39
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
40
+ sequence_length)`.
41
+
42
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
43
+ heads.
44
+ image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
45
+ Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
46
+ sequence_length, hidden_size)`.
47
+
48
+ image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
49
+ """
50
+ loss: Optional[torch.FloatTensor] = None
51
+ logits: torch.FloatTensor = None
52
+ past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None
53
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
54
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
55
+ image_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
56
+
57
+
58
+ class TaiVisionMultiModalProjector(nn.Module):
59
+ """
60
+ Multimodal projector that cast the image features into the same dimension space as the language model
61
+ """
62
+ def __init__(self, config: TaiVisionLMConfig, dropout=0.1):
63
+ super().__init__()
64
+ self.net = nn.Sequential(
65
+ nn.Linear(config.vision_config.projection_dim, 4*config.vision_config.projection_dim, bias=True),
66
+ nn.GELU(),
67
+ nn.Linear(4*config.vision_config.projection_dim, config.hidden_size, bias=True),
68
+ nn.Dropout(dropout)
69
+ )
70
+
71
+ def forward(self, image_features):
72
+ hidden_states = self.net(image_features).to(image_features.dtype)
73
+ return hidden_states
74
+
75
+
76
+ TRAVISIONLM_START_DOCSTRING = r"""
77
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
78
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
79
+ etc.)
80
+
81
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
82
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
83
+ and behavior.
84
+
85
+ Parameters:
86
+ config ([`TaiVisionLMConfig`]):
87
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
88
+ load the weights associated with the model, only the configuration. Check out the
89
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
90
+ """
91
+
92
+ @add_start_docstrings(
93
+ "The bare TaiVision Model outputting raw hidden-states without any specific head on top.",
94
+ TRAVISIONLM_START_DOCSTRING,
95
+ )
96
+ class TaiVisionPreTrainedModel(PreTrainedModel):
97
+ config_class = TaiVisionLMConfig
98
+ base_model_prefix = "model"
99
+ supports_gradient_checkpointing = True
100
+ _no_split_modules = ["TaiVisionMultiModalProjector"]
101
+ _skip_keys_device_placement = "past_key_values"
102
+ _supports_flash_attn_2 = True
103
+ _supports_sdpa = True
104
+
105
+ def _init_weights(self, module):
106
+ # Do NOT init the weights of the model using this class call, this is a ported version,
107
+ # hence not intended to be trained from scratch.
108
+ std = (
109
+ self.config.initializer_range
110
+ if hasattr(self.config, "initializer_range")
111
+ else self.config.text_config.initializer_range
112
+ )
113
+
114
+ if hasattr(module, "class_embedding"):
115
+ module.class_embedding.data.normal_(mean=0.0, std=std)
116
+
117
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
118
+ module.weight.data.normal_(mean=0.0, std=std)
119
+ if module.bias is not None:
120
+ module.bias.data.zero_()
121
+ elif isinstance(module, nn.Embedding):
122
+ module.weight.data.normal_(mean=0.0, std=std)
123
+ if module.padding_idx is not None:
124
+ module.weight.data[module.padding_idx].zero_()
125
+
126
+ @property
127
+ def _supports_sdpa(self):
128
+ """
129
+ Retrieve language_model's attribute to check whether the model supports
130
+ SDPA or not.
131
+ """
132
+ return self.language_model._supports_sdpa
133
+
134
+
135
+ @add_start_docstrings(
136
+ """The TaiVisionLM model which consists of a vision backbone and a language model.""",
137
+ TRAVISIONLM_START_DOCSTRING,
138
+ )
139
+ class TaiVisionForCausalLM(TaiVisionPreTrainedModel):
140
+ def __init__(self, config: TaiVisionLMConfig):
141
+ super(TaiVisionForCausalLM, self).__init__(config)
142
+ self.vocab_size = config.text_config.vocab_size
143
+ self.pad_token_id = -1 if config.pad_token_id == None else config.pad_token_id
144
+ self._attn_implementation = config._attn_implementation
145
+ self.gradient_checkpointing = False
146
+
147
+ self.vision_tower = AutoModel.from_config(config=config.vision_config)
148
+ self.vision_projector = TaiVisionMultiModalProjector(config)
149
+
150
+ language_model = AutoModelForCausalLM.from_config(
151
+ config=config.text_config, attn_implementation=self._attn_implementation
152
+ )
153
+ if language_model._tied_weights_keys is not None:
154
+ self._tied_weights_keys = [f"language_model.{k}" for k in language_model._tied_weights_keys]
155
+
156
+ self.language_model = language_model
157
+ self.post_init()
158
+
159
+ def load_pretrained(self):
160
+ '''
161
+ load the pretrained weights for language model and vision model
162
+ '''
163
+ import transformers
164
+ language_model = AutoModelForCausalLM.from_pretrained("benchang1110/Taiwan-tinyllama-v1.0-chat")
165
+ if language_model.vocab_size != self.vocab_size:
166
+ print("vocab size mismatch, resize the token embeddings for the pretained language model")
167
+ language_model.resize_token_embeddings(self.vocab_size)
168
+ self.language_model = language_model
169
+ vision_model = transformers.SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224")
170
+ self.vision_tower = vision_model
171
+
172
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.get_input_embeddings with PaliGemma->TaiVisionLM
173
+ def get_input_embeddings(self):
174
+ return self.language_model.get_input_embeddings()
175
+
176
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.set_input_embeddings with PaliGemma->TaiVisionLM
177
+ def set_input_embeddings(self, value):
178
+ self.language_model.set_input_embeddings(value)
179
+
180
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.get_output_embeddings with PaliGemma->TaiVisionLM
181
+ def get_output_embeddings(self):
182
+ return self.language_model.get_output_embeddings()
183
+
184
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.set_output_embeddings with PaliGemma->TaiVisionLM
185
+ def set_output_embeddings(self, new_embeddings):
186
+ self.language_model.set_output_embeddings(new_embeddings)
187
+
188
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.set_decoder with PaliGemma->TaiVisionLM
189
+ def set_decoder(self, decoder):
190
+ self.language_model.set_decoder(decoder)
191
+
192
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.get_decoder with PaliGemma->TaiVisionLM
193
+ def get_decoder(self):
194
+ return self.language_model.get_decoder()
195
+
196
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.tie_weights with PaliGemma->TaiVisionLM
197
+ def tie_weights(self):
198
+ return self.language_model.tie_weights()
199
+
200
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, pad_to_multiple_of=None) -> nn.Embedding:
201
+ # TODO: config.vocab_size is deprecated and will be removed in v4.43.
202
+ # `resize_token_embeddings` should work from `modeling_utils.py``
203
+ model_embeds = self.language_model.resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
204
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
205
+ self.config.vocab_size = model_embeds.num_embeddings
206
+ self.vocab_size = model_embeds.num_embeddings
207
+ return model_embeds
208
+
209
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration._merge_input_ids_with_image_features with PaliGemma->TaiVisionLM
210
+ def _update_causal_mask(
211
+ self, attention_mask, token_type_ids, inputs_embeds, past_key_values, cache_position, is_training: bool = False
212
+ ):
213
+ using_static_cache = isinstance(past_key_values, StaticCache)
214
+ dtype, device = inputs_embeds.dtype, inputs_embeds.device
215
+ min_dtype = torch.finfo(dtype).min
216
+ sequence_length = inputs_embeds.shape[1]
217
+ if using_static_cache:
218
+ target_length = past_key_values.get_max_length()
219
+ else:
220
+ target_length = (
221
+ attention_mask.shape[-1]
222
+ if isinstance(attention_mask, torch.Tensor)
223
+ else cache_position[0] + sequence_length + 1
224
+ )
225
+
226
+ if attention_mask is not None and attention_mask.dim() == 4:
227
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
228
+ causal_mask = attention_mask
229
+ else:
230
+ causal_mask = torch.full(
231
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
232
+ )
233
+ # Causal diagonal mask only if training, otherwise attend to the whole prefix. Training-specific attn for prefix is handled below
234
+ if sequence_length != 1:
235
+ if is_training:
236
+ causal_mask = torch.triu(causal_mask, diagonal=1)
237
+ else:
238
+ causal_mask = torch.zeros_like(causal_mask)
239
+
240
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
241
+ causal_mask = causal_mask[None, None, :, :].expand(inputs_embeds.shape[0], 1, -1, -1)
242
+ if attention_mask is not None:
243
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
244
+ mask_length = attention_mask.shape[-1]
245
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)
246
+ padding_mask = padding_mask == 0
247
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
248
+ padding_mask, min_dtype
249
+ )
250
+ # we are training thus we need to create a full mask on the image + prefix but causal on suffix
251
+ if is_training:
252
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
253
+ token_type_ids[:, None, None, :].to(causal_mask.device) == 0, 0
254
+ )
255
+ return causal_mask
256
+
257
+
258
+ def forward(
259
+ self,
260
+ input_ids: torch.LongTensor = None,
261
+ pixel_values: torch.FloatTensor = None,
262
+ attention_mask: Optional[torch.Tensor] = None,
263
+ position_ids: Optional[torch.LongTensor] = None,
264
+ past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None,
265
+ token_type_ids: Optional[torch.LongTensor] = None,
266
+ cache_position: Optional[torch.LongTensor] = None,
267
+ inputs_embeds: Optional[torch.FloatTensor] = None,
268
+ labels: Optional[torch.LongTensor] = None,
269
+ use_cache: Optional[bool] = None,
270
+ output_attentions: Optional[bool] = None,
271
+ output_hidden_states: Optional[bool] = None,
272
+ return_dict: Optional[bool] = None,
273
+ ) -> Union[Tuple, TaiVisionCausalLMOutputWithPast]:
274
+ r"""
275
+ Args:
276
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
277
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
278
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
279
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
280
+
281
+ Returns:
282
+
283
+ Example:
284
+
285
+ ```python
286
+ >>> from PIL import Image
287
+ >>> import requests
288
+ >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
289
+
290
+ >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/PaliGemma-test-224px-hf")
291
+ >>> processor = AutoProcessor.from_pretrained("google/PaliGemma-test-224px-hf")
292
+
293
+ >>> prompt = "answer en Where is the cow standing?"
294
+ >>> url = "https://huggingface.co/gv-hf/PaliGemma-test-224px-hf/resolve/main/cow_beach_1.png"
295
+ >>> image = Image.open(requests.get(url, stream=True).raw)
296
+
297
+ >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
298
+
299
+ >>> # Generate
300
+ >>> generate_ids = model.generate(**inputs, max_length=30)
301
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
302
+ "answer en Where is the cow standing?\nbeach"
303
+ ```"""
304
+
305
+ if (input_ids is None) ^ (inputs_embeds is not None):
306
+ raise ValueError(
307
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
308
+ )
309
+
310
+ if pixel_values is not None and inputs_embeds is not None:
311
+ raise ValueError(
312
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
313
+ )
314
+
315
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
316
+ output_hidden_states = (
317
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
318
+ )
319
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
320
+
321
+ is_training = token_type_ids is not None and labels is not None
322
+
323
+ if inputs_embeds is None:
324
+ inputs_embeds = self.get_input_embeddings()(input_ids)
325
+
326
+ if cache_position is None:
327
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
328
+ cache_position = torch.arange(
329
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
330
+ )
331
+
332
+ if position_ids is None:
333
+ position_ids = cache_position.unsqueeze(0) + 1 # Paligemma positions are 1-indexed
334
+
335
+ # Merge text and images
336
+ if pixel_values is not None:
337
+ image_outputs = self.vision_tower(pixel_values.to(inputs_embeds.dtype))
338
+ selected_image_feature = image_outputs.last_hidden_state
339
+ image_features = self.vision_projector(selected_image_feature)
340
+ image_features = image_features / (self.config.hidden_size**0.5)
341
+
342
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1).expand_as(inputs_embeds)
343
+ if inputs_embeds[special_image_mask].numel() != image_features.numel():
344
+ image_tokens_in_text = torch.sum(input_ids == self.config.image_token_index)
345
+ raise ValueError(
346
+ f"Number of images does not match number of special image tokens in the input text. "
347
+ f"Got {image_tokens_in_text} image tokens in the text but {image_features.shape[0] * image_features.shape[1]} "
348
+ "tokens from image embeddings."
349
+ )
350
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
351
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
352
+
353
+ # mask out pad-token-ids in labels for BC
354
+ if labels is not None and self.pad_token_id in labels:
355
+ logger.warning_once(
356
+ "`labels` contains `pad_token_id` which will be masked with `config.ignore_index`. ",
357
+ "You have to mask out `pad_token_id` when preparing `labels`, this behavior will be removed in v.4.46.",
358
+ )
359
+ labels = torch.where(input_ids == self.pad_token_id, self.config.ignore_index, labels)
360
+
361
+ causal_mask = self._update_causal_mask(
362
+ attention_mask, token_type_ids, inputs_embeds, past_key_values, cache_position, is_training
363
+ )
364
+
365
+ outputs = self.language_model(
366
+ attention_mask=causal_mask,
367
+ position_ids=position_ids,
368
+ past_key_values=past_key_values,
369
+ inputs_embeds=inputs_embeds,
370
+ use_cache=use_cache,
371
+ output_attentions=output_attentions,
372
+ output_hidden_states=output_hidden_states,
373
+ return_dict=return_dict,
374
+ cache_position=cache_position,
375
+ )
376
+
377
+ logits = outputs.logits
378
+ logits = logits.float()
379
+ loss = None
380
+ if labels is not None:
381
+ shift_logits = logits[..., :-1, :]
382
+ shift_labels = labels[..., 1:]
383
+ if attention_mask is not None:
384
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
385
+ shift_attention_mask = attention_mask[..., 1:]
386
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
387
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
388
+ else:
389
+ shift_logits = shift_logits.contiguous()
390
+ shift_labels = shift_labels.contiguous()
391
+ # Flatten the tokens
392
+ loss_fct = nn.CrossEntropyLoss()
393
+
394
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
395
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
396
+ loss = loss_fct(flat_logits, flat_labels)
397
+ if not return_dict:
398
+ output = (logits,) + outputs[1:]
399
+ return (loss,) + output if loss is not None else output
400
+
401
+ return TaiVisionCausalLMOutputWithPast(
402
+ loss=loss,
403
+ logits=logits,
404
+ past_key_values=outputs.past_key_values,
405
+ hidden_states=outputs.hidden_states,
406
+ attentions=outputs.attentions,
407
+ )
408
+
409
+ def prepare_inputs_for_generation(
410
+ self,
411
+ input_ids,
412
+ past_key_values=None,
413
+ inputs_embeds=None,
414
+ cache_position=None,
415
+ position_ids=None,
416
+ pixel_values=None,
417
+ attention_mask=None,
418
+ token_type_ids=None,
419
+ use_cache=True,
420
+ **kwargs,
421
+ ):
422
+ model_inputs = self.language_model.prepare_inputs_for_generation(
423
+ input_ids,
424
+ past_key_values=past_key_values,
425
+ inputs_embeds=inputs_embeds,
426
+ attention_mask=attention_mask,
427
+ cache_position=cache_position,
428
+ **kwargs,
429
+ )
430
+
431
+ model_inputs["token_type_ids"] = token_type_ids
432
+
433
+ # position_ids in Paligemma are 1-indexed
434
+ if model_inputs.get("position_ids") is not None:
435
+ model_inputs["position_ids"] += 1
436
+
437
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
438
+ # Otherwise we need pixel values to be passed to model. NOTE: use_cache=False needs pixel_values always
439
+ if cache_position[0] == 0:
440
+ model_inputs["pixel_values"] = pixel_values
441
+
442
+ return model_inputs
443
+
444
+
445
+
446
+ if __name__ == '__main__':
447
+ import transformers
448
+ config = transformers.AutoConfig.from_pretrained("benchang1110/TaiVision-base",trust_remote_code=True)
449
+ model = TaiVisionForCausalLM(config).to("cuda")
450
+ print(model)
451
+ model.save_pretrained
452
+ # Test forward
453
+ import torch
454
+ from PIL import Image
455
+ import requests
456
+ # Initialize processor
457
+ processor = transformers.AutoProcessor.from_pretrained("benchang1110/TaiVision-base", trust_remote_code=True)
458
+
459
+ # Load image
460
+ url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg"
461
+ image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
462
+
463
+ # Define prompt and label
464
+ prompt = "What is the color of the car?"
465
+ label = "I am fine, thank you."
466
+
467
+ # Process inputs
468
+ inputs = processor(prompts=prompt,images=image, return_tensors="pt", padding=False, max_length=512).to('cuda')
469
+
470
+ outputs = model.generate(**inputs, max_length=512, do_sample=True, pad_token_id=processor.tokenizer.pad_token_id)
471
+ print(processor.decode(outputs[0], skip_special_tokens=True))
472
+