karroyan commited on
Commit
03e60fb
·
1 Parent(s): c44799d

feature(lxy): add model card and model

Browse files
.gitattributes CHANGED
@@ -33,3 +33,20 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ config.json filter=lfs diff=lfs merge=lfs -text
37
+ model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
38
+ processor_config.json filter=lfs diff=lfs merge=lfs -text
39
+ tokenizer_config.json filter=lfs diff=lfs merge=lfs -text
40
+ vocab.json filter=lfs diff=lfs merge=lfs -text
41
+ added_tokens.json filter=lfs diff=lfs merge=lfs -text
42
+ preprocessor_config.json filter=lfs diff=lfs merge=lfs -text
43
+ special_tokens_map.json filter=lfs diff=lfs merge=lfs -text
44
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
45
+ video_preprocessor_config.json filter=lfs diff=lfs merge=lfs -text
46
+ generation_config.json filter=lfs diff=lfs merge=lfs -text
47
+ model-00001-of-00004.safetensors filter=lfs diff=lfs merge=lfs -text
48
+ model-00002-of-00004.safetensors filter=lfs diff=lfs merge=lfs -text
49
+ model-00003-of-00004.safetensors filter=lfs diff=lfs merge=lfs -text
50
+ model-00004-of-00004.safetensors filter=lfs diff=lfs merge=lfs -text
51
+ classification_head.pt filter=lfs diff=lfs merge=lfs -text
52
+ chat_template.jinja filter=lfs diff=lfs merge=lfs -text
Modelfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ollama modelfile auto-generated by llamafactory
2
+
3
+ FROM .
4
+
5
+ TEMPLATE """{{ if .System }}<|im_start|>system
6
+ {{ .System }}<|im_end|>
7
+ {{ end }}{{ range .Messages }}{{ if eq .Role "user" }}<|im_start|>user
8
+ {{ .Content }}<|im_end|>
9
+ <|im_start|>assistant
10
+ {{ else if eq .Role "assistant" }}{{ .Content }}<|im_end|>
11
+ {{ end }}{{ end }}"""
12
+
13
+ SYSTEM """You are a helpful assistant."""
14
+
15
+ PARAMETER stop "<|im_end|>"
16
+ PARAMETER num_ctx 4096
README.md ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HUMOR-RM (Keye-VL Version)
2
+
3
+ <div align="center">
4
+
5
+ **[Paper](https://arxiv.org/abs/2512.24555)** | **[Project Page](https://github.com/karroyan/MemeGenerator)**
6
+
7
+ </div>
8
+
9
+ ## Model Summary
10
+
11
+ **HUMOR-RM** is a pairwise reward model designed to evaluate and rank the humor quality of internet memes. It serves as the preference model in the **HUMOR** (Hierarchical Understanding and Meme Optimization) framework.
12
+
13
+ This specific version is fine-tuned on **Keye-VL**, utilizing a dataset of pairwise meme comparisons (ranked by human annotators). It takes two memes (sharing the same template) as input and predicts which one is funnier, providing a consistent proxy for human preference.
14
+
15
+ ## Model Details
16
+
17
+ * **Framework:** LLaMA-Factory
18
+ * **Base Model:** [Keye-VL](https://huggingface.co/Kwai-Keye/Keye-VL-8B-Preview)
19
+ * **Task:** Pairwise Classification / Reward Modeling
20
+ * **Input:** Image Pair + Text Prompt
21
+ * **Output:** Preference Score (Logits indicating )
22
+
23
+ ## Requirements
24
+
25
+ This model is built using the **LLaMA-Factory** framework structure. To run inference, you must have `llamafactory` installed.
26
+
27
+ ```bash
28
+ git clone https://github.com/hiyouga/LLaMA-Factory.git
29
+ cd LLaMA-Factory
30
+ pip install -e .
31
+
32
+ ```
33
+
34
+ ## How to Use
35
+
36
+ Since this model uses a custom classification head on top of Keye-VL, we recommend using the provided wrapper class for inference.
37
+
38
+ ### 1. Configuration (`config.yaml`)
39
+
40
+ Create a `config.yaml` file pointing to the base model and this adapter:
41
+
42
+ ```yaml
43
+ model_name_or_path: Kwai-Kolors/Keye-VL
44
+ adapter_name_or_path: path_to_this_repo # or Local Path
45
+ template: keye # Important: Must match Keye-VL template
46
+ trust_remote_code: true
47
+ finetuning_type: lora
48
+
49
+ ```
50
+
51
+ ### 2. Python Inference Code
52
+
53
+ ```python
54
+ import torch
55
+ import yaml
56
+ from llamafactory.hparams import get_infer_args
57
+ from llamafactory.model import load_tokenizer, get_template_and_fix_tokenizer
58
+ from llamafactory.model import AutoModelForBinaryClassification
59
+ from llamafactory.model.model_utils.classification_head import prepare_classification_model
60
+ from llamafactory.model.patcher import patch_classification_model
61
+ from transformers import AutoConfig, AutoModel
62
+
63
+ class MemeScorer:
64
+ def __init__(self, config_path):
65
+ with open(config_path) as f:
66
+ config = yaml.safe_load(f)
67
+
68
+ # Force RM configuration
69
+ config.update({'stage': 'rm_class', 'finetuning_type': 'lora'})
70
+ model_args, data_args, _, _ = get_infer_args(config)
71
+
72
+ # 1. Load Tokenizer & Template
73
+ tokenizer_mod = load_tokenizer(model_args)
74
+ self.tokenizer = tokenizer_mod["tokenizer"]
75
+ self.processor = tokenizer_mod.get("processor")
76
+ self.template = get_template_and_fix_tokenizer(self.tokenizer, data_args)
77
+
78
+ # 2. Load Base Model
79
+ print("Loading Keye-VL Base...")
80
+ self.model = AutoModel.from_pretrained(
81
+ model_args.model_name_or_path,
82
+ trust_remote_code=True,
83
+ device_map="auto",
84
+ torch_dtype=torch.float16
85
+ )
86
+
87
+ # 3. Attach & Load Reward Head
88
+ prepare_classification_model(self.model)
89
+ self.model = AutoModelForBinaryClassification.from_pretrained(self.model)
90
+ patch_classification_model(self.model)
91
+
92
+ if model_args.adapter_name_or_path:
93
+ self.model.load_classification_head(model_args.adapter_name_or_path[0])
94
+ print("Loaded Humor Adapter.")
95
+
96
+ self.model.eval()
97
+
98
+ def score(self, img1_path, img2_path, prompt="Which meme is funnier?"):
99
+ # Construct Input
100
+ messages = [{"role": "user", "content": prompt}, {"role": "assistant", "content": ""}]
101
+ images = [img1_path, img2_path]
102
+
103
+ # Tokenize using Template
104
+ proc_msgs = self.template.mm_plugin.process_messages(messages, images, [], [], self.processor)
105
+ input_ids, _ = self.template.mm_plugin.process_token_ids([], [], images, [], [], self.tokenizer, self.processor)
106
+ encoded = self.template.encode_multiturn(self.tokenizer, proc_msgs, None, None)
107
+ input_ids += encoded[0][0]
108
+
109
+ # Forward Pass
110
+ inputs = {
111
+ "input_ids": torch.tensor([input_ids]).to(self.model.device),
112
+ "attention_mask": torch.tensor([[1]*len(input_ids)]).to(self.model.device),
113
+ "images": [images] # Image processor handling depends on Keye-VL version
114
+ }
115
+
116
+ with torch.no_grad():
117
+ logits = self.model(**inputs).logits.cpu().numpy()[0]
118
+
119
+ # Logits: [Score_Pair_0, Score_Pair_1] (Depends on exact head config, usually prob(A>B))
120
+ return logits
121
+
122
+ # Usage
123
+ if __name__ == "__main__":
124
+ scorer = MemeScorer("config.yaml")
125
+ scores = scorer.score("meme_a.jpg", "meme_b.jpg")
126
+ print(f"Scores: {scores} (Winner: {'A' if scores[0] > scores[1] else 'B'})")
127
+
128
+ ```
129
+
130
+ ## Intended Use
131
+
132
+ * **Group-wise Ranking:** Evaluating a set of generated captions for a single meme template to select the best punchline.
133
+ * **RLHF/RLAIF:** Providing reward signals for Reinforcement Learning training of meme generators.
134
+
135
+ ## Training Data
136
+
137
+ The model was trained on the **HUMOR-Preference Dataset**, which consists of 5 difficulty tiers of meme pairs:
138
+
139
+ 1. **Wrong Text:** Original vs. Random text.
140
+ 2. **Wrong Location:** Correct text vs. Misplaced text box.
141
+ 3. **Boring:** Original vs. Non-humorous description.
142
+ 4. **Detailed Boring:** Subtle text changes that kill the joke.
143
+ 5. **Generated:** Fine-grained comparison between model-generated memes.
144
+
145
+ ## Citation
146
+
147
+ ```bibtex
148
+ @article{li2025perception,
149
+ title={From Perception to Punchline: Empowering VLM with the Art of In-the-wild Meme},
150
+ author={Li, Xueyan and Xue, Yingyi and Jiang, Mengjie and Zhu, Qingzi and Niu, Yazhe},
151
+ journal={arXiv preprint arXiv:2512.24555},
152
+ year={2025}
153
+ }
154
+
155
+ ```
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4b4f1361af884c8f2f3e6edadde8d2039f77fadf8b4daedc1df6af4230c36e0
3
+ size 889
chat_template.jinja ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b17137645c544af2d4558d36a6723777b736b4045bda225eeedf90595cc774ed
3
+ size 897
classification_head.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a4507f576af45b71156ebd5382754310a07eac5f35370d3332cfbb236b8cf36
3
+ size 134269853
config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ed5da7a182713754123a7c85553e5f5769ea9572188af255d71bc54fa0b89b7
3
+ size 1884
configuration_keye.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from transformers.configuration_utils import PretrainedConfig
15
+ from transformers.modeling_rope_utils import rope_config_validation
16
+
17
+
18
+ class KeyeVisionConfig(PretrainedConfig):
19
+ model_type = "Keye"
20
+ base_config_key = "vision_config"
21
+
22
+ def __init__(
23
+ self,
24
+ hidden_size=768,
25
+ intermediate_size=3072,
26
+ num_hidden_layers=12,
27
+ num_attention_heads=12,
28
+ num_channels=3,
29
+ image_size=224,
30
+ patch_size=14,
31
+ hidden_act="gelu_pytorch_tanh",
32
+ layer_norm_eps=1e-6,
33
+ attention_dropout=0.0,
34
+ spatial_merge_size=2,
35
+ temporal_patch_size=2,
36
+ tokens_per_second=2,
37
+ **kwargs,
38
+ ):
39
+ super().__init__(**kwargs)
40
+
41
+ self.hidden_size = hidden_size
42
+ self.intermediate_size = intermediate_size
43
+ self.num_hidden_layers = num_hidden_layers
44
+ self.num_attention_heads = num_attention_heads
45
+ self.num_channels = num_channels
46
+ self.patch_size = patch_size
47
+ self.image_size = image_size
48
+ self.attention_dropout = attention_dropout
49
+ self.layer_norm_eps = layer_norm_eps
50
+ self.hidden_act = hidden_act
51
+ self.spatial_merge_size = spatial_merge_size
52
+ self.temporal_patch_size = temporal_patch_size
53
+ self.tokens_per_second = tokens_per_second
54
+
55
+
56
+ class KeyeConfig(PretrainedConfig):
57
+ r"""
58
+ This is the configuration class to store the configuration of a [`KeyeForConditionalGeneration`].
59
+
60
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
61
+ documentation from [`PretrainedConfig`] for more information.
62
+
63
+
64
+ Args:
65
+ vocab_size (`int`, *optional*, defaults to 152064):
66
+ Vocabulary size of the Keye model. Defines the number of different tokens that can be represented by the
67
+ `inputs_ids` passed when calling [`KeyeForConditionalGeneration`]
68
+ hidden_size (`int`, *optional*, defaults to 8192):
69
+ Dimension of the hidden representations.
70
+ intermediate_size (`int`, *optional*, defaults to 29568):
71
+ Dimension of the MLP representations.
72
+ num_hidden_layers (`int`, *optional*, defaults to 80):
73
+ Number of hidden layers in the Transformer encoder.
74
+ num_attention_heads (`int`, *optional*, defaults to 64):
75
+ Number of attention heads for each attention layer in the Transformer encoder.
76
+ num_key_value_heads (`int`, *optional*, defaults to 8):
77
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
78
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
79
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
80
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
81
+ by meanpooling all the original heads within that group. For more details checkout [this
82
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
83
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
84
+ The non-linear activation function (function or string) in the decoder.
85
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
86
+ The maximum sequence length that this model might ever be used with.
87
+ initializer_range (`float`, *optional*, defaults to 0.02):
88
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
89
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
90
+ The epsilon used by the rms normalization layers.
91
+ use_cache (`bool`, *optional*, defaults to `True`):
92
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
93
+ relevant if `config.is_decoder=True`.
94
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
95
+ Whether the model's input and output word embeddings should be tied.
96
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
97
+ The base period of the RoPE embeddings.
98
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
99
+ Whether to use sliding window attention.
100
+ sliding_window (`int`, *optional*, defaults to 4096):
101
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
102
+ max_window_layers (`int`, *optional*, defaults to 80):
103
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
104
+ attention_dropout (`float`, *optional*, defaults to 0.0):
105
+ The dropout ratio for the attention probabilities.
106
+ vision_config (`Dict`, *optional*):
107
+ The config for the visual encoder initialization.
108
+ rope_scaling (`Dict`, *optional*):
109
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
110
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
111
+ accordingly.
112
+ Expected contents:
113
+ `rope_type` (`str`):
114
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
115
+ 'llama3'], with 'default' being the original RoPE implementation.
116
+ `factor` (`float`, *optional*):
117
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
118
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
119
+ original maximum pre-trained length.
120
+ `original_max_position_embeddings` (`int`, *optional*):
121
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
122
+ pretraining.
123
+ `attention_factor` (`float`, *optional*):
124
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
125
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
126
+ `factor` field to infer the suggested value.
127
+ `beta_fast` (`float`, *optional*):
128
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
129
+ ramp function. If unspecified, it defaults to 32.
130
+ `beta_slow` (`float`, *optional*):
131
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
132
+ ramp function. If unspecified, it defaults to 1.
133
+ `short_factor` (`List[float]`, *optional*):
134
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
135
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
136
+ size divided by the number of attention heads divided by 2
137
+ `long_factor` (`List[float]`, *optional*):
138
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
139
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
140
+ size divided by the number of attention heads divided by 2
141
+ `low_freq_factor` (`float`, *optional*):
142
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
143
+ `high_freq_factor` (`float`, *optional*):
144
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
145
+
146
+ ```python
147
+ >>> from transformers import KeyeForConditionalGeneration, KeyeConfig
148
+
149
+ >>> # Initializing a Keye style configuration
150
+ >>> configuration = KeyeConfig()
151
+
152
+ >>> # Initializing a model from the Keye style configuration
153
+ >>> model = KeyeForConditionalGeneration(configuration)
154
+
155
+ >>> # Accessing the model configuration
156
+ >>> configuration = model.config
157
+ ```"""
158
+
159
+ model_type = "Keye"
160
+ sub_configs = {"vision_config": KeyeVisionConfig}
161
+ keys_to_ignore_at_inference = ["past_key_values"]
162
+ # Default tensor parallel plan for base model `Keye`
163
+ base_model_tp_plan = {
164
+ "layers.*.self_attn.q_proj": "colwise",
165
+ "layers.*.self_attn.k_proj": "colwise",
166
+ "layers.*.self_attn.v_proj": "colwise",
167
+ "layers.*.self_attn.o_proj": "rowwise",
168
+ "layers.*.mlp.gate_proj": "colwise",
169
+ "layers.*.mlp.up_proj": "colwise",
170
+ "layers.*.mlp.down_proj": "rowwise",
171
+ }
172
+ base_model_pp_plan = {
173
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
174
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
175
+ "norm": (["hidden_states"], ["hidden_states"]),
176
+ }
177
+
178
+ def __init__(
179
+ self,
180
+ vocab_size=152064,
181
+ hidden_size=8192,
182
+ intermediate_size=29568,
183
+ num_hidden_layers=80,
184
+ num_attention_heads=64,
185
+ num_key_value_heads=8,
186
+ hidden_act="silu",
187
+ max_position_embeddings=32768,
188
+ initializer_range=0.02,
189
+ rms_norm_eps=1e-05,
190
+ use_cache=True,
191
+ tie_word_embeddings=False,
192
+ rope_theta=1000000.0,
193
+ use_sliding_window=False,
194
+ sliding_window=4096,
195
+ max_window_layers=80,
196
+ attention_dropout=0.0,
197
+ vision_config=None,
198
+ rope_scaling=None,
199
+ **kwargs,
200
+ ):
201
+ if isinstance(vision_config, dict):
202
+ self.vision_config = self.sub_configs["vision_config"](**vision_config)
203
+ elif vision_config is None:
204
+ self.vision_config = self.sub_configs["vision_config"]()
205
+
206
+ self.vocab_size = vocab_size
207
+ self.max_position_embeddings = max_position_embeddings
208
+ self.hidden_size = hidden_size
209
+ self.intermediate_size = intermediate_size
210
+ self.num_hidden_layers = num_hidden_layers
211
+ self.num_attention_heads = num_attention_heads
212
+ self.use_sliding_window = use_sliding_window
213
+ self.sliding_window = sliding_window
214
+ self.max_window_layers = max_window_layers
215
+
216
+ # for backward compatibility
217
+ if num_key_value_heads is None:
218
+ num_key_value_heads = num_attention_heads
219
+
220
+ self.num_key_value_heads = num_key_value_heads
221
+ self.hidden_act = hidden_act
222
+ self.initializer_range = initializer_range
223
+ self.rms_norm_eps = rms_norm_eps
224
+ self.use_cache = use_cache
225
+ self.rope_theta = rope_theta
226
+ self.attention_dropout = attention_dropout
227
+ self.rope_scaling = rope_scaling
228
+
229
+ # Validate the correctness of rotary position embeddings parameters
230
+ # BC: if there is a 'type' field, move it to 'rope_type'.
231
+ # and change type from 'mrope' to 'default' because `mrope` does default RoPE calculations
232
+ # one can set it to "linear"/"dynamic" etc. to have scaled RoPE
233
+ # TODO: @raushan update config in the hub
234
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
235
+ if self.rope_scaling["type"] == "mrope":
236
+ self.rope_scaling["type"] = "default"
237
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
238
+ rope_config_validation(self, ignore_keys={"mrope_section"})
239
+
240
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
241
+
242
+
243
+ __all__ = ["KeyeConfig"]
generation_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:644cc4ff956b4caac4d8852570191391813831039ed1d64947feeffa023901ab
3
+ size 214
image_processing_keye.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Image processor class for Keye."""
15
+
16
+ import math
17
+ from typing import Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
22
+ from torchvision.transforms import functional as TF
23
+ from transformers.image_transforms import (
24
+ convert_to_rgb,
25
+ resize,
26
+ to_channel_dimension_format,
27
+ )
28
+ from transformers.image_utils import (
29
+ OPENAI_CLIP_MEAN,
30
+ OPENAI_CLIP_STD,
31
+ ChannelDimension,
32
+ PILImageResampling,
33
+ get_image_size,
34
+ infer_channel_dimension_format,
35
+ is_scaled_image,
36
+ is_valid_image,
37
+ make_list_of_images,
38
+ to_numpy_array,
39
+ valid_images,
40
+ validate_preprocess_arguments,
41
+ )
42
+ from transformers.utils import TensorType, is_vision_available, logging
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ if is_vision_available():
49
+ from PIL import Image
50
+
51
+ ImageInput = Union[
52
+ "PIL.Image.Image",
53
+ np.ndarray,
54
+ "torch.Tensor",
55
+ List["PIL.Image.Image"],
56
+ List[np.ndarray],
57
+ List["torch.Tensor"],
58
+ ] # noqa
59
+
60
+
61
+ VideoInput = Union[
62
+ List["PIL.Image.Image"],
63
+ "np.ndarray",
64
+ "torch.Tensor",
65
+ List["np.ndarray"],
66
+ List["torch.Tensor"],
67
+ List[List["PIL.Image.Image"]],
68
+ List[List["np.ndarrray"]],
69
+ List[List["torch.Tensor"]],
70
+ ] # noqa
71
+
72
+
73
+ def make_batched_images(images) -> List[List[ImageInput]]:
74
+ """
75
+ Accepts images in list or nested list format, and makes a list of images for preprocessing.
76
+
77
+ Args:
78
+ images (`Union[List[List[ImageInput]], List[ImageInput], ImageInput]`):
79
+ The input image.
80
+
81
+ Returns:
82
+ list: A list of images.
83
+ """
84
+ if (
85
+ isinstance(images, (list, tuple))
86
+ and isinstance(images[0], (list, tuple))
87
+ and is_valid_image(images[0][0])
88
+ ):
89
+ return [img for img_list in images for img in img_list]
90
+
91
+ elif isinstance(images, (list, tuple)) and is_valid_image(images[0]):
92
+ return images
93
+
94
+ elif is_valid_image(images):
95
+ return [images]
96
+
97
+ raise ValueError(f"Could not make batched images from {images}")
98
+
99
+
100
+ def adjust_size(size, patch_size):
101
+ num_patches = size // patch_size
102
+ if num_patches % 2 != 0: # 如果是奇数,减1
103
+ num_patches -= 1
104
+ return num_patches * patch_size
105
+
106
+
107
+ def make_batched_videos(videos) -> List[VideoInput]:
108
+ if (
109
+ isinstance(videos, (list, tuple))
110
+ and isinstance(videos[0], (list, tuple))
111
+ and is_valid_image(videos[0][0])
112
+ ):
113
+ return videos
114
+
115
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
116
+ if isinstance(videos[0], Image.Image):
117
+ return [videos]
118
+ elif len(videos[0].shape) == 4:
119
+ return [list(video) for video in videos]
120
+
121
+ elif is_valid_image(videos) and len(videos.shape) == 4:
122
+ return [list(videos)]
123
+
124
+ raise ValueError(f"Could not make batched video from {videos}")
125
+
126
+
127
+ def smart_resize(
128
+ height: int,
129
+ width: int,
130
+ factor: int = 28,
131
+ min_pixels: int = 28 * 28 * 130,
132
+ max_pixels: int = 28 * 28 * 1280,
133
+ ):
134
+ """Rescales the image so that the following conditions are met:
135
+
136
+ 1. Both dimensions (height and width) are divisible by 'factor'.
137
+
138
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
139
+
140
+ 3. The aspect ratio of the image is maintained as closely as possible.
141
+
142
+ """
143
+ # if height < factor or width < factor:
144
+ # raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")
145
+ # if int(height < factor//4) + int(width < factor//4):
146
+ # raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor//4}")
147
+
148
+ if height < factor:
149
+ print(f"smart_resize: height={height} < factor={factor}, reset height=factor")
150
+ width = round((width * factor) / height)
151
+ height = factor
152
+
153
+ if width < factor:
154
+ print(f"smart_resize: width={width} < factor={factor}, reset width=factor")
155
+ height = round((height * factor) / width)
156
+ width = factor
157
+
158
+ if max(height, width) / min(height, width) > 200:
159
+ raise ValueError(
160
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
161
+ )
162
+ h_bar = round(height / factor) * factor
163
+ w_bar = round(width / factor) * factor
164
+ if h_bar * w_bar > max_pixels:
165
+ beta = math.sqrt((height * width) / max_pixels)
166
+ h_bar = math.floor(height / beta / factor) * factor
167
+ w_bar = math.floor(width / beta / factor) * factor
168
+ elif h_bar * w_bar < min_pixels:
169
+ beta = math.sqrt(min_pixels / (height * width))
170
+ h_bar = math.ceil(height * beta / factor) * factor
171
+ w_bar = math.ceil(width * beta / factor) * factor
172
+ return h_bar, w_bar
173
+
174
+
175
+ class SiglipImageProcessor(BaseImageProcessor):
176
+ r"""
177
+ Constructs a Siglip image processor that dynamically resizes images based on the original images.
178
+
179
+ Args:
180
+ do_resize (`bool`, *optional*, defaults to `True`):
181
+ Whether to resize the image's (height, width) dimensions.
182
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
183
+ Resampling filter to use when resizing the image.
184
+ do_rescale (`bool`, *optional*, defaults to `True`):
185
+ Whether to rescale the image by the specified scale `rescale_factor`.
186
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
187
+ Scale factor to use if rescaling the image.
188
+ do_normalize (`bool`, *optional*, defaults to `True`):
189
+ Whether to normalize the image.
190
+ image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
191
+ Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
192
+ image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
193
+ Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image.
194
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
195
+ Whether to convert the image to RGB.
196
+ min_pixels (`int`, *optional*, defaults to `28 * 28 * 130`):
197
+ The min pixels of the image to resize the image.
198
+ max_pixels (`int`, *optional*, defaults to `28 * 28 * 1670`):
199
+ The max pixels of the image to resize the image.
200
+ patch_size (`int`, *optional*, defaults to 14):
201
+ The spacial patch size of the vision encoder.
202
+ temporal_patch_size (`int`, *optional*, defaults to 2):
203
+ The temporal patch size of the vision encoder.
204
+ merge_size (`int`, *optional*, defaults to 2):
205
+ The merge size of the vision encoder to llm encoder.
206
+ """
207
+
208
+ model_input_names = [
209
+ "pixel_values",
210
+ "image_grid_thw",
211
+ "pixel_values_videos",
212
+ "video_grid_thw",
213
+ ]
214
+
215
+ def __init__(
216
+ self,
217
+ do_resize: bool = True,
218
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
219
+ do_rescale: bool = True,
220
+ rescale_factor: Union[int, float] = 1 / 255,
221
+ do_normalize: bool = True,
222
+ image_mean: Optional[Union[float, List[float]]] = None,
223
+ image_std: Optional[Union[float, List[float]]] = None,
224
+ do_convert_rgb: bool = True,
225
+ min_pixels: int = 28 * 28 * 130,
226
+ max_pixels: int = 28 * 28 * 1280,
227
+ patch_size: int = 14,
228
+ temporal_patch_size: int = 1,
229
+ merge_size: int = 2,
230
+ **kwargs,
231
+ ) -> None:
232
+ super().__init__(**kwargs)
233
+ self.do_resize = do_resize
234
+ self.resample = resample
235
+ self.do_rescale = do_rescale
236
+ self.rescale_factor = rescale_factor
237
+ self.do_normalize = do_normalize
238
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
239
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
240
+ self.min_pixels = min_pixels
241
+ self.max_pixels = max_pixels
242
+ self.patch_size = patch_size
243
+ self.temporal_patch_size = temporal_patch_size
244
+ self.merge_size = merge_size
245
+ self.size = {"min_pixels": min_pixels, "max_pixels": max_pixels} # not used
246
+ self.do_convert_rgb = do_convert_rgb
247
+
248
+ def mvit_rescale(self, image: Image.Image, merge_size: int = 2) -> Image.Image:
249
+ try:
250
+ w, h = image.size
251
+ except:
252
+ raise ValueError(str((type(image), image)))
253
+ patch_size = self.patch_size
254
+
255
+ if (w // patch_size) * (h // patch_size) > self.in_token_limit:
256
+ scale = math.sqrt(
257
+ self.in_token_limit / ((w // patch_size) * (h // patch_size))
258
+ )
259
+ new_w, new_h = int(w * scale), int(h * scale)
260
+
261
+ image = image.resize((new_w, new_h), Image.Resampling.BICUBIC)
262
+ if self.pad_input:
263
+ new_w, new_h = image.size
264
+ pad_size_h = merge_size * patch_size
265
+ pad_size_w = merge_size * patch_size
266
+
267
+ pad_h = (pad_size_h - new_h % pad_size_h) % pad_size_h
268
+ pad_w = (pad_size_w - new_w % pad_size_w) % pad_size_w
269
+
270
+ image = TF.pad(image, (0, 0, pad_w, pad_h))
271
+ else:
272
+ new_w, new_h = image.size
273
+ new_w = new_w - new_w % patch_size
274
+ new_h = new_h - new_h % patch_size
275
+
276
+ new_w = adjust_size(new_w, patch_size)
277
+ new_h = adjust_size(new_h, patch_size)
278
+
279
+ image = TF.center_crop(image, (new_h, new_w))
280
+
281
+ w, h = image.size
282
+ if w // patch_size >= 512 or h // patch_size >= 512:
283
+ new_h = min(patch_size * 510, h)
284
+ new_w = min(patch_size * 510, w)
285
+ image = TF.center_crop(image, (new_h, new_w))
286
+ # raise ValueError("Exceed pos emb")
287
+ return image
288
+
289
+ def _preprocess(
290
+ self,
291
+ images: Union[ImageInput, VideoInput],
292
+ do_resize: bool = None,
293
+ resample: PILImageResampling = None,
294
+ do_rescale: bool = None,
295
+ rescale_factor: float = None,
296
+ do_normalize: bool = None,
297
+ image_mean: Optional[Union[float, List[float]]] = None,
298
+ image_std: Optional[Union[float, List[float]]] = None,
299
+ do_convert_rgb: bool = None,
300
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
301
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
302
+ ):
303
+ """
304
+ Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
305
+
306
+ Args:
307
+ images (`ImageInput`):
308
+ Image or batch of images to preprocess. Expects pixel values ranging from 0 to 255. If pixel values range from 0 to 1, set `do_rescale=False`.
309
+ vision_info (`List[Dict]`, *optional*):
310
+ Optional list of dictionaries containing additional information about vision inputs.
311
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
312
+ Whether to resize the image.
313
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
314
+ Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums.
315
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
316
+ Whether to rescale the image.
317
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
318
+ Scale factor to use if rescaling the image.
319
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
320
+ Whether to normalize the image.
321
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
322
+ Mean to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
323
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
324
+ Standard deviation to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
325
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
326
+ Whether to convert the image to RGB.
327
+ data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
328
+ The channel dimension format for the output image. Can be one of:
329
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
330
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
331
+ - Unset: Use the channel dimension format of the input image.
332
+ input_data_format (`ChannelDimension` or `str`, *optional*):
333
+ The channel dimension format for the input image. Can be one of:
334
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
335
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
336
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
337
+ """
338
+ images = make_list_of_images(images)
339
+
340
+ if do_convert_rgb:
341
+ images = [convert_to_rgb(image) for image in images]
342
+
343
+ # All transformations expect numpy arrays.
344
+ images = [to_numpy_array(image) for image in images]
345
+
346
+ if is_scaled_image(images[0]) and do_rescale:
347
+ logger.warning_once(
348
+ "It looks like you are trying to rescale already rescaled images. If the input"
349
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
350
+ )
351
+ if input_data_format is None:
352
+ # We assume that all images have the same channel dimension format.
353
+ input_data_format = infer_channel_dimension_format(images[0])
354
+
355
+ height, width = get_image_size(images[0], channel_dim=input_data_format)
356
+ resized_height, resized_width = height, width
357
+ processed_images = []
358
+
359
+ for image in images:
360
+ if do_resize:
361
+ resized_height, resized_width = smart_resize(
362
+ height,
363
+ width,
364
+ factor=self.patch_size * self.merge_size,
365
+ min_pixels=self.min_pixels,
366
+ max_pixels=self.max_pixels,
367
+ )
368
+ image = resize(
369
+ image,
370
+ size=(resized_height, resized_width),
371
+ resample=resample,
372
+ input_data_format=input_data_format,
373
+ )
374
+
375
+ if do_rescale:
376
+ image = self.rescale(
377
+ image, scale=rescale_factor, input_data_format=input_data_format
378
+ )
379
+
380
+ if do_normalize:
381
+ image = self.normalize(
382
+ image=image,
383
+ mean=image_mean,
384
+ std=image_std,
385
+ input_data_format=input_data_format,
386
+ )
387
+ image = to_channel_dimension_format(
388
+ image, data_format, input_channel_dim=input_data_format
389
+ )
390
+ processed_images.append(image)
391
+
392
+ patches = np.array(processed_images)
393
+ if data_format == ChannelDimension.LAST:
394
+ patches = patches.transpose(0, 3, 1, 2)
395
+ if patches.shape[0] == 1:
396
+ patches = np.tile(patches, (self.temporal_patch_size, 1, 1, 1))
397
+ init_patches = patches
398
+ channel = patches.shape[1]
399
+ grid_t = patches.shape[0] // self.temporal_patch_size
400
+ grid_h, grid_w = (
401
+ resized_height // self.patch_size,
402
+ resized_width // self.patch_size,
403
+ )
404
+ patches = patches.reshape(
405
+ grid_t,
406
+ self.temporal_patch_size,
407
+ channel,
408
+ grid_h,
409
+ self.patch_size,
410
+ grid_w,
411
+ self.patch_size,
412
+ )
413
+ patches = patches.transpose(0, 3, 5, 2, 1, 4, 6)
414
+ assert self.temporal_patch_size == 1
415
+ flatten_patches = patches.reshape(
416
+ grid_t * grid_h * grid_w, channel, self.patch_size, self.patch_size
417
+ )
418
+ return flatten_patches, (grid_t, grid_h, grid_w)
419
+
420
+ def preprocess(
421
+ self,
422
+ images: ImageInput,
423
+ videos: VideoInput = None,
424
+ do_resize: bool = None,
425
+ size: Dict[str, int] = None,
426
+ resample: PILImageResampling = None,
427
+ do_rescale: bool = None,
428
+ rescale_factor: float = None,
429
+ do_normalize: bool = None,
430
+ image_mean: Optional[Union[float, List[float]]] = None,
431
+ image_std: Optional[Union[float, List[float]]] = None,
432
+ do_convert_rgb: bool = None,
433
+ return_tensors: Optional[Union[str, TensorType]] = None,
434
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
435
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
436
+ ):
437
+ """
438
+ Args:
439
+ images (`ImageInput`):
440
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
441
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
442
+ videos (`VideoInput`):
443
+ Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
444
+ passing in videos with pixel values between 0 and 1, set `do_rescale=False`.
445
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
446
+ Whether to resize the image.
447
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
448
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
449
+ the longest edge resized to keep the input aspect ratio.
450
+ resample (`int`, *optional*, defaults to `self.resample`):
451
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
452
+ has an effect if `do_resize` is set to `True`.
453
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
454
+ Whether to rescale the image.
455
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
456
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
457
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
458
+ Whether to normalize the image.
459
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
460
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
461
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
462
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
463
+ `True`.
464
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
465
+ Whether to convert the image to RGB.
466
+ return_tensors (`str` or `TensorType`, *optional*):
467
+ The type of tensors to return. Can be one of:
468
+ - Unset: Return a list of `np.ndarray`.
469
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
470
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
471
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
472
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
473
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
474
+ The channel dimension format for the output image. Can be one of:
475
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
476
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
477
+ - Unset: Use the channel dimension format of the input image.
478
+ input_data_format (`ChannelDimension` or `str`, *optional*):
479
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
480
+ from the input image. Can be one of:
481
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
482
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
483
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
484
+
485
+ """
486
+ do_resize = do_resize if do_resize is not None else self.do_resize
487
+ size = size if size is not None else self.size
488
+ resample = resample if resample is not None else self.resample
489
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
490
+ rescale_factor = (
491
+ rescale_factor if rescale_factor is not None else self.rescale_factor
492
+ )
493
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
494
+ image_mean = image_mean if image_mean is not None else self.image_mean
495
+ image_std = image_std if image_std is not None else self.image_std
496
+ do_convert_rgb = (
497
+ do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
498
+ )
499
+
500
+ if images is not None:
501
+ images = make_batched_images(images)
502
+ if videos is not None:
503
+ videos = make_batched_videos(videos)
504
+
505
+ if images is not None and not valid_images(images):
506
+ raise ValueError(
507
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
508
+ "torch.Tensor, tf.Tensor or jax.ndarray."
509
+ )
510
+
511
+ validate_preprocess_arguments(
512
+ rescale_factor=rescale_factor,
513
+ do_normalize=do_normalize,
514
+ image_mean=image_mean,
515
+ image_std=image_std,
516
+ do_resize=do_resize,
517
+ size=size,
518
+ resample=resample,
519
+ )
520
+
521
+ if images is not None:
522
+ pixel_values, vision_grid_thws = [], []
523
+ for image in images:
524
+ patches, image_grid_thw = self._preprocess(
525
+ image,
526
+ do_resize=do_resize,
527
+ resample=resample,
528
+ do_rescale=do_rescale,
529
+ rescale_factor=rescale_factor,
530
+ do_normalize=do_normalize,
531
+ image_mean=image_mean,
532
+ image_std=image_std,
533
+ data_format=data_format,
534
+ do_convert_rgb=do_convert_rgb,
535
+ input_data_format=input_data_format,
536
+ )
537
+ pixel_values.extend(patches)
538
+ vision_grid_thws.append(image_grid_thw)
539
+ pixel_values = np.array(pixel_values)
540
+ vision_grid_thws = np.array(vision_grid_thws)
541
+ data = {"pixel_values": pixel_values, "image_grid_thw": vision_grid_thws}
542
+
543
+ if videos is not None:
544
+ pixel_values, vision_grid_thws = [], []
545
+ for images in videos:
546
+ patches, video_grid_thw = self._preprocess(
547
+ images,
548
+ do_resize=do_resize,
549
+ resample=resample,
550
+ do_rescale=do_rescale,
551
+ rescale_factor=rescale_factor,
552
+ do_normalize=do_normalize,
553
+ image_mean=image_mean,
554
+ image_std=image_std,
555
+ data_format=data_format,
556
+ do_convert_rgb=do_convert_rgb,
557
+ input_data_format=input_data_format,
558
+ )
559
+ pixel_values.extend(patches)
560
+ vision_grid_thws.append(video_grid_thw)
561
+ pixel_values = np.array(pixel_values)
562
+ vision_grid_thws = np.array(vision_grid_thws)
563
+ data = {
564
+ "pixel_values_videos": pixel_values,
565
+ "video_grid_thw": vision_grid_thws,
566
+ }
567
+
568
+ return BatchFeature(data=data, tensor_type=return_tensors)
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03257615730248372fd633710d64a270faab96737ac0ae2027e9894d11a2d91e
3
+ size 4991719792
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00f392b5ce2509fd924c86025d5072edfd22fb04a0cc0efd4b97f97e223b0d23
3
+ size 4983069200
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdc80b3e2e235cb1f56a6efc0d5d717504b398be2fdec1d38dc17b7c4a413d5c
3
+ size 4915943752
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f994778c3dc28739504ae3cb577e99a83d4bdd03488a01e53a4f0d0fb0af4c3
3
+ size 2503030568
model.safetensors.index.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4607f680933da37725696b43563e2a9250fe66562e591c5af73256c261195abb
3
+ size 78140
modeling_keye.py ADDED
The diff for this file is too large to render. See raw diff
 
preprocessor_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ef2328d6779b0546e02145bbbb8405da83cafcd2153bdf25b266cabebb3ae65
3
+ size 670
processing_keye.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Keye Team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from typing import List, Union, TypedDict
21
+ import numpy as np
22
+ from transformers.feature_extraction_utils import BatchFeature
23
+ from transformers.processing_utils import (
24
+ ProcessorMixin,
25
+ Unpack,
26
+ )
27
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
28
+ import torch
29
+
30
+
31
+ ImageInput = Union[
32
+ "PIL.Image.Image",
33
+ np.ndarray,
34
+ "torch.Tensor",
35
+ List["PIL.Image.Image"],
36
+ List[np.ndarray],
37
+ List["torch.Tensor"],
38
+ ] # noqa
39
+
40
+
41
+ VideoInput = Union[
42
+ List["PIL.Image.Image"],
43
+ "np.ndarray",
44
+ "torch.Tensor",
45
+ List["np.ndarray"],
46
+ List["torch.Tensor"],
47
+ List[List["PIL.Image.Image"]],
48
+ List[List["np.ndarrray"]],
49
+ List[List["torch.Tensor"]],
50
+ ] # noqa
51
+
52
+
53
+ class KeyeVideosProcessorKwargs(TypedDict, total=False):
54
+ fps: Union[List[float], float]
55
+
56
+
57
+ class KeyeProcessorKwargs(TypedDict, total=False):
58
+ videos_kwargs: KeyeVideosProcessorKwargs
59
+
60
+
61
+ # Default values for processor kwargs
62
+ KEYE_PROCESSOR_DEFAULTS = {
63
+ "text_kwargs": {
64
+ "padding": False,
65
+ },
66
+ "videos_kwargs": {"fps": 2.0},
67
+ }
68
+
69
+
70
+ class KeyeProcessor(ProcessorMixin):
71
+ r"""
72
+ [`KeyeProcessor`] offers all the functionalities of [`SiglipImageProcessor`] and [`Qwen2TokenizerFast`]. See the
73
+ [`~KeyeProcessor.__call__`] and [`~KeyeProcessor.decode`] for more information.
74
+ Args:
75
+ image_processor ([`SiglipImageProcessor`], *optional*):
76
+ The image processor is a required input.
77
+ tokenizer ([`Qwen2TokenizerFast`], *optional*):
78
+ The tokenizer is a required input.
79
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
80
+ in a chat into a tokenizable string.
81
+ """
82
+
83
+ attributes = ["image_processor", "tokenizer"]
84
+ valid_kwargs = [
85
+ "chat_template",
86
+ "image_std",
87
+ "min_pixels",
88
+ "image_mean",
89
+ "merge_size",
90
+ "image_processor_type",
91
+ "temporal_patch_size",
92
+ "patch_size",
93
+ "max_pixels",
94
+ ]
95
+
96
+ image_processor_class = "AutoImageProcessor"
97
+ tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
98
+
99
+ def __init__(
100
+ self, image_processor=None, tokenizer=None, chat_template=None, **kwargs
101
+ ):
102
+ self.image_token = (
103
+ "<|image_pad|>"
104
+ if not hasattr(tokenizer, "image_token")
105
+ else tokenizer.image_token
106
+ )
107
+ self.video_token = (
108
+ "<|video_pad|>"
109
+ if not hasattr(tokenizer, "video_token")
110
+ else tokenizer.video_token
111
+ )
112
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
113
+
114
+ def __call__(
115
+ self,
116
+ images: ImageInput = None,
117
+ text: Union[
118
+ TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]
119
+ ] = None,
120
+ videos: VideoInput = None,
121
+ **kwargs: Unpack[KeyeProcessorKwargs],
122
+ ) -> BatchFeature:
123
+ """
124
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
125
+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
126
+ the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
127
+ SiglipImageProcessor's [`~SiglipImageProcessor.__call__`] if `vision_infos` is not `None`.
128
+
129
+ Args:
130
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
131
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
132
+ tensor. Both channels-first and channels-last formats are supported.
133
+ text (`str`, `List[str]`, `List[List[str]]`):
134
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
135
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
136
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
137
+ videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
138
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
139
+ tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
140
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
141
+ If set, will return tensors of a particular framework. Acceptable values are:
142
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
143
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
144
+ - `'np'`: Return NumPy `np.ndarray` objects.
145
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
146
+
147
+ Returns:
148
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
149
+
150
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
151
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
152
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
153
+ `None`).
154
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
155
+ - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
156
+ - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
157
+ - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
158
+ - **second_per_grid_ts** -- List of video seconds per time grid. Returned when `videos` is not `None`.
159
+ """
160
+ output_kwargs = self._merge_kwargs(
161
+ KeyeProcessorKwargs,
162
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
163
+ **kwargs,
164
+ )
165
+
166
+ if images is not None:
167
+ image_inputs = self.image_processor(images=images, return_tensors="pt")
168
+ image_inputs["pixel_values"] = image_inputs["pixel_values"]
169
+ image_grid_thw = image_inputs["image_grid_thw"]
170
+
171
+ else:
172
+ image_inputs = {}
173
+ image_grid_thw = None
174
+
175
+ if videos is not None:
176
+ # TODO: add video processing
177
+ videos_inputs = self.image_processor(
178
+ images=None, videos=videos, **output_kwargs["images_kwargs"]
179
+ )
180
+ video_grid_thw = videos_inputs["video_grid_thw"]
181
+
182
+ fps = output_kwargs["videos_kwargs"].pop("fps", 2.0)
183
+ if isinstance(fps, (int, float)):
184
+ second_per_grid_ts = [
185
+ self.image_processor.temporal_patch_size / fps
186
+ ] * len(video_grid_thw)
187
+ elif hasattr(fps, "__len__") and len(fps) == len(video_grid_thw):
188
+ second_per_grid_ts = [
189
+ self.image_processor.temporal_patch_size / tmp for tmp in fps
190
+ ]
191
+ else:
192
+ raise ValueError(
193
+ f"The length of fps ({len(fps) if hasattr(fps, '__len__') else fps}) must be equal to the length of video_grid_thw ({len(video_grid_thw)}) or fps should be a single number."
194
+ )
195
+ videos_inputs.update(
196
+ {"second_per_grid_ts": torch.tensor(second_per_grid_ts)}
197
+ )
198
+
199
+ else:
200
+ videos_inputs = {}
201
+ video_grid_thw = None
202
+
203
+ if not isinstance(text, list):
204
+ text = [text]
205
+
206
+ if image_grid_thw is not None:
207
+ index = 0
208
+ for i in range(len(text)):
209
+ while self.image_token in text[i]:
210
+ text[i] = text[i].replace(
211
+ self.image_token,
212
+ "<|placeholder|>"
213
+ * (
214
+ image_grid_thw[index].prod()
215
+ // self.image_processor.merge_size
216
+ // self.image_processor.merge_size
217
+ ),
218
+ 1,
219
+ )
220
+ index += 1
221
+ text[i] = text[i].replace("<|placeholder|>", self.image_token)
222
+
223
+ if video_grid_thw is not None:
224
+ index = 0
225
+ for i in range(len(text)):
226
+ while self.video_token in text[i]:
227
+ text[i] = text[i].replace(
228
+ self.video_token,
229
+ "<|placeholder|>"
230
+ * (
231
+ video_grid_thw[index].prod()
232
+ // self.image_processor.merge_size
233
+ // self.image_processor.merge_size
234
+ ),
235
+ 1,
236
+ )
237
+ index += 1
238
+ text[i] = text[i].replace("<|placeholder|>", self.video_token)
239
+
240
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
241
+
242
+ return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs})
243
+
244
+ def batch_decode(self, *args, **kwargs):
245
+ """
246
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
247
+ refer to the docstring of this method for more information.
248
+ """
249
+ return self.tokenizer.batch_decode(*args, **kwargs)
250
+
251
+ def decode(self, *args, **kwargs):
252
+ """
253
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
254
+ the docstring of this method for more information.
255
+ """
256
+ return self.tokenizer.decode(*args, **kwargs)
257
+
258
+ def post_process_image_text_to_text(
259
+ self,
260
+ generated_outputs,
261
+ skip_special_tokens=True,
262
+ clean_up_tokenization_spaces=False,
263
+ **kwargs,
264
+ ):
265
+ """
266
+ Post-process the output of the model to decode the text.
267
+
268
+ Args:
269
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
270
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
271
+ or `(sequence_length,)`.
272
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
273
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
274
+ Clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
275
+ Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
276
+ **kwargs:
277
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
278
+
279
+ Returns:
280
+ `List[str]`: The decoded text.
281
+ """
282
+ return self.tokenizer.batch_decode(
283
+ generated_outputs,
284
+ skip_special_tokens=skip_special_tokens,
285
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
286
+ **kwargs,
287
+ )
288
+
289
+ @property
290
+ def model_input_names(self):
291
+ tokenizer_input_names = self.tokenizer.model_input_names
292
+ image_processor_input_names = self.image_processor.model_input_names
293
+ names_from_processor = list(
294
+ dict.fromkeys(tokenizer_input_names + image_processor_input_names)
295
+ )
296
+ return names_from_processor + ["second_per_grid_ts"]
297
+
298
+
299
+ __all__ = ["KeyeProcessor", "KeyeProcessor_moonvit", "KeyeProcessor"]
processor_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ebdfbb344ade75d6cfc4c1ba0019562ae99cb0c3f378fd41026dcf839c3fe3b
3
+ size 115
special_tokens_map.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c3505ea31bcd68a04dd363b0867f069dc90ca1a1796cbf4c4027ee0663909ba
3
+ size 477
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f59a2da0c95ebeeaea61b43e770ba6939c770fb227b0f89a2f0b203519a1d5c
3
+ size 11423826
tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da107c355e35a72b6803befb28f9e1bc841757c3f9695521427147bb0e6c9532
3
+ size 6518
video_preprocessor_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:caa66a5efec40232005736e255bef439afa9853d7b1249e925ba627fc60d2758
3
+ size 1730
vocab.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910
3
+ size 2776833