Video-Text-to-Text
Transformers
Safetensors
English
Chinese
mllama
text-generation
multimodal
video
vision-language
sft
custom_code
text-generation-inference
Instructions to use OpenMOSS-Team/moss-video-preview-sft with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use OpenMOSS-Team/moss-video-preview-sft with Transformers:
# Load model directly from transformers import AutoProcessor, AutoModelForCausalLM processor = AutoProcessor.from_pretrained("OpenMOSS-Team/moss-video-preview-sft", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("OpenMOSS-Team/moss-video-preview-sft", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload folder using huggingface_hub
Browse files- chat_template.json +4 -0
- config.json +206 -8
- configuration_video_mllama.py +375 -0
- image_processing_video_mllama.py +930 -0
- modeling_video_mllama.py +0 -0
- processing_video_mllama.py +836 -0
chat_template.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"chat_template": "{{- bos_token }}\n{%- if custom_tools is defined %}\n {%- set tools = custom_tools %}\n{%- endif %}\n{%- if not tools_in_user_message is defined %}\n {%- set tools_in_user_message = true %}\n{%- endif %}\n{%- if not date_string is defined %}\n {%- if strftime_now is defined %}\n {%- set date_string = strftime_now(\"%d %b %Y\") %}\n {%- else %}\n {%- set date_string = \"26 Jul 2024\" %}\n {%- endif %}\n{%- endif %}\n{%- if not tools is defined %}\n {%- set tools = none %}\n{%- endif %}\n\n{#- This block extracts the system message. #}\n{%- if messages[0]['role'] == 'system' %}\n {%- set system_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n {%- set user_supplied_system_message = true %}\n{%- else %}\n {%- set system_message = none %}\n {%- set user_supplied_system_message = false %}\n{%- endif %}\n\n{#- Find out if there are any images, not used here but kept for consistency #}\n{% set image_ns = namespace(has_images=false) %}\n{%- for message in messages %}\n {%- if message['content'] is iterable and message['content'] is not string %}\n {%- for content in message['content'] %}\n {%- if content['type'] == 'image' %}\n {%- set image_ns.has_images = true %}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n{%- endfor %}\n\n{#- System message printing logic: This block now ensures complete replacement. #}\n{{- \"<|start_header_id|>system<|end_header_id|>\\n\\n\" }}\n{%- if user_supplied_system_message %}\n {{- system_message }}\n{%- else %}\n {{- \"You are a helpful AI assistant. Respond to the user's request based on the provided text and/or images.\" }}\n{%- endif %}\n{{- \"<|eot_id|>\" }}\n\n{#- Custom tools are passed in a user message with some extra guidance #}\n{%- if tools_in_user_message and not tools is none %}\n {#- Extract the first user message so we can plug it in here #}\n {%- if messages | length != 0 %}\n {%- set first_user_message = messages[0]['content']|trim %}\n {%- set messages = messages[1:] %}\n {%- else %}\n {{- raise_exception(\"Cannot put tools in the first user message when there's no first user message!\") }}\n {%- endif %}\n {{- '<|start_header_id|>user<|end_header_id|>\\n\\n' -}}\n {{- \"Given the following functions, please respond with a JSON for a function call \" }}\n {{- \"with its proper arguments that best answers the given prompt.\\n\\n\" }}\n {{- 'Respond in the format {\\\"name\\\": function name, \\\"parameters\\\": dictionary of argument name and its value}.' }}\n {{- \"Do not use variables.\\n\\n\" }}\n {%- for t in tools %}\n {{- t | tojson(indent=4) }}\n {{- \"\\n\\n\" }}\n {%- endfor %}\n {{- first_user_message + \"<|eot_id|>\"}}\n{%- endif %}\n\n{%- for message in messages %}\n {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %}\n {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\\n\\n' }}\n {%- if message['content'] is string %}\n {{- message['content'] }}\n {%- else %}\n {%- for content in message['content'] %}\n {%- if content['type'] == 'image' %}\n {{- '<|image|>' }}\n {%- elif content['type'] == 'video' %}\n {{- '<|video|>' }}\n {%- elif content['type'] == 'text' %}\n {{- content['text'] }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n {{- '<|eot_id|>' }}\n {%- elif 'tool_calls' in message %}\n {%- if not message.tool_calls|length == 1 %}\n {{- raise_exception(\"This model only supports single tool-calls at once!\") }}\n {%- endif %}\n {%- set tool_call = message.tool_calls[0].function %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' -}}\n {{- '{\\\"name\\\": \\\"' + tool_call.name + '\\\", ' }}\n {{- '\\\"parameters\\\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- \"}\" }}\n {{- \"<|eot_id|>\" }}\n {%- elif message.role == \"tool\" or message.role == \"ipython\" %}\n {{- \"<|start_header_id|>ipython<|end_header_id|>\\n\\n\" }}\n {%- if message.content is mapping or message.content is iterable %}\n {{- message.content | tojson }}\n {%- else %}\n {{- message.content }}\n {%- endif %}\n {{- \"<|eot_id|>\" }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|start_header_id|>assistant<|end_header_id|>\\n\\n' }}\n{%- endif %}\n"
|
| 3 |
+
}
|
| 4 |
+
|
config.json
CHANGED
|
@@ -1,18 +1,87 @@
|
|
| 1 |
{
|
| 2 |
-
"_name_or_path": "/inspire/hdd/project/embodied-multimodality/public/pywang/Streaming-Video-LLM/saves/streaming_video_pretrain_1_5_stage/32_node_20250702_mllm_pretrain_stage_1_123_image470k_video1369k",
|
| 3 |
"architectures": [
|
| 4 |
"VideoMllamaForConditionalGeneration"
|
| 5 |
],
|
| 6 |
-
"hidden_size": 4096,
|
| 7 |
"image_token_index": 128256,
|
| 8 |
-
"model_type": "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
"text_config": {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
"eos_token_id": [
|
| 11 |
128001,
|
| 12 |
128008,
|
| 13 |
128009
|
| 14 |
],
|
| 15 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"rope_scaling": {
|
| 17 |
"factor": 8.0,
|
| 18 |
"high_freq_factor": 4.0,
|
|
@@ -20,14 +89,143 @@
|
|
| 20 |
"original_max_position_embeddings": 8192,
|
| 21 |
"rope_type": "llama3"
|
| 22 |
},
|
| 23 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
},
|
| 25 |
"torch_dtype": "bfloat16",
|
| 26 |
"transformers_version": "4.47.1",
|
| 27 |
-
"use_cache": false,
|
| 28 |
"vision_config": {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
"image_size": 560,
|
| 30 |
-
"
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
}
|
| 33 |
}
|
|
|
|
| 1 |
{
|
|
|
|
| 2 |
"architectures": [
|
| 3 |
"VideoMllamaForConditionalGeneration"
|
| 4 |
],
|
|
|
|
| 5 |
"image_token_index": 128256,
|
| 6 |
+
"model_type": "video_mllama",
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_video_mllama.VideoMllamaConfig",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_video_mllama.VideoMllamaForConditionalGeneration",
|
| 10 |
+
"AutoModel": "modeling_video_mllama.VideoMllamaForConditionalGeneration",
|
| 11 |
+
"AutoProcessor": "processing_video_mllama.VideoMllamaProcessor"
|
| 12 |
+
},
|
| 13 |
"text_config": {
|
| 14 |
+
"_name_or_path": "",
|
| 15 |
+
"add_cross_attention": false,
|
| 16 |
+
"architectures": null,
|
| 17 |
+
"bad_words_ids": null,
|
| 18 |
+
"begin_suppress_tokens": null,
|
| 19 |
+
"bos_token_id": 128000,
|
| 20 |
+
"chunk_size_feed_forward": 0,
|
| 21 |
+
"cross_attention_hidden_size": null,
|
| 22 |
+
"cross_attention_layers": [
|
| 23 |
+
3,
|
| 24 |
+
8,
|
| 25 |
+
13,
|
| 26 |
+
18,
|
| 27 |
+
23,
|
| 28 |
+
28,
|
| 29 |
+
33,
|
| 30 |
+
38
|
| 31 |
+
],
|
| 32 |
+
"decoder_start_token_id": null,
|
| 33 |
+
"diversity_penalty": 0.0,
|
| 34 |
+
"do_sample": false,
|
| 35 |
+
"dropout": 0,
|
| 36 |
+
"early_stopping": false,
|
| 37 |
+
"encoder_no_repeat_ngram_size": 0,
|
| 38 |
"eos_token_id": [
|
| 39 |
128001,
|
| 40 |
128008,
|
| 41 |
128009
|
| 42 |
],
|
| 43 |
+
"exponential_decay_length_penalty": null,
|
| 44 |
+
"finetuning_task": null,
|
| 45 |
+
"forced_bos_token_id": null,
|
| 46 |
+
"forced_eos_token_id": null,
|
| 47 |
+
"hidden_act": "silu",
|
| 48 |
+
"hidden_size": 4096,
|
| 49 |
+
"id2label": {
|
| 50 |
+
"0": "LABEL_0",
|
| 51 |
+
"1": "LABEL_1"
|
| 52 |
+
},
|
| 53 |
+
"initializer_range": 0.02,
|
| 54 |
+
"intermediate_size": 14336,
|
| 55 |
+
"is_decoder": false,
|
| 56 |
+
"is_encoder_decoder": false,
|
| 57 |
+
"label2id": {
|
| 58 |
+
"LABEL_0": 0,
|
| 59 |
+
"LABEL_1": 1
|
| 60 |
+
},
|
| 61 |
+
"length_penalty": 1.0,
|
| 62 |
+
"max_length": 20,
|
| 63 |
+
"max_position_embeddings": 131072,
|
| 64 |
+
"min_length": 0,
|
| 65 |
+
"model_type": "video_mllama_text_model",
|
| 66 |
+
"no_repeat_ngram_size": 0,
|
| 67 |
+
"num_attention_heads": 32,
|
| 68 |
+
"num_beam_groups": 1,
|
| 69 |
+
"num_beams": 1,
|
| 70 |
+
"num_hidden_layers": 40,
|
| 71 |
+
"num_key_value_heads": 8,
|
| 72 |
+
"num_return_sequences": 1,
|
| 73 |
+
"output_attentions": false,
|
| 74 |
+
"output_hidden_states": false,
|
| 75 |
+
"output_scores": false,
|
| 76 |
+
"pad_token_id": 128004,
|
| 77 |
+
"prefix": null,
|
| 78 |
+
"problem_type": null,
|
| 79 |
+
"pruned_heads": {},
|
| 80 |
+
"remove_invalid_values": false,
|
| 81 |
+
"repetition_penalty": 1.0,
|
| 82 |
+
"return_dict": true,
|
| 83 |
+
"return_dict_in_generate": false,
|
| 84 |
+
"rms_norm_eps": 1e-05,
|
| 85 |
"rope_scaling": {
|
| 86 |
"factor": 8.0,
|
| 87 |
"high_freq_factor": 4.0,
|
|
|
|
| 89 |
"original_max_position_embeddings": 8192,
|
| 90 |
"rope_type": "llama3"
|
| 91 |
},
|
| 92 |
+
"rope_theta": 500000.0,
|
| 93 |
+
"sep_token_id": null,
|
| 94 |
+
"suppress_tokens": null,
|
| 95 |
+
"task_specific_params": null,
|
| 96 |
+
"temperature": 1.0,
|
| 97 |
+
"tf_legacy_loss": false,
|
| 98 |
+
"tie_encoder_decoder": false,
|
| 99 |
+
"tie_word_embeddings": false,
|
| 100 |
+
"tokenizer_class": null,
|
| 101 |
+
"top_k": 50,
|
| 102 |
+
"top_p": 1.0,
|
| 103 |
+
"torch_dtype": "bfloat16",
|
| 104 |
+
"torchscript": false,
|
| 105 |
+
"typical_p": 1.0,
|
| 106 |
+
"use_bfloat16": false,
|
| 107 |
+
"use_cache": true,
|
| 108 |
+
"vocab_size": 128256
|
| 109 |
},
|
| 110 |
"torch_dtype": "bfloat16",
|
| 111 |
"transformers_version": "4.47.1",
|
|
|
|
| 112 |
"vision_config": {
|
| 113 |
+
"_name_or_path": "",
|
| 114 |
+
"add_cross_attention": false,
|
| 115 |
+
"vision_ignore_attention_mask": true,
|
| 116 |
+
"merge_size": 4,
|
| 117 |
+
"merge_mode": "average",
|
| 118 |
+
"architectures": null,
|
| 119 |
+
"attention_heads": 16,
|
| 120 |
+
"bad_words_ids": null,
|
| 121 |
+
"begin_suppress_tokens": null,
|
| 122 |
+
"bos_token_id": null,
|
| 123 |
+
"chunk_size_feed_forward": 0,
|
| 124 |
+
"cross_attention_hidden_size": null,
|
| 125 |
+
"decoder_start_token_id": null,
|
| 126 |
+
"diversity_penalty": 0.0,
|
| 127 |
+
"do_sample": false,
|
| 128 |
+
"early_stopping": false,
|
| 129 |
+
"encoder_no_repeat_ngram_size": 0,
|
| 130 |
+
"eos_token_id": null,
|
| 131 |
+
"exponential_decay_length_penalty": null,
|
| 132 |
+
"finetuning_task": null,
|
| 133 |
+
"forced_bos_token_id": null,
|
| 134 |
+
"forced_eos_token_id": null,
|
| 135 |
+
"hidden_act": "gelu",
|
| 136 |
+
"hidden_size": 1280,
|
| 137 |
+
"id2label": {
|
| 138 |
+
"0": "LABEL_0",
|
| 139 |
+
"1": "LABEL_1"
|
| 140 |
+
},
|
| 141 |
"image_size": 560,
|
| 142 |
+
"intermediate_layers_indices": [
|
| 143 |
+
3,
|
| 144 |
+
7,
|
| 145 |
+
15,
|
| 146 |
+
23,
|
| 147 |
+
30
|
| 148 |
+
],
|
| 149 |
+
"intermediate_size": 5120,
|
| 150 |
+
"is_decoder": false,
|
| 151 |
+
"is_encoder_decoder": false,
|
| 152 |
+
"label2id": {
|
| 153 |
+
"LABEL_0": 0,
|
| 154 |
+
"LABEL_1": 1
|
| 155 |
+
},
|
| 156 |
+
"length_penalty": 1.0,
|
| 157 |
+
"max_length": 20,
|
| 158 |
+
"max_num_tiles": 4,
|
| 159 |
+
"min_length": 0,
|
| 160 |
+
"model_type": "video_mllama_vision_model",
|
| 161 |
+
"no_repeat_ngram_size": 0,
|
| 162 |
+
"norm_eps": 1e-05,
|
| 163 |
+
"num_beam_groups": 1,
|
| 164 |
+
"num_beams": 1,
|
| 165 |
+
"num_channels": 3,
|
| 166 |
+
"num_global_layers": 8,
|
| 167 |
+
"num_hidden_layers": 32,
|
| 168 |
+
"num_return_sequences": 1,
|
| 169 |
+
"output_attentions": false,
|
| 170 |
+
"output_hidden_states": false,
|
| 171 |
+
"output_scores": false,
|
| 172 |
+
"pad_token_id": null,
|
| 173 |
+
"patch_size": 14,
|
| 174 |
+
"prefix": null,
|
| 175 |
+
"problem_type": null,
|
| 176 |
+
"pruned_heads": {},
|
| 177 |
+
"remove_invalid_values": false,
|
| 178 |
+
"repetition_penalty": 1.0,
|
| 179 |
+
"return_dict": true,
|
| 180 |
+
"return_dict_in_generate": false,
|
| 181 |
+
"sep_token_id": null,
|
| 182 |
+
"supported_aspect_ratios": [
|
| 183 |
+
[
|
| 184 |
+
1,
|
| 185 |
+
1
|
| 186 |
+
],
|
| 187 |
+
[
|
| 188 |
+
1,
|
| 189 |
+
2
|
| 190 |
+
],
|
| 191 |
+
[
|
| 192 |
+
1,
|
| 193 |
+
3
|
| 194 |
+
],
|
| 195 |
+
[
|
| 196 |
+
1,
|
| 197 |
+
4
|
| 198 |
+
],
|
| 199 |
+
[
|
| 200 |
+
2,
|
| 201 |
+
1
|
| 202 |
+
],
|
| 203 |
+
[
|
| 204 |
+
2,
|
| 205 |
+
2
|
| 206 |
+
],
|
| 207 |
+
[
|
| 208 |
+
3,
|
| 209 |
+
1
|
| 210 |
+
],
|
| 211 |
+
[
|
| 212 |
+
4,
|
| 213 |
+
1
|
| 214 |
+
]
|
| 215 |
+
],
|
| 216 |
+
"suppress_tokens": null,
|
| 217 |
+
"task_specific_params": null,
|
| 218 |
+
"temperature": 1.0,
|
| 219 |
+
"tf_legacy_loss": false,
|
| 220 |
+
"tie_encoder_decoder": false,
|
| 221 |
+
"tie_word_embeddings": true,
|
| 222 |
+
"tokenizer_class": null,
|
| 223 |
+
"top_k": 50,
|
| 224 |
+
"top_p": 1.0,
|
| 225 |
+
"torch_dtype": "bfloat16",
|
| 226 |
+
"torchscript": false,
|
| 227 |
+
"typical_p": 1.0,
|
| 228 |
+
"use_bfloat16": false,
|
| 229 |
+
"vision_output_dim": 7680
|
| 230 |
}
|
| 231 |
}
|
configuration_video_mllama.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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2024 HuggingFace Inc. team. All rights reserved.
|
| 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 |
+
"""VideoMllama model configuration"""
|
| 15 |
+
|
| 16 |
+
from typing import Dict, List, Optional
|
| 17 |
+
|
| 18 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 19 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
| 20 |
+
from transformers.utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class VideoMllamaVisionConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`VideoMllamaVisionModel`]. It is used to instantiate an
|
| 29 |
+
VideoMllama vision model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 30 |
+
with the defaults will yield a similar configuration to that of the VideoMllama-11B.
|
| 31 |
+
|
| 32 |
+
e.g. [meta-llama/Llama-3.2-11B-Vision](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision)
|
| 33 |
+
|
| 34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 35 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
hidden_size (`int`, *optional*, defaults to 1280):
|
| 39 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 40 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 41 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 42 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 44 |
+
Number of hidden layers in the Transformer encoder.
|
| 45 |
+
num_global_layers (`int`, *optional*, defaults to 8):
|
| 46 |
+
Number of global layers in the Transformer encoder.
|
| 47 |
+
Vision model has a second transformer encoder, called global.
|
| 48 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 49 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 50 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 51 |
+
Number of channels in the input image.
|
| 52 |
+
intermediate_size (`int`, *optional*, defaults to 5120):
|
| 53 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 54 |
+
vision_output_dim (`int`, *optional*, defaults to 7680):
|
| 55 |
+
Dimensionality of the vision model output. Includes output of transformer
|
| 56 |
+
encoder with intermediate layers and global transformer encoder.
|
| 57 |
+
image_size (`int`, *optional*, defaults to 448):
|
| 58 |
+
The size (resolution) of each image *tile*.
|
| 59 |
+
patch_size (`int`, *optional*, defaults to 14):
|
| 60 |
+
The size (resolution) of each patch.
|
| 61 |
+
norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 62 |
+
The epsilon used by the layer normalization layers.
|
| 63 |
+
max_num_tiles (`int`, *optional*, defaults to 4):
|
| 64 |
+
Maximum number of tiles for image splitting.
|
| 65 |
+
intermediate_layers_indices (`List[int]`, *optional*, defaults to [3, 7, 15, 23, 30]):
|
| 66 |
+
Indices of intermediate layers of transformer encoder from which to extract and output features.
|
| 67 |
+
These output features are concatenated with final hidden state of transformer encoder.
|
| 68 |
+
supported_aspect_ratios (`List[List[int]]`, *optional*):
|
| 69 |
+
List of supported aspect ratios for image splitting. If not specified, the default supported aspect ratios
|
| 70 |
+
are [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]] for `max_num_tiles=4`.
|
| 71 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 72 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 73 |
+
|
| 74 |
+
Example:
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
>>> from transformers import VideoMllamaVisionConfig, VideoMllamaVisionModel
|
| 78 |
+
|
| 79 |
+
>>> # Initializing a Llama config
|
| 80 |
+
>>> config = VideoMllamaVisionConfig()
|
| 81 |
+
|
| 82 |
+
>>> # Initializing a vision model from the VideoMllama-11b style configuration
|
| 83 |
+
>>> model = VideoMllamaVisionModel(config)
|
| 84 |
+
|
| 85 |
+
>>> # Accessing the model configuration
|
| 86 |
+
>>> configuration = model.config
|
| 87 |
+
```"""
|
| 88 |
+
|
| 89 |
+
model_type = "video_mllama_vision_model"
|
| 90 |
+
base_config_key = "vision_config"
|
| 91 |
+
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
hidden_size: int = 1280,
|
| 95 |
+
hidden_act: str = "gelu",
|
| 96 |
+
num_hidden_layers: int = 32,
|
| 97 |
+
num_global_layers: int = 8,
|
| 98 |
+
num_attention_heads: int = 16,
|
| 99 |
+
num_channels: int = 3,
|
| 100 |
+
intermediate_size: int = 5120,
|
| 101 |
+
vision_output_dim: int = 7680,
|
| 102 |
+
image_size: int = 448,
|
| 103 |
+
patch_size: int = 14,
|
| 104 |
+
norm_eps: float = 1e-5,
|
| 105 |
+
max_num_tiles: int = 4,
|
| 106 |
+
intermediate_layers_indices: Optional[List[int]] = None,
|
| 107 |
+
supported_aspect_ratios: Optional[List[List[int]]] = None,
|
| 108 |
+
initializer_range: float = 0.02,
|
| 109 |
+
vision_ignore_attention_mask: bool = True,
|
| 110 |
+
merge_size: int = 4,
|
| 111 |
+
merge_mode: str = "average",
|
| 112 |
+
**kwargs,
|
| 113 |
+
):
|
| 114 |
+
if supported_aspect_ratios is None:
|
| 115 |
+
if max_num_tiles != 4:
|
| 116 |
+
raise ValueError("max_num_tiles must be 4 for default supported aspect ratios")
|
| 117 |
+
supported_aspect_ratios = [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]]
|
| 118 |
+
|
| 119 |
+
if intermediate_layers_indices is None:
|
| 120 |
+
intermediate_layers_indices = [3, 7, 15, 23, 30]
|
| 121 |
+
|
| 122 |
+
self.hidden_size = hidden_size
|
| 123 |
+
self.hidden_act = hidden_act
|
| 124 |
+
self.num_hidden_layers = num_hidden_layers
|
| 125 |
+
self.num_channels = num_channels
|
| 126 |
+
self.intermediate_size = intermediate_size
|
| 127 |
+
self.image_size = image_size
|
| 128 |
+
self.vision_output_dim = vision_output_dim
|
| 129 |
+
self.patch_size = patch_size
|
| 130 |
+
self.intermediate_layers_indices = intermediate_layers_indices
|
| 131 |
+
self.num_global_layers = num_global_layers
|
| 132 |
+
self.max_num_tiles = max_num_tiles
|
| 133 |
+
self.norm_eps = norm_eps
|
| 134 |
+
self.attention_heads = num_attention_heads
|
| 135 |
+
self.supported_aspect_ratios = supported_aspect_ratios
|
| 136 |
+
self.initializer_range = initializer_range
|
| 137 |
+
self.vision_ignore_attention_mask = vision_ignore_attention_mask
|
| 138 |
+
self.merge_size = merge_size
|
| 139 |
+
self.merge_mode = merge_mode
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
super().__init__(**kwargs)
|
| 143 |
+
|
| 144 |
+
@property
|
| 145 |
+
def max_aspect_ratio_id(self) -> int:
|
| 146 |
+
return len(self.supported_aspect_ratios)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class VideoMllamaTextConfig(PretrainedConfig):
|
| 150 |
+
r"""
|
| 151 |
+
This is the configuration class to store the configuration of a [`VideoMllamaTextModel`]. It is used to instantiate an
|
| 152 |
+
VideoMllama text model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 153 |
+
with the defaults will yield a similar configuration to that of the VideoMllama-11B.
|
| 154 |
+
|
| 155 |
+
e.g. [meta-llama/Llama-3.2-11B-Vision](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision)
|
| 156 |
+
|
| 157 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 158 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
vocab_size (`int`, *optional*, defaults to 128256):
|
| 162 |
+
Vocabulary size of the VideoMllama text model. Defines the maximum number of different tokens that can be represented
|
| 163 |
+
by the `inputs_ids` passed when calling [`VideoMllamaTextModel`].
|
| 164 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 165 |
+
Dimensionality of the embeddings and hidden states.
|
| 166 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"silu"`):
|
| 167 |
+
The non-linear activation function (function or string) in the encoder and pooler.
|
| 168 |
+
num_hidden_layers (`int`, *optional*, defaults to 40):
|
| 169 |
+
Number of hidden layers in the Transformer encoder.
|
| 170 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 171 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 172 |
+
num_key_value_heads (`int`, *optional*, defaults to 8):
|
| 173 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If not
|
| 174 |
+
specified, will default to `num_attention_heads`.
|
| 175 |
+
intermediate_size (`int`, *optional*, defaults to 14336):
|
| 176 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 177 |
+
rope_theta (`float`, *optional*, defaults to `500000.0`):
|
| 178 |
+
The base period of the RoPE embeddings.
|
| 179 |
+
rope_scaling (`Dict`, *optional*):
|
| 180 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
| 181 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
| 182 |
+
accordingly.
|
| 183 |
+
Expected contents:
|
| 184 |
+
`rope_type` (`str`):
|
| 185 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
| 186 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
| 187 |
+
`factor` (`float`, *optional*):
|
| 188 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
| 189 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
| 190 |
+
original maximum pre-trained length.
|
| 191 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
| 192 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
| 193 |
+
pretraining.
|
| 194 |
+
`attention_factor` (`float`, *optional*):
|
| 195 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
| 196 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
| 197 |
+
`factor` field to infer the suggested value.
|
| 198 |
+
`beta_fast` (`float`, *optional*):
|
| 199 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
| 200 |
+
ramp function. If unspecified, it defaults to 32.
|
| 201 |
+
`beta_slow` (`float`, *optional*):
|
| 202 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
| 203 |
+
ramp function. If unspecified, it defaults to 1.
|
| 204 |
+
`short_factor` (`List[float]`, *optional*):
|
| 205 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
| 206 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 207 |
+
size divided by the number of attention heads divided by 2
|
| 208 |
+
`long_factor` (`List[float]`, *optional*):
|
| 209 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
| 210 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 211 |
+
size divided by the number of attention heads divided by 2
|
| 212 |
+
`low_freq_factor` (`float`, *optional*):
|
| 213 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
| 214 |
+
`high_freq_factor` (`float`, *optional*):
|
| 215 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
| 216 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 217 |
+
The epsilon used by the rms normalization layers.
|
| 218 |
+
max_position_embeddings (`int`, *optional*, defaults to 131072):
|
| 219 |
+
The maximum sequence length that this model might ever be used with.
|
| 220 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 221 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 222 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 223 |
+
Whether or not the model should return the last key/values attentions.
|
| 224 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 225 |
+
Whether to tie weight embeddings
|
| 226 |
+
cross_attention_layers (`List[int]`, *optional*):
|
| 227 |
+
Indices of the cross attention layers. If not specified, will default to [3, 8, 13, 18, 23, 28, 33, 38].
|
| 228 |
+
dropout (`float`, *optional*, defaults to 0):
|
| 229 |
+
The dropout probability for self- and cross-attention layers.
|
| 230 |
+
bos_token_id (`int`, *optional*, defaults to 128000):
|
| 231 |
+
The id of the beginning of sentence token.
|
| 232 |
+
eos_token_id (`int`, *optional*, defaults to 128001):
|
| 233 |
+
The id of the end of sentence token.
|
| 234 |
+
pad_token_id (`int`, *optional*, defaults to 128004):
|
| 235 |
+
The id of the padding token.
|
| 236 |
+
|
| 237 |
+
Example:
|
| 238 |
+
|
| 239 |
+
```python
|
| 240 |
+
>>> from transformers import VideoMllamaTextModel, VideoMllamaTextConfig
|
| 241 |
+
|
| 242 |
+
>>> # Initializing a VideoMllama text config
|
| 243 |
+
>>> config = VideoMllamaTextConfig()
|
| 244 |
+
|
| 245 |
+
>>> # Initializing a model from the VideoMllama text configuration
|
| 246 |
+
>>> model = VideoMllamaTextModel(config)
|
| 247 |
+
|
| 248 |
+
>>> # Accessing the model configuration
|
| 249 |
+
>>> configuration = model.config
|
| 250 |
+
```"""
|
| 251 |
+
|
| 252 |
+
model_type = "video_mllama_text_model"
|
| 253 |
+
base_config_key = "text_config"
|
| 254 |
+
|
| 255 |
+
def __init__(
|
| 256 |
+
self,
|
| 257 |
+
vocab_size: int = 128256,
|
| 258 |
+
hidden_size: int = 4096,
|
| 259 |
+
hidden_act: str = "silu",
|
| 260 |
+
num_hidden_layers: int = 40,
|
| 261 |
+
num_attention_heads: int = 32,
|
| 262 |
+
num_key_value_heads: int = 8,
|
| 263 |
+
intermediate_size: int = 14_336,
|
| 264 |
+
rope_theta: float = 500_000,
|
| 265 |
+
rope_scaling: Optional[Dict] = None,
|
| 266 |
+
rms_norm_eps: float = 1e-5,
|
| 267 |
+
max_position_embeddings: int = 131_072,
|
| 268 |
+
initializer_range: float = 0.02,
|
| 269 |
+
use_cache: bool = True,
|
| 270 |
+
tie_word_embeddings: bool = False,
|
| 271 |
+
cross_attention_layers: Optional[List[int]] = None,
|
| 272 |
+
dropout: float = 0,
|
| 273 |
+
bos_token_id: int = 128000,
|
| 274 |
+
eos_token_id: int = 128001,
|
| 275 |
+
pad_token_id: Optional[int] = 128004,
|
| 276 |
+
**kwargs,
|
| 277 |
+
):
|
| 278 |
+
if cross_attention_layers is None:
|
| 279 |
+
cross_attention_layers = [3, 8, 13, 18, 23, 28, 33, 38]
|
| 280 |
+
|
| 281 |
+
self.vocab_size = vocab_size
|
| 282 |
+
self.num_hidden_layers = num_hidden_layers
|
| 283 |
+
self.cross_attention_layers = cross_attention_layers
|
| 284 |
+
self.hidden_size = hidden_size
|
| 285 |
+
self.num_attention_heads = num_attention_heads
|
| 286 |
+
self.num_key_value_heads = num_key_value_heads
|
| 287 |
+
self.initializer_range = initializer_range
|
| 288 |
+
self.use_cache = use_cache
|
| 289 |
+
self.rope_theta = rope_theta
|
| 290 |
+
self.rms_norm_eps = rms_norm_eps
|
| 291 |
+
self.intermediate_size = intermediate_size
|
| 292 |
+
self.dropout = dropout
|
| 293 |
+
self.hidden_act = hidden_act
|
| 294 |
+
self.rope_scaling = rope_scaling
|
| 295 |
+
self.max_position_embeddings = max_position_embeddings
|
| 296 |
+
rope_config_validation(self)
|
| 297 |
+
|
| 298 |
+
super().__init__(
|
| 299 |
+
pad_token_id=pad_token_id,
|
| 300 |
+
bos_token_id=bos_token_id,
|
| 301 |
+
eos_token_id=eos_token_id,
|
| 302 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 303 |
+
**kwargs,
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class VideoMllamaConfig(PretrainedConfig):
|
| 308 |
+
r"""
|
| 309 |
+
This is the configuration class to store the configuration of a [`VideoMllamaForConditionalGeneration`]. It is used to instantiate an
|
| 310 |
+
VideoMllama model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 311 |
+
with the defaults will yield a similar configuration to that of the VideoMllama-9B.
|
| 312 |
+
|
| 313 |
+
e.g. [meta-llama/Llama-3.2-11B-Vision](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision)
|
| 314 |
+
|
| 315 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 316 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 317 |
+
|
| 318 |
+
Args:
|
| 319 |
+
vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `VideoMllamaVisionConfig`):
|
| 320 |
+
The config object or dictionary of the vision backbone.
|
| 321 |
+
text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `VideoMllamaTextConfig`):
|
| 322 |
+
The config object or dictionary of the text backbone.
|
| 323 |
+
image_token_index (`int`, *optional*, defaults to 128256):
|
| 324 |
+
The image token index to encode the image prompt.
|
| 325 |
+
|
| 326 |
+
Example:
|
| 327 |
+
|
| 328 |
+
```python
|
| 329 |
+
>>> from transformers import VideoMllamaForConditionalGeneration, VideoMllamaConfig, VideoMllamaVisionConfig, VideoMllamaTextConfig
|
| 330 |
+
|
| 331 |
+
>>> # Initializing a CLIP-vision config
|
| 332 |
+
>>> vision_config = VideoMllamaVisionConfig()
|
| 333 |
+
|
| 334 |
+
>>> # Initializing a Llama config
|
| 335 |
+
>>> text_config = VideoMllamaTextConfig()
|
| 336 |
+
|
| 337 |
+
>>> # Initializing a VideoMllama-11b style configuration
|
| 338 |
+
>>> configuration = VideoMllamaConfig(vision_config, text_config)
|
| 339 |
+
|
| 340 |
+
>>> # Initializing a model from the VideoMllama-11b style configuration
|
| 341 |
+
>>> model = VideoMllamaForConditionalGeneration(configuration)
|
| 342 |
+
|
| 343 |
+
>>> # Accessing the model configuration
|
| 344 |
+
>>> configuration = model.config
|
| 345 |
+
```"""
|
| 346 |
+
|
| 347 |
+
model_type = "video_mllama"
|
| 348 |
+
sub_configs = {"text_config": VideoMllamaTextConfig, "vision_config": VideoMllamaVisionConfig}
|
| 349 |
+
|
| 350 |
+
def __init__(
|
| 351 |
+
self,
|
| 352 |
+
vision_config=None,
|
| 353 |
+
text_config=None,
|
| 354 |
+
image_token_index=128256,
|
| 355 |
+
**kwargs,
|
| 356 |
+
):
|
| 357 |
+
if vision_config is None:
|
| 358 |
+
self.vision_config = VideoMllamaVisionConfig()
|
| 359 |
+
logger.info("vision_config is None, using default VideoMllama vision config")
|
| 360 |
+
elif isinstance(vision_config, dict):
|
| 361 |
+
self.vision_config = VideoMllamaVisionConfig(**vision_config)
|
| 362 |
+
elif isinstance(vision_config, VideoMllamaVisionConfig):
|
| 363 |
+
self.vision_config = vision_config
|
| 364 |
+
|
| 365 |
+
self.image_token_index = image_token_index
|
| 366 |
+
|
| 367 |
+
if text_config is None:
|
| 368 |
+
self.text_config = VideoMllamaTextConfig()
|
| 369 |
+
logger.info("text_config is None, using default VideoMllama text config")
|
| 370 |
+
elif isinstance(text_config, dict):
|
| 371 |
+
self.text_config = VideoMllamaTextConfig(**text_config)
|
| 372 |
+
elif isinstance(text_config, VideoMllamaTextConfig):
|
| 373 |
+
self.text_config = text_config
|
| 374 |
+
|
| 375 |
+
super().__init__(**kwargs)
|
image_processing_video_mllama.py
ADDED
|
@@ -0,0 +1,930 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 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 |
+
import math
|
| 17 |
+
from functools import lru_cache
|
| 18 |
+
from typing import Dict, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
|
| 23 |
+
from transformers.image_transforms import (
|
| 24 |
+
PaddingMode,
|
| 25 |
+
get_image_size,
|
| 26 |
+
pad,
|
| 27 |
+
resize,
|
| 28 |
+
)
|
| 29 |
+
from transformers.image_utils import (
|
| 30 |
+
IMAGENET_STANDARD_MEAN,
|
| 31 |
+
IMAGENET_STANDARD_STD,
|
| 32 |
+
ChannelDimension,
|
| 33 |
+
ImageInput,
|
| 34 |
+
PILImageResampling,
|
| 35 |
+
infer_channel_dimension_format,
|
| 36 |
+
is_valid_image,
|
| 37 |
+
is_vision_available,
|
| 38 |
+
to_numpy_array,
|
| 39 |
+
validate_preprocess_arguments,
|
| 40 |
+
)
|
| 41 |
+
from transformers.utils import TensorType, logging
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if is_vision_available():
|
| 45 |
+
import PIL
|
| 46 |
+
from PIL import Image
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
logger = logging.get_logger(__name__)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@lru_cache(maxsize=10)
|
| 53 |
+
def get_all_supported_aspect_ratios(max_image_tiles: int) -> List[Tuple[int, int]]:
|
| 54 |
+
"""
|
| 55 |
+
Computes all allowed aspect ratios for a given maximum number of input tiles.
|
| 56 |
+
|
| 57 |
+
This function calculates all possible arrangements of tiles that can be formed
|
| 58 |
+
within the constraint of the maximum number of tiles. Each arrangement is
|
| 59 |
+
represented by its aspect ratio (width/height) and the corresponding tile configuration.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
max_image_tiles (`int`):
|
| 63 |
+
The maximum number of tiles allowed.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
`List[Tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height)
|
| 67 |
+
configuration in terms of number of tiles.
|
| 68 |
+
|
| 69 |
+
Example:
|
| 70 |
+
>>> get_all_supported_aspect_ratios(4)
|
| 71 |
+
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1), (4, 1)]
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
aspect_ratios = []
|
| 75 |
+
for width in range(1, max_image_tiles + 1):
|
| 76 |
+
for height in range(1, max_image_tiles + 1):
|
| 77 |
+
if width * height <= max_image_tiles:
|
| 78 |
+
aspect_ratios.append((width, height))
|
| 79 |
+
return aspect_ratios
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_image_size_fit_to_canvas(
|
| 83 |
+
image_height: int,
|
| 84 |
+
image_width: int,
|
| 85 |
+
canvas_height: int,
|
| 86 |
+
canvas_width: int,
|
| 87 |
+
tile_size: int,
|
| 88 |
+
) -> Tuple[int, int]:
|
| 89 |
+
"""
|
| 90 |
+
Calculates the new size of an image to fit within a canvas while maintaining aspect ratio.
|
| 91 |
+
|
| 92 |
+
This function calculates the optimal size for an image to fit within a canvas defined by
|
| 93 |
+
canvas_height and canvas_width, while ensuring that the image dimensions are not smaller than
|
| 94 |
+
tile_size. If the image is larger than the canvas, the returned size will fit within the canvas.
|
| 95 |
+
If the image already fits within the canvas, the size remains unchanged.
|
| 96 |
+
The aspect ratio of the original image is preserved.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
image_height (`int`):
|
| 100 |
+
The height of the original image.
|
| 101 |
+
image_width (`int`):
|
| 102 |
+
The width of the original image.
|
| 103 |
+
canvas_height (`int`):
|
| 104 |
+
The height of the canvas.
|
| 105 |
+
canvas_width (`int`):
|
| 106 |
+
The width of the canvas.
|
| 107 |
+
tile_size (`int`):
|
| 108 |
+
The tile size.
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
`Tuple[int, int]`: A tuple containing the new height and width of the image.
|
| 112 |
+
|
| 113 |
+
"""
|
| 114 |
+
# Set target image size in between `tile_size` and canvas_size
|
| 115 |
+
target_width = np.clip(image_width, tile_size, canvas_width)
|
| 116 |
+
target_height = np.clip(image_height, tile_size, canvas_height)
|
| 117 |
+
|
| 118 |
+
scale_h = target_height / image_height
|
| 119 |
+
scale_w = target_width / image_width
|
| 120 |
+
|
| 121 |
+
if scale_w < scale_h:
|
| 122 |
+
new_width = target_width
|
| 123 |
+
new_height = min(math.floor(image_height * scale_w), target_height)
|
| 124 |
+
else:
|
| 125 |
+
new_height = target_height
|
| 126 |
+
new_width = min(math.floor(image_width * scale_h), target_width)
|
| 127 |
+
|
| 128 |
+
return new_height, new_width
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@lru_cache(maxsize=100)
|
| 132 |
+
def get_optimal_tiled_canvas(
|
| 133 |
+
image_height: int,
|
| 134 |
+
image_width: int,
|
| 135 |
+
max_image_tiles: int,
|
| 136 |
+
tile_size: int,
|
| 137 |
+
) -> Tuple[int, int]:
|
| 138 |
+
r"""
|
| 139 |
+
Determines the best canvas based on image and tile size and maximum number of tiles.
|
| 140 |
+
|
| 141 |
+
First, calculates possible resolutions based on the maximum number of tiles and tile size.
|
| 142 |
+
For example for max_image_tiles=2, tile_size=100, possible tile arrangements are:
|
| 143 |
+
[(1, 1), (1, 2), (2, 1)] and corresponding canvas sizes are:
|
| 144 |
+
[(100, 100), (100, 200), (200, 100)]
|
| 145 |
+
|
| 146 |
+
For each possible resolution, calculates the scaling factors for
|
| 147 |
+
width and height, and selects the smallest one, which is the limiting side.
|
| 148 |
+
E.g. to match the canvas you can upscale height by 2x, and width by 1.5x,
|
| 149 |
+
therefore, the maximum upscaling you can do is min(2, 1.5) = 1.5.
|
| 150 |
+
|
| 151 |
+
If upscaling is possible (any of the scaling factors is greater than 1),
|
| 152 |
+
then picks the smallest upscaling factor > 1.
|
| 153 |
+
|
| 154 |
+
If upscaling is not possible, then picks the largest scaling factor <= 1, i.e.
|
| 155 |
+
reduce downscaling as much as possible.
|
| 156 |
+
|
| 157 |
+
If there are multiple resolutions with the same max scale, we pick the one with the lowest area,
|
| 158 |
+
to minimize padding. E.g., the same image can be upscaled to 224x224 and 224x448, but the latter
|
| 159 |
+
has more padding.
|
| 160 |
+
|
| 161 |
+
Example of canvases made from tiles:
|
| 162 |
+
|
| 163 |
+
To visualize how the image can fit onto different tile grids, let's try fitting an ASCII cat into the tiles.
|
| 164 |
+
|
| 165 |
+
Here's an ASCII cat image you want to fit into the tiles:
|
| 166 |
+
|
| 167 |
+
/\_/\
|
| 168 |
+
( o.o )
|
| 169 |
+
> ^ <
|
| 170 |
+
|
| 171 |
+
If `num_tiles=6`, possible tile grids would look like this:
|
| 172 |
+
|
| 173 |
+
**2x3 Canvas (2 tiles wide, 3 tiles tall)**: -> total of 6 tiles
|
| 174 |
+
+-------+-------+
|
| 175 |
+
| /\_/\ | 0 | <- Cat image split across two tiles horizontally
|
| 176 |
+
+-------+-------+
|
| 177 |
+
| > ^ < | 0 | <- Remaining part of the cat occupies the left tile
|
| 178 |
+
+-------+-------+
|
| 179 |
+
|( o.o )| 0 |
|
| 180 |
+
+-------+-------+
|
| 181 |
+
|
| 182 |
+
**3x2 Canvas (3 tiles wide, 2 tiles tall)**: -> total of 6 tiles
|
| 183 |
+
+-------+-------+-------+
|
| 184 |
+
| /\_/\ |( o.o )| 0 | <- Cat image occupies the first two tiles, 1 tile remains empty
|
| 185 |
+
+-------+-------+-------+
|
| 186 |
+
| > ^ < | 0 | 0 | <- Remaining part of the cat occupies the left tile
|
| 187 |
+
+-------+-------+-------+
|
| 188 |
+
|
| 189 |
+
**1x6 Canvas (1 tile wide, 6 tiles tall)**: -> total of 6 tiles
|
| 190 |
+
+-------+
|
| 191 |
+
| /\_/\ | <- Top part of the cat
|
| 192 |
+
+-------+
|
| 193 |
+
|( o.o )| <- Middle part of the cat
|
| 194 |
+
+-------+
|
| 195 |
+
| > ^ < | <- Bottom part of the cat
|
| 196 |
+
+-------+
|
| 197 |
+
| 0 |
|
| 198 |
+
+-------+
|
| 199 |
+
| 0 |
|
| 200 |
+
+-------+
|
| 201 |
+
| 0 |
|
| 202 |
+
+-------+
|
| 203 |
+
|
| 204 |
+
Given that the tiles you get depend on the chosen aspect ratio, you have to add
|
| 205 |
+
embedding in the modeling code to help it know if it got a 3x2 or a 1x6 or a 2x3
|
| 206 |
+
aspect ratio.
|
| 207 |
+
|
| 208 |
+
The function tests these arrangements to find the smallest canvas where the image fits.
|
| 209 |
+
If multiple canvases fit, it selects the one where the dimensions are closest to the image size.
|
| 210 |
+
|
| 211 |
+
In this case the first canvas is the closest to the original image.
|
| 212 |
+
|
| 213 |
+
You then feed all of the tiles to the model:
|
| 214 |
+
|
| 215 |
+
+-------+-------+-------+-------+-------+-------+
|
| 216 |
+
- | /\_/\ |( o.o )| > ^ < | 0 | 0 | 0 | <- Last canvas
|
| 217 |
+
+-------+-------+-------+-------+-------+-------+
|
| 218 |
+
|
| 219 |
+
+-------+-------+-------+-------+-------+-------+
|
| 220 |
+
- | /\_/\ | 0 |( o.o )| 0 | > ^ < | 0 | <- First canvas
|
| 221 |
+
+-------+-------+-------+-------+-------+-------+
|
| 222 |
+
|
| 223 |
+
+-------+-------+-------+-------+-------+-------+
|
| 224 |
+
- | /\_/\ |( o.o )| 0 | > ^ < | 0 | 0 | <- second canvas
|
| 225 |
+
+-------+-------+-------+-------+-------+-------+
|
| 226 |
+
|
| 227 |
+
For each tile, you have num_channels (usually RGB so 3), tile_width, tile_height
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
image_height (`int`):
|
| 231 |
+
The height of the image.
|
| 232 |
+
image_width (`int`):
|
| 233 |
+
The width of the image.
|
| 234 |
+
max_image_tiles (`int`):
|
| 235 |
+
The maximum number of tiles any image can be split into.
|
| 236 |
+
tile_size (`int`):
|
| 237 |
+
The tile size.
|
| 238 |
+
|
| 239 |
+
Returns:
|
| 240 |
+
`Tuple[int, int]`: The best canvas resolution [height, width] for the given image.
|
| 241 |
+
"""
|
| 242 |
+
possible_tile_arrangements = get_all_supported_aspect_ratios(max_image_tiles)
|
| 243 |
+
possible_canvas_sizes = np.array(possible_tile_arrangements) * tile_size
|
| 244 |
+
|
| 245 |
+
# get all possible resolutions heights/widths
|
| 246 |
+
target_heights, target_widths = np.array(possible_canvas_sizes).T
|
| 247 |
+
|
| 248 |
+
# get scaling factors to resize the image without distortion
|
| 249 |
+
scale_h = target_heights / image_height
|
| 250 |
+
scale_w = target_widths / image_width
|
| 251 |
+
|
| 252 |
+
# get the min scale between width and height (limiting side -> no distortion)
|
| 253 |
+
scales = np.where(scale_w > scale_h, scale_h, scale_w)
|
| 254 |
+
|
| 255 |
+
# filter only scales that allow upscaling
|
| 256 |
+
upscaling_options = scales[scales >= 1]
|
| 257 |
+
if len(upscaling_options) > 0:
|
| 258 |
+
selected_scale = np.min(upscaling_options)
|
| 259 |
+
else:
|
| 260 |
+
# no upscaling possible,
|
| 261 |
+
# get the minimum downscaling (max scale for scales<1)
|
| 262 |
+
downscaling_options = scales[scales < 1]
|
| 263 |
+
selected_scale = np.max(downscaling_options)
|
| 264 |
+
|
| 265 |
+
# get all resolutions that support this scaling factor,
|
| 266 |
+
# e.g. you can upscale to 224x224, 224x448, 224x672 without distortion
|
| 267 |
+
chosen_canvas = possible_canvas_sizes[scales == selected_scale]
|
| 268 |
+
|
| 269 |
+
# if there are multiple resolutions,
|
| 270 |
+
# get the one with minimum area to reduce padding
|
| 271 |
+
if len(chosen_canvas) > 1:
|
| 272 |
+
areas = chosen_canvas[:, 0] * chosen_canvas[:, 1]
|
| 273 |
+
optimal_idx = np.argmin(areas)
|
| 274 |
+
optimal_canvas = chosen_canvas[optimal_idx]
|
| 275 |
+
else:
|
| 276 |
+
optimal_canvas = chosen_canvas[0]
|
| 277 |
+
|
| 278 |
+
return optimal_canvas
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def split_to_tiles(image: np.ndarray, num_tiles_height: int, num_tiles_width: int) -> np.ndarray:
|
| 282 |
+
"""
|
| 283 |
+
Split an image into a specified number of tiles along its width and height dimensions.
|
| 284 |
+
|
| 285 |
+
Args:
|
| 286 |
+
image (`np.ndarray`):
|
| 287 |
+
Input image with shape (num_channels, height, width).
|
| 288 |
+
num_tiles_height (`int`):
|
| 289 |
+
Number of tiles to split the image into along its height.
|
| 290 |
+
num_tiles_width (`int`):
|
| 291 |
+
Number of tiles to split the image into along its width.
|
| 292 |
+
|
| 293 |
+
Returns:
|
| 294 |
+
`np.ndarray`:
|
| 295 |
+
Array of image tiles with shape (num_tiles_width * num_tiles_height, num_channels, tile_height, tile_width).
|
| 296 |
+
"""
|
| 297 |
+
num_channels, height, width = image.shape
|
| 298 |
+
tile_height = height // num_tiles_height
|
| 299 |
+
tile_width = width // num_tiles_width
|
| 300 |
+
|
| 301 |
+
image = image.reshape(num_channels, num_tiles_height, tile_height, num_tiles_width, tile_width)
|
| 302 |
+
|
| 303 |
+
# Permute to (num_tiles_height, num_tiles_width, num_channels, tile_height, tile_width)
|
| 304 |
+
image = image.transpose(1, 3, 0, 2, 4)
|
| 305 |
+
|
| 306 |
+
# Reshape into the desired output shape (num_tiles_width * num_tiles_height, num_channels, tile_height, tile_width)
|
| 307 |
+
image = image.reshape(num_tiles_width * num_tiles_height, num_channels, tile_height, tile_width)
|
| 308 |
+
|
| 309 |
+
return np.ascontiguousarray(image)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def build_aspect_ratio_mask(aspect_ratios: List[List[Tuple[int, int]]], max_image_tiles: int) -> np.ndarray:
|
| 313 |
+
"""
|
| 314 |
+
Builds a mask for the aspect ratios of the images.
|
| 315 |
+
|
| 316 |
+
Args:
|
| 317 |
+
aspect_ratios (`List[List[Tuple[int, int]]]`):
|
| 318 |
+
A list of lists containing aspect ratios for each image in the batch.
|
| 319 |
+
Each aspect ratio is represented as a tuple of (width, height) in terms of number of tiles.
|
| 320 |
+
max_image_tiles (`int`):
|
| 321 |
+
The maximum number of tiles any image can be split into.
|
| 322 |
+
|
| 323 |
+
Returns:
|
| 324 |
+
`np.ndarray`: A 3D numpy array of shape (batch_size, max_num_images, max_image_tiles).
|
| 325 |
+
The mask contains 1s for valid tiles and 0s for padding.
|
| 326 |
+
"""
|
| 327 |
+
batch_size = len(aspect_ratios)
|
| 328 |
+
max_num_images = max([len(row) for row in aspect_ratios])
|
| 329 |
+
|
| 330 |
+
aspect_ratio_mask = np.zeros((batch_size, max_num_images, max_image_tiles), dtype=np.int64)
|
| 331 |
+
|
| 332 |
+
# Set the first tile to 1 for all aspect ratios
|
| 333 |
+
# because in original implementation aspect ratios are padded with (1, 1),
|
| 334 |
+
# but original code examples are not built to handle batches, so we might remove it later
|
| 335 |
+
aspect_ratio_mask[:, :, 0] = 1
|
| 336 |
+
|
| 337 |
+
# Set the aspect ratio mask for the rest of the tiles
|
| 338 |
+
for i, sample_aspect_ratios in enumerate(aspect_ratios):
|
| 339 |
+
for j, (num_tiles_w, num_tiles_h) in enumerate(sample_aspect_ratios):
|
| 340 |
+
aspect_ratio_mask[i, j, : num_tiles_w * num_tiles_h] = 1
|
| 341 |
+
|
| 342 |
+
return aspect_ratio_mask
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def pack_images(
|
| 346 |
+
batch_images: List[List[np.ndarray]],
|
| 347 |
+
max_image_tiles: int,
|
| 348 |
+
) -> Tuple[np.ndarray, List[List[int]]]:
|
| 349 |
+
"""
|
| 350 |
+
Stack a list of lists of images with variable lengths into a numpy array, applying zero padding as needed.
|
| 351 |
+
Each list in the input represents a batch sample, and each image within a list is expected to be
|
| 352 |
+
pre-split into tiles. The resulting array will have a shape of
|
| 353 |
+
(batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width).
|
| 354 |
+
|
| 355 |
+
Args:
|
| 356 |
+
batch_images (`List[List[np.ndarray]]`):
|
| 357 |
+
A list of lists of image tiles. Each inner list represents
|
| 358 |
+
a batch sample containing multiple images, where each image is pre-split into tiles.
|
| 359 |
+
The shape of each tile array is (num_tiles, channels, tile_height, tile_width).
|
| 360 |
+
max_image_tiles (int):
|
| 361 |
+
The maximum number of tiles any image was potantially split.
|
| 362 |
+
|
| 363 |
+
Returns:
|
| 364 |
+
`Tuple[np.ndarray, List[List[int]]]`: A tuple containing:
|
| 365 |
+
- stacked_images (`np.ndarray`):
|
| 366 |
+
A numpy array of stacked images with shape
|
| 367 |
+
(batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width).
|
| 368 |
+
- all_num_tiles (`List[List[int]]`):
|
| 369 |
+
A list of lists containing the number of tiles
|
| 370 |
+
for each image in each batch sample.
|
| 371 |
+
"""
|
| 372 |
+
|
| 373 |
+
# Determine output shape
|
| 374 |
+
batch_size = len(batch_images)
|
| 375 |
+
max_num_images = max([len(images) for images in batch_images])
|
| 376 |
+
shapes = [image.shape for images in batch_images for image in images]
|
| 377 |
+
_, channels, tile_height, tile_width = shapes[0]
|
| 378 |
+
|
| 379 |
+
# Initialize the stacked images array with zeros
|
| 380 |
+
stacked_images = np.zeros(
|
| 381 |
+
(batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width),
|
| 382 |
+
dtype=np.float32,
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
# Fill the stacked images array with the tiled images from the batch
|
| 386 |
+
all_num_tiles = []
|
| 387 |
+
for i, images in enumerate(batch_images):
|
| 388 |
+
num_sample_tiles = []
|
| 389 |
+
for j, image in enumerate(images):
|
| 390 |
+
num_tiles = image.shape[0]
|
| 391 |
+
stacked_images[i, j, :num_tiles] = image
|
| 392 |
+
num_sample_tiles.append(num_tiles)
|
| 393 |
+
all_num_tiles.append(num_sample_tiles)
|
| 394 |
+
|
| 395 |
+
return stacked_images, all_num_tiles
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def pack_aspect_ratios(aspect_ratios: List[List[Tuple[int, int]]], pad_value: int = 1) -> np.ndarray:
|
| 399 |
+
"""
|
| 400 |
+
Stack a list of aspect ratios into a numpy array.
|
| 401 |
+
|
| 402 |
+
Args:
|
| 403 |
+
aspect_ratios (`List[List[Tuple[int, int]]]`):
|
| 404 |
+
A list of aspect ratios.
|
| 405 |
+
pad_value (`int`, *optional*, defaults to 1):
|
| 406 |
+
The value to pad the aspect ratios with.
|
| 407 |
+
|
| 408 |
+
Returns:
|
| 409 |
+
`np.ndarray`:
|
| 410 |
+
The aspect ratios stacked into a numpy array with shape (batch_size, max_num_images, 2).
|
| 411 |
+
"""
|
| 412 |
+
batch_size = len(aspect_ratios)
|
| 413 |
+
max_num_images = max([len(row) for row in aspect_ratios])
|
| 414 |
+
|
| 415 |
+
aspect_ratios_stacked = np.full((batch_size, max_num_images, 2), pad_value, dtype=np.int64)
|
| 416 |
+
for i, row in enumerate(aspect_ratios):
|
| 417 |
+
if len(row) > 0:
|
| 418 |
+
aspect_ratios_stacked[i, : len(row)] = np.array(row)
|
| 419 |
+
return aspect_ratios_stacked
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def convert_aspect_ratios_to_ids(aspect_ratios: List[List[Tuple[int, int]]], max_image_tiles: int) -> np.ndarray:
|
| 423 |
+
"""
|
| 424 |
+
Convert aspect ratio tuples to unique ids.
|
| 425 |
+
|
| 426 |
+
For batch padding we use 0, because there might be different number of images in each batch.
|
| 427 |
+
The aspect ratio ids start from 1, with 1 corresponding to the first supported aspect ratio.
|
| 428 |
+
|
| 429 |
+
Args:
|
| 430 |
+
aspect_ratios (`List[List[Tuple[int, int]]]`):
|
| 431 |
+
A list of aspect ratios for each image in the batch.
|
| 432 |
+
max_image_tiles (`int`):
|
| 433 |
+
The maximum number of tiles any image can be split into.
|
| 434 |
+
|
| 435 |
+
Returns:
|
| 436 |
+
`np.ndarray`:
|
| 437 |
+
The aspect ratios ids as a numpy array with shape (batch_size, max_num_images).
|
| 438 |
+
Each id corresponds to the index of the aspect ratio in the list of supported aspect ratios,
|
| 439 |
+
offset by 1 (so 0 can be used for padding).
|
| 440 |
+
"""
|
| 441 |
+
|
| 442 |
+
batch_size = len(aspect_ratios)
|
| 443 |
+
max_num_images = max([len(row) for row in aspect_ratios])
|
| 444 |
+
supported_aspect_ratios = get_all_supported_aspect_ratios(max_image_tiles)
|
| 445 |
+
|
| 446 |
+
aspect_ratios_ids = np.zeros((batch_size, max_num_images), dtype=np.int64)
|
| 447 |
+
for i, sample_aspect_ratios in enumerate(aspect_ratios):
|
| 448 |
+
for j, (num_tiles_h, num_tiles_w) in enumerate(sample_aspect_ratios):
|
| 449 |
+
aspect_ratios_ids[i, j] = supported_aspect_ratios.index((num_tiles_h, num_tiles_w)) + 1
|
| 450 |
+
return aspect_ratios_ids
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def to_channel_dimension_format(
|
| 454 |
+
image: np.ndarray,
|
| 455 |
+
channel_dim: Union[ChannelDimension, str],
|
| 456 |
+
input_channel_dim: Optional[Union[ChannelDimension, str]] = None,
|
| 457 |
+
) -> np.ndarray:
|
| 458 |
+
"""
|
| 459 |
+
Converts `image` to the channel dimension format specified by `channel_dim`.
|
| 460 |
+
|
| 461 |
+
Args:
|
| 462 |
+
image (`numpy.ndarray`):
|
| 463 |
+
The image to have its channel dimension set.
|
| 464 |
+
channel_dim (`ChannelDimension`):
|
| 465 |
+
The channel dimension format to use.
|
| 466 |
+
input_channel_dim (`ChannelDimension`, *optional*):
|
| 467 |
+
The channel dimension format of the input image. If not provided, it will be inferred from the input image.
|
| 468 |
+
|
| 469 |
+
Returns:
|
| 470 |
+
`np.ndarray`:
|
| 471 |
+
The image with the channel dimension set to `channel_dim`.
|
| 472 |
+
"""
|
| 473 |
+
if not isinstance(image, np.ndarray):
|
| 474 |
+
raise ValueError(f"Input image must be of type np.ndarray, got {type(image)}")
|
| 475 |
+
|
| 476 |
+
if input_channel_dim is None:
|
| 477 |
+
input_channel_dim = infer_channel_dimension_format(image)
|
| 478 |
+
|
| 479 |
+
target_channel_dim = ChannelDimension(channel_dim)
|
| 480 |
+
if input_channel_dim == target_channel_dim:
|
| 481 |
+
return image
|
| 482 |
+
|
| 483 |
+
if target_channel_dim == ChannelDimension.FIRST:
|
| 484 |
+
image = image.transpose((2, 0, 1))
|
| 485 |
+
elif target_channel_dim == ChannelDimension.LAST:
|
| 486 |
+
image = image.transpose((1, 2, 0))
|
| 487 |
+
else:
|
| 488 |
+
raise ValueError("Unsupported channel dimension format: {}".format(channel_dim))
|
| 489 |
+
|
| 490 |
+
return image
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
# Copied from transformers.models.idefics2.image_processing_idefics2.convert_to_rgb
|
| 494 |
+
def convert_to_rgb(image: ImageInput) -> ImageInput:
|
| 495 |
+
"""
|
| 496 |
+
Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image
|
| 497 |
+
as is.
|
| 498 |
+
Args:
|
| 499 |
+
image (Image):
|
| 500 |
+
The image to convert.
|
| 501 |
+
"""
|
| 502 |
+
if not isinstance(image, PIL.Image.Image):
|
| 503 |
+
return image
|
| 504 |
+
|
| 505 |
+
# `image.convert("RGB")` would only work for .jpg images, as it creates a wrong background
|
| 506 |
+
# for transparent images. The call to `alpha_composite` handles this case
|
| 507 |
+
if image.mode == "RGB":
|
| 508 |
+
return image
|
| 509 |
+
|
| 510 |
+
image_rgba = image.convert("RGBA")
|
| 511 |
+
background = Image.new("RGBA", image_rgba.size, (255, 255, 255))
|
| 512 |
+
alpha_composite = Image.alpha_composite(background, image_rgba)
|
| 513 |
+
alpha_composite = alpha_composite.convert("RGB")
|
| 514 |
+
return alpha_composite
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
# Modified from transformers.models.idefics2.image_processing_idefics2.make_list_of_images
|
| 518 |
+
def make_list_of_images(images: ImageInput) -> List[List[Optional[np.ndarray]]]:
|
| 519 |
+
"""
|
| 520 |
+
Convert a single image or a list of images to a list of numpy arrays.
|
| 521 |
+
|
| 522 |
+
Args:
|
| 523 |
+
images (`ImageInput`):
|
| 524 |
+
A single image or a list of images.
|
| 525 |
+
|
| 526 |
+
Returns:
|
| 527 |
+
A list of numpy arrays.
|
| 528 |
+
"""
|
| 529 |
+
# If it's a single image, convert it to a list of lists
|
| 530 |
+
if is_valid_image(images):
|
| 531 |
+
output_images = [[images]]
|
| 532 |
+
# If it's a list of images, it's a single batch, so convert it to a list of lists
|
| 533 |
+
elif isinstance(images, (list, tuple)) and is_valid_list_of_images(images):
|
| 534 |
+
output_images = [images]
|
| 535 |
+
# If it's a list of batches, it's already in the right format
|
| 536 |
+
elif (
|
| 537 |
+
isinstance(images, (list, tuple))
|
| 538 |
+
and all(isinstance(images_i, (list, tuple)) for images_i in images)
|
| 539 |
+
and any(is_valid_list_of_images(images_i) for images_i in images)
|
| 540 |
+
):
|
| 541 |
+
output_images = images
|
| 542 |
+
else:
|
| 543 |
+
raise ValueError(
|
| 544 |
+
"Invalid input type. Must be a single image, a list of images, or a list of batches of images."
|
| 545 |
+
)
|
| 546 |
+
return output_images
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def is_valid_list_of_images(images: List):
|
| 550 |
+
return images and all(is_valid_image(image) for image in images)
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def _validate_size(size: Dict[str, int]) -> None:
|
| 554 |
+
if not ("height" in size and "width" in size):
|
| 555 |
+
raise ValueError(f"Argument `size` must be a dictionary with keys 'height' and 'width'. Got: {size}")
|
| 556 |
+
if size["height"] != size["width"]:
|
| 557 |
+
raise ValueError(f"Argument `size` must have the same height and width, got {size}")
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def _validate_mllama_preprocess_arguments(do_resize, size, do_pad, max_image_tiles):
|
| 561 |
+
if not do_pad:
|
| 562 |
+
raise ValueError("VideoMllamaImageProcessor doesn't support `do_pad=False` mode.")
|
| 563 |
+
if not do_resize:
|
| 564 |
+
raise ValueError("VideoMllamaImageProcessor doesn't support `do_resize=False` mode.")
|
| 565 |
+
if max_image_tiles is None or max_image_tiles <= 0:
|
| 566 |
+
raise ValueError(f"VideoMllamaImageProcessor `max_image_tiles` must be a positive integer, got {max_image_tiles}.")
|
| 567 |
+
_validate_size(size)
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
class VideoMllamaImageProcessor(BaseImageProcessor):
|
| 571 |
+
"""
|
| 572 |
+
Constructs a VideoMllama image processor.
|
| 573 |
+
|
| 574 |
+
Args:
|
| 575 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 576 |
+
Whether to convert the image to RGB. This is useful if the input image is of a different format e.g. RGBA.
|
| 577 |
+
Only has an effect if the input image is in the PIL format.
|
| 578 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 579 |
+
Whether to resize the image.
|
| 580 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 581 |
+
Size of the image tile. Should be a dictionary containing 'height' and 'width' keys, both with integer values.
|
| 582 |
+
The height and width values should be equal.
|
| 583 |
+
resample (`int`, *optional*, defaults to `Resampling.BILINEAR`):
|
| 584 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 585 |
+
has an effect if `do_resize` is set to `True`.
|
| 586 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 587 |
+
Whether to rescale the image.
|
| 588 |
+
rescale_factor (`float`, *optional*, defaults to 0.0):
|
| 589 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 590 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 591 |
+
Whether to normalize the image.
|
| 592 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 593 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 594 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 595 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 596 |
+
`True`.
|
| 597 |
+
do_pad (`bool`, *optional*, defaults to `True`):
|
| 598 |
+
Whether or not to pad the images to the largest height and width in the batch.
|
| 599 |
+
max_image_tiles (`int`, *optional*, defaults to 4):
|
| 600 |
+
The maximum number of tiles to split the image into.
|
| 601 |
+
"""
|
| 602 |
+
|
| 603 |
+
model_input_names = ["pixel_values", "num_tiles", "aspect_ratio_ids", "aspect_ratio_mask"]
|
| 604 |
+
|
| 605 |
+
def __init__(
|
| 606 |
+
self,
|
| 607 |
+
do_convert_rgb: bool = True,
|
| 608 |
+
do_resize: bool = True,
|
| 609 |
+
size: Optional[Dict[str, int]] = None,
|
| 610 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 611 |
+
do_rescale: bool = True,
|
| 612 |
+
rescale_factor: float = 1 / 255,
|
| 613 |
+
do_normalize: bool = True,
|
| 614 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 615 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 616 |
+
do_pad: bool = True,
|
| 617 |
+
max_image_tiles: int = 4,
|
| 618 |
+
**kwargs,
|
| 619 |
+
) -> None:
|
| 620 |
+
super().__init__(**kwargs)
|
| 621 |
+
self.do_convert_rgb = do_convert_rgb
|
| 622 |
+
self.do_resize = do_resize
|
| 623 |
+
self.size = size if size is not None else {"height": 224, "width": 224}
|
| 624 |
+
self.resample = resample
|
| 625 |
+
self.do_rescale = do_rescale
|
| 626 |
+
self.rescale_factor = rescale_factor
|
| 627 |
+
self.do_normalize = do_normalize
|
| 628 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
| 629 |
+
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
| 630 |
+
self.do_pad = do_pad
|
| 631 |
+
self.max_image_tiles = max_image_tiles
|
| 632 |
+
|
| 633 |
+
_validate_mllama_preprocess_arguments(self.do_resize, self.size, self.do_pad, self.max_image_tiles)
|
| 634 |
+
|
| 635 |
+
def preprocess(
|
| 636 |
+
self,
|
| 637 |
+
images: ImageInput,
|
| 638 |
+
do_convert_rgb: Optional[bool] = None,
|
| 639 |
+
do_resize: Optional[bool] = None,
|
| 640 |
+
size: Optional[Dict[str, int]] = None,
|
| 641 |
+
resample: Optional[PILImageResampling] = None,
|
| 642 |
+
do_rescale: Optional[bool] = None,
|
| 643 |
+
rescale_factor: Optional[float] = None,
|
| 644 |
+
do_normalize: Optional[bool] = None,
|
| 645 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 646 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 647 |
+
do_pad: Optional[bool] = None,
|
| 648 |
+
max_image_tiles: Optional[int] = None,
|
| 649 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 650 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 651 |
+
):
|
| 652 |
+
"""
|
| 653 |
+
Preprocess a batch of images.
|
| 654 |
+
|
| 655 |
+
Args:
|
| 656 |
+
images (`ImageInput`):
|
| 657 |
+
A list of images to preprocess.
|
| 658 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 659 |
+
Whether to convert the image to RGB.
|
| 660 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 661 |
+
Whether to resize the image.
|
| 662 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 663 |
+
Size of the image tile. Should be a dictionary containing 'height' and 'width' keys, both with integer values.
|
| 664 |
+
The height and width values should be equal.
|
| 665 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 666 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 667 |
+
has an effect if `do_resize` is set to `True`.
|
| 668 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 669 |
+
Whether to rescale the image.
|
| 670 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 671 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 672 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 673 |
+
Whether to normalize the image.
|
| 674 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 675 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 676 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 677 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 678 |
+
`True`.
|
| 679 |
+
do_pad (`bool`, *optional*, defaults to `self.do_pad`):
|
| 680 |
+
Whether or not to pad the images to the largest height and width in the batch.
|
| 681 |
+
max_image_tiles (`int`, *optional*, defaults to `self.max_image_tiles`):
|
| 682 |
+
The maximum number of tiles to split the image into.
|
| 683 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 684 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 685 |
+
from the input image. Can be one of:
|
| 686 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 687 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 688 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 689 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 690 |
+
The type of tensors to return. Can be one of:
|
| 691 |
+
- Unset: Return a list of `np.ndarray`.
|
| 692 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 693 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 694 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 695 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 696 |
+
|
| 697 |
+
Returns:
|
| 698 |
+
`BatchFeature` of the following structure:
|
| 699 |
+
- **pixel_values** (`TensorType`): The preprocessed pixel values.
|
| 700 |
+
- **aspect_ratio_ids** (`TensorType`): The aspect ratio ids of the images.
|
| 701 |
+
- **num_tiles** (`List[List[int]]`): The number of tiles for each image in the batch.
|
| 702 |
+
"""
|
| 703 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 704 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 705 |
+
size = size if size is not None else self.size
|
| 706 |
+
resample = resample if resample is not None else self.resample
|
| 707 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 708 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 709 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 710 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 711 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 712 |
+
do_pad = do_pad if do_pad is not None else self.do_pad
|
| 713 |
+
max_image_tiles = max_image_tiles if max_image_tiles is not None else self.max_image_tiles
|
| 714 |
+
|
| 715 |
+
validate_preprocess_arguments(
|
| 716 |
+
do_rescale=do_rescale,
|
| 717 |
+
rescale_factor=rescale_factor,
|
| 718 |
+
do_normalize=do_normalize,
|
| 719 |
+
image_mean=image_mean,
|
| 720 |
+
image_std=image_std,
|
| 721 |
+
do_resize=do_resize,
|
| 722 |
+
size=size,
|
| 723 |
+
resample=resample,
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
# extra validation
|
| 727 |
+
_validate_mllama_preprocess_arguments(do_resize, size, do_pad, max_image_tiles)
|
| 728 |
+
|
| 729 |
+
images_list = make_list_of_images(images)
|
| 730 |
+
|
| 731 |
+
if self.do_convert_rgb:
|
| 732 |
+
images_list = [[convert_to_rgb(image) for image in images] for images in images_list]
|
| 733 |
+
|
| 734 |
+
images_list = [[to_numpy_array(image) for image in images] for images in images_list]
|
| 735 |
+
|
| 736 |
+
batch_images = []
|
| 737 |
+
batch_aspect_ratios = []
|
| 738 |
+
|
| 739 |
+
# iterate over batch samples
|
| 740 |
+
for images in images_list:
|
| 741 |
+
sample_images = []
|
| 742 |
+
sample_aspect_ratios = []
|
| 743 |
+
|
| 744 |
+
# iterate over images in a batch sample
|
| 745 |
+
for image in images:
|
| 746 |
+
# convert images to channels first format for faster processing
|
| 747 |
+
# LAST is slower for `pad` and not supported by `split_to_tiles`
|
| 748 |
+
data_format = ChannelDimension.FIRST
|
| 749 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 750 |
+
|
| 751 |
+
# do_resize=False is not supported, validated
|
| 752 |
+
image, aspect_ratio = self.resize(
|
| 753 |
+
image=image,
|
| 754 |
+
size=size,
|
| 755 |
+
resample=resample,
|
| 756 |
+
max_image_tiles=max_image_tiles,
|
| 757 |
+
input_data_format=data_format,
|
| 758 |
+
data_format=data_format,
|
| 759 |
+
)
|
| 760 |
+
|
| 761 |
+
# do_pad=False is not supported, validated
|
| 762 |
+
image = self.pad(
|
| 763 |
+
image=image,
|
| 764 |
+
size=size,
|
| 765 |
+
aspect_ratio=aspect_ratio,
|
| 766 |
+
input_data_format=data_format,
|
| 767 |
+
data_format=data_format,
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
if do_rescale:
|
| 771 |
+
image = self.rescale(
|
| 772 |
+
image=image,
|
| 773 |
+
scale=rescale_factor,
|
| 774 |
+
input_data_format=input_data_format,
|
| 775 |
+
data_format=data_format,
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
if do_normalize:
|
| 779 |
+
image = self.normalize(
|
| 780 |
+
image=image,
|
| 781 |
+
mean=image_mean,
|
| 782 |
+
std=image_std,
|
| 783 |
+
input_data_format=input_data_format,
|
| 784 |
+
data_format=data_format,
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
num_tiles_height, num_tiles_width = aspect_ratio
|
| 788 |
+
image = split_to_tiles(image, num_tiles_height, num_tiles_width)
|
| 789 |
+
|
| 790 |
+
sample_images.append(image)
|
| 791 |
+
sample_aspect_ratios.append((num_tiles_height, num_tiles_width))
|
| 792 |
+
|
| 793 |
+
batch_images.append(sample_images)
|
| 794 |
+
batch_aspect_ratios.append(sample_aspect_ratios)
|
| 795 |
+
|
| 796 |
+
images, num_tiles = pack_images(batch_images, max_image_tiles)
|
| 797 |
+
|
| 798 |
+
aspect_ratio_ids = convert_aspect_ratios_to_ids(batch_aspect_ratios, max_image_tiles=max_image_tiles)
|
| 799 |
+
aspect_ratio_mask = build_aspect_ratio_mask(batch_aspect_ratios, max_image_tiles=max_image_tiles)
|
| 800 |
+
|
| 801 |
+
# images (np.ndarray) with shape (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width)
|
| 802 |
+
# aspect_ratio_ids (np.ndarray) with shape (batch_size, max_num_images) - aspect ratio ids for each image, padded to max_num_images with 0
|
| 803 |
+
# num_tiles (List[List[int]]) with (batch_size, num_images_in_batch) - real number of tiles for each image, not padded
|
| 804 |
+
# aspect_ratio_mask (np.ndarray) with shape (batch_size, max_num_images, max_image_tiles) - number of tiles for each image, padded to max_num_images with 0
|
| 805 |
+
encoded_inputs = BatchFeature(
|
| 806 |
+
data={
|
| 807 |
+
"pixel_values": images,
|
| 808 |
+
"aspect_ratio_ids": aspect_ratio_ids,
|
| 809 |
+
"aspect_ratio_mask": aspect_ratio_mask,
|
| 810 |
+
},
|
| 811 |
+
tensor_type=return_tensors,
|
| 812 |
+
)
|
| 813 |
+
encoded_inputs["num_tiles"] = num_tiles
|
| 814 |
+
|
| 815 |
+
return encoded_inputs
|
| 816 |
+
|
| 817 |
+
def pad(
|
| 818 |
+
self,
|
| 819 |
+
image: np.ndarray,
|
| 820 |
+
size: Dict[str, int],
|
| 821 |
+
aspect_ratio: Tuple[int, int],
|
| 822 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 823 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 824 |
+
) -> np.ndarray:
|
| 825 |
+
"""
|
| 826 |
+
Pad an image to the `size` x `aspect_ratio`. For example, if size is {height: 224, width: 224} and aspect ratio is
|
| 827 |
+
(1, 2), the image will be padded to 224x448.
|
| 828 |
+
|
| 829 |
+
Args:
|
| 830 |
+
image (`np.ndarray`):
|
| 831 |
+
Image to resize.
|
| 832 |
+
size (`Dict[str, int]`):
|
| 833 |
+
Size of the output image.
|
| 834 |
+
aspect_ratio (`Tuple[int, int]`):
|
| 835 |
+
The aspect ratio of the image.
|
| 836 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 837 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 838 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 839 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 840 |
+
|
| 841 |
+
Returns:
|
| 842 |
+
`np.ndarray`: The padded image.
|
| 843 |
+
"""
|
| 844 |
+
|
| 845 |
+
_validate_size(size)
|
| 846 |
+
|
| 847 |
+
image_height, image_width = get_image_size(image, channel_dim=input_data_format)
|
| 848 |
+
num_tiles_height, num_tiles_width = aspect_ratio
|
| 849 |
+
padded_height = num_tiles_height * size["height"]
|
| 850 |
+
padded_width = num_tiles_width * size["width"]
|
| 851 |
+
pad_size = ((0, padded_height - image_height), (0, padded_width - image_width))
|
| 852 |
+
|
| 853 |
+
image = pad(
|
| 854 |
+
image,
|
| 855 |
+
pad_size,
|
| 856 |
+
mode=PaddingMode.CONSTANT,
|
| 857 |
+
constant_values=0,
|
| 858 |
+
data_format=data_format,
|
| 859 |
+
input_data_format=input_data_format,
|
| 860 |
+
)
|
| 861 |
+
|
| 862 |
+
return image
|
| 863 |
+
|
| 864 |
+
def resize(
|
| 865 |
+
self,
|
| 866 |
+
image: np.ndarray,
|
| 867 |
+
size: Dict[str, int],
|
| 868 |
+
max_image_tiles: int,
|
| 869 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 870 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 871 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 872 |
+
) -> Union[np.ndarray, Tuple[int, int]]:
|
| 873 |
+
"""
|
| 874 |
+
Resizes an image to fit within a tiled canvas while maintaining its aspect ratio.
|
| 875 |
+
The optimal canvas size is calculated based on the maximum number of tiles and the tile size.
|
| 876 |
+
|
| 877 |
+
The function first determines the best tile arrangement for the image, then resizes the image
|
| 878 |
+
to fit within this canvas. The resized image and the number of tiles along the height and width
|
| 879 |
+
dimensions are returned.
|
| 880 |
+
|
| 881 |
+
Args:
|
| 882 |
+
image (`np.ndarray`):
|
| 883 |
+
Image to resize.
|
| 884 |
+
size (`Dict[str, int]`):
|
| 885 |
+
Size of the output image.
|
| 886 |
+
max_image_tiles (`int`):
|
| 887 |
+
The maximum number of tiles to split the image into.
|
| 888 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 889 |
+
Resampling filter to use when resizing the image.
|
| 890 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 891 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 892 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 893 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 894 |
+
|
| 895 |
+
Returns:
|
| 896 |
+
`Union[np.ndarray, Tuple[int, int]]`: The resized image and a tuple containing the number of tiles
|
| 897 |
+
along the height and width dimensions.
|
| 898 |
+
"""
|
| 899 |
+
|
| 900 |
+
_validate_size(size)
|
| 901 |
+
|
| 902 |
+
image_height, image_width = get_image_size(image, channel_dim=input_data_format)
|
| 903 |
+
tile_size = size["height"]
|
| 904 |
+
|
| 905 |
+
canvas_height, canvas_width = get_optimal_tiled_canvas(
|
| 906 |
+
image_height=image_height,
|
| 907 |
+
image_width=image_width,
|
| 908 |
+
max_image_tiles=max_image_tiles,
|
| 909 |
+
tile_size=tile_size,
|
| 910 |
+
)
|
| 911 |
+
num_tiles_height = canvas_height // tile_size
|
| 912 |
+
num_tiles_width = canvas_width // tile_size
|
| 913 |
+
|
| 914 |
+
new_height, new_width = get_image_size_fit_to_canvas(
|
| 915 |
+
image_height=image_height,
|
| 916 |
+
image_width=image_width,
|
| 917 |
+
canvas_height=canvas_height,
|
| 918 |
+
canvas_width=canvas_width,
|
| 919 |
+
tile_size=tile_size,
|
| 920 |
+
)
|
| 921 |
+
|
| 922 |
+
image = resize(
|
| 923 |
+
image,
|
| 924 |
+
(new_height, new_width),
|
| 925 |
+
resample=resample,
|
| 926 |
+
data_format=data_format,
|
| 927 |
+
input_data_format=input_data_format,
|
| 928 |
+
)
|
| 929 |
+
|
| 930 |
+
return image, (num_tiles_height, num_tiles_width)
|
modeling_video_mllama.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
processing_video_mllama.py
ADDED
|
@@ -0,0 +1,836 @@
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 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 |
+
"""Processor class for VideoMllama."""
|
| 17 |
+
|
| 18 |
+
import av
|
| 19 |
+
import cv2
|
| 20 |
+
import math
|
| 21 |
+
import numpy as np
|
| 22 |
+
import concurrent.futures
|
| 23 |
+
|
| 24 |
+
from PIL import Image
|
| 25 |
+
from typing import List, Optional, Union, Tuple
|
| 26 |
+
|
| 27 |
+
from transformers.feature_extraction_utils import BatchFeature
|
| 28 |
+
from transformers.image_utils import ImageInput, to_numpy_array
|
| 29 |
+
from transformers.processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, Unpack
|
| 30 |
+
from transformers.tokenization_utils_base import (
|
| 31 |
+
PreTokenizedInput,
|
| 32 |
+
TextInput,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
from .image_processing_video_mllama import make_list_of_images
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class VideoMllamaImagesKwargs(ImagesKwargs, total=False):
|
| 42 |
+
max_image_tiles: Optional[int]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class VideoMllamaProcessorKwargs(ProcessingKwargs, total=False):
|
| 46 |
+
images_kwargs: VideoMllamaImagesKwargs
|
| 47 |
+
add_video_position_encoding: Optional[bool]
|
| 48 |
+
|
| 49 |
+
_defaults = {
|
| 50 |
+
"image_kwargs": {
|
| 51 |
+
"max_image_tiles": 1,
|
| 52 |
+
},
|
| 53 |
+
"add_video_position_encoding": True,
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# --- Start of new video sampling functions (adapted from streaming/mm_plugin.py) ---
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def validate_frame_sampling(sample_indices, frames, max_missing_frames=2, max_missing_ratio=0.1):
|
| 61 |
+
"""
|
| 62 |
+
Validate the completeness of sampled frames.
|
| 63 |
+
"""
|
| 64 |
+
expected_count = len(sample_indices)
|
| 65 |
+
actual_count = len(frames)
|
| 66 |
+
missing_count = expected_count - actual_count
|
| 67 |
+
|
| 68 |
+
if missing_count <= 0:
|
| 69 |
+
return
|
| 70 |
+
|
| 71 |
+
missing_ratio = missing_count / expected_count
|
| 72 |
+
|
| 73 |
+
if missing_count > max_missing_frames and missing_ratio > max_missing_ratio:
|
| 74 |
+
raise ValueError(
|
| 75 |
+
f"Too many frames missing: {missing_count}/{expected_count} "
|
| 76 |
+
f"({missing_ratio:.1%}) frames missing, exceeding "
|
| 77 |
+
f"{max_missing_ratio:.0%} threshold."
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _get_video_sample_frames(video_stream, total_frames: int = 0, **kwargs) -> np.ndarray:
|
| 82 |
+
"""
|
| 83 |
+
Core logic to compute video sample frame indices.
|
| 84 |
+
"""
|
| 85 |
+
video_fps: float = kwargs.get("video_fps", 1.0)
|
| 86 |
+
video_minlen: int = kwargs.get("video_minlen", 8)
|
| 87 |
+
video_maxlen: int = kwargs.get("video_maxlen", 256)
|
| 88 |
+
|
| 89 |
+
obtained_total_frames = int(video_stream.frames)
|
| 90 |
+
|
| 91 |
+
duration = float(video_stream.duration * video_stream.time_base)
|
| 92 |
+
frame_rate = float(video_stream.average_rate)
|
| 93 |
+
calculated_total_frames = round(duration * frame_rate)
|
| 94 |
+
assert video_fps <= frame_rate, f"Sampling frequency ({video_fps}) must be less than or equal to video frame rate ({frame_rate})"
|
| 95 |
+
|
| 96 |
+
total_frames_num = [x for x in [total_frames, obtained_total_frames, calculated_total_frames] if x > 0]
|
| 97 |
+
final_total_frames = min(total_frames_num) if total_frames_num else 0
|
| 98 |
+
if final_total_frames == 0:
|
| 99 |
+
raise AttributeError("Unable to obtain or calculate the total number of frames in the video.")
|
| 100 |
+
|
| 101 |
+
target_total_frames = int(math.ceil(duration * video_fps - 1e-6))
|
| 102 |
+
sample_frames = max(target_total_frames, video_minlen)
|
| 103 |
+
sample_frames = min(sample_frames, video_maxlen, final_total_frames)
|
| 104 |
+
|
| 105 |
+
if target_total_frames == sample_frames and video_fps > 0 and frame_rate > 0:
|
| 106 |
+
sample_indices = np.arange(target_total_frames, dtype=np.int32)
|
| 107 |
+
sample_indices = (sample_indices * frame_rate / video_fps).astype(np.int32)
|
| 108 |
+
else:
|
| 109 |
+
sample_indices = np.linspace(0, final_total_frames - 1, sample_frames).astype(np.int32)
|
| 110 |
+
|
| 111 |
+
return sample_indices
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _get_cv2_video_sample_frames(video_path: str, total_frames: int = 0, **kwargs) -> np.ndarray:
|
| 115 |
+
container = av.open(video_path, "r")
|
| 116 |
+
video_stream = next(stream for stream in container.streams if stream.type == "video")
|
| 117 |
+
sample_indices = _get_video_sample_frames(video_stream, total_frames=total_frames, **kwargs)
|
| 118 |
+
return sample_indices
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def get_video_sample_frames_av(video_path: str, **kwargs) -> List[Image.Image]:
|
| 122 |
+
container = av.open(video_path, "r")
|
| 123 |
+
video_stream = next(stream for stream in container.streams if stream.type == "video")
|
| 124 |
+
|
| 125 |
+
sample_indices = _get_video_sample_frames(video_stream, **kwargs)
|
| 126 |
+
sample_indices_set = set(sample_indices)
|
| 127 |
+
|
| 128 |
+
frames: List[Image.Image] = []
|
| 129 |
+
|
| 130 |
+
container.seek(0)
|
| 131 |
+
for frame_idx, frame in enumerate(container.decode(video_stream)):
|
| 132 |
+
if frame_idx in sample_indices_set:
|
| 133 |
+
frames.append(frame.to_image())
|
| 134 |
+
if len(frames) == len(sample_indices):
|
| 135 |
+
break
|
| 136 |
+
|
| 137 |
+
validate_frame_sampling(sample_indices, frames)
|
| 138 |
+
|
| 139 |
+
return frames
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def get_cv2_video_sample_frames_multithread(video_path: str, **kwargs) -> List[Image.Image]:
|
| 143 |
+
num_threads: int = kwargs.get("frame_extract_num_threads", 4)
|
| 144 |
+
num_threads = int(num_threads)
|
| 145 |
+
|
| 146 |
+
cap = cv2.VideoCapture(video_path)
|
| 147 |
+
if not cap.isOpened():
|
| 148 |
+
raise ValueError(f"Unable to open video file: {video_path}")
|
| 149 |
+
|
| 150 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 151 |
+
cap.release()
|
| 152 |
+
|
| 153 |
+
frame_indices = _get_cv2_video_sample_frames(video_path, total_frames=total_frames, **kwargs)
|
| 154 |
+
|
| 155 |
+
unique_frames: List[Optional[np.ndarray]] = [None] * len(frame_indices)
|
| 156 |
+
index_map = {idx: pos for pos, idx in enumerate(frame_indices)}
|
| 157 |
+
|
| 158 |
+
chunks = np.array_split(frame_indices, min(num_threads, len(frame_indices)))
|
| 159 |
+
|
| 160 |
+
def worker(chunk_indices):
|
| 161 |
+
local_cap = cv2.VideoCapture(video_path)
|
| 162 |
+
if not local_cap.isOpened():
|
| 163 |
+
return
|
| 164 |
+
|
| 165 |
+
if chunk_indices[0] > 0:
|
| 166 |
+
local_cap.set(cv2.CAP_PROP_POS_FRAMES, chunk_indices[0])
|
| 167 |
+
|
| 168 |
+
frame_idx_cursor = chunk_indices[0]
|
| 169 |
+
chunk_cursor = 0
|
| 170 |
+
|
| 171 |
+
while chunk_cursor < len(chunk_indices):
|
| 172 |
+
target_idx = chunk_indices[chunk_cursor]
|
| 173 |
+
ok = local_cap.grab()
|
| 174 |
+
if not ok:
|
| 175 |
+
break
|
| 176 |
+
|
| 177 |
+
if frame_idx_cursor == target_idx:
|
| 178 |
+
ret, frame = local_cap.retrieve()
|
| 179 |
+
if ret:
|
| 180 |
+
unique_pos = index_map[target_idx]
|
| 181 |
+
unique_frames[unique_pos] = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 182 |
+
chunk_cursor += 1
|
| 183 |
+
frame_idx_cursor += 1
|
| 184 |
+
local_cap.release()
|
| 185 |
+
|
| 186 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
|
| 187 |
+
list(executor.map(worker, [chunk for chunk in chunks if len(chunk) > 0]))
|
| 188 |
+
|
| 189 |
+
pil_frames = [Image.fromarray(frame) for frame in unique_frames if frame is not None]
|
| 190 |
+
|
| 191 |
+
validate_frame_sampling(frame_indices, pil_frames)
|
| 192 |
+
|
| 193 |
+
if not pil_frames:
|
| 194 |
+
return get_video_sample_frames_av(video_path, **kwargs)
|
| 195 |
+
|
| 196 |
+
return pil_frames
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# --- End of new video sampling functions ---
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def get_cross_attention_token_mask(
|
| 203 |
+
input_ids: List[int],
|
| 204 |
+
attention_mask: List[int],
|
| 205 |
+
image_token_id: int,
|
| 206 |
+
video_token_id: int,
|
| 207 |
+
frame_num_per_video: List[int],
|
| 208 |
+
cross_attention_token_mask_pad_token_id: int = -100,
|
| 209 |
+
) -> Tuple[List[int], List[int], List[int]]:
|
| 210 |
+
"""
|
| 211 |
+
Generate a cross-attention-token-mask for each input_tokens in the input sequence.
|
| 212 |
+
This function implements a causal attention logic:
|
| 213 |
+
- A text token can see all image tokens that appeared before it.
|
| 214 |
+
- An image token can see itself and all image tokens that appeared before it.
|
| 215 |
+
"""
|
| 216 |
+
# 1. Convert video tokens to image tokens
|
| 217 |
+
input_ids_np = np.array(input_ids, dtype=np.int64)
|
| 218 |
+
if video_token_id in input_ids_np:
|
| 219 |
+
total_vid_num = np.sum(input_ids_np == video_token_id)
|
| 220 |
+
f_num_per_vid = frame_num_per_video[:total_vid_num]
|
| 221 |
+
|
| 222 |
+
convert_input_ids_list = []
|
| 223 |
+
convert_attention_mask_list = []
|
| 224 |
+
vid_idx = 0
|
| 225 |
+
for token_id, mask_val in zip(input_ids_np, attention_mask):
|
| 226 |
+
if token_id == video_token_id:
|
| 227 |
+
vid_len = f_num_per_vid[vid_idx]
|
| 228 |
+
vid_idx += 1
|
| 229 |
+
convert_input_ids_list.extend([image_token_id] * vid_len)
|
| 230 |
+
convert_attention_mask_list.extend([mask_val] * vid_len)
|
| 231 |
+
else:
|
| 232 |
+
convert_input_ids_list.append(token_id)
|
| 233 |
+
convert_attention_mask_list.append(mask_val)
|
| 234 |
+
convert_input_ids = np.array(convert_input_ids_list, dtype=np.int64)
|
| 235 |
+
convert_attention_mask = np.array(convert_attention_mask_list, dtype=np.int64)
|
| 236 |
+
else:
|
| 237 |
+
convert_input_ids = input_ids_np
|
| 238 |
+
convert_attention_mask = np.array(attention_mask, dtype=np.int64)
|
| 239 |
+
|
| 240 |
+
# 2. Generate the sparse attention mask based on causal visibility
|
| 241 |
+
is_image = convert_input_ids == image_token_id
|
| 242 |
+
# Cumulative count of images up to and including the current position
|
| 243 |
+
image_count_cumulative = np.cumsum(is_image)
|
| 244 |
+
# Cumulative count of images up to the previous position
|
| 245 |
+
image_count_before = np.pad(image_count_cumulative[:-1], (1, 0), "constant", constant_values=0)
|
| 246 |
+
|
| 247 |
+
# For text tokens, num_seen = image_count_before.
|
| 248 |
+
# For image tokens, num_seen = image_count_cumulative (sees itself).
|
| 249 |
+
num_images_seen = np.where(is_image, image_count_cumulative, image_count_before)
|
| 250 |
+
|
| 251 |
+
# Convert num_seen to sparse mask value (num_seen - 1).
|
| 252 |
+
vision_masks = np.full(len(convert_input_ids), cross_attention_token_mask_pad_token_id, dtype=np.int64)
|
| 253 |
+
valid_mask = num_images_seen > 0
|
| 254 |
+
vision_masks[valid_mask] = num_images_seen[valid_mask] - 1
|
| 255 |
+
|
| 256 |
+
return vision_masks.tolist(), convert_input_ids.tolist(), convert_attention_mask.tolist()
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def convert_sparse_cross_attention_mask_to_dense(
|
| 260 |
+
cross_attention_token_masks: np.ndarray,
|
| 261 |
+
num_tiles: List[List[int]],
|
| 262 |
+
max_num_tiles: int,
|
| 263 |
+
cross_attention_token_mask_pad_token_id: int = -100,
|
| 264 |
+
) -> np.ndarray:
|
| 265 |
+
"""
|
| 266 |
+
Convert the cross attention mask indices to a cross attention mask 4D array.
|
| 267 |
+
|
| 268 |
+
This function takes a sparse representation of cross attention masks and converts it to a dense 4D numpy array.
|
| 269 |
+
The sparse representation is a tensor that defines [the range of images that can be seen] for [each input token].
|
| 270 |
+
"""
|
| 271 |
+
batch_size, length = cross_attention_token_masks.shape
|
| 272 |
+
max_num_images = max([len(n_tiles) for n_tiles in num_tiles]) if num_tiles else 0
|
| 273 |
+
|
| 274 |
+
cross_attention_mask = np.zeros(
|
| 275 |
+
shape=(batch_size, length, max_num_images, max_num_tiles),
|
| 276 |
+
dtype=np.int64,
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
if max_num_images == 0:
|
| 280 |
+
return cross_attention_mask
|
| 281 |
+
|
| 282 |
+
for batch_idx, (sparse_mask, n_tiles) in enumerate(zip(cross_attention_token_masks, num_tiles)):
|
| 283 |
+
# For each image, find all text tokens that are allowed to see it.
|
| 284 |
+
# A token with sparse_mask value N can see all images with index i <= N.
|
| 285 |
+
for image_idx, mask_n_tiles in enumerate(n_tiles):
|
| 286 |
+
# Find all token positions where the sparse mask value is >= the current image's index.
|
| 287 |
+
# This correctly implements the causal logic.
|
| 288 |
+
visible_token_indices = (sparse_mask >= image_idx) & (sparse_mask != cross_attention_token_mask_pad_token_id)
|
| 289 |
+
# Set the attention mask to 1 for these tokens and the current image.
|
| 290 |
+
cross_attention_mask[batch_idx, visible_token_indices, image_idx, :mask_n_tiles] = 1
|
| 291 |
+
|
| 292 |
+
return cross_attention_mask
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def build_string_from_input(prompt: str, bos_token: str, image_token: str, video_token: str) -> str:
|
| 296 |
+
"""
|
| 297 |
+
Builds a string from the input prompt by adding `bos_token` if not already present.
|
| 298 |
+
It handles prompts starting with image or video tokens.
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
if bos_token in prompt:
|
| 302 |
+
return prompt
|
| 303 |
+
|
| 304 |
+
num_media_tokens_on_start = 0
|
| 305 |
+
media_tokens = []
|
| 306 |
+
|
| 307 |
+
while prompt.startswith(image_token) or prompt.startswith(video_token):
|
| 308 |
+
if prompt.startswith(image_token):
|
| 309 |
+
prompt = prompt[len(image_token) :]
|
| 310 |
+
media_tokens.append(image_token)
|
| 311 |
+
elif prompt.startswith(video_token):
|
| 312 |
+
prompt = prompt[len(video_token) :]
|
| 313 |
+
media_tokens.append(video_token)
|
| 314 |
+
num_media_tokens_on_start += 1
|
| 315 |
+
|
| 316 |
+
print(f"No bos_token `{bos_token}` in prompt, so it is added after the {num_media_tokens_on_start} media tokens at the start of the prompt.")
|
| 317 |
+
|
| 318 |
+
return f"{''.join(media_tokens)}{bos_token}{prompt}"
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
VIDEO_MLLAMA_PROCESSOR_PAD_POSITION_ID = 0
|
| 322 |
+
VIDEO_MLLAMA_PROCESSOR_CROSS_ATTENTION_TOKEN_MASK_PAD_TOKEN_ID = -100
|
| 323 |
+
|
| 324 |
+
class VideoMllamaProcessor(ProcessorMixin):
|
| 325 |
+
r"""
|
| 326 |
+
Constructs a VideoMllama processor which wraps [`VideoMllamaImageProcessor`] and
|
| 327 |
+
[`PretrainedTokenizerFast`] into a single processor that inherits both the image processor and
|
| 328 |
+
tokenizer functionalities. See the [`~VideoMllamaProcessor.__call__`] and [`~OwlViTProcessor.decode`] for more
|
| 329 |
+
information.
|
| 330 |
+
The preferred way of passing kwargs is as a dictionary per modality, see usage example below.
|
| 331 |
+
```python
|
| 332 |
+
from transformers import VideoMllamaProcessor
|
| 333 |
+
from PIL import Image
|
| 334 |
+
|
| 335 |
+
processor = VideoMllamaProcessor.from_pretrained("meta-llama/Llama-3.2-11B-Vision")
|
| 336 |
+
|
| 337 |
+
processor(
|
| 338 |
+
images=your_pil_image,
|
| 339 |
+
text=["<|image|>If I had to write a haiku for this one"],
|
| 340 |
+
images_kwargs = {"size": {"height": 448, "width": 448}},
|
| 341 |
+
text_kwargs = {"padding": "right"},
|
| 342 |
+
common_kwargs = {"return_tensors": "pt"},
|
| 343 |
+
)
|
| 344 |
+
```
|
| 345 |
+
|
| 346 |
+
Args:
|
| 347 |
+
image_processor ([`VideoMllamaImageProcessor`]):
|
| 348 |
+
The image processor is a required input.
|
| 349 |
+
tokenizer ([`PreTrainedTokenizer`, `PreTrainedTokenizerFast`]):
|
| 350 |
+
The tokenizer is a required input.
|
| 351 |
+
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
attributes = ["image_processor", "tokenizer"]
|
| 355 |
+
image_processor_class = "AutoImageProcessor"
|
| 356 |
+
tokenizer_class = "PreTrainedTokenizerFast"
|
| 357 |
+
|
| 358 |
+
_defaults = {
|
| 359 |
+
"image_kwargs": {
|
| 360 |
+
"max_image_tiles": 1,
|
| 361 |
+
},
|
| 362 |
+
"add_video_position_encoding": True,
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
def __init__(self, image_processor, tokenizer, video_fps = None, video_minlen = None, video_maxlen = None,frame_extract_num_threads = None, extract_frame_func = None, max_image_tiles: Optional[int] = None, **kwargs):
|
| 366 |
+
# User-facing placeholders
|
| 367 |
+
self.image_placeholder = "<image>"
|
| 368 |
+
self.video_placeholder = "<video>"
|
| 369 |
+
self.tokenizer = tokenizer
|
| 370 |
+
|
| 371 |
+
super().__init__(image_processor, tokenizer)
|
| 372 |
+
if max_image_tiles is not None:
|
| 373 |
+
self.image_processor.max_image_tiles = max_image_tiles
|
| 374 |
+
|
| 375 |
+
if not hasattr(self.tokenizer, "image_token"):
|
| 376 |
+
self.image_token = "<|image|>"
|
| 377 |
+
self.image_token_id = self.tokenizer.convert_tokens_to_ids(self.image_token)
|
| 378 |
+
else:
|
| 379 |
+
self.image_token = self.tokenizer.image_token
|
| 380 |
+
self.image_token_id = self.tokenizer.image_token_id
|
| 381 |
+
|
| 382 |
+
if not hasattr(self.tokenizer, "video_token"):
|
| 383 |
+
self.video_token = "<|video|>"
|
| 384 |
+
self.video_token_id = self.tokenizer.convert_tokens_to_ids(self.video_token)
|
| 385 |
+
else:
|
| 386 |
+
self.video_token = self.tokenizer.video_token
|
| 387 |
+
self.video_token_id = self.tokenizer.video_token_id
|
| 388 |
+
|
| 389 |
+
self.add_video_position_encoding = self._defaults["add_video_position_encoding"]
|
| 390 |
+
|
| 391 |
+
self.pad_position_id = VIDEO_MLLAMA_PROCESSOR_PAD_POSITION_ID
|
| 392 |
+
self.cross_attention_token_mask_pad_token_id = VIDEO_MLLAMA_PROCESSOR_CROSS_ATTENTION_TOKEN_MASK_PAD_TOKEN_ID
|
| 393 |
+
|
| 394 |
+
# New configuration for video frame sampling
|
| 395 |
+
if video_fps is None:
|
| 396 |
+
self.video_fps = getattr(image_processor, "video_fps", 1.0)
|
| 397 |
+
if video_minlen is None:
|
| 398 |
+
self.video_minlen = getattr(image_processor, "video_minlen", 8)
|
| 399 |
+
if video_maxlen is None:
|
| 400 |
+
self.video_maxlen = getattr(image_processor, "video_maxlen", 256)
|
| 401 |
+
if frame_extract_num_threads is None:
|
| 402 |
+
self.frame_extract_num_threads = getattr(image_processor, "frame_extract_num_threads", 4)
|
| 403 |
+
if extract_frame_func is None:
|
| 404 |
+
self.extract_frame_func = getattr(image_processor, "extract_frame_func", "cv2") # Options: "av", "cv2"
|
| 405 |
+
|
| 406 |
+
self.bos_token = self.tokenizer.bos_token
|
| 407 |
+
self.chat_template = self.tokenizer.chat_template
|
| 408 |
+
|
| 409 |
+
def _pad_sequences(
|
| 410 |
+
self,
|
| 411 |
+
sequences: List[List[int]],
|
| 412 |
+
pad_value: int,
|
| 413 |
+
max_length: Optional[int] = None,
|
| 414 |
+
padding_side: str = "right",
|
| 415 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 416 |
+
) -> np.ndarray:
|
| 417 |
+
if not sequences:
|
| 418 |
+
return np.array([], dtype=np.int64)
|
| 419 |
+
|
| 420 |
+
if max_length is None:
|
| 421 |
+
max_length = max(len(seq) for seq in sequences)
|
| 422 |
+
|
| 423 |
+
if pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
|
| 424 |
+
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
|
| 425 |
+
|
| 426 |
+
padded_sequences = np.full((len(sequences), max_length), pad_value, dtype=np.int64)
|
| 427 |
+
|
| 428 |
+
for i, seq in enumerate(sequences):
|
| 429 |
+
length = len(seq)
|
| 430 |
+
if padding_side == "right":
|
| 431 |
+
padded_sequences[i, :length] = seq
|
| 432 |
+
else: # left
|
| 433 |
+
padded_sequences[i, -length:] = seq
|
| 434 |
+
return padded_sequences
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def __call__(
|
| 438 |
+
self,
|
| 439 |
+
text: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
|
| 440 |
+
images: Optional[Union[ImageInput, str, List[str], List[List[str]]]] = None,
|
| 441 |
+
videos: Optional[Union[str, List[str], List[List[str]]]] = None,
|
| 442 |
+
**kwargs: Unpack[VideoMllamaProcessorKwargs],
|
| 443 |
+
) -> BatchFeature:
|
| 444 |
+
"""
|
| 445 |
+
Main method to prepare text(s), image(s) and video(s) to be fed as input to the model. This method forwards the `text`
|
| 446 |
+
arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
|
| 447 |
+
the text. To prepare the image(s), this method forwards the `images` arguments to
|
| 448 |
+
VideoMllamaImageProcessor's [`~VideoMllamaImageProcessor.__call__`] if `images` is not `None`. Videos are first
|
| 449 |
+
processed into frames and then handled as images.
|
| 450 |
+
|
| 451 |
+
Args:
|
| 452 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
| 453 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 454 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 455 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 456 |
+
images (`str`, `PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[str]`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
| 457 |
+
The image or batch of images to be prepared. Can be a single image path, a single PIL image, or a
|
| 458 |
+
list of paths or PIL images. When a list of single images is passed, it's treated as a batch of samples.
|
| 459 |
+
videos (`str`, `List[str]`, `List[List[str]]`):
|
| 460 |
+
The video or batch of videos to be prepared. Can be a single video path, a list of video paths (which
|
| 461 |
+
is treated as a batch), or a list of lists of video paths (already batched).
|
| 462 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 463 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 464 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 465 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 466 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 467 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 468 |
+
Returns:
|
| 469 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 470 |
+
|
| 471 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 472 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 473 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 474 |
+
`None`).
|
| 475 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 476 |
+
"""
|
| 477 |
+
# Step 0: Sanity checks
|
| 478 |
+
# Step 0.1: Convert empty lists to None
|
| 479 |
+
if images is not None and isinstance(images, list) and len(images) == 0:
|
| 480 |
+
images = None
|
| 481 |
+
if videos is not None and isinstance(videos, list) and len(videos) == 0:
|
| 482 |
+
videos = None
|
| 483 |
+
|
| 484 |
+
# Step 0.2: If no text, images, or videos are provided, raise an error
|
| 485 |
+
if text is None and images is None and videos is None:
|
| 486 |
+
raise ValueError("You have to specify either `text`, `images` or `videos`.")
|
| 487 |
+
# Step 0.3: If no text is provided, at least one of images or videos must be present
|
| 488 |
+
if text is None and not (images or videos):
|
| 489 |
+
raise ValueError("If no text is provided, at least one of images or videos must be present.")
|
| 490 |
+
|
| 491 |
+
# Step 1: Pop video-specific kwargs to allow overriding class-level settings
|
| 492 |
+
video_fps = kwargs.pop("video_fps", self.video_fps)
|
| 493 |
+
video_minlen = kwargs.pop("video_minlen", self.video_minlen)
|
| 494 |
+
video_maxlen = kwargs.pop("video_maxlen", self.video_maxlen)
|
| 495 |
+
frame_extract_num_threads = kwargs.pop("frame_extract_num_threads", self.frame_extract_num_threads)
|
| 496 |
+
extract_frame_func = kwargs.pop("extract_frame_func", self.extract_frame_func)
|
| 497 |
+
max_image_tiles = kwargs.pop("max_image_tiles", self.image_processor.max_image_tiles)
|
| 498 |
+
|
| 499 |
+
# Step 2: Standardize inputs
|
| 500 |
+
# Step 2.1: Standardize text
|
| 501 |
+
# Step 2.1.1: If text is a string, convert it to a list of strings
|
| 502 |
+
if text is not None and isinstance(text, str):
|
| 503 |
+
text = [text]
|
| 504 |
+
# Step 2.1.2: Replace user-facing placeholders with tokenizer's special tokens
|
| 505 |
+
if text is not None:
|
| 506 |
+
processed_text: List[str] = []
|
| 507 |
+
for t in text:
|
| 508 |
+
# Can be List[str] or str
|
| 509 |
+
if isinstance(t, str):
|
| 510 |
+
t = t.replace(self.image_placeholder, self.image_token)
|
| 511 |
+
t = t.replace(self.video_placeholder, self.video_token)
|
| 512 |
+
processed_text.append(t)
|
| 513 |
+
text = processed_text
|
| 514 |
+
|
| 515 |
+
# Step 2.2: Normalize images
|
| 516 |
+
# If the input `images` is a string or a list of strings, open them into PIL Images first.
|
| 517 |
+
# Then, let `make_list_of_images` handle the rest.
|
| 518 |
+
loaded_images: Optional[ImageInput] = None
|
| 519 |
+
if images is not None:
|
| 520 |
+
if isinstance(images, str):
|
| 521 |
+
loaded_images = Image.open(images)
|
| 522 |
+
elif isinstance(images, list) and all(isinstance(i, str) for i in images):
|
| 523 |
+
loaded_images = [Image.open(i) for i in images]
|
| 524 |
+
elif isinstance(images, list) and all(isinstance(i, list) for i in images) and all(isinstance(j, str) for i in images for j in i):
|
| 525 |
+
loaded_images = [[Image.open(j) for j in i] for i in images]
|
| 526 |
+
else:
|
| 527 |
+
# If it's already a PIL Image, a list of PIL Images, or other formats, keep it as is.
|
| 528 |
+
loaded_images = images
|
| 529 |
+
images_list = make_list_of_images(loaded_images) if loaded_images is not None else None
|
| 530 |
+
|
| 531 |
+
# Step 2.3: Normalize videos
|
| 532 |
+
# If the input `videos` is a string (video_path), convert it to a list of strings
|
| 533 |
+
videos_list: Optional[List[List[str]]] = None
|
| 534 |
+
if videos is not None:
|
| 535 |
+
if isinstance(videos, str):
|
| 536 |
+
videos_list = [[videos]] # Batch of 1, sample with 1 video
|
| 537 |
+
elif isinstance(videos, list) and all(isinstance(i, str) for i in videos):
|
| 538 |
+
videos_list = [videos] # Batch of 1, sample with multiple videos
|
| 539 |
+
elif isinstance(videos, list) and all(isinstance(i, list) for i in videos) and all(isinstance(j, str) for i in videos for j in i):
|
| 540 |
+
videos_list = videos # Already in correct batch format
|
| 541 |
+
else:
|
| 542 |
+
raise ValueError(f"Invalid video input type: {type(videos)}")
|
| 543 |
+
|
| 544 |
+
# Step 3: Initialize the output kwargs
|
| 545 |
+
# Step 3.1: Initialize the output kwargs with `default values` and `kwargs` provided by the user
|
| 546 |
+
output_kwargs = self._merge_kwargs(
|
| 547 |
+
VideoMllamaProcessorKwargs,
|
| 548 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 549 |
+
**kwargs,
|
| 550 |
+
)
|
| 551 |
+
# Step 3.2: Pop the kwargs from the output kwargs to get `common_kwargs`, `text_kwargs`, and `images_kwargs`
|
| 552 |
+
common_kwargs = output_kwargs["common_kwargs"]
|
| 553 |
+
text_kwargs = output_kwargs["text_kwargs"]
|
| 554 |
+
images_kwargs = output_kwargs["images_kwargs"]
|
| 555 |
+
|
| 556 |
+
# [** Final data to be returned **]
|
| 557 |
+
data = {}
|
| 558 |
+
|
| 559 |
+
# Step 4: Text processing
|
| 560 |
+
original_encoding = {}
|
| 561 |
+
if text is not None:
|
| 562 |
+
batch_size = len(text)
|
| 563 |
+
# Step 4.1: Check n_images_in_text and n_videos_in_text to make sure they match the number of images and videos provided
|
| 564 |
+
if images_list is not None and len(images_list) != batch_size:
|
| 565 |
+
raise ValueError(
|
| 566 |
+
f"The number of samples in `text` ({batch_size}) and `images` ({len(images_list)}) do not match."
|
| 567 |
+
)
|
| 568 |
+
if videos_list is not None and len(videos_list) != batch_size:
|
| 569 |
+
raise ValueError(
|
| 570 |
+
f"The number of samples in `text` ({batch_size}) and `videos` ({len(videos_list)}) do not match."
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
n_images_in_text = [t.count(self.image_token) for t in text]
|
| 574 |
+
n_videos_in_text = [t.count(self.video_token) for t in text]
|
| 575 |
+
|
| 576 |
+
# Early validation for media token and provided media counts
|
| 577 |
+
n_images_provided = [len(img) for img in images_list] if images_list else [0] * len(text)
|
| 578 |
+
if any(img1 != img2 for img1, img2 in zip(n_images_in_text, n_images_provided)):
|
| 579 |
+
raise ValueError(
|
| 580 |
+
"Number of image tokens does not match number of images provided. "
|
| 581 |
+
f"Found {n_images_in_text} image tokens and {n_images_provided} images."
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
n_videos_provided = [len(vid) for vid in videos_list] if videos_list else [0] * len(text)
|
| 585 |
+
if any(vid1 != vid2 for vid1, vid2 in zip(n_videos_in_text, n_videos_provided)):
|
| 586 |
+
raise ValueError(
|
| 587 |
+
"Number of video tokens does not match number of videos provided. "
|
| 588 |
+
f"Found {n_videos_in_text} video tokens and {n_videos_provided} videos."
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
# Step 4.2: Build the text to be encoded. Specifically, if `bos_token` not exist, add it to the beginning of the text.
|
| 592 |
+
# text_to_encode = [
|
| 593 |
+
# build_string_from_input(text_item, self.bos_token, self.image_token, self.video_token)
|
| 594 |
+
# for text_item in text
|
| 595 |
+
# ]
|
| 596 |
+
|
| 597 |
+
# Step 4.2: Use the original text instead of the processed text
|
| 598 |
+
text_to_encode = text
|
| 599 |
+
# Step 4.3: Encode the text
|
| 600 |
+
original_encoding = self.tokenizer(text_to_encode, **text_kwargs)
|
| 601 |
+
|
| 602 |
+
# Step 4.4: Update the final data with the processed text encoding
|
| 603 |
+
if original_encoding:
|
| 604 |
+
data.update(original_encoding)
|
| 605 |
+
|
| 606 |
+
# Step 5: Image and Video processing
|
| 607 |
+
# This part handles image and video loading, frame extraction, and ordering.
|
| 608 |
+
batch_media = []
|
| 609 |
+
frame_num_per_video_batch = []
|
| 610 |
+
# Step 5.1: Determine the number of samples to process.
|
| 611 |
+
num_samples = 0
|
| 612 |
+
if text is not None:
|
| 613 |
+
num_samples = len(text)
|
| 614 |
+
else:
|
| 615 |
+
# If text is not provided, determine sample count from the longer of images/videos lists.
|
| 616 |
+
# We've already validated that at least one of them is present.
|
| 617 |
+
num_img_samples = len(images_list) if images_list else 0
|
| 618 |
+
num_vid_samples = len(videos_list) if videos_list else 0
|
| 619 |
+
num_samples = max(num_img_samples, num_vid_samples)
|
| 620 |
+
|
| 621 |
+
# No text provided, process media in default order (images first, then videos).
|
| 622 |
+
print("No text provided, processing media in default order (images first, then videos).")
|
| 623 |
+
|
| 624 |
+
for i in range(num_samples):
|
| 625 |
+
sample_images = images_list[i] if images_list and i < len(images_list) else []
|
| 626 |
+
sample_videos = videos_list[i] if videos_list and i < len(videos_list) else []
|
| 627 |
+
|
| 628 |
+
# Step 5.2: Determine the media order
|
| 629 |
+
media_order = []
|
| 630 |
+
if text is not None:
|
| 631 |
+
# Determine media order from text tokens
|
| 632 |
+
txt = text[i]
|
| 633 |
+
img_tokens_in_text = [(pos, "image") for pos, char in enumerate(txt) if txt.startswith(self.image_token, pos)]
|
| 634 |
+
vid_tokens_in_text = [(pos, "video") for pos, char in enumerate(txt) if txt.startswith(self.video_token, pos)]
|
| 635 |
+
# sort by position and get only the media type
|
| 636 |
+
media_order = [media_type for _, media_type in sorted(img_tokens_in_text + vid_tokens_in_text)]
|
| 637 |
+
else:
|
| 638 |
+
# Default order: all images, then all videos
|
| 639 |
+
media_order.extend(["image"] * len(sample_images))
|
| 640 |
+
media_order.extend(["video"] * len(sample_videos))
|
| 641 |
+
|
| 642 |
+
# Step 5.3: Add images and videos to the batch in the order of `media_order`
|
| 643 |
+
media_for_sample = []
|
| 644 |
+
num_frames_per_video_sample = []
|
| 645 |
+
image_idx = 0
|
| 646 |
+
video_idx = 0
|
| 647 |
+
|
| 648 |
+
for media_type in media_order:
|
| 649 |
+
if media_type == "image":
|
| 650 |
+
media_for_sample.append(sample_images[image_idx])
|
| 651 |
+
image_idx += 1
|
| 652 |
+
elif media_type == "video":
|
| 653 |
+
video_path = sample_videos[video_idx]
|
| 654 |
+
|
| 655 |
+
sampling_kwargs = {
|
| 656 |
+
"video_fps": video_fps,
|
| 657 |
+
"video_minlen": video_minlen,
|
| 658 |
+
"video_maxlen": video_maxlen,
|
| 659 |
+
"frame_extract_num_threads": frame_extract_num_threads,
|
| 660 |
+
}
|
| 661 |
+
try:
|
| 662 |
+
if extract_frame_func == "cv2":
|
| 663 |
+
frames = get_cv2_video_sample_frames_multithread(video_path, **sampling_kwargs)
|
| 664 |
+
else: # "av"
|
| 665 |
+
frames = get_video_sample_frames_av(video_path, **sampling_kwargs)
|
| 666 |
+
except Exception as e:
|
| 667 |
+
raise ValueError(f"This video format is not supported.\nvideo processing failed: {e}")
|
| 668 |
+
|
| 669 |
+
media_for_sample.extend(frames)
|
| 670 |
+
num_frames_per_video_sample.append(len(frames))
|
| 671 |
+
video_idx += 1
|
| 672 |
+
|
| 673 |
+
batch_media.append(media_for_sample)
|
| 674 |
+
frame_num_per_video_batch.append(num_frames_per_video_sample)
|
| 675 |
+
|
| 676 |
+
# Step 5.4: Process images with image_processor
|
| 677 |
+
num_tiles_batch = []
|
| 678 |
+
if any(batch_media):
|
| 679 |
+
images_kwargs["max_image_tiles"] = max_image_tiles
|
| 680 |
+
image_features = self.image_processor(batch_media, **images_kwargs)
|
| 681 |
+
num_tiles_batch = image_features.pop("num_tiles")
|
| 682 |
+
data.update(image_features)
|
| 683 |
+
|
| 684 |
+
# Step 6: Calculate cross attention token masks
|
| 685 |
+
if original_encoding:
|
| 686 |
+
cross_attention_token_masks = []
|
| 687 |
+
final_input_ids = []
|
| 688 |
+
final_attention_mask = []
|
| 689 |
+
|
| 690 |
+
# Step 6.1: Check if the attention mask is provided
|
| 691 |
+
has_attention_mask = "attention_mask" in original_encoding
|
| 692 |
+
|
| 693 |
+
for i, token_ids in enumerate(original_encoding["input_ids"]):
|
| 694 |
+
# Step 6.2: Get the attention mask for the sample
|
| 695 |
+
attention_mask_for_sample = (
|
| 696 |
+
original_encoding["attention_mask"][i] if has_attention_mask else [1] * len(token_ids)
|
| 697 |
+
)
|
| 698 |
+
# Step 6.3: Get the cross attention token masks for the sample
|
| 699 |
+
mask, converted_ids, converted_attn_mask = get_cross_attention_token_mask(
|
| 700 |
+
token_ids,
|
| 701 |
+
attention_mask_for_sample,
|
| 702 |
+
self.image_token_id,
|
| 703 |
+
self.video_token_id,
|
| 704 |
+
frame_num_per_video_batch[i],
|
| 705 |
+
self.cross_attention_token_mask_pad_token_id,
|
| 706 |
+
)
|
| 707 |
+
# Step 6.4: Append the `cross_attention_token_masks`, converted `final_input_ids`, and converted `converted_attn_mask` for the sample
|
| 708 |
+
cross_attention_token_masks.append(np.array(mask))
|
| 709 |
+
final_input_ids.append(converted_ids)
|
| 710 |
+
final_attention_mask.append(converted_attn_mask)
|
| 711 |
+
|
| 712 |
+
# Step 7: Calculate position_ids and vision_position_ids
|
| 713 |
+
if original_encoding:
|
| 714 |
+
batch_position_ids = []
|
| 715 |
+
batch_vision_position_ids = []
|
| 716 |
+
|
| 717 |
+
# NOTE: The logic is now changed to KEEP the <|image|> tokens in the input_ids.
|
| 718 |
+
# `final_input_ids` already contains the full sequence, and we will not filter it.
|
| 719 |
+
for i, ids in enumerate(final_input_ids):
|
| 720 |
+
# Step 7.1: Calculate `attention_mask_arr` and `image_mask` for `position_ids`
|
| 721 |
+
ids_arr = np.array(ids, dtype=np.int64)
|
| 722 |
+
attention_mask_arr = np.array(final_attention_mask[i], dtype=np.int64)
|
| 723 |
+
image_mask = ids_arr == self.image_token_id
|
| 724 |
+
|
| 725 |
+
# Step 7.2: Calculate `position_ids`
|
| 726 |
+
# Always calculate `position_ids`.
|
| 727 |
+
position_ids = np.cumsum(attention_mask_arr, dtype=np.int64) - 1
|
| 728 |
+
position_ids[attention_mask_arr == 0] = self.pad_position_id
|
| 729 |
+
batch_position_ids.append(position_ids)
|
| 730 |
+
|
| 731 |
+
# Step 7.3: Calculate `vision_position_ids`
|
| 732 |
+
# `vision_position_ids` are only calculated if add_video_position_encoding is enabled and we have media input
|
| 733 |
+
if self.add_video_position_encoding and any(batch_media):
|
| 734 |
+
batch_vision_position_ids.append(position_ids[image_mask])
|
| 735 |
+
|
| 736 |
+
# Step 8: Padding
|
| 737 |
+
if original_encoding:
|
| 738 |
+
# Step 8.1: Pad `input_ids`
|
| 739 |
+
data["input_ids"] = self._pad_sequences(
|
| 740 |
+
final_input_ids,
|
| 741 |
+
self.tokenizer.pad_token_id,
|
| 742 |
+
padding_side=self.tokenizer.padding_side,
|
| 743 |
+
pad_to_multiple_of=text_kwargs.get("pad_to_multiple_of"),
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
# Step 8.2: Pad `attention_mask`
|
| 747 |
+
data["attention_mask"] = self._pad_sequences(
|
| 748 |
+
final_attention_mask,
|
| 749 |
+
0,
|
| 750 |
+
padding_side=self.tokenizer.padding_side,
|
| 751 |
+
pad_to_multiple_of=text_kwargs.get("pad_to_multiple_of"),
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
# Step 8.3: Pad `padded_cross_attention_token_masks`
|
| 755 |
+
padded_cross_attention_token_masks = self._pad_sequences(
|
| 756 |
+
cross_attention_token_masks,
|
| 757 |
+
self.cross_attention_token_mask_pad_token_id,
|
| 758 |
+
padding_side=self.tokenizer.padding_side,
|
| 759 |
+
pad_to_multiple_of=text_kwargs.get("pad_to_multiple_of"),
|
| 760 |
+
)
|
| 761 |
+
|
| 762 |
+
# Step 8.4: Pad `position_ids`
|
| 763 |
+
data["position_ids"] = self._pad_sequences(
|
| 764 |
+
batch_position_ids,
|
| 765 |
+
self.pad_position_id,
|
| 766 |
+
padding_side=self.tokenizer.padding_side,
|
| 767 |
+
pad_to_multiple_of=text_kwargs.get("pad_to_multiple_of"),
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
# Step 8.5: Pad `vision_position_ids`
|
| 771 |
+
if self.add_video_position_encoding and any(batch_media):
|
| 772 |
+
# For vision_position_ids, we don't pad to multiple of.
|
| 773 |
+
# It must be right-padded to align with multi-modal feature processing.
|
| 774 |
+
data["vision_position_ids"] = self._pad_sequences(
|
| 775 |
+
batch_vision_position_ids,
|
| 776 |
+
self.pad_position_id,
|
| 777 |
+
padding_side="right",
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
# Step 9: Convert sparse cross attention token masks to dense
|
| 781 |
+
# original_encoding is not empty means: input_text is not empty
|
| 782 |
+
# num_tiles_batch is not empty means: images or videos are provided
|
| 783 |
+
if original_encoding and num_tiles_batch:
|
| 784 |
+
# shape is (batch_size, seq_len, max_num_images, max_num_tiles)
|
| 785 |
+
cross_attention_mask = convert_sparse_cross_attention_mask_to_dense(
|
| 786 |
+
padded_cross_attention_token_masks,
|
| 787 |
+
num_tiles=num_tiles_batch,
|
| 788 |
+
max_num_tiles=max_image_tiles,
|
| 789 |
+
cross_attention_token_mask_pad_token_id=self.cross_attention_token_mask_pad_token_id,
|
| 790 |
+
)
|
| 791 |
+
data["cross_attention_mask"] = cross_attention_mask
|
| 792 |
+
|
| 793 |
+
# Step 10: Return the batch feature
|
| 794 |
+
return_tensors = common_kwargs.pop("return_tensors", None)
|
| 795 |
+
batch_feature = BatchFeature(data=data, tensor_type=return_tensors)
|
| 796 |
+
|
| 797 |
+
return batch_feature
|
| 798 |
+
|
| 799 |
+
def batch_decode(self, *args, **kwargs):
|
| 800 |
+
"""
|
| 801 |
+
This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 802 |
+
refer to the docstring of this method for more information.
|
| 803 |
+
"""
|
| 804 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 805 |
+
|
| 806 |
+
def decode(self, *args, **kwargs):
|
| 807 |
+
"""
|
| 808 |
+
This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 809 |
+
the docstring of this method for more information.
|
| 810 |
+
"""
|
| 811 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 812 |
+
|
| 813 |
+
def post_process_image_text_to_text(self, generated_outputs):
|
| 814 |
+
"""
|
| 815 |
+
Post-process the output of the model to decode the text.
|
| 816 |
+
|
| 817 |
+
Args:
|
| 818 |
+
generated_outputs (`torch.Tensor` or `np.ndarray`):
|
| 819 |
+
The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
|
| 820 |
+
or `(sequence_length,)`.
|
| 821 |
+
|
| 822 |
+
Returns:
|
| 823 |
+
`List[str]`: The decoded text.
|
| 824 |
+
"""
|
| 825 |
+
return self.tokenizer.batch_decode(
|
| 826 |
+
generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
@property
|
| 830 |
+
def model_input_names(self):
|
| 831 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 832 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 833 |
+
model_inputs = list(tokenizer_input_names + image_processor_input_names + ["cross_attention_mask"])
|
| 834 |
+
if self.add_video_position_encoding:
|
| 835 |
+
model_inputs.extend(["position_ids", "vision_position_ids"])
|
| 836 |
+
return model_inputs
|