Mihaiii commited on
Commit
c28ed6a
·
verified ·
1 Parent(s): 9ebf7ec

Upload 5 files

Browse files
args (1).json ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "AIDC-AI/Ovis2-4B",
3
+ "model_type": "ovis1_6",
4
+ "model_revision": null,
5
+ "task_type": "causal_lm",
6
+ "torch_dtype": "bfloat16",
7
+ "attn_impl": null,
8
+ "num_labels": null,
9
+ "rope_scaling": null,
10
+ "device_map": null,
11
+ "local_repo_path": null,
12
+ "template": "ovis1_6",
13
+ "system": null,
14
+ "max_length": 2048,
15
+ "truncation_strategy": "left",
16
+ "max_pixels": null,
17
+ "tools_prompt": "react_en",
18
+ "norm_bbox": null,
19
+ "padding_side": "right",
20
+ "loss_scale": "last_round",
21
+ "sequence_parallel_size": 1,
22
+ "use_chat_template": true,
23
+ "template_backend": "swift",
24
+ "dataset": [
25
+ "Mihaiii/SROIE_2019_text_recognition-other-cols-5"
26
+ ],
27
+ "val_dataset": [],
28
+ "split_dataset_ratio": 0.01,
29
+ "data_seed": 42,
30
+ "dataset_num_proc": 4,
31
+ "streaming": false,
32
+ "enable_cache": false,
33
+ "download_mode": "reuse_dataset_if_exists",
34
+ "columns": {},
35
+ "strict": false,
36
+ "remove_unused_columns": false,
37
+ "model_name": [
38
+ null,
39
+ null
40
+ ],
41
+ "model_author": [
42
+ null,
43
+ null
44
+ ],
45
+ "custom_dataset_info": [],
46
+ "quant_method": null,
47
+ "quant_bits": null,
48
+ "hqq_axis": null,
49
+ "bnb_4bit_compute_dtype": "bfloat16",
50
+ "bnb_4bit_quant_type": "nf4",
51
+ "bnb_4bit_use_double_quant": true,
52
+ "bnb_4bit_quant_storage": null,
53
+ "max_new_tokens": 64,
54
+ "temperature": 0.9,
55
+ "top_k": null,
56
+ "top_p": null,
57
+ "repetition_penalty": null,
58
+ "num_beams": 1,
59
+ "stream": false,
60
+ "stop_words": [],
61
+ "logprobs": false,
62
+ "top_logprobs": null,
63
+ "ckpt_dir": null,
64
+ "load_dataset_config": null,
65
+ "lora_modules": [],
66
+ "tuner_backend": "peft",
67
+ "train_type": "lora",
68
+ "adapters": [],
69
+ "seed": 42,
70
+ "model_kwargs": {},
71
+ "load_args": true,
72
+ "load_data_args": false,
73
+ "use_hf": true,
74
+ "hub_token": null,
75
+ "custom_register_path": [],
76
+ "ignore_args_error": false,
77
+ "use_swift_lora": false,
78
+ "output_dir": "/workspace/output/v39-20250215-125538",
79
+ "overwrite_output_dir": false,
80
+ "do_train": false,
81
+ "do_eval": false,
82
+ "do_predict": false,
83
+ "eval_strategy": "steps",
84
+ "prediction_loss_only": false,
85
+ "per_device_train_batch_size": 4,
86
+ "per_device_eval_batch_size": 4,
87
+ "per_gpu_train_batch_size": null,
88
+ "per_gpu_eval_batch_size": null,
89
+ "gradient_accumulation_steps": 1,
90
+ "eval_accumulation_steps": null,
91
+ "eval_delay": 0,
92
+ "torch_empty_cache_steps": null,
93
+ "learning_rate": 1e-05,
94
+ "weight_decay": 0.1,
95
+ "adam_beta1": 0.9,
96
+ "adam_beta2": 0.999,
97
+ "adam_epsilon": 1e-08,
98
+ "max_grad_norm": 1.0,
99
+ "num_train_epochs": 1.0,
100
+ "max_steps": -1,
101
+ "lr_scheduler_type": "cosine",
102
+ "lr_scheduler_kwargs": null,
103
+ "warmup_ratio": 0.05,
104
+ "warmup_steps": 0,
105
+ "log_level": "passive",
106
+ "log_level_replica": "warning",
107
+ "log_on_each_node": true,
108
+ "logging_dir": "/workspace/output/v39-20250215-125538/runs",
109
+ "logging_strategy": "steps",
110
+ "logging_first_step": true,
111
+ "logging_steps": 5,
112
+ "logging_nan_inf_filter": true,
113
+ "save_strategy": "steps",
114
+ "save_steps": 250.0,
115
+ "save_total_limit": 2,
116
+ "save_safetensors": true,
117
+ "save_on_each_node": false,
118
+ "save_only_model": false,
119
+ "restore_callback_states_from_checkpoint": false,
120
+ "no_cuda": false,
121
+ "use_cpu": false,
122
+ "use_mps_device": false,
123
+ "jit_mode_eval": false,
124
+ "use_ipex": false,
125
+ "bf16": true,
126
+ "fp16": false,
127
+ "fp16_opt_level": "O1",
128
+ "half_precision_backend": "auto",
129
+ "bf16_full_eval": false,
130
+ "fp16_full_eval": false,
131
+ "tf32": null,
132
+ "local_rank": -1,
133
+ "ddp_backend": null,
134
+ "tpu_num_cores": null,
135
+ "tpu_metrics_debug": false,
136
+ "debug": null,
137
+ "dataloader_drop_last": false,
138
+ "eval_steps": 50.0,
139
+ "dataloader_num_workers": 4,
140
+ "dataloader_prefetch_factor": null,
141
+ "past_index": -1,
142
+ "run_name": null,
143
+ "disable_tqdm": null,
144
+ "label_names": null,
145
+ "load_best_model_at_end": false,
146
+ "metric_for_best_model": null,
147
+ "greater_is_better": null,
148
+ "ignore_data_skip": false,
149
+ "fsdp": "",
150
+ "fsdp_min_num_params": 0,
151
+ "fsdp_config": null,
152
+ "fsdp_transformer_layer_cls_to_wrap": null,
153
+ "accelerator_config": {
154
+ "dispatch_batches": false
155
+ },
156
+ "deepspeed": null,
157
+ "label_smoothing_factor": 0.0,
158
+ "optim": "adamw_torch",
159
+ "optim_args": null,
160
+ "adafactor": false,
161
+ "group_by_length": false,
162
+ "length_column_name": "length",
163
+ "report_to": [
164
+ "tensorboard"
165
+ ],
166
+ "ddp_find_unused_parameters": null,
167
+ "ddp_bucket_cap_mb": null,
168
+ "ddp_broadcast_buffers": null,
169
+ "dataloader_pin_memory": true,
170
+ "dataloader_persistent_workers": false,
171
+ "skip_memory_metrics": true,
172
+ "use_legacy_prediction_loop": false,
173
+ "push_to_hub": false,
174
+ "resume_from_checkpoint": null,
175
+ "hub_model_id": null,
176
+ "hub_strategy": "every_save",
177
+ "hub_private_repo": null,
178
+ "hub_always_push": false,
179
+ "gradient_checkpointing": true,
180
+ "gradient_checkpointing_kwargs": null,
181
+ "include_inputs_for_metrics": false,
182
+ "include_for_metrics": [],
183
+ "eval_do_concat_batches": true,
184
+ "fp16_backend": "auto",
185
+ "evaluation_strategy": "steps",
186
+ "push_to_hub_model_id": null,
187
+ "push_to_hub_organization": null,
188
+ "push_to_hub_token": null,
189
+ "mp_parameters": "",
190
+ "auto_find_batch_size": false,
191
+ "full_determinism": false,
192
+ "torchdynamo": null,
193
+ "ray_scope": "last",
194
+ "ddp_timeout": 1800,
195
+ "torch_compile": false,
196
+ "torch_compile_backend": null,
197
+ "torch_compile_mode": null,
198
+ "dispatch_batches": null,
199
+ "split_batches": null,
200
+ "include_tokens_per_second": false,
201
+ "include_num_input_tokens_seen": false,
202
+ "neftune_noise_alpha": null,
203
+ "optim_target_modules": null,
204
+ "batch_eval_metrics": false,
205
+ "eval_on_start": false,
206
+ "use_liger_kernel": false,
207
+ "eval_use_gather_object": false,
208
+ "average_tokens_across_devices": false,
209
+ "sortish_sampler": false,
210
+ "predict_with_generate": false,
211
+ "generation_max_length": null,
212
+ "generation_num_beams": null,
213
+ "generation_config": null,
214
+ "freeze_parameters": [
215
+ "visual_tokenizer"
216
+ ],
217
+ "freeze_parameters_ratio": 0.0,
218
+ "trainable_parameters": [],
219
+ "freeze_llm": false,
220
+ "freeze_vit": true,
221
+ "freeze_aligner": true,
222
+ "target_modules": [
223
+ "all-linear"
224
+ ],
225
+ "target_regex": null,
226
+ "modules_to_save": [],
227
+ "lora_rank": 8,
228
+ "lora_alpha": 32,
229
+ "lora_dropout": 0.05,
230
+ "lora_bias": "none",
231
+ "lora_dtype": null,
232
+ "lorap_lr_ratio": null,
233
+ "use_rslora": false,
234
+ "use_dora": false,
235
+ "lora_ga_batch_size": 2,
236
+ "lora_ga_iters": 2,
237
+ "lora_ga_max_length": 1024,
238
+ "lora_ga_direction": "ArB2r",
239
+ "lora_ga_scale": "stable",
240
+ "lora_ga_stable_gamma": 16,
241
+ "init_weights": true,
242
+ "fourier_n_frequency": 2000,
243
+ "fourier_scaling": 300.0,
244
+ "boft_block_size": 4,
245
+ "boft_block_num": 0,
246
+ "boft_n_butterfly_factor": 1,
247
+ "boft_dropout": 0.0,
248
+ "vera_rank": 256,
249
+ "vera_projection_prng_key": 0,
250
+ "vera_dropout": 0.0,
251
+ "vera_d_initial": 0.1,
252
+ "adapter_act": "gelu",
253
+ "adapter_length": 128,
254
+ "use_galore": false,
255
+ "galore_target_modules": null,
256
+ "galore_rank": 128,
257
+ "galore_update_proj_gap": 50,
258
+ "galore_scale": 1.0,
259
+ "galore_proj_type": "std",
260
+ "galore_optim_per_parameter": false,
261
+ "galore_with_embedding": false,
262
+ "galore_quantization": false,
263
+ "galore_proj_quant": false,
264
+ "galore_proj_bits": 4,
265
+ "galore_proj_group_size": 256,
266
+ "galore_cos_threshold": 0.4,
267
+ "galore_gamma_proj": 2,
268
+ "galore_queue_size": 5,
269
+ "adalora_target_r": 8,
270
+ "adalora_init_r": 12,
271
+ "adalora_tinit": 0,
272
+ "adalora_tfinal": 0,
273
+ "adalora_deltaT": 1,
274
+ "adalora_beta1": 0.85,
275
+ "adalora_beta2": 0.85,
276
+ "adalora_orth_reg_weight": 0.5,
277
+ "llamapro_num_new_blocks": 4,
278
+ "llamapro_num_groups": null,
279
+ "lisa_activated_layers": 0,
280
+ "lisa_step_interval": 20,
281
+ "reft_layer_key": null,
282
+ "reft_layers": null,
283
+ "reft_rank": 4,
284
+ "reft_intervention_type": "LoreftIntervention",
285
+ "reft_args": null,
286
+ "use_liger": false,
287
+ "model_layer_cls_name": null,
288
+ "metric_warmup_step": 0,
289
+ "fsdp_num": 1,
290
+ "acc_steps": 1,
291
+ "add_version": true,
292
+ "resume_only_model": false,
293
+ "check_model": true,
294
+ "create_checkpoint_symlink": false,
295
+ "packing": false,
296
+ "lazy_tokenize": true,
297
+ "external_plugins": [],
298
+ "loss_type": null,
299
+ "optimizer": null,
300
+ "metric": null,
301
+ "acc_strategy": "token",
302
+ "reward_model": null,
303
+ "reward_adapters": [],
304
+ "reward_model_type": null,
305
+ "reward_model_revision": null,
306
+ "num_ppo_epochs": 4,
307
+ "whiten_rewards": false,
308
+ "kl_coef": 0.05,
309
+ "cliprange": 0.2,
310
+ "vf_coef": 0.1,
311
+ "cliprange_value": 0.2,
312
+ "gamma": 1.0,
313
+ "lam": 0.95,
314
+ "num_mini_batches": 1,
315
+ "local_rollout_forward_batch_size": 64,
316
+ "num_sample_generations": 10,
317
+ "response_length": 512,
318
+ "missing_eos_penalty": null,
319
+ "vllm_max_num_seqs": 256,
320
+ "vllm_enforce_eager": false,
321
+ "vllm_limit_mm_per_prompt": null,
322
+ "vllm_enable_prefix_caching": true,
323
+ "cosine_min_len_value_wrong": 0.0,
324
+ "cosine_max_len_value_wrong": -0.5,
325
+ "cosine_min_len_value_correct": 1.0,
326
+ "cosine_max_len_value_correct": 0.5,
327
+ "cosine_max_len": null,
328
+ "repetition_n_grams": 3,
329
+ "repetition_max_penalty": -1.0,
330
+ "num_generations": 4,
331
+ "max_completion_length": 1024,
332
+ "ds3_gather_for_generation": true,
333
+ "reward_funcs": [
334
+ "db_accuracy"
335
+ ],
336
+ "reward_weights": null,
337
+ "log_completions": false,
338
+ "use_vllm": false,
339
+ "vllm_device": "auto",
340
+ "vllm_gpu_memory_utilization": 0.9,
341
+ "vllm_max_model_len": null,
342
+ "rlhf_type": "grpo",
343
+ "ref_model": null,
344
+ "ref_model_type": null,
345
+ "ref_model_revision": null,
346
+ "beta": 0.04,
347
+ "label_smoothing": 0,
348
+ "rpo_alpha": 1.0,
349
+ "cpo_alpha": 1.0,
350
+ "simpo_gamma": 1,
351
+ "desirable_weight": 1.0,
352
+ "undesirable_weight": 1.0,
353
+ "rank": -1,
354
+ "global_world_size": 1,
355
+ "local_world_size": 1,
356
+ "model_suffix": "Ovis2-4B",
357
+ "model_info": "ModelInfo(model_type='ovis1_6', model_dir='/root/.cache/huggingface/hub/models--AIDC-AI--Ovis2-4B/snapshots/5e1d0dbd5f3ba42246de46d03bb4de70224dbafd', torch_dtype=torch.bfloat16, max_model_len=32768, quant_method=None, quant_bits=None, config=None, task_type='causal_lm', num_labels=None)",
358
+ "model_meta": "ModelMeta(model_type='ovis1_6', model_groups=[ModelGroup(models=[Model(ms_model_id='AIDC-AI/Ovis1.6-Gemma2-9B', hf_model_id='AIDC-AI/Ovis1.6-Gemma2-9B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='AIDC-AI/Ovis1.6-Gemma2-9B-GPTQ-Int4', hf_model_id='AIDC-AI/Ovis1.6-Gemma2-9B-GPTQ-Int4', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='AIDC-AI/Ovis1.6-Gemma2-27B', hf_model_id='AIDC-AI/Ovis1.6-Gemma2-27B', model_path=None, ms_revision=None, hf_revision=None)], ignore_patterns=None, requires=None, tags=[])], template='ovis1_6', get_function=<function get_model_tokenizer_ovis at 0x79c0d1fbe830>, model_arch='ovis1_6', architectures=['Ovis'], additional_saved_files=[], torch_dtype=None, is_multimodal=True, is_reward=False, task_type=None, ignore_patterns=[], requires=['transformers>=4.42'], tags=['vision'])",
359
+ "model_dir": "/root/.cache/huggingface/hub/models--AIDC-AI--Ovis2-4B/snapshots/5e1d0dbd5f3ba42246de46d03bb4de70224dbafd",
360
+ "hub": "<class 'swift.hub.hub.HFHub'>",
361
+ "training_args": "GRPOConfig(output_dir='/workspace/output/v39-20250215-125538', overwrite_output_dir=False, do_train=False, do_eval=True, do_predict=False, eval_strategy=<IntervalStrategy.STEPS: 'steps'>, prediction_loss_only=False, per_device_train_batch_size=4, per_device_eval_batch_size=4, per_gpu_train_batch_size=None, per_gpu_eval_batch_size=None, gradient_accumulation_steps=1, eval_accumulation_steps=None, eval_delay=0, torch_empty_cache_steps=None, learning_rate=1e-05, weight_decay=0.1, adam_beta1=0.9, adam_beta2=0.999, adam_epsilon=1e-08, max_grad_norm=1.0, num_train_epochs=1.0, max_steps=-1, lr_scheduler_type=<SchedulerType.COSINE: 'cosine'>, lr_scheduler_kwargs=None, warmup_ratio=0.05, warmup_steps=0, log_level='passive', log_level_replica='warning', log_on_each_node=True, logging_dir='/workspace/output/v39-20250215-125538/runs', logging_strategy=<IntervalStrategy.STEPS: 'steps'>, logging_first_step=True, logging_steps=5, logging_nan_inf_filter=True, save_strategy=<SaveStrategy.STEPS: 'steps'>, save_steps=250, save_total_limit=2, save_safetensors=True, save_on_each_node=False, save_only_model=False, restore_callback_states_from_checkpoint=False, no_cuda=False, use_cpu=False, use_mps_device=False, seed=42, data_seed=42, jit_mode_eval=False, use_ipex=False, bf16=True, fp16=False, fp16_opt_level='O1', half_precision_backend='auto', bf16_full_eval=False, fp16_full_eval=False, tf32=None, local_rank=0, ddp_backend=None, tpu_num_cores=None, tpu_metrics_debug=False, debug=[], dataloader_drop_last=False, eval_steps=50, dataloader_num_workers=4, dataloader_prefetch_factor=None, past_index=-1, run_name='/workspace/output/v39-20250215-125538', disable_tqdm=False, remove_unused_columns=False, label_names=None, load_best_model_at_end=False, metric_for_best_model=None, greater_is_better=None, ignore_data_skip=False, fsdp=[], fsdp_min_num_params=0, fsdp_config={'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}, fsdp_transformer_layer_cls_to_wrap=None, accelerator_config=AcceleratorConfig(split_batches=False, dispatch_batches=False, even_batches=True, use_seedable_sampler=True, non_blocking=False, gradient_accumulation_kwargs=None, use_configured_state=False), deepspeed=None, label_smoothing_factor=0.0, optim=<OptimizerNames.ADAMW_TORCH: 'adamw_torch'>, optim_args=None, adafactor=False, group_by_length=False, length_column_name='length', report_to=['tensorboard'], ddp_find_unused_parameters=None, ddp_bucket_cap_mb=None, ddp_broadcast_buffers=None, dataloader_pin_memory=True, dataloader_persistent_workers=False, skip_memory_metrics=True, use_legacy_prediction_loop=False, push_to_hub=False, resume_from_checkpoint=None, hub_model_id=None, hub_strategy=<HubStrategy.EVERY_SAVE: 'every_save'>, hub_token=None, hub_private_repo=None, hub_always_push=False, gradient_checkpointing=True, gradient_checkpointing_kwargs=None, include_inputs_for_metrics=False, include_for_metrics=[], eval_do_concat_batches=True, fp16_backend='auto', evaluation_strategy='steps', push_to_hub_model_id=None, push_to_hub_organization=None, push_to_hub_token=None, mp_parameters='', auto_find_batch_size=False, full_determinism=False, torchdynamo=None, ray_scope='last', ddp_timeout=1800, torch_compile=False, torch_compile_backend=None, torch_compile_mode=None, dispatch_batches=None, split_batches=None, include_tokens_per_second=None, include_num_input_tokens_seen=None, neftune_noise_alpha=None, optim_target_modules=None, batch_eval_metrics=False, eval_on_start=False, use_liger_kernel=False, eval_use_gather_object=False, average_tokens_across_devices=None, model_init_kwargs=None, max_prompt_length=512, num_generations=4, temperature=0.9, max_completion_length=1024, ds3_gather_for_generation=True, use_vllm=False, vllm_device='auto', vllm_gpu_memory_utilization=0.9, vllm_dtype='auto', vllm_max_model_len=None, beta=0.04, reward_weights=None, sync_ref_model=False, ref_model_mixup_alpha=0.9, ref_model_sync_steps=64, log_completions=False, acc_strategy='token', sequence_parallel_size=1, check_model=True, train_sampler_random=True, is_encoder_decoder=False, metric_warmup_step=0, train_dataset_sample=-1, fsdp_num=1, acc_steps=1, train_type='lora', optimizer=None, galore_config=None, vllm_max_num_seqs=256, vllm_enforce_eager=False, vllm_limit_mm_per_prompt=None, vllm_enable_prefix_caching=True, cosine_min_len_value_wrong=0.0, cosine_max_len_value_wrong=-0.5, cosine_min_len_value_correct=1.0, cosine_max_len_value_correct=0.5, cosine_max_len=1024, repetition_n_grams=3, repetition_max_penalty=-1.0, top_k=None, top_p=None, repetition_penalty=None)"
362
+ }
configuration_aimv2.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # copied from https://huggingface.co/apple/aimv2-huge-patch14-448
2
+ from typing import Any
3
+
4
+ from transformers.configuration_utils import PretrainedConfig
5
+
6
+ __all__ = ["AIMv2Config"]
7
+
8
+
9
+ class AIMv2Config(PretrainedConfig):
10
+ """This is the configuration class to store the configuration of an [`AIMv2Model`].
11
+
12
+ Instantiating a configuration with the defaults will yield a similar configuration
13
+ to that of the [apple/aimv2-large-patch14-224](https://huggingface.co/apple/aimv2-large-patch14-224).
14
+
15
+ Args:
16
+ hidden_size: Dimension of the hidden representations.
17
+ intermediate_size: Dimension of the SwiGLU representations.
18
+ num_hidden_layers: Number of hidden layers in the Transformer.
19
+ num_attention_heads: Number of attention heads for each attention layer
20
+ in the Transformer.
21
+ num_channels: Number of input channels.
22
+ image_size: Image size.
23
+ patch_size: Patch size.
24
+ rms_norm_eps: Epsilon value used for the RMS normalization layer.
25
+ attention_dropout: Dropout ratio for attention probabilities.
26
+ projection_dropout: Dropout ratio for the projection layer after the attention.
27
+ qkv_bias: Whether to add a bias to the queries, keys and values.
28
+ use_bias: Whether to add a bias in the feed-forward and projection layers.
29
+ kwargs: Keyword arguments for the [`PretrainedConfig`].
30
+ """
31
+
32
+ model_type: str = "aimv2"
33
+
34
+ def __init__(
35
+ self,
36
+ hidden_size: int = 1024,
37
+ intermediate_size: int = 2816,
38
+ num_hidden_layers: int = 24,
39
+ num_attention_heads: int = 8,
40
+ num_channels: int = 3,
41
+ image_size: int = 224,
42
+ patch_size: int = 14,
43
+ rms_norm_eps: float = 1e-5,
44
+ attention_dropout: float = 0.0,
45
+ projection_dropout: float = 0.0,
46
+ qkv_bias: bool = False,
47
+ use_bias: bool = False,
48
+ **kwargs: Any,
49
+ ):
50
+ super().__init__(**kwargs)
51
+ self.hidden_size = hidden_size
52
+ self.intermediate_size = intermediate_size
53
+ self.num_hidden_layers = num_hidden_layers
54
+ self.num_attention_heads = num_attention_heads
55
+ self.num_channels = num_channels
56
+ self.patch_size = patch_size
57
+ self.image_size = image_size
58
+ self.attention_dropout = attention_dropout
59
+ self.rms_norm_eps = rms_norm_eps
60
+
61
+ self.projection_dropout = projection_dropout
62
+ self.qkv_bias = qkv_bias
63
+ self.use_bias = use_bias
generation_config.json CHANGED
@@ -11,5 +11,5 @@
11
  "temperature": 0.7,
12
  "top_k": 20,
13
  "top_p": 0.8,
14
- "transformers_version": "4.49.0"
15
  }
 
11
  "temperature": 0.7,
12
  "top_k": 20,
13
  "top_p": 0.8,
14
+ "transformers_version": "4.46.2"
15
  }
modeling_aimv2.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # adapted from https://huggingface.co/apple/aimv2-huge-patch14-448 (modification: add gradient checkpoint support)
2
+ from typing import Optional, Tuple, Union
3
+
4
+ import torch
5
+ from .configuration_aimv2 import AIMv2Config
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+ from transformers.modeling_outputs import BaseModelOutputWithNoAttention
9
+ from transformers.modeling_utils import PreTrainedModel
10
+
11
+ __all__ = ["AIMv2Model"]
12
+
13
+
14
+ class RMSNorm(nn.Module):
15
+ def __init__(self, dim: int, eps: float = 1e-6):
16
+ super().__init__()
17
+ self.weight = nn.Parameter(torch.ones(dim))
18
+ self.eps = eps
19
+
20
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
21
+ output = self._norm(x.float()).type_as(x)
22
+ return output * self.weight
23
+
24
+ def extra_repr(self) -> str:
25
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
26
+
27
+ def _norm(self, x: torch.Tensor) -> torch.Tensor:
28
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
29
+
30
+
31
+ class AIMv2SwiGLUFFN(nn.Module):
32
+ def __init__(self, config: AIMv2Config):
33
+ super().__init__()
34
+ hidden_features = config.intermediate_size
35
+ in_features = config.hidden_size
36
+ bias = config.use_bias
37
+
38
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
39
+ self.fc2 = nn.Linear(hidden_features, in_features, bias=bias)
40
+ self.fc3 = nn.Linear(in_features, hidden_features, bias=bias)
41
+
42
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
43
+ x = F.silu(self.fc1(x)) * self.fc3(x)
44
+ x = self.fc2(x)
45
+ return x
46
+
47
+
48
+ class AIMv2PatchEmbed(nn.Module):
49
+ def __init__(self, config: AIMv2Config):
50
+ super().__init__()
51
+ self.proj = nn.Conv2d(
52
+ config.num_channels,
53
+ config.hidden_size,
54
+ kernel_size=(config.patch_size, config.patch_size),
55
+ stride=(config.patch_size, config.patch_size),
56
+ )
57
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
58
+
59
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
60
+ x = self.proj(x).flatten(2).transpose(1, 2)
61
+ x = self.norm(x)
62
+ return x
63
+
64
+
65
+ class AIMv2ViTPreprocessor(nn.Module):
66
+ def __init__(self, config: AIMv2Config):
67
+ super().__init__()
68
+ num_patches = (config.image_size // config.patch_size) ** 2
69
+
70
+ self.patchifier = AIMv2PatchEmbed(config)
71
+ self.pos_embed = nn.Parameter(torch.zeros((1, num_patches, config.hidden_size)))
72
+
73
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
74
+ tokens = self.patchifier(x)
75
+ _, N, _ = tokens.shape
76
+ pos_embed = self.pos_embed.to(tokens.device)
77
+ tokens = tokens + pos_embed[:, :N]
78
+ return tokens
79
+
80
+
81
+ class AIMv2Attention(nn.Module):
82
+ def __init__(self, config: AIMv2Config):
83
+ super().__init__()
84
+ dim = config.hidden_size
85
+
86
+ self.num_heads = config.num_attention_heads
87
+ self.qkv = nn.Linear(dim, dim * 3, bias=config.qkv_bias)
88
+ self.attn_drop = nn.Dropout(config.attention_dropout)
89
+ self.proj = nn.Linear(dim, dim, bias=config.use_bias)
90
+ self.proj_drop = nn.Dropout(config.projection_dropout)
91
+
92
+ def forward(
93
+ self, x: torch.Tensor, mask: Optional[torch.Tensor] = None
94
+ ) -> torch.Tensor:
95
+ B, N, C = x.shape
96
+ qkv = (
97
+ self.qkv(x)
98
+ .reshape(B, N, 3, self.num_heads, C // self.num_heads)
99
+ .permute(2, 0, 3, 1, 4)
100
+ )
101
+ q, k, v = qkv.unbind(0)
102
+
103
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
104
+ x = x.transpose(1, 2).contiguous().reshape(B, N, C)
105
+ x = self.proj(x)
106
+ x = self.proj_drop(x)
107
+ return x
108
+
109
+
110
+ class AIMv2Block(nn.Module):
111
+ def __init__(self, config: AIMv2Config):
112
+ super().__init__()
113
+ self.attn = AIMv2Attention(config)
114
+ self.norm_1 = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
115
+ self.mlp = AIMv2SwiGLUFFN(config)
116
+ self.norm_2 = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
117
+
118
+ def forward(
119
+ self, x: torch.Tensor, mask: Optional[torch.Tensor] = None
120
+ ) -> torch.Tensor:
121
+ x = x + self.attn(self.norm_1(x), mask)
122
+ x = x + self.mlp(self.norm_2(x))
123
+ return x
124
+
125
+
126
+ class AIMv2Transformer(nn.Module):
127
+ def __init__(self, config: AIMv2Config):
128
+ super().__init__()
129
+ self.blocks = nn.ModuleList(
130
+ [AIMv2Block(config) for _ in range(config.num_hidden_layers)]
131
+ )
132
+ self.post_trunk_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
133
+ self.gradient_checkpointing = False
134
+
135
+ def forward(
136
+ self,
137
+ tokens: torch.Tensor,
138
+ mask: Optional[torch.Tensor] = None,
139
+ output_hidden_states: bool = False,
140
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, ...]]]:
141
+ hidden_states = () if output_hidden_states else None
142
+ for block in self.blocks:
143
+ if self.gradient_checkpointing and self.training:
144
+ tokens = self._gradient_checkpointing_func(block.__call__, tokens, mask)
145
+ else:
146
+ tokens = block(tokens, mask)
147
+ if output_hidden_states:
148
+ hidden_states += (tokens,)
149
+ tokens = self.post_trunk_norm(tokens)
150
+ return tokens, hidden_states
151
+
152
+
153
+ class AIMv2PretrainedModel(PreTrainedModel):
154
+ config_class = AIMv2Config
155
+ base_model_prefix = "aimv2"
156
+ supports_gradient_checkpointing = True
157
+ main_input_name = "pixel_values"
158
+ _no_split_modules = ["AIMv2ViTPreprocessor", "AIMv2Block"]
159
+ _supports_sdpa = True
160
+
161
+
162
+ class AIMv2Model(AIMv2PretrainedModel):
163
+ def __init__(self, config: AIMv2Config):
164
+ super().__init__(config)
165
+ self.preprocessor = AIMv2ViTPreprocessor(config)
166
+ self.trunk = AIMv2Transformer(config)
167
+
168
+ def forward(
169
+ self,
170
+ pixel_values: torch.Tensor,
171
+ mask: Optional[torch.Tensor] = None,
172
+ output_hidden_states: Optional[bool] = None,
173
+ return_dict: Optional[bool] = None,
174
+ ) -> Union[
175
+ Tuple[torch.Tensor],
176
+ Tuple[torch.Tensor, Tuple[torch.Tensor, ...]],
177
+ BaseModelOutputWithNoAttention,
178
+ ]:
179
+ if output_hidden_states is None:
180
+ output_hidden_states = self.config.output_hidden_states
181
+ if return_dict is None:
182
+ return_dict = self.config.use_return_dict
183
+
184
+ x = self.preprocessor(pixel_values)
185
+ x, hidden_states = self.trunk(
186
+ x, mask, output_hidden_states=output_hidden_states
187
+ )
188
+
189
+ if not return_dict:
190
+ res = (x,)
191
+ res += (hidden_states,) if output_hidden_states else ()
192
+ return res
193
+
194
+ return BaseModelOutputWithNoAttention(
195
+ last_hidden_state=x,
196
+ hidden_states=hidden_states,
197
+ )
198
+
modeling_ovis.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2025 AIDC-AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ #
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ import os
17
+ import importlib.metadata
18
+
19
+ from packaging import version
20
+ from importlib import import_module
21
+ from typing import List, Callable, Union, Optional, Dict
22
+
23
+ import PIL.Image
24
+ import torch
25
+ from torch import Tensor
26
+ from torch.nn import init
27
+ from torch.nn.functional import softmax, gumbel_softmax, pad
28
+ from transformers.utils import is_flash_attn_2_available
29
+ from transformers import PreTrainedModel, AutoModel, AutoTokenizer, AutoModelForCausalLM, AutoImageProcessor
30
+ from transformers.generation.utils import GenerateOutput
31
+
32
+ from .configuration_ovis import BaseVisualTokenizerConfig, Aimv2VisualTokenizerConfig
33
+ from .configuration_ovis import OvisConfig, ConversationFormatter
34
+ from .configuration_ovis import IGNORE_ID, IMAGE_ATOM_ID, IMAGE_INDICATOR_IDS, IMAGE_TOKEN_ID
35
+
36
+ # ----------------------------------------------------------------------
37
+ # Visual Tokenizer
38
+ # ----------------------------------------------------------------------
39
+ class BaseVisualTokenizer(PreTrainedModel):
40
+ base_model_prefix = "backbone"
41
+ main_input_name = None
42
+ _image_processor_class = None
43
+ _image_processor_kwargs = {}
44
+ _backbone_class = None
45
+ _backbone_name_or_path = None
46
+
47
+ def __init__(self, config: BaseVisualTokenizerConfig, *inputs, **kwargs):
48
+ super().__init__(config, *inputs, **kwargs)
49
+ self.image_processor = AutoImageProcessor.from_pretrained(kwargs['image_processor_name_or_path'])
50
+ self.backbone = AutoModel.from_config(self.config.backbone_config)
51
+ head_dim = self.config.vocab_size - len(IMAGE_INDICATOR_IDS) # reserved tokens for IMAGE_INDICATORS
52
+ self.head = torch.nn.Sequential(
53
+ torch.nn.Linear(
54
+ self.backbone.config.hidden_size * self.config.hidden_stride * self.config.hidden_stride, head_dim,
55
+ bias=False
56
+ ),
57
+ torch.nn.LayerNorm(head_dim)
58
+ )
59
+
60
+ assert all((self.image_processor.do_resize,
61
+ not getattr(self.image_processor, 'do_center_crop', False),
62
+ self.image_processor.do_rescale,
63
+ self.image_processor.do_normalize
64
+ )), f"image_processor `{self.image_processor}` is not supported currently"
65
+
66
+ def get_backbone(self):
67
+ return self.backbone
68
+
69
+ def get_image_processor(self):
70
+ return self.image_processor
71
+
72
+ def mock_input(self):
73
+ height, width = self.get_image_size()
74
+ return torch.zeros(1, 3, height, width), self.construct_image_placeholders((1, 1))
75
+
76
+ def get_head(self):
77
+ return self.head
78
+
79
+ def get_image_size(self):
80
+ raise NotImplementedError
81
+
82
+ @staticmethod
83
+ def construct_image_placeholders(grid):
84
+ image_placeholders = [IMAGE_INDICATOR_IDS[0], IMAGE_ATOM_ID, IMAGE_INDICATOR_IDS[1]]
85
+ if grid[0] * grid[1] > 1:
86
+ for r in range(grid[0]):
87
+ for c in range(grid[1]):
88
+ image_placeholders.append(IMAGE_ATOM_ID)
89
+ if c < grid[1] - 1:
90
+ image_placeholders.append(IMAGE_INDICATOR_IDS[2])
91
+ if r < grid[0] - 1:
92
+ image_placeholders.append(IMAGE_INDICATOR_IDS[3])
93
+ image_placeholders.append(IMAGE_INDICATOR_IDS[4])
94
+ return image_placeholders
95
+
96
+ def preprocess_image(self, image: PIL.Image.Image, max_partition=9, covering_threshold=0.9, convert_to_rgb=True):
97
+ def _preprocess(img: PIL.Image.Image, side):
98
+ # first resize and preprocess
99
+ w, h = img.size
100
+ if w == h:
101
+ new_width = new_height = side
102
+ elif w > h:
103
+ new_width = side
104
+ new_height = int(h / w * new_width)
105
+ else:
106
+ new_height = side
107
+ new_width = int(w / h * new_height)
108
+ new_size = dict(height=new_height, width=new_width)
109
+ pixel_values = self.image_processor.preprocess(img, size=new_size, return_tensors='pt')['pixel_values']
110
+
111
+ # then pad to square
112
+ square_values = torch.zeros([1, 3, side, side], dtype=pixel_values.dtype, device=pixel_values.device)
113
+ new_height, new_width = pixel_values.shape[2:]
114
+ if new_height == new_width:
115
+ square_values[:, :, :, :] = pixel_values
116
+ elif new_height > new_width:
117
+ from_index = (side - new_width) // 2
118
+ square_values[:, :, :, from_index:from_index + new_width] = pixel_values
119
+ else:
120
+ from_index = (side - new_height) // 2
121
+ square_values[:, :, from_index:from_index + new_height, :] = pixel_values
122
+
123
+ return square_values
124
+
125
+ def _partition(img, grid):
126
+ w, h = img.size
127
+ row_height = h // grid[0]
128
+ col_width = w // grid[1]
129
+
130
+ partition = []
131
+ for row in range(grid[0]):
132
+ for col in range(grid[1]):
133
+ left = col * col_width
134
+ upper = row * row_height
135
+ right = w if col == grid[1] - 1 else (col + 1) * col_width
136
+ lower = h if row == grid[0] - 1 else (row + 1) * row_height
137
+ partition.append((left, upper, right, lower))
138
+
139
+ return partition
140
+
141
+ def _covering_area(left, upper, right, lower, side):
142
+ w = right - left
143
+ h = lower - upper
144
+ w, h = max(w, h), min(w, h)
145
+ if w > side:
146
+ h = h / w * side
147
+ w = side
148
+ return w * h
149
+
150
+ def _get_best_grid(img, side):
151
+ img_area = img.size[0] * img.size[1]
152
+
153
+ candidate_grids = []
154
+ for i in range(1, max_partition + 1):
155
+ for j in range(1, max_partition + 1):
156
+ if i * j <= max_partition:
157
+ candidate_grids.append((i, j))
158
+
159
+ all_grids = []
160
+ good_grids = []
161
+ for grid in candidate_grids:
162
+ partition = _partition(img, grid)
163
+ covering_ratio = sum([_covering_area(*p, side) for p in partition]) / img_area
164
+ assert covering_ratio <= 1.0
165
+ all_grids.append((grid, covering_ratio))
166
+ if covering_ratio > covering_threshold:
167
+ good_grids.append((grid, covering_ratio))
168
+
169
+ if len(good_grids) > 0:
170
+ # pick the good partition with minimum #sub_images and break the tie using covering_ratio
171
+ return sorted(good_grids, key=lambda x: (x[0][0] * x[0][1], -x[1]))[0][0]
172
+ else:
173
+ # pick the partition with maximum covering_ratio and break the tie using #sub_images
174
+ return sorted(all_grids, key=lambda x: (-x[1], x[0][0] * x[0][1]))[0][0]
175
+
176
+ if convert_to_rgb and image.mode != 'RGB':
177
+ image = image.convert('RGB')
178
+
179
+ sides = self.get_image_size()
180
+ if sides[0] != sides[1]:
181
+ raise ValueError('get_image_size() returns non-square size')
182
+ side = sides[0]
183
+ grid = _get_best_grid(image, side)
184
+ partition = _partition(image, grid)
185
+ crops = [image.crop(p) for p in partition]
186
+ if len(crops) > 1:
187
+ crops.insert(0, image)
188
+ pixel_values = torch.cat([_preprocess(crop, side) for crop in crops], dim=0)
189
+ image_placeholders = self.construct_image_placeholders(grid)
190
+ return pixel_values, image_placeholders
191
+
192
+ def tokenize(self, logits):
193
+ def st_argmax(y_soft, dim): # straight-through softmax
194
+ index = y_soft.max(dim, keepdim=True)[1]
195
+ y_hard = torch.zeros_like(y_soft, memory_format=torch.legacy_contiguous_format).scatter_(dim, index, 1.0)
196
+ ret = y_hard - y_soft.detach() + y_soft
197
+ return ret
198
+
199
+ if self.config.tokenize_function == 'softmax':
200
+ tokens = softmax(logits, dim=-1)
201
+ elif self.config.tokenize_function == 'gumbel_argmax':
202
+ tokens = gumbel_softmax(logits, tau=self.config.tau, hard=True)
203
+ elif self.config.tokenize_function == 'st_argmax':
204
+ tokens = st_argmax(logits, dim=-1)
205
+ else:
206
+ raise ValueError(
207
+ f'Invalid `max_type`, expected softmax or gumbel_argmax or st_argmax, but got {self.config.tokenize_function}')
208
+ return tokens
209
+
210
+ def encode(self, pixel_values):
211
+ output = self.backbone(pixel_values, output_hidden_states=True, return_dict=True)
212
+ features = output.hidden_states[-1]
213
+ if self.config.drop_cls_token:
214
+ features = features[:, 1:, :]
215
+
216
+ # merge number of `hidden_stride * hidden_stride` hidden states together to reduce token sequence length
217
+ # e.g., for hidden_stride=2, this leads to a token length reduction: 1024 -> 256 for aimv2
218
+ if self.config.hidden_stride > 1:
219
+ n, l, d = features.shape # this `d` maybe different from the above `d
220
+ sqrt_l = int(l ** 0.5)
221
+ assert sqrt_l ** 2 == l, "The token sequence length should be a perfect square."
222
+ features = features.reshape(n, sqrt_l, sqrt_l, d)
223
+ pl = (self.config.hidden_stride - (sqrt_l % self.config.hidden_stride)) % self.config.hidden_stride
224
+ features = pad(features, (0, 0, 0, pl, 0, pl), "constant", 0)
225
+ sqrt_l += pl
226
+ features = features.reshape(n, sqrt_l // self.config.hidden_stride, self.config.hidden_stride,
227
+ sqrt_l // self.config.hidden_stride, self.config.hidden_stride, d)
228
+ features = features.permute(0, 1, 3, 2, 4, 5) # [n, sqrt_l/hs, sqrt_l/hs, hs, hs, d]
229
+ features = features.flatten(3) # [n, sqrt_l/hs, sqrt_l/hs, hs*hs*d]
230
+ features = features.reshape(
231
+ n, -1, self.config.hidden_stride * self.config.hidden_stride * d)
232
+
233
+ return features
234
+
235
+ def forward(self, pixel_values) -> torch.Tensor: # [BatchSize, ImageShape] -> [BatchSize, #Token, VocabSize]
236
+ features = self.encode(pixel_values)
237
+ logits = self.head(features)
238
+ tokens = self.tokenize(logits)
239
+ # tokens' shape is [BatchSize, #Token, VocabSize-5], so padding with [BatchSize, #Token, 5], after
240
+ # which, tokens' shape should become [BatchSize, #Token, VocabSize]
241
+ batch_size, token_len, _ = tokens.shape
242
+ padding_tensor = torch.zeros(size=(batch_size, token_len, len(IMAGE_INDICATOR_IDS)),
243
+ dtype=tokens.dtype,
244
+ device=tokens.device,
245
+ layout=tokens.layout,
246
+ requires_grad=False)
247
+ tokens = torch.cat((tokens, padding_tensor), dim=2)
248
+ return tokens
249
+
250
+
251
+ class Aimv2VisualTokenizer(BaseVisualTokenizer):
252
+ config_class = Aimv2VisualTokenizerConfig
253
+ supports_gradient_checkpointing = True
254
+ _no_split_modules = ["AIMv2ViTPreprocessor", "AIMv2Block"]
255
+ _image_processor_kwargs = dict(do_center_crop=False)
256
+
257
+ def get_image_size(self):
258
+ height = self.image_processor.crop_size["height"]
259
+ width = self.image_processor.crop_size["width"]
260
+ return height, width
261
+
262
+
263
+ AutoModel.register(Aimv2VisualTokenizerConfig, Aimv2VisualTokenizer)
264
+
265
+
266
+ # ----------------------------------------------------------------------
267
+ # Ovis
268
+ # ----------------------------------------------------------------------
269
+ class VisualEmbedding(torch.nn.Embedding):
270
+ def forward(self, visual_tokens: Tensor) -> Tensor:
271
+ if visual_tokens.dtype in [torch.int8, torch.int16, torch.int32, torch.int64, torch.long]:
272
+ return super().forward(visual_tokens)
273
+ return torch.matmul(visual_tokens, self.weight)
274
+
275
+ def reset_parameters(self, mean=0., std=1.) -> None:
276
+ init.normal_(self.weight, mean=mean, std=std)
277
+ self._fill_padding_idx_with_zero()
278
+
279
+
280
+ class OvisPreTrainedModel(PreTrainedModel):
281
+ config_class = OvisConfig
282
+ base_model_prefix = "ovis"
283
+
284
+
285
+ class Ovis(OvisPreTrainedModel):
286
+
287
+ def __init__(self, config: OvisConfig, *inputs, **kwargs):
288
+ super().__init__(config, *inputs, **kwargs)
289
+ attn_kwargs = dict()
290
+ if self.config.llm_attn_implementation:
291
+ if self.config.llm_attn_implementation == "flash_attention_2":
292
+ assert (is_flash_attn_2_available() and
293
+ version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.6.3")), \
294
+ "Using `flash_attention_2` requires having `flash_attn>=2.6.3` installed."
295
+ attn_kwargs["attn_implementation"] = self.config.llm_attn_implementation
296
+ self.llm = AutoModelForCausalLM.from_config(self.config.llm_config, **attn_kwargs)
297
+ assert self.config.hidden_size == self.llm.config.hidden_size, "hidden size mismatch"
298
+ self.text_tokenizer = AutoTokenizer.from_pretrained(self.config.name_or_path)
299
+ self.visual_tokenizer = AutoModel.from_config(self.config.visual_tokenizer_config,
300
+ image_processor_name_or_path=self.config.name_or_path)
301
+ self.vte = VisualEmbedding(
302
+ self.config.visual_tokenizer_config.vocab_size,
303
+ self.config.hidden_size,
304
+ device=self.visual_tokenizer.device,
305
+ dtype=self.visual_tokenizer.dtype
306
+ )
307
+
308
+ def _merge_modules(modules_list: tuple):
309
+ merged_modules = []
310
+ for modules in modules_list:
311
+ merged_modules.extend(modules if modules else [])
312
+ return merged_modules
313
+
314
+ self._no_split_modules = _merge_modules((self.llm._no_split_modules, self.visual_tokenizer._no_split_modules))
315
+ self._skip_keys_device_placement = self.llm._skip_keys_device_placement
316
+ self._keep_in_fp32_modules = _merge_modules(
317
+ (self.llm._keep_in_fp32_modules, self.visual_tokenizer._keep_in_fp32_modules))
318
+ self.is_parallelizable = all((self.llm.is_parallelizable, self.visual_tokenizer.is_parallelizable))
319
+ self.supports_gradient_checkpointing = True
320
+ self._supports_flash_attn_2 = True
321
+
322
+ def get_text_tokenizer(self):
323
+ return self.text_tokenizer
324
+
325
+ def get_visual_tokenizer(self):
326
+ return self.visual_tokenizer
327
+
328
+ def tie_weights(self):
329
+ if not self.config.disable_tie_weight:
330
+ self.get_llm().tie_weights()
331
+
332
+ def get_llm(self):
333
+ return self.llm
334
+
335
+ def get_vte(self):
336
+ return self.vte
337
+
338
+ def get_wte(self):
339
+ return self.llm.get_input_embeddings()
340
+
341
+ def get_conversation_formatter(self) -> ConversationFormatter:
342
+ if getattr(self, 'conversation_formatter', None) is None:
343
+ self.conversation_formatter = getattr(import_module(".configuration_ovis", __package__),
344
+ self.config.conversation_formatter_class)(self.text_tokenizer)
345
+ return self.conversation_formatter
346
+
347
+ def forward(
348
+ self,
349
+ input_ids: torch.Tensor,
350
+ attention_mask: torch.Tensor,
351
+ labels: Optional[torch.Tensor],
352
+ pixel_values: List[Optional[torch.Tensor]],
353
+ **kwargs
354
+ ):
355
+ # assert self.training, "`forward` can only be used in training. For inference, use `generate`."
356
+ _, inputs_embeds, labels, attention_mask = self.merge_multimodal(
357
+ text_input_ids=input_ids,
358
+ text_attention_masks=attention_mask,
359
+ text_labels=labels,
360
+ pixel_values=pixel_values
361
+ )
362
+ return self.llm(inputs_embeds=inputs_embeds, labels=labels, attention_mask=attention_mask, **kwargs)
363
+
364
+ def merge_multimodal(
365
+ self,
366
+ text_input_ids: torch.Tensor,
367
+ text_attention_masks: torch.Tensor,
368
+ text_labels: Optional[torch.Tensor],
369
+ pixel_values: List[Optional[torch.Tensor]],
370
+ left_padding: bool = False
371
+ ):
372
+ input_device = text_input_ids.device
373
+ visual_vocab_szie = self.get_visual_tokenizer().config.vocab_size
374
+ visual_indicator_embeds = self.get_vte()(
375
+ torch.tensor(
376
+ list(range(visual_vocab_szie - 5, visual_vocab_szie)),
377
+ dtype=torch.long,
378
+ device=self.get_visual_tokenizer().device
379
+ )
380
+ ).to(device=input_device)
381
+
382
+ if self.training:
383
+ # When training, to be compatible with deepspeed zero, each sample has to include pixel_value tensor.
384
+ # For text-only sample, one can simply use a full zero tensor as pixel_value, which will be ignored
385
+ # (see below in this function); so, the gradient will not be affected.
386
+ num_images = [x.shape[0] for x in pixel_values]
387
+ visual_tokens = self.visual_tokenizer(torch.cat([x for x in pixel_values], dim=0))
388
+ visual_embeds = torch.split(self.get_vte()(visual_tokens).to(dtype=self.dtype, device=input_device),
389
+ split_size_or_sections=num_images, dim=0)
390
+ visual_input_ids = torch.split(torch.argmax(visual_tokens, dim=-1).to(device=input_device),
391
+ split_size_or_sections=num_images, dim=0)
392
+ visual_labels = [torch.full(x.shape, IGNORE_ID, dtype=torch.long, device=input_device) for x in
393
+ visual_input_ids]
394
+ else:
395
+ # When inference, sample can include only text with `None` pixel_value
396
+ num_images = [x.shape[0] if x is not None else 0 for x in pixel_values]
397
+ if sum(num_images) > 0:
398
+ visual_tokens = self.visual_tokenizer(torch.cat([x for x in pixel_values if x is not None], dim=0))
399
+ visual_embeds = torch.split(self.get_vte()(visual_tokens).to(dtype=self.dtype, device=input_device),
400
+ split_size_or_sections=num_images, dim=0)
401
+ visual_input_ids = torch.split(torch.argmax(visual_tokens, dim=-1).to(device=input_device),
402
+ split_size_or_sections=num_images, dim=0)
403
+ visual_labels = [torch.full(x.shape, IGNORE_ID, dtype=torch.long, device=input_device) for x in
404
+ visual_input_ids]
405
+ else:
406
+ # just placeholders
407
+ visual_embeds = [None] * len(num_images)
408
+ visual_input_ids = [None] * len(num_images)
409
+ visual_labels = [None] * len(num_images)
410
+ # just placeholders
411
+ if text_labels is None:
412
+ text_labels = torch.full(text_input_ids.shape, IGNORE_ID, dtype=torch.long, device=input_device)
413
+
414
+ input_embeds = []
415
+ attention_masks = []
416
+ labels = []
417
+ for text_input_id, text_label, text_attention_mask, visual_embed, visual_input_id, visual_label in zip(
418
+ text_input_ids, text_labels, text_attention_masks, visual_embeds, visual_input_ids, visual_labels
419
+ ):
420
+ placeholder_token_mask = torch.lt(text_input_id, 0)
421
+ text_embed = self.get_wte()(torch.masked_fill(text_input_id, placeholder_token_mask, 0))
422
+ for i, indicator_id in enumerate(IMAGE_INDICATOR_IDS):
423
+ text_embed[text_input_id == indicator_id] = visual_indicator_embeds[i]
424
+ image_atom_positions = torch.where(torch.eq(text_input_id, IMAGE_ATOM_ID))[0].tolist()
425
+ if len(image_atom_positions) > 0:
426
+ input_embed_parts = []
427
+ attention_mask_parts = []
428
+ label_parts = []
429
+ prev_image_atom_position = -1
430
+ for index, image_atom_position in enumerate(image_atom_positions):
431
+ input_embed_parts.append(
432
+ text_embed[prev_image_atom_position + 1:image_atom_position, :])
433
+ label_parts.append(
434
+ text_label[prev_image_atom_position + 1:image_atom_position])
435
+ attention_mask_parts.append(
436
+ text_attention_mask[prev_image_atom_position + 1:image_atom_position])
437
+ input_embed_parts.append(visual_embed[index])
438
+ attention_mask_parts.append(
439
+ torch.ones_like(visual_label[index], dtype=torch.bool))
440
+ label_parts.append(visual_label[index])
441
+ prev_image_atom_position = image_atom_position
442
+ if prev_image_atom_position + 1 < text_input_id.shape[0]:
443
+ input_embed_parts.append(
444
+ text_embed[prev_image_atom_position + 1:, :])
445
+ attention_mask_parts.append(
446
+ text_attention_mask[prev_image_atom_position + 1:])
447
+ label_parts.append(
448
+ text_label[prev_image_atom_position + 1:])
449
+ input_embed = torch.cat(input_embed_parts, dim=0)
450
+ attention_mask = torch.cat(attention_mask_parts, dim=0)
451
+ label = torch.cat(label_parts, dim=0)
452
+ else:
453
+ input_embed = text_embed
454
+ attention_mask = text_attention_mask
455
+ label = text_label
456
+ if self.training:
457
+ # Make visual_embed & visual_indicator_embeds involved in the backward graph,
458
+ # to be compatible with deepspeed zero and ddp.
459
+ input_embed += torch.sum(visual_embed * 0.0) + torch.sum(visual_indicator_embeds * 0.0)
460
+ input_embeds.append(input_embed)
461
+ attention_masks.append(attention_mask)
462
+ labels.append(label)
463
+
464
+ if self.training: # padding to self.config.multimodal_max_length for increased training speed
465
+ padding_size = max(0, self.config.multimodal_max_length - len(input_embeds[0]))
466
+ input_embeds[0] = torch.nn.ConstantPad2d((0, 0, 0, padding_size), 0.0)(input_embeds[0])
467
+ attention_masks[0] = torch.nn.ConstantPad1d((0, padding_size), False)(attention_masks[0])
468
+ labels[0] = torch.nn.ConstantPad1d((0, padding_size), IGNORE_ID)(labels[0])
469
+ batch_input_embeds = self.pad_truncate_sequence(input_embeds, batch_first=True, padding_value=0.0, left_padding=left_padding)
470
+ batch_attention_mask = self.pad_truncate_sequence(attention_masks, batch_first=True, padding_value=False, left_padding=left_padding)
471
+ batch_labels = self.pad_truncate_sequence(labels, batch_first=True, padding_value=IGNORE_ID, left_padding=left_padding)
472
+
473
+ return visual_input_ids, batch_input_embeds, batch_labels, batch_attention_mask
474
+
475
+ def pad_truncate_sequence(self, sequences: List[torch.Tensor], batch_first: bool = True, padding_value: float = 0.0, left_padding: bool = False) -> torch.Tensor:
476
+ if not left_padding:
477
+ pad_sequence = torch.nn.utils.rnn.pad_sequence(sequences, batch_first=batch_first, padding_value=padding_value)
478
+ return pad_sequence[:,:self.config.multimodal_max_length]
479
+ else:
480
+ pad_sequence = torch.nn.utils.rnn.pad_sequence([i.flip(dims=[0]) for i in sequences],batch_first=True, padding_value=padding_value).flip(dims=[1])
481
+ return pad_sequence[:,-self.config.multimodal_max_length:]
482
+
483
+ def preprocess_inputs(
484
+ self,
485
+ text_or_conversations: Union[List[Dict], str],
486
+ images: Optional[List[PIL.Image.Image]],
487
+ max_partition=9,
488
+ generation_preface='',
489
+ return_labels=False,
490
+ propagate_exception=True,
491
+ frame_selector=None,
492
+ frame_selector_kwargs=None
493
+ ):
494
+ # convert text to conversations
495
+ if isinstance(text_or_conversations, str):
496
+ conversations = [{
497
+ "from": "human",
498
+ "value": text_or_conversations
499
+ }]
500
+ elif isinstance(text_or_conversations, list):
501
+ conversations = text_or_conversations
502
+ else:
503
+ raise ValueError(f'Invalid type of `text_or_conversations`, expected `List[Dict]` or `str`,'
504
+ f' but got {type(text_or_conversations)}')
505
+
506
+ if frame_selector is not None:
507
+ frame_selector_kwargs = frame_selector_kwargs or {}
508
+ conversations, images = frame_selector(conversations=conversations, frames=images, **frame_selector_kwargs)
509
+
510
+ # format conversations
511
+ prompt, raw_input_ids, raw_labels = self.get_conversation_formatter().format(
512
+ conversations, generation_preface=generation_preface)
513
+
514
+ # place image placeholders
515
+ input_ids = []
516
+ labels = []
517
+ pixel_values = []
518
+ invalidate_label = False
519
+ image_token_indices = [i for i, v in enumerate(raw_input_ids) if v == IMAGE_TOKEN_ID]
520
+ last_image_token_index = -1
521
+ for i in range(len(image_token_indices)):
522
+ head = 0 if i == 0 else image_token_indices[i - 1] + 1
523
+ tail = image_token_indices[i]
524
+ last_image_token_index = tail
525
+ input_ids.extend(raw_input_ids[head:tail])
526
+ labels.extend(raw_labels[head:tail])
527
+ try:
528
+ image = images[i]
529
+ raw_pixel_values, image_placeholders = self.visual_tokenizer.preprocess_image(
530
+ image, max_partition=max_partition)
531
+ except Exception as e:
532
+ if propagate_exception:
533
+ raise e
534
+ logging.exception(e)
535
+ invalidate_label = True
536
+ raw_pixel_values, image_placeholders = self.visual_tokenizer.mock_input()
537
+ input_ids.extend(image_placeholders)
538
+ labels.extend([IGNORE_ID] * len(image_placeholders))
539
+ pixel_values.append(raw_pixel_values)
540
+ input_ids.extend(raw_input_ids[last_image_token_index + 1:])
541
+ labels.extend(raw_labels[last_image_token_index + 1:])
542
+
543
+ # return tensors
544
+ input_ids = torch.tensor(input_ids, dtype=torch.long)
545
+ labels = torch.tensor([IGNORE_ID] * len(labels) if invalidate_label else labels, dtype=torch.long)
546
+ pixel_values = torch.cat(pixel_values, dim=0) if len(pixel_values) > 0 else None
547
+
548
+ if return_labels:
549
+ return prompt, input_ids, pixel_values, labels
550
+ else:
551
+ return prompt, input_ids, pixel_values
552
+
553
+ def save_pretrained(
554
+ self,
555
+ save_directory: Union[str, os.PathLike],
556
+ is_main_process: bool = True,
557
+ state_dict: Optional[dict] = None,
558
+ save_function: Callable = torch.save,
559
+ push_to_hub: bool = False,
560
+ max_shard_size: Union[int, str] = "5GB",
561
+ safe_serialization: bool = True,
562
+ variant: Optional[str] = None,
563
+ token: Optional[Union[str, bool]] = None,
564
+ save_peft_format: bool = True,
565
+ **kwargs
566
+ ):
567
+ super().save_pretrained(save_directory,
568
+ is_main_process=is_main_process,
569
+ state_dict=state_dict,
570
+ save_function=save_function,
571
+ safe_serialization=safe_serialization)
572
+ self.get_text_tokenizer().save_pretrained(save_directory)
573
+ self.get_visual_tokenizer().get_image_processor().save_pretrained(save_directory)
574
+
575
+ def generate(
576
+ self,
577
+ inputs: Optional[torch.Tensor] = None,
578
+ **kwargs
579
+ ) -> Union[GenerateOutput, torch.LongTensor]:
580
+ _, inputs_embeds, labels, attention_mask = self.merge_multimodal(
581
+ text_input_ids=inputs,
582
+ text_attention_masks=kwargs.pop('attention_mask'),
583
+ text_labels=None,
584
+ pixel_values=kwargs.pop('pixel_values'),
585
+ left_padding=True
586
+ )
587
+ inputs_embeds = inputs_embeds.detach()
588
+ torch.cuda.empty_cache()
589
+
590
+ return self.llm.generate(inputs=None, inputs_embeds=inputs_embeds, attention_mask=attention_mask, **kwargs)