tjellm commited on
Commit
5a7e7bc
1 Parent(s): 26a68a6

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -35,3 +35,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  onnx/directml/phi-3-vision-128k-instruct-int4/model.onnx.data filter=lfs diff=lfs merge=lfs -text
37
  onnx/cpu_and_mobile/cpu-int4-rtn-block-32/model.onnx.data filter=lfs diff=lfs merge=lfs -text
 
 
 
 
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  onnx/directml/phi-3-vision-128k-instruct-int4/model.onnx.data filter=lfs diff=lfs merge=lfs -text
37
  onnx/cpu_and_mobile/cpu-int4-rtn-block-32/model.onnx.data filter=lfs diff=lfs merge=lfs -text
38
+ onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/phi-3-v-128k-instruct-text-embedding.onnx.data filter=lfs diff=lfs merge=lfs -text
39
+ onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/phi-3-v-128k-instruct-text.onnx.data filter=lfs diff=lfs merge=lfs -text
40
+ onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/phi-3-v-128k-instruct-vision.onnx.data filter=lfs diff=lfs merge=lfs -text
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/config.json ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Phi-3-vision-128k-instruct",
3
+ "architectures": [
4
+ "Phi3VForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi3_v.Phi3VConfig",
9
+ "AutoModelForCausalLM": "modeling_phi3_v.Phi3VForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "embd_layer": {
13
+ "embedding_cls": "image",
14
+ "hd_transform_order": "sub_glb",
15
+ "projection_cls": "mlp",
16
+ "use_hd_transform": true,
17
+ "with_learnable_separator": true
18
+ },
19
+ "eos_token_id": 2,
20
+ "hidden_act": "silu",
21
+ "hidden_size": 3072,
22
+ "img_processor": {
23
+ "image_dim_out": 1024,
24
+ "model_name": "openai/clip-vit-large-patch14-336",
25
+ "name": "clip_vision_model",
26
+ "num_img_tokens": 144
27
+ },
28
+ "initializer_range": 0.02,
29
+ "intermediate_size": 8192,
30
+ "max_position_embeddings": 131072,
31
+ "model_type": "phi3_v",
32
+ "num_attention_heads": 32,
33
+ "num_hidden_layers": 32,
34
+ "num_key_value_heads": 32,
35
+ "original_max_position_embeddings": 4096,
36
+ "rms_norm_eps": 1e-05,
37
+ "rope_scaling": {
38
+ "long_factor": [
39
+ 1.0299999713897705,
40
+ 1.0499999523162842,
41
+ 1.0499999523162842,
42
+ 1.0799999237060547,
43
+ 1.2299998998641968,
44
+ 1.2299998998641968,
45
+ 1.2999999523162842,
46
+ 1.4499999284744263,
47
+ 1.5999999046325684,
48
+ 1.6499998569488525,
49
+ 1.8999998569488525,
50
+ 2.859999895095825,
51
+ 3.68999981880188,
52
+ 5.419999599456787,
53
+ 5.489999771118164,
54
+ 5.489999771118164,
55
+ 9.09000015258789,
56
+ 11.579999923706055,
57
+ 15.65999984741211,
58
+ 15.769999504089355,
59
+ 15.789999961853027,
60
+ 18.360000610351562,
61
+ 21.989999771118164,
62
+ 23.079999923706055,
63
+ 30.009998321533203,
64
+ 32.35000228881836,
65
+ 32.590003967285156,
66
+ 35.56000518798828,
67
+ 39.95000457763672,
68
+ 53.840003967285156,
69
+ 56.20000457763672,
70
+ 57.95000457763672,
71
+ 59.29000473022461,
72
+ 59.77000427246094,
73
+ 59.920005798339844,
74
+ 61.190006256103516,
75
+ 61.96000671386719,
76
+ 62.50000762939453,
77
+ 63.3700065612793,
78
+ 63.48000717163086,
79
+ 63.48000717163086,
80
+ 63.66000747680664,
81
+ 63.850006103515625,
82
+ 64.08000946044922,
83
+ 64.760009765625,
84
+ 64.80001068115234,
85
+ 64.81001281738281,
86
+ 64.81001281738281
87
+ ],
88
+ "short_factor": [
89
+ 1.05,
90
+ 1.05,
91
+ 1.05,
92
+ 1.1,
93
+ 1.1,
94
+ 1.1,
95
+ 1.2500000000000002,
96
+ 1.2500000000000002,
97
+ 1.4000000000000004,
98
+ 1.4500000000000004,
99
+ 1.5500000000000005,
100
+ 1.8500000000000008,
101
+ 1.9000000000000008,
102
+ 2.000000000000001,
103
+ 2.000000000000001,
104
+ 2.000000000000001,
105
+ 2.000000000000001,
106
+ 2.000000000000001,
107
+ 2.000000000000001,
108
+ 2.000000000000001,
109
+ 2.000000000000001,
110
+ 2.000000000000001,
111
+ 2.000000000000001,
112
+ 2.000000000000001,
113
+ 2.000000000000001,
114
+ 2.000000000000001,
115
+ 2.000000000000001,
116
+ 2.000000000000001,
117
+ 2.000000000000001,
118
+ 2.000000000000001,
119
+ 2.000000000000001,
120
+ 2.000000000000001,
121
+ 2.1000000000000005,
122
+ 2.1000000000000005,
123
+ 2.2,
124
+ 2.3499999999999996,
125
+ 2.3499999999999996,
126
+ 2.3499999999999996,
127
+ 2.3499999999999996,
128
+ 2.3999999999999995,
129
+ 2.3999999999999995,
130
+ 2.6499999999999986,
131
+ 2.6999999999999984,
132
+ 2.8999999999999977,
133
+ 2.9499999999999975,
134
+ 3.049999999999997,
135
+ 3.049999999999997,
136
+ 3.049999999999997
137
+ ],
138
+ "type": "su"
139
+ },
140
+ "rope_theta": 10000.0,
141
+ "sliding_window": 131072,
142
+ "tie_word_embeddings": false,
143
+ "torch_dtype": "bfloat16",
144
+ "transformers_version": "4.38.1",
145
+ "use_cache": true,
146
+ "vocab_size": 32064,
147
+ "_attn_implementation": "flash_attention_2"
148
+ }
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/configuration_phi3_v.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ Phi-3-V model configuration"""
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ PHI3V_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/Phi-3-vision-128k-instruct": "https://huggingface.co/microsoft/Phi-3-vision-128k-instruct/resolve/main/config.json",
27
+ }
28
+
29
+
30
+ class Phi3VConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`Phi3VModel`]. It is used to instantiate a Phi-3
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the
35
+ [microsoft/Phi-3-vision-128k-instruct](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct).
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 32064):
40
+ Vocabulary size of the Phi-3-V model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`Phi3VModel`].
42
+ hidden_size (`int`, *optional*, defaults to 3072):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 8192):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer decoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer decoder.
50
+ num_key_value_heads (`int`, *optional*):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
57
+ `num_attention_heads`.
58
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
59
+ Dropout probability for mlp outputs.
60
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
61
+ The dropout ratio for the embeddings.
62
+ attention_dropout (`float`, *optional*, defaults to 0.0):
63
+ The dropout ratio after computing the attention scores.
64
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
65
+ The non-linear activation function (function or string) in the decoder.
66
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
67
+ The maximum sequence length that this model might ever be used with.
68
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
69
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
70
+ original RoPE embeddings when using long scaling.
71
+ initializer_range (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
74
+ The epsilon value used for the RMSNorm.
75
+ use_cache (`bool`, *optional*, defaults to `True`):
76
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
77
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
78
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
79
+ Whether to tie weight embeddings
80
+ rope_theta (`float`, *optional*, defaults to 10000.0):
81
+ The base period of the RoPE embeddings.
82
+ rope_scaling (`dict`, *optional*):
83
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
84
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be either `su` or `yarn` and
85
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
86
+ divided by the number of attention heads divided by 2.
87
+ bos_token_id (`int`, *optional*, defaults to 1):
88
+ The id of the "beginning-of-sequence" token.
89
+ eos_token_id (`int`, *optional*, defaults to 32000):
90
+ The id of the "end-of-sequence" token.
91
+ pad_token_id (`int`, *optional*, defaults to 32000):
92
+ The id of the padding token.
93
+ sliding_window (`int`, *optional*):
94
+ Sliding window attention window size. If `None`, no sliding window is applied.
95
+ embd_layer (`str`, *optional*, defaults to `"default"`):
96
+ The embedding layer to use. Can be either `"default"` or `"image"`. "default" uses the standard embedding for text.
97
+ Example:
98
+ ```python
99
+ >>> from transformers import Phi3VModel, Phi3VConfig
100
+ >>> # Initializing a Phi-3-V style configuration
101
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-vision-128k-instruct")
102
+ >>> # Initializing a model from the configuration
103
+ >>> model = Phi3VModel(configuration)
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+
108
+ model_type = "phi3_v"
109
+ keys_to_ignore_at_inference = ["past_key_values"]
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=32064,
114
+ hidden_size=3072,
115
+ intermediate_size=8192,
116
+ num_hidden_layers=32,
117
+ num_attention_heads=32,
118
+ num_key_value_heads=None,
119
+ resid_pdrop=0.0,
120
+ embd_pdrop=0.0,
121
+ attention_dropout=0.0,
122
+ hidden_act="silu",
123
+ max_position_embeddings=4096,
124
+ original_max_position_embeddings=4096,
125
+ initializer_range=0.02,
126
+ rms_norm_eps=1e-5,
127
+ use_cache=True,
128
+ tie_word_embeddings=False,
129
+ rope_theta=10000.0,
130
+ rope_scaling=None,
131
+ bos_token_id=1,
132
+ eos_token_id=32000,
133
+ pad_token_id=32000,
134
+ sliding_window=None,
135
+ embd_layer: str = "default",
136
+ **kwargs,
137
+ ):
138
+ self.vocab_size = vocab_size
139
+ self.hidden_size = hidden_size
140
+ self.intermediate_size = intermediate_size
141
+ self.num_hidden_layers = num_hidden_layers
142
+ self.num_attention_heads = num_attention_heads
143
+
144
+ if num_key_value_heads is None:
145
+ num_key_value_heads = num_attention_heads
146
+
147
+ self.num_key_value_heads = num_key_value_heads
148
+ self.resid_pdrop = resid_pdrop
149
+ self.embd_pdrop = embd_pdrop
150
+ self.attention_dropout = attention_dropout
151
+ self.hidden_act = hidden_act
152
+ self.max_position_embeddings = max_position_embeddings
153
+ self.original_max_position_embeddings = original_max_position_embeddings
154
+ self.initializer_range = initializer_range
155
+ self.rms_norm_eps = rms_norm_eps
156
+ self.use_cache = use_cache
157
+ self.rope_theta = rope_theta
158
+ self.rope_scaling = rope_scaling
159
+ self._rope_scaling_validation()
160
+ self.sliding_window = sliding_window
161
+ self.embd_layer = embd_layer
162
+
163
+
164
+ super().__init__(
165
+ bos_token_id=bos_token_id,
166
+ eos_token_id=eos_token_id,
167
+ pad_token_id=pad_token_id,
168
+ tie_word_embeddings=tie_word_embeddings,
169
+ **kwargs,
170
+ )
171
+
172
+ def _rope_scaling_validation(self):
173
+ """
174
+ Validate the `rope_scaling` configuration.
175
+ """
176
+ if self.rope_scaling is None:
177
+ return
178
+
179
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
180
+ raise ValueError(
181
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
182
+ f"got {self.rope_scaling}"
183
+ )
184
+ rope_scaling_type = self.rope_scaling.get("type", None)
185
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
186
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
187
+ if rope_scaling_type is None or rope_scaling_type not in ["su", "yarn"]:
188
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['su', 'yarn'], got {rope_scaling_type}")
189
+ if not (
190
+ isinstance(rope_scaling_short_factor, list)
191
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
192
+ ):
193
+ raise ValueError(
194
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
195
+ )
196
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
197
+ raise ValueError(
198
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
199
+ )
200
+ if not (
201
+ isinstance(rope_scaling_long_factor, list)
202
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
203
+ ):
204
+ raise ValueError(
205
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
206
+ )
207
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
208
+ raise ValueError(
209
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
210
+ )
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/genai_config.json ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": {
3
+ "bos_token_id": 1,
4
+ "context_length": 131072,
5
+ "decoder": {
6
+ "session_options": {
7
+ "log_id": "onnxruntime-genai",
8
+ "provider_options": []
9
+ },
10
+ "filename": "phi-3-v-128k-instruct-text.onnx",
11
+ "head_size": 96,
12
+ "hidden_size": 3072,
13
+ "inputs": {
14
+ "inputs_embeds": "inputs_embeds",
15
+ "attention_mask": "attention_mask",
16
+ "past_key_names": "past_key_values.%d.key",
17
+ "past_value_names": "past_key_values.%d.value"
18
+ },
19
+ "outputs": {
20
+ "logits": "logits",
21
+ "present_key_names": "present.%d.key",
22
+ "present_value_names": "present.%d.value"
23
+ },
24
+ "num_attention_heads": 32,
25
+ "num_hidden_layers": 32,
26
+ "num_key_value_heads": 32
27
+ },
28
+ "embedding": {
29
+ "filename": "phi-3-v-128k-instruct-text-embedding.onnx",
30
+ "inputs": {
31
+ "input_ids": "input_ids"
32
+ },
33
+ "outputs": {
34
+ "inputs_embeds": "inputs_embeds"
35
+ }
36
+ },
37
+ "vision": {
38
+ "filename": "phi-3-v-128k-instruct-vision.onnx",
39
+ "inputs": {
40
+ "pixel_values": "pixel_values",
41
+ "image_sizes": "image_sizes"
42
+ },
43
+ "outputs": {
44
+ "visual_features": "visual_features"
45
+ }
46
+ },
47
+ "eos_token_id": [
48
+ 2,
49
+ 32000,
50
+ 32001,
51
+ 32007
52
+ ],
53
+ "pad_token_id": 32000,
54
+ "type": "phi3v",
55
+ "vocab_size": 32064
56
+ },
57
+ "search": {
58
+ "diversity_penalty": 0.0,
59
+ "do_sample": false,
60
+ "early_stopping": true,
61
+ "length_penalty": 1.0,
62
+ "max_length": 131072,
63
+ "min_length": 0,
64
+ "no_repeat_ngram_size": 0,
65
+ "num_beams": 1,
66
+ "num_return_sequences": 1,
67
+ "past_present_share_buffer": true,
68
+ "repetition_penalty": 1.0,
69
+ "temperature": 1.0,
70
+ "top_k": 1,
71
+ "top_p": 1.0
72
+ }
73
+ }
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/image_processing_phi3_v.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Image processor class for Phi3-V."""
17
+
18
+ from typing import List, Optional, Union
19
+
20
+ import numpy as np
21
+
22
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
23
+ from transformers.image_transforms import (
24
+ convert_to_rgb,
25
+ )
26
+ from transformers.image_utils import (
27
+ OPENAI_CLIP_MEAN,
28
+ OPENAI_CLIP_STD,
29
+ ImageInput,
30
+ make_list_of_images,
31
+ valid_images,
32
+ )
33
+ from transformers.utils import TensorType, is_vision_available, logging
34
+
35
+ from transformers import AutoImageProcessor
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+
40
+ if is_vision_available():
41
+ from PIL import Image
42
+
43
+ import torch
44
+ import torchvision
45
+
46
+ def padding_336(b):
47
+ width, height = b.size
48
+ tar = int(np.ceil(height / 336) * 336)
49
+ top_padding = int((tar - height)/2)
50
+ bottom_padding = tar - height - top_padding
51
+ left_padding = 0
52
+ right_padding = 0
53
+ b = torchvision.transforms.functional.pad(b, [left_padding, top_padding, right_padding, bottom_padding], fill=[255,255,255])
54
+
55
+ return b
56
+
57
+ def calc_padded_size(width, height, padding_unit=336):
58
+ target_height = int(np.ceil(height / padding_unit) * padding_unit)
59
+ top_padding = int((target_height - height) / 2)
60
+ bottom_padding = target_height - height - top_padding
61
+ left_padding = 0
62
+ right_padding = 0
63
+ padded_width = width + left_padding + right_padding
64
+ padded_height = height + top_padding + bottom_padding
65
+ return padded_width, padded_height
66
+
67
+ def HD_transform(img, hd_num=16):
68
+ width, height = img.size
69
+ trans = False
70
+ if width < height:
71
+ img = img.transpose(Image.TRANSPOSE)
72
+ trans = True
73
+ width, height = img.size
74
+ ratio = (width/ height)
75
+ scale = 1
76
+ while scale*np.ceil(scale/ratio) <= hd_num:
77
+ scale += 1
78
+ scale -= 1
79
+ new_w = int(scale * 336)
80
+ new_h = int(new_w / ratio)
81
+
82
+ img = torchvision.transforms.functional.resize(img, [new_h, new_w],)
83
+ img = padding_336(img)
84
+ width, height = img.size
85
+ if trans:
86
+ img = img.transpose(Image.TRANSPOSE)
87
+
88
+ return img
89
+
90
+ def calc_hd_transform_size(width, height, hd_num=16):
91
+ transposed = False
92
+ if width < height:
93
+ width, height = height, width
94
+ transposed = True
95
+
96
+ ratio = width / height
97
+ scale = 1
98
+ while scale * np.ceil(scale / ratio) <= hd_num:
99
+ scale += 1
100
+ scale -= 1
101
+
102
+ new_width = int(scale * 336)
103
+ new_height = int(new_width / ratio)
104
+
105
+ padded_width, padded_height = calc_padded_size(new_width, new_height)
106
+
107
+ if transposed:
108
+ padded_width, padded_height = padded_height, padded_width
109
+
110
+ return padded_width, padded_height
111
+
112
+ def pad_to_max_num_crops_tensor(images, max_crops=5):
113
+ """
114
+ images: B x 3 x H x W, B<=max_crops
115
+ """
116
+ B, _, H, W = images.shape
117
+ if B < max_crops:
118
+ pad = torch.zeros(max_crops - B, 3, H, W, dtype=images.dtype, device=images.device)
119
+ images = torch.cat([images, pad], dim=0)
120
+ return images
121
+
122
+
123
+ class Phi3VImageProcessor(BaseImageProcessor):
124
+ r"""
125
+ Constructs a Phi3 image processor. Based on [`CLIPImageProcessor`] with incorporation of additional techniques
126
+ for processing high resolution images as explained in the [InternLM-XComposer2-4KHD](https://arxiv.org/pdf/2404.06512)
127
+ Args:
128
+ image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
129
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
130
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
131
+ image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
132
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
133
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
134
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
135
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
136
+ Whether to convert the image to RGB.
137
+ """
138
+
139
+ model_input_names = ["pixel_values"]
140
+
141
+ def __init__(
142
+ self,
143
+ num_crops: int = 1,
144
+ image_mean: Optional[Union[float, List[float]]] = None,
145
+ image_std: Optional[Union[float, List[float]]] = None,
146
+ do_convert_rgb: bool = True,
147
+ **kwargs,
148
+ ) -> None:
149
+ super().__init__(**kwargs)
150
+ self.num_crops = num_crops
151
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
152
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
153
+ self.do_convert_rgb = do_convert_rgb
154
+
155
+ def calc_num_image_tokens(
156
+ self,
157
+ images: ImageInput
158
+ ):
159
+ """ Calculate the number of image tokens for each image.
160
+ Args:
161
+ images (`ImageInput`):
162
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
163
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
164
+ """
165
+ images = make_list_of_images(images)
166
+
167
+ if not valid_images(images):
168
+ raise ValueError(
169
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
170
+ "torch.Tensor, tf.Tensor or jax.ndarray."
171
+ )
172
+
173
+ images = [image.convert('RGB') for image in images]
174
+ # (H, W, C)
175
+ elems = [HD_transform(im, hd_num = self.num_crops) for im in images]
176
+ shapes = [[im.size[1], im.size[0]] for im in elems]
177
+ num_img_tokens = [int((h//336*w//336+1)*144 + 1 + (h//336+1)*12) for h, w in shapes]
178
+ return num_img_tokens
179
+
180
+ def calc_num_image_tokens_from_image_size(self, width, height):
181
+ """
182
+ Calculate the number of image tokens for a given image size.
183
+ Args:
184
+ width (`int`): Width of the image.
185
+ height (`int`): Height of the image.
186
+ """
187
+ new_width, new_height = calc_hd_transform_size(width, height, hd_num=self.num_crops)
188
+ num_img_tokens = int((new_height // 336 * new_width // 336 + 1) * 144 + 1 + (new_height // 336 + 1) * 12)
189
+ return num_img_tokens
190
+
191
+ def preprocess(
192
+ self,
193
+ images: ImageInput,
194
+ image_mean: Optional[Union[float, List[float]]] = None,
195
+ image_std: Optional[Union[float, List[float]]] = None,
196
+ do_convert_rgb: bool = None,
197
+ return_tensors: Optional[Union[str, TensorType]] = None,
198
+ ):
199
+ """
200
+ Args:
201
+ images (`ImageInput`):
202
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
203
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
204
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
205
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
206
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
207
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
208
+ `True`.
209
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
210
+ Whether to convert the image to RGB.
211
+ return_tensors (`str` or `TensorType`, *optional*):
212
+ The type of tensors to return. Can be one of:
213
+ - Unset: Return a list of `np.ndarray`.
214
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
215
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
216
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
217
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
218
+ """
219
+ image_mean = image_mean if image_mean is not None else self.image_mean
220
+ image_std = image_std if image_std is not None else self.image_std
221
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
222
+
223
+ images = make_list_of_images(images)
224
+
225
+ if not valid_images(images):
226
+ raise ValueError(
227
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
228
+ "torch.Tensor, tf.Tensor or jax.ndarray."
229
+ )
230
+
231
+ if do_convert_rgb:
232
+ images = [convert_to_rgb(image) for image in images]
233
+
234
+ image_sizes = []
235
+ img_processor = torchvision.transforms.Compose([
236
+ torchvision.transforms.ToTensor(),
237
+ torchvision.transforms.Normalize(image_mean, image_std)
238
+ ])
239
+
240
+ # PIL images
241
+ # HD_transform pad images to size of multiiply of 336, 336
242
+ # convert to RGB first
243
+ images = [image.convert('RGB') for image in images]
244
+ elems = [HD_transform(im, hd_num = self.num_crops) for im in images]
245
+ # tensor transform and normalize
246
+ hd_images = [img_processor(im) for im in elems]
247
+ # create global image
248
+ global_image = [torch.nn.functional.interpolate(im.unsqueeze(0).float(), size=(336, 336), mode='bicubic',).to(im.dtype) for im in hd_images]
249
+
250
+ # [(3, h, w)], where h, w is multiple of 336
251
+ shapes = [[im.size(1), im.size(2)] for im in hd_images]
252
+ num_img_tokens = [int((h//336*w//336+1)*144 + 1 + (h//336+1)*12) for h, w in shapes]
253
+ # reshape to channel dimension -> (num_images, num_crops, 3, 336, 336)
254
+ # (1, 3, h//336, 336, w//336, 336) -> (1, h//336, w//336, 3, 336, 336) -> (h//336*w//336, 3, 336, 336)
255
+ hd_images_reshape = [im.reshape(1, 3, h//336, 336, w//336, 336).permute(0,2,4,1,3,5).reshape(-1, 3, 336, 336).contiguous() for im, (h, w) in zip(hd_images, shapes)]
256
+ # concat global image and local image
257
+ hd_images_reshape = [torch.cat([_global_image] + [_im], dim=0) for _global_image, _im in zip(global_image, hd_images_reshape)]
258
+
259
+ # pad to max_num_crops
260
+ image_transformed = [pad_to_max_num_crops_tensor(im, self.num_crops+1) for im in hd_images_reshape]
261
+ image_transformed = torch.stack(image_transformed, dim=0)
262
+ image_sizes = [torch.LongTensor(_shapes) for _shapes in shapes]
263
+ padded_images = image_transformed
264
+ image_sizes = shapes
265
+
266
+ data = {"pixel_values": padded_images,
267
+ "image_sizes": image_sizes,
268
+ "num_img_tokens": num_img_tokens
269
+ }
270
+
271
+ return BatchFeature(data=data, tensor_type=return_tensors)
272
+
273
+ AutoImageProcessor.register("Phi3VImageProcessor", Phi3VImageProcessor)
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/phi-3-v-128k-instruct-text-embedding.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80d4bef0a944c6c826e2aab6b9ba3384c208142167b6f108f7c1fbca0cf1b2ec
3
+ size 411
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/phi-3-v-128k-instruct-text-embedding.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ff71ee46ce8a76b05e327bc2fa13fe694723621bc0ddb857efc326934881e75
3
+ size 394002432
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/phi-3-v-128k-instruct-text.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:255026552017d9cdf4041b5140609158afd2b185463098e69b68ab6083869e1e
3
+ size 52125012
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/phi-3-v-128k-instruct-text.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81967c3ae100a6b9a47abe34ecb9ee7ef9256bbb36aae02fc22faec4f571d69f
3
+ size 2327285760
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/phi-3-v-128k-instruct-vision.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ca4a1114104165c6ae99087f4ca5001500be2328db5d6254b8cd369f21b3a83
3
+ size 402875
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/phi-3-v-128k-instruct-vision.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:890b25ca58548e0e7ea88ce4325a58d08e753cc179dfa4893e09e7594d02b860
3
+ size 444899848
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/preprocessor_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_phi3_v.Phi3VProcessor",
4
+ "AutoImageProcessor": "image_processing_phi3_v.Phi3VImageProcessor"
5
+ },
6
+ "num_crops": 16,
7
+ "image_mean": [
8
+ 0.48145466,
9
+ 0.4578275,
10
+ 0.40821073
11
+ ],
12
+ "image_processor_type": "Phi3VImageProcessor",
13
+ "image_std": [
14
+ 0.26862954,
15
+ 0.26130258,
16
+ 0.27577711
17
+ ],
18
+ "processor_class": "Phi3VProcessor",
19
+ "num_img_tokens": 144
20
+ }
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/processing_phi3_v.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Processor class for Phi3-V.
18
+ """
19
+ import re
20
+ from typing import List, Optional, Union
21
+
22
+ import torch
23
+
24
+ import transformers
25
+ from transformers.feature_extraction_utils import BatchFeature
26
+ from transformers.image_utils import ImageInput
27
+ from transformers.processing_utils import ProcessorMixin
28
+ from transformers.tokenization_utils_base import PaddingStrategy, TextInput, TruncationStrategy
29
+ from transformers.utils import TensorType
30
+ from .image_processing_phi3_v import Phi3VImageProcessor
31
+ transformers.Phi3VImageProcessor = Phi3VImageProcessor
32
+
33
+ class Phi3VProcessor(ProcessorMixin):
34
+ r"""
35
+ Constructs a Phi3-V processor which wraps a Phi3-V image processor and a LLaMa tokenizer into a single processor.
36
+ [`Phi3VProcessor`] offers all the functionalities of [`Phi3VImageProcessor`] and [`LlamaTokenizerFast`]. See the
37
+ [`~Phi3VProcessor.__call__`] and [`~Phi3VProcessor.decode`] for more information.
38
+ Args:
39
+ image_processor ([`Phi3VImageProcessor`], *optional*):
40
+ The image processor is a required input.
41
+ tokenizer ([`LlamaTokenizerFast`], *optional*):
42
+ The tokenizer is a required input.
43
+ """
44
+
45
+ attributes = ["image_processor", "tokenizer"]
46
+ image_processor_class = "Phi3VImageProcessor"
47
+ tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
48
+ special_image_token = "<|image|>"
49
+
50
+ def __init__(self, image_processor, tokenizer):
51
+ self.image_processor = image_processor
52
+ self.tokenizer = tokenizer
53
+ self.num_img_tokens = image_processor.num_img_tokens
54
+ self.img_tokens = [f"<|image_{i+1}|>" for i in range(1000000)]
55
+
56
+ def __call__(
57
+ self,
58
+ text: Union[TextInput, List[TextInput]],
59
+ images: ImageInput = None,
60
+ padding: Union[bool, str, PaddingStrategy] = False,
61
+ truncation: Union[bool, str, TruncationStrategy] = None,
62
+ max_length=None,
63
+ return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
64
+ ) -> BatchFeature:
65
+ """
66
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
67
+ and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
68
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
69
+ Phi3ImageProcessor's [`~Phi3ImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
70
+ of the above two methods for more information.
71
+ Args:
72
+ text (`str`, `List[str]`, `List[List[str]]`):
73
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
74
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
75
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
76
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
77
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
78
+ tensor. Both channels-first and channels-last formats are supported.
79
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
80
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
81
+ index) among:
82
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
83
+ sequence if provided).
84
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
85
+ acceptable input length for the model if that argument is not provided.
86
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
87
+ lengths).
88
+ max_length (`int`, *optional*):
89
+ Maximum length of the returned list and optionally padding length (see above).
90
+ truncation (`bool`, *optional*):
91
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
92
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
93
+ If set, will return tensors of a particular framework. Acceptable values are:
94
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
95
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
96
+ - `'np'`: Return NumPy `np.ndarray` objects.
97
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
98
+ Returns:
99
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
100
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
101
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
102
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
103
+ `None`).
104
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
105
+ """
106
+ if images is not None:
107
+ image_inputs = self.image_processor(images, return_tensors=return_tensors)
108
+ else:
109
+ image_inputs = {}
110
+ inputs = self._convert_images_texts_to_inputs(image_inputs, text, padding=padding, truncation=truncation, max_length=max_length, return_tensors=return_tensors)
111
+ return inputs
112
+
113
+ def calc_num_image_tokens(self, images: ImageInput):
114
+ """ Calculate the number of image tokens for each image.
115
+ Args:
116
+ images (`ImageInput`):
117
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
118
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
119
+ """
120
+ return self.image_processor.calc_num_image_tokens(images)
121
+
122
+ def calc_num_image_tokens_from_image_size(self, width, height):
123
+ """ Calculate the number of image token for an image with given width and height.
124
+ Args:
125
+ width (`int`):
126
+ Width of the image.
127
+ height (`int`):
128
+ Height of the image.
129
+ """
130
+ return self.image_processor.calc_num_image_tokens_from_image_size(width, height)
131
+
132
+
133
+ @property
134
+ def special_image_token_id(self):
135
+ return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
136
+
137
+ def get_special_image_token_id(self):
138
+ return self.tokenizer.convert_tokens_to_ids(self.special_image_token)
139
+
140
+ def _convert_images_texts_to_inputs(self, images, texts, padding=False, truncation=None, max_length=None, return_tensors=None):
141
+
142
+ if not len(images):
143
+ model_inputs = self.tokenizer(texts, return_tensors=return_tensors, padding=padding, truncation=truncation, max_length=max_length)
144
+ return BatchFeature(data={**model_inputs})
145
+
146
+ pattern = r"<\|image_\d+\|>"
147
+ prompt_chunks = [self.tokenizer(chunk).input_ids for chunk in re.split(pattern, texts)]
148
+
149
+ if 'num_img_tokens' in images:
150
+ num_img_tokens = images['num_img_tokens']
151
+ else:
152
+ assert 'num_crops' in images, 'num_crops must be provided in images if num_img_tokens is not provided'
153
+ num_crops = images['num_crops']
154
+ num_img_tokens = [_num_crops * self.num_img_tokens for _num_crops in num_crops]
155
+
156
+ images, image_sizes = images['pixel_values'], images['image_sizes']
157
+
158
+ # image_tags needs to start from 1 to n
159
+ image_tags = re.findall(pattern, texts)
160
+ # image_ids = [int(s.split("|")[1].split("_")[-1]) * -1 for s in image_tags]
161
+ # image_ids_pad = [[iid]*num_img_tokens[i] for i, iid in enumerate(image_ids)]
162
+ image_ids = [int(s.split("|")[1].split("_")[-1]) for s in image_tags]
163
+ unique_image_ids = sorted(list(set(image_ids)))
164
+ # image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be [1, 4, 5]
165
+ # check the condition
166
+ assert unique_image_ids == list(range(1, len(unique_image_ids)+1)), f"image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be {unique_image_ids}"
167
+ # total images must be the same as the number of image tags
168
+ assert len(unique_image_ids) == len(images), f"total images must be the same as the number of image tags, got {len(unique_image_ids)} image tags and {len(images)} images"
169
+
170
+ image_ids_pad = [[-iid]*num_img_tokens[iid-1] for iid in image_ids]
171
+
172
+ def insert_separator(X, sep_list):
173
+ if len(X) > len(sep_list):
174
+ sep_list.append([])
175
+ return [ele for sublist in zip(X, sep_list) for ele in sublist]
176
+ input_ids = []
177
+ offset = 0
178
+ for x in insert_separator(prompt_chunks, image_ids_pad):
179
+ input_ids.extend(x[offset:])
180
+
181
+ input_ids = torch.tensor(input_ids, dtype=torch.long).unsqueeze(0)
182
+ attention_mask = (input_ids > -1000000).to(torch.long)
183
+
184
+ return BatchFeature(data={"input_ids": input_ids,
185
+ "attention_mask": attention_mask,
186
+ "pixel_values": images,
187
+ "image_sizes": image_sizes})
188
+
189
+
190
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
191
+ def batch_decode(self, *args, **kwargs):
192
+ """
193
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
194
+ refer to the docstring of this method for more information.
195
+ """
196
+ return self.tokenizer.batch_decode(*args, **kwargs)
197
+
198
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
199
+ def decode(self, *args, **kwargs):
200
+ """
201
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
202
+ the docstring of this method for more information.
203
+ """
204
+ return self.tokenizer.decode(*args, **kwargs)
205
+
206
+ @property
207
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
208
+ def model_input_names(self):
209
+ tokenizer_input_names = self.tokenizer.model_input_names
210
+ image_processor_input_names = self.image_processor.model_input_names
211
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/processor_config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "processor": {
3
+ "name": "image_processing",
4
+ "transforms": [
5
+ {
6
+ "operation": {
7
+ "name": "decode_image",
8
+ "domain": "com.microsoft.extensions",
9
+ "type": "DecodeImage",
10
+ "attrs": {
11
+ "color_space": "BGR"
12
+ }
13
+ }
14
+ },
15
+ {
16
+ "operation": {
17
+ "name": "convert_to_rgb",
18
+ "domain": "com.microsoft.extensions",
19
+ "type": "ConvertRGB"
20
+ }
21
+ },
22
+ {
23
+ "operation": {
24
+ "name": "phi3_image_transform",
25
+ "domain": "com.microsoft.extensions",
26
+ "type": "Phi3ImageTransform",
27
+ "attrs": {
28
+ "num_crops": 16,
29
+ "num_img_tokens": 144
30
+ }
31
+ }
32
+ }
33
+ ]
34
+ }
35
+ }
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/special_tokens_map.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|system|>",
4
+ "<|end|>",
5
+ "<|user|>",
6
+ "<|end|>"
7
+ ],
8
+ "bos_token": {
9
+ "content": "<s>",
10
+ "lstrip": false,
11
+ "normalized": false,
12
+ "rstrip": false,
13
+ "single_word": false
14
+ },
15
+ "eos_token": {
16
+ "content": "<|endoftext|>",
17
+ "lstrip": false,
18
+ "normalized": false,
19
+ "rstrip": false,
20
+ "single_word": false
21
+ },
22
+ "pad_token": {
23
+ "content": "<|endoftext|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false
28
+ },
29
+ "unk_token": {
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ }
36
+ }
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
onnx/cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/tokenizer_config.json ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": true,
26
+ "single_word": false,
27
+ "special": false
28
+ },
29
+ "32000": {
30
+ "content": "<|endoftext|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "32001": {
38
+ "content": "<|assistant|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": true,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "32002": {
46
+ "content": "<|placeholder1|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": true,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "32003": {
54
+ "content": "<|placeholder2|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": true,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "32004": {
62
+ "content": "<|placeholder3|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": true,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "32005": {
70
+ "content": "<|placeholder4|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": true,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "32006": {
78
+ "content": "<|system|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "32007": {
86
+ "content": "<|end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "32008": {
94
+ "content": "<|placeholder5|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": true,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "32009": {
102
+ "content": "<|placeholder6|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": true,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "32010": {
110
+ "content": "<|user|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "32011": {
118
+ "content": "<|step|>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": true,
122
+ "single_word": false,
123
+ "special": true
124
+ },
125
+ "32012": {
126
+ "content": "<|function_output|>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": true,
130
+ "single_word": false,
131
+ "special": true
132
+ },
133
+ "32013": {
134
+ "content": "<|tag|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": true,
138
+ "single_word": false,
139
+ "special": true
140
+ },
141
+ "32014": {
142
+ "content": "<|function_call|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": true,
146
+ "single_word": false,
147
+ "special": true
148
+ },
149
+ "32015": {
150
+ "content": "<|raw|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": true,
154
+ "single_word": false,
155
+ "special": true
156
+ },
157
+ "32016": {
158
+ "content": "<|continue|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": true,
162
+ "single_word": false,
163
+ "special": true
164
+ },
165
+ "32017": {
166
+ "content": "<|function_list|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": true,
170
+ "single_word": false,
171
+ "special": true
172
+ },
173
+ "32018": {
174
+ "content": "<|calc|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": true,
178
+ "single_word": false,
179
+ "special": true
180
+ },
181
+ "32019": {
182
+ "content": "<|code|>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": true,
186
+ "single_word": false,
187
+ "special": true
188
+ },
189
+ "32020": {
190
+ "content": "<|/code|>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": true,
194
+ "single_word": false,
195
+ "special": true
196
+ },
197
+ "32021": {
198
+ "content": "<|summary|>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": true,
202
+ "single_word": false,
203
+ "special": true
204
+ },
205
+ "32022": {
206
+ "content": "<|resource|>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": true,
210
+ "single_word": false,
211
+ "special": true
212
+ },
213
+ "32023": {
214
+ "content": "<|assistant_mask|>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": true,
218
+ "single_word": false,
219
+ "special": true
220
+ },
221
+ "32024": {
222
+ "content": "<|start|>",
223
+ "lstrip": false,
224
+ "normalized": false,
225
+ "rstrip": true,
226
+ "single_word": false,
227
+ "special": true
228
+ },
229
+ "32025": {
230
+ "content": "<|message|>",
231
+ "lstrip": false,
232
+ "normalized": false,
233
+ "rstrip": true,
234
+ "single_word": false,
235
+ "special": true
236
+ },
237
+ "32026": {
238
+ "content": "<|fim_prefix|>",
239
+ "lstrip": false,
240
+ "normalized": false,
241
+ "rstrip": true,
242
+ "single_word": false,
243
+ "special": true
244
+ },
245
+ "32027": {
246
+ "content": "<|fim_middle|>",
247
+ "lstrip": false,
248
+ "normalized": false,
249
+ "rstrip": true,
250
+ "single_word": false,
251
+ "special": true
252
+ },
253
+ "32028": {
254
+ "content": "<|fim_suffix|>",
255
+ "lstrip": false,
256
+ "normalized": false,
257
+ "rstrip": true,
258
+ "single_word": false,
259
+ "special": true
260
+ },
261
+ "32029": {
262
+ "content": "<|meta_start|>",
263
+ "lstrip": false,
264
+ "normalized": false,
265
+ "rstrip": true,
266
+ "single_word": false,
267
+ "special": true
268
+ },
269
+ "32030": {
270
+ "content": "<|ipynb_marker|>",
271
+ "lstrip": false,
272
+ "normalized": false,
273
+ "rstrip": true,
274
+ "single_word": false,
275
+ "special": true
276
+ },
277
+ "32031": {
278
+ "content": "<|diff_marker|>",
279
+ "lstrip": false,
280
+ "normalized": false,
281
+ "rstrip": true,
282
+ "single_word": false,
283
+ "special": true
284
+ },
285
+ "32032": {
286
+ "content": "<|ghissue|>",
287
+ "lstrip": false,
288
+ "normalized": false,
289
+ "rstrip": true,
290
+ "single_word": false,
291
+ "special": true
292
+ },
293
+ "32033": {
294
+ "content": "<|ghreview|>",
295
+ "lstrip": false,
296
+ "normalized": false,
297
+ "rstrip": true,
298
+ "single_word": false,
299
+ "special": true
300
+ },
301
+ "32034": {
302
+ "content": "<|disc_start|>",
303
+ "lstrip": false,
304
+ "normalized": false,
305
+ "rstrip": true,
306
+ "single_word": false,
307
+ "special": true
308
+ },
309
+ "32035": {
310
+ "content": "<|disc_sep|>",
311
+ "lstrip": false,
312
+ "normalized": false,
313
+ "rstrip": true,
314
+ "single_word": false,
315
+ "special": true
316
+ },
317
+ "32036": {
318
+ "content": "<|disc_thread|><|query|>",
319
+ "lstrip": false,
320
+ "normalized": false,
321
+ "rstrip": true,
322
+ "single_word": false,
323
+ "special": true
324
+ },
325
+ "32037": {
326
+ "content": "<|/query|>",
327
+ "lstrip": false,
328
+ "normalized": false,
329
+ "rstrip": true,
330
+ "single_word": false,
331
+ "special": true
332
+ },
333
+ "32038": {
334
+ "content": "<|data|>",
335
+ "lstrip": false,
336
+ "normalized": false,
337
+ "rstrip": true,
338
+ "single_word": false,
339
+ "special": true
340
+ },
341
+ "32039": {
342
+ "content": "<|/data|>",
343
+ "lstrip": false,
344
+ "normalized": false,
345
+ "rstrip": true,
346
+ "single_word": false,
347
+ "special": true
348
+ },
349
+ "32040": {
350
+ "content": "<|sys|>",
351
+ "lstrip": false,
352
+ "normalized": false,
353
+ "rstrip": true,
354
+ "single_word": false,
355
+ "special": true
356
+ },
357
+ "32041": {
358
+ "content": "<|/sys|>",
359
+ "lstrip": false,
360
+ "normalized": false,
361
+ "rstrip": true,
362
+ "single_word": false,
363
+ "special": true
364
+ },
365
+ "32042": {
366
+ "content": "<|inst|>",
367
+ "lstrip": false,
368
+ "normalized": false,
369
+ "rstrip": true,
370
+ "single_word": false,
371
+ "special": true
372
+ },
373
+ "32043": {
374
+ "content": "<|/inst|>",
375
+ "lstrip": false,
376
+ "normalized": false,
377
+ "rstrip": true,
378
+ "single_word": false,
379
+ "special": true
380
+ },
381
+ "32044": {
382
+ "content": "<|image|>",
383
+ "lstrip": false,
384
+ "normalized": false,
385
+ "rstrip": true,
386
+ "single_word": false,
387
+ "special": true
388
+ }
389
+ },
390
+ "additional_special_tokens": [
391
+ "<|system|>",
392
+ "<|end|>",
393
+ "<|user|>",
394
+ "<|end|>"
395
+ ],
396
+ "bos_token": "<s>",
397
+ "chat_template": "{{ bos_token }}{% for message in messages %}{% if loop.last and message['role'] == 'user' %}<|user|>\n<|image_1|>\n{{ message['content'] }}\n<|end|>\n<|assistant|>\n{% elif message['role'] == 'user' %}<|user|>\n{{ message['content'] }}\n<|end|>\n<|assistant|>\n{% elif message['role'] == 'assistant' %}{{ message['content'] }}\n<|end|>\n{% endif %}{% endfor %}",
398
+ "clean_up_tokenization_spaces": false,
399
+ "eos_token": "<|endoftext|>",
400
+ "model_max_length": 131072,
401
+ "pad_token": "<|endoftext|>",
402
+ "padding_side": "right",
403
+ "sp_model_kwargs": {},
404
+ "tokenizer_class": "LlamaTokenizer",
405
+ "unk_token": "<unk>",
406
+ "use_default_system_prompt": false
407
+ }