benchang1110 commited on
Commit
b26c61c
1 Parent(s): dc2913a

Upload TaiVisionForCausalLM

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./upload",
3
+ "architectures": [
4
+ "TaiVisionForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_taivisionlm.TaiVisionLMConfig",
8
+ "AutoModelForCausalLM": "modeling_taivisionlm.TaiVisionForCausalLM"
9
+ },
10
+ "hidden_size": 2048,
11
+ "ignore_index": -100,
12
+ "image_token_index": 32000,
13
+ "model_type": "taivisionlm",
14
+ "num_image_tokens": 196,
15
+ "projection_dim": 768,
16
+ "text_config": {
17
+ "architecture": [
18
+ "LlamaForCausalLM"
19
+ ],
20
+ "hidden_size": 2048,
21
+ "intermediate_size": 5632,
22
+ "model_type": "llama",
23
+ "num_hidden_layers": 22,
24
+ "num_key_value_heads": 4,
25
+ "rms_norm_eps": 1e-05,
26
+ "torch_dtype": "bfloat16",
27
+ "vocab_size": 32001
28
+ },
29
+ "torch_dtype": "float32",
30
+ "transformers_version": "4.44.0",
31
+ "vision_config": {
32
+ "model_type": "siglip_vision_model",
33
+ "projection_dim": 768
34
+ }
35
+ }
configuration_taivisionlm.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TaiVisionLM configuration"""
2
+
3
+ from transformers import PretrainedConfig
4
+ from transformers import logging, CONFIG_MAPPING
5
+ import warnings
6
+ import transformers
7
+
8
+ logger = logging.get_logger(__name__)
9
+
10
+ class TaiVisionLMConfig(PretrainedConfig):
11
+ model_type = "taivisionlm"
12
+ is_composition = False
13
+
14
+ def __init__(
15
+ self,
16
+ vision_config=None,
17
+ text_config=None,
18
+ ignore_index=-100,
19
+ image_token_idx=32000,
20
+ vocab_size=32001,
21
+ projection_dim=768,
22
+ hidden_size=2048,
23
+ **kwargs,
24
+ ):
25
+ self.ignore_index = ignore_index
26
+ self.image_token_index = image_token_idx
27
+ self._vocab_size = vocab_size
28
+ self.projection_dim = projection_dim
29
+ self.hidden_size = hidden_size
30
+ self.vision_config = vision_config
31
+ self.is_encoder_decoder = False
32
+
33
+ if isinstance(self.vision_config, dict):
34
+ vision_config["model_type"] = (
35
+ vision_config["model_type"] if "model_type" in vision_config else "siglip_vision_model"
36
+ )
37
+ self.vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
38
+ elif vision_config is None:
39
+ self.vision_config = CONFIG_MAPPING["siglip_vision_model"](
40
+ attention_dropout=0.0,
41
+ hidden_act="gelu_pytorch_tanh",
42
+ hidden_size=768,
43
+ image_size=224,
44
+ intermediate_size=3072,
45
+ layer_norm_eps=1e-06,
46
+ num_attention_heads=12,
47
+ num_channels=3,
48
+ num_hidden_layers=12,
49
+ patch_size=16,
50
+ )
51
+
52
+ self.vocab_size = vocab_size
53
+ self.text_config = text_config
54
+
55
+ if isinstance(self.text_config, dict):
56
+ text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "gpt2"
57
+ self.text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
58
+ elif text_config is None:
59
+ self.text_config = CONFIG_MAPPING["llama"](
60
+ architecture= ["LlamaForCausalLM"],
61
+ hidden_act = "silu",
62
+ attention_bias = False,
63
+ attention_dropout = 0.0,
64
+ bos_token_id = 1,
65
+ eos_token_id = 2,
66
+ hidden_size = 2048,
67
+ initializer_range = 0.02,
68
+ intermediate_size = 5632,
69
+ max_position_embeddings = 2048,
70
+ model_type = "llama",
71
+ num_attention_heads = 32,
72
+ num_hidden_layers = 22,
73
+ num_key_value_heads = 4,
74
+ pretraining_tp = 1,
75
+ rms_norm_eps = 1e-05,
76
+ rope_scaling = None,
77
+ rope_theta = 10000.0,
78
+ tie_word_embeddings = False,
79
+ torch_dtype = "bfloat16",
80
+ transformers_version = "4.40.2",
81
+ use_cache = True,
82
+ vocab_size = 32001
83
+ )
84
+ self.num_image_tokens = (self.vision_config.image_size // self.vision_config.patch_size) ** 2
85
+ self.pad_token_id = self.text_config.pad_token_id
86
+ self.vision_config.projection_dim = projection_dim
87
+ super().__init__(**kwargs)
88
+
89
+ @property
90
+ def vocab_size(self):
91
+ warnings.warn(
92
+ "The `vocab_size` attribute is deprecated and will be removed in v4.44, Please use `text_config.vocab_size` instead.",
93
+ FutureWarning,
94
+ )
95
+ return self._vocab_size
96
+
97
+ @vocab_size.setter
98
+ def vocab_size(self, value):
99
+ self._vocab_size = value
100
+
101
+ def to_dict(self):
102
+ output = super().to_dict()
103
+ output.pop("_vocab_size", None)
104
+ return output
105
+
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:f0414a3e74dae9b3e7e53b13785fab81adbf7236243ba8dba50c5152df0abb0f
3
+ size 4806424752
modeling_taivisionlm.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_language_model(self, model_id = "benchang1110/Taiwan-tinyllama-v1.0-chat"):
160
+ language_model = AutoModelForCausalLM.from_pretrained(model_id)
161
+ if language_model.vocab_size != self.vocab_size:
162
+ print("vocab size mismatch, resize the token embeddings for the pretained language model")
163
+ language_model.resize_token_embeddings(self.vocab_size)
164
+ self.language_model.load_state_dict(language_model.state_dict(),strict=True)
165
+
166
+ def load_vision_model(self,model_id = "google/siglip-base-patch16-224"):
167
+ import transformers
168
+ vision_model = transformers.SiglipVisionModel.from_pretrained(model_id)
169
+ self.vision_tower.load_state_dict(vision_model.state_dict(),strict=True)
170
+
171
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.get_input_embeddings with PaliGemma->TaiVisionLM
172
+ def get_input_embeddings(self):
173
+ return self.language_model.get_input_embeddings()
174
+
175
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.set_input_embeddings with PaliGemma->TaiVisionLM
176
+ def set_input_embeddings(self, value):
177
+ self.language_model.set_input_embeddings(value)
178
+
179
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.get_output_embeddings with PaliGemma->TaiVisionLM
180
+ def get_output_embeddings(self):
181
+ return self.language_model.get_output_embeddings()
182
+
183
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.set_output_embeddings with PaliGemma->TaiVisionLM
184
+ def set_output_embeddings(self, new_embeddings):
185
+ self.language_model.set_output_embeddings(new_embeddings)
186
+
187
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.set_decoder with PaliGemma->TaiVisionLM
188
+ def set_decoder(self, decoder):
189
+ self.language_model.set_decoder(decoder)
190
+
191
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.get_decoder with PaliGemma->TaiVisionLM
192
+ def get_decoder(self):
193
+ return self.language_model.get_decoder()
194
+
195
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration.tie_weights with PaliGemma->TaiVisionLM
196
+ def tie_weights(self):
197
+ return self.language_model.tie_weights()
198
+
199
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, pad_to_multiple_of=None) -> nn.Embedding:
200
+ # TODO: config.vocab_size is deprecated and will be removed in v4.43.
201
+ # `resize_token_embeddings` should work from `modeling_utils.py``
202
+ model_embeds = self.language_model.resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
203
+ self.config.text_config.vocab_size = model_embeds.num_embeddings
204
+ self.config.vocab_size = model_embeds.num_embeddings
205
+ self.vocab_size = model_embeds.num_embeddings
206
+ return model_embeds
207
+
208
+ # Copied from transformers.models.paligemma.modeling_paligemma.PaliGemmaForConditionalGeneration._merge_input_ids_with_image_features with PaliGemma->TaiVisionLM
209
+ def _update_causal_mask(
210
+ self, attention_mask, token_type_ids, inputs_embeds, past_key_values, cache_position, is_training: bool = False
211
+ ):
212
+ using_static_cache = isinstance(past_key_values, StaticCache)
213
+ dtype, device = inputs_embeds.dtype, inputs_embeds.device
214
+ min_dtype = torch.finfo(dtype).min
215
+ sequence_length = inputs_embeds.shape[1]
216
+ if using_static_cache:
217
+ target_length = past_key_values.get_max_length()
218
+ else:
219
+ target_length = (
220
+ attention_mask.shape[-1]
221
+ if isinstance(attention_mask, torch.Tensor)
222
+ else cache_position[0] + sequence_length + 1
223
+ )
224
+
225
+ if attention_mask is not None and attention_mask.dim() == 4:
226
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
227
+ causal_mask = attention_mask
228
+ else:
229
+ causal_mask = torch.full(
230
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
231
+ )
232
+ # Causal diagonal mask only if training, otherwise attend to the whole prefix. Training-specific attn for prefix is handled below
233
+ if sequence_length != 1:
234
+ if is_training:
235
+ causal_mask = torch.triu(causal_mask, diagonal=1)
236
+ else:
237
+ causal_mask = torch.zeros_like(causal_mask)
238
+
239
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
240
+ causal_mask = causal_mask[None, None, :, :].expand(inputs_embeds.shape[0], 1, -1, -1)
241
+ if attention_mask is not None:
242
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
243
+ mask_length = attention_mask.shape[-1]
244
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)
245
+ padding_mask = padding_mask == 0
246
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
247
+ padding_mask, min_dtype
248
+ )
249
+ # we are training thus we need to create a full mask on the image + prefix but causal on suffix
250
+ if is_training:
251
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
252
+ token_type_ids[:, None, None, :].to(causal_mask.device) == 0, 0
253
+ )
254
+ return causal_mask
255
+
256
+
257
+ def forward(
258
+ self,
259
+ input_ids: torch.LongTensor = None,
260
+ pixel_values: torch.FloatTensor = None,
261
+ attention_mask: Optional[torch.Tensor] = None,
262
+ position_ids: Optional[torch.LongTensor] = None,
263
+ past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None,
264
+ token_type_ids: Optional[torch.LongTensor] = None,
265
+ cache_position: Optional[torch.LongTensor] = None,
266
+ inputs_embeds: Optional[torch.FloatTensor] = None,
267
+ labels: Optional[torch.LongTensor] = None,
268
+ use_cache: Optional[bool] = None,
269
+ output_attentions: Optional[bool] = None,
270
+ output_hidden_states: Optional[bool] = None,
271
+ return_dict: Optional[bool] = None,
272
+ ) -> Union[Tuple, TaiVisionCausalLMOutputWithPast]:
273
+ r"""
274
+ Args:
275
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
276
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
277
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
278
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
279
+
280
+ Returns:
281
+
282
+ Example:
283
+
284
+ ```python
285
+ >>> from PIL import Image
286
+ >>> import requests
287
+ >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
288
+
289
+ >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/PaliGemma-test-224px-hf")
290
+ >>> processor = AutoProcessor.from_pretrained("google/PaliGemma-test-224px-hf")
291
+
292
+ >>> prompt = "answer en Where is the cow standing?"
293
+ >>> url = "https://huggingface.co/gv-hf/PaliGemma-test-224px-hf/resolve/main/cow_beach_1.png"
294
+ >>> image = Image.open(requests.get(url, stream=True).raw)
295
+
296
+ >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
297
+
298
+ >>> # Generate
299
+ >>> generate_ids = model.generate(**inputs, max_length=30)
300
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
301
+ "answer en Where is the cow standing?\nbeach"
302
+ ```"""
303
+
304
+ if (input_ids is None) ^ (inputs_embeds is not None):
305
+ raise ValueError(
306
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
307
+ )
308
+
309
+ if pixel_values is not None and inputs_embeds is not None:
310
+ raise ValueError(
311
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
312
+ )
313
+
314
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
315
+ output_hidden_states = (
316
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
317
+ )
318
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
319
+
320
+ is_training = token_type_ids is not None and labels is not None
321
+
322
+ if inputs_embeds is None:
323
+ inputs_embeds = self.get_input_embeddings()(input_ids)
324
+
325
+ if cache_position is None:
326
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
327
+ cache_position = torch.arange(
328
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
329
+ )
330
+
331
+ if position_ids is None:
332
+ position_ids = cache_position.unsqueeze(0) + 1 # Paligemma positions are 1-indexed
333
+
334
+ # Merge text and images
335
+ if pixel_values is not None:
336
+ image_outputs = self.vision_tower(pixel_values.to(inputs_embeds.dtype))
337
+ selected_image_feature = image_outputs.last_hidden_state
338
+ image_features = self.vision_projector(selected_image_feature)
339
+ image_features = image_features / (self.config.hidden_size**0.5)
340
+
341
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1).expand_as(inputs_embeds)
342
+ if inputs_embeds[special_image_mask].numel() != image_features.numel():
343
+ image_tokens_in_text = torch.sum(input_ids == self.config.image_token_index)
344
+ raise ValueError(
345
+ f"Number of images does not match number of special image tokens in the input text. "
346
+ f"Got {image_tokens_in_text} image tokens in the text but {image_features.shape[0] * image_features.shape[1]} "
347
+ "tokens from image embeddings."
348
+ )
349
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
350
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
351
+
352
+ # mask out pad-token-ids in labels for BC
353
+ if labels is not None and self.pad_token_id in labels:
354
+ logger.warning_once(
355
+ "`labels` contains `pad_token_id` which will be masked with `config.ignore_index`. ",
356
+ "You have to mask out `pad_token_id` when preparing `labels`, this behavior will be removed in v.4.46.",
357
+ )
358
+ labels = torch.where(input_ids == self.pad_token_id, self.config.ignore_index, labels)
359
+
360
+ causal_mask = self._update_causal_mask(
361
+ attention_mask, token_type_ids, inputs_embeds, past_key_values, cache_position, is_training
362
+ )
363
+
364
+ outputs = self.language_model(
365
+ attention_mask=causal_mask,
366
+ position_ids=position_ids,
367
+ past_key_values=past_key_values,
368
+ inputs_embeds=inputs_embeds,
369
+ use_cache=use_cache,
370
+ output_attentions=output_attentions,
371
+ output_hidden_states=output_hidden_states,
372
+ return_dict=return_dict,
373
+ cache_position=cache_position,
374
+ )
375
+
376
+ logits = outputs.logits
377
+ logits = logits.float()
378
+ loss = None
379
+ if labels is not None:
380
+ shift_logits = logits[..., :-1, :]
381
+ shift_labels = labels[..., 1:]
382
+ if attention_mask is not None:
383
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
384
+ shift_attention_mask = attention_mask[..., 1:]
385
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
386
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
387
+ else:
388
+ shift_logits = shift_logits.contiguous()
389
+ shift_labels = shift_labels.contiguous()
390
+ # Flatten the tokens
391
+ loss_fct = nn.CrossEntropyLoss()
392
+
393
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
394
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
395
+ loss = loss_fct(flat_logits, flat_labels)
396
+ if not return_dict:
397
+ output = (logits,) + outputs[1:]
398
+ return (loss,) + output if loss is not None else output
399
+
400
+ return TaiVisionCausalLMOutputWithPast(
401
+ loss=loss,
402
+ logits=logits,
403
+ past_key_values=outputs.past_key_values,
404
+ hidden_states=outputs.hidden_states,
405
+ attentions=outputs.attentions,
406
+ )
407
+
408
+ def prepare_inputs_for_generation(
409
+ self,
410
+ input_ids,
411
+ past_key_values=None,
412
+ inputs_embeds=None,
413
+ cache_position=None,
414
+ position_ids=None,
415
+ pixel_values=None,
416
+ attention_mask=None,
417
+ token_type_ids=None,
418
+ use_cache=True,
419
+ **kwargs,
420
+ ):
421
+ model_inputs = self.language_model.prepare_inputs_for_generation(
422
+ input_ids,
423
+ past_key_values=past_key_values,
424
+ inputs_embeds=inputs_embeds,
425
+ attention_mask=attention_mask,
426
+ cache_position=cache_position,
427
+ **kwargs,
428
+ )
429
+
430
+ model_inputs["token_type_ids"] = token_type_ids
431
+
432
+ # position_ids in Paligemma are 1-indexed
433
+ if model_inputs.get("position_ids") is not None:
434
+ model_inputs["position_ids"] += 1
435
+
436
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
437
+ # Otherwise we need pixel values to be passed to model. NOTE: use_cache=False needs pixel_values always
438
+ if cache_position[0] == 0:
439
+ model_inputs["pixel_values"] = pixel_values
440
+
441
+ return model_inputs