JiaqiLiu commited on
Commit
9f03e03
·
verified ·
1 Parent(s): 2113015

Upload folder using huggingface_hub

Browse files
args.json ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "output_dir": "/project/6101776/xzhan576/532G-project/output/deepseek_ocr2_chartqa_stage3_joint_from_query_qwen2_with_lora_v1/v0-20260409-152815",
3
+ "overwrite_output_dir": false,
4
+ "do_train": false,
5
+ "do_eval": false,
6
+ "do_predict": false,
7
+ "eval_strategy": "no",
8
+ "prediction_loss_only": false,
9
+ "per_device_train_batch_size": 4,
10
+ "per_device_eval_batch_size": 4,
11
+ "per_gpu_train_batch_size": null,
12
+ "per_gpu_eval_batch_size": null,
13
+ "gradient_accumulation_steps": 8,
14
+ "eval_accumulation_steps": null,
15
+ "eval_delay": 0,
16
+ "torch_empty_cache_steps": null,
17
+ "learning_rate": 3e-05,
18
+ "weight_decay": 0.0,
19
+ "adam_beta1": 0.9,
20
+ "adam_beta2": 0.95,
21
+ "adam_epsilon": 1e-08,
22
+ "max_grad_norm": 1.0,
23
+ "num_train_epochs": 1.0,
24
+ "max_steps": -1,
25
+ "lr_scheduler_type": "cosine_with_min_lr",
26
+ "lr_scheduler_kwargs": "{\"min_lr\": 3e-6}",
27
+ "warmup_ratio": 0.1,
28
+ "warmup_steps": 0,
29
+ "log_level": "passive",
30
+ "log_level_replica": "warning",
31
+ "log_on_each_node": true,
32
+ "logging_dir": "/project/6101776/xzhan576/532G-project/output/deepseek_ocr2_chartqa_stage3_joint_from_query_qwen2_with_lora_v1/v0-20260409-152815/runs",
33
+ "logging_strategy": "steps",
34
+ "logging_first_step": true,
35
+ "logging_steps": 5,
36
+ "logging_nan_inf_filter": true,
37
+ "save_strategy": "steps",
38
+ "save_steps": 200.0,
39
+ "save_total_limit": 2,
40
+ "save_safetensors": true,
41
+ "save_on_each_node": false,
42
+ "save_only_model": false,
43
+ "restore_callback_states_from_checkpoint": false,
44
+ "no_cuda": false,
45
+ "use_cpu": false,
46
+ "use_mps_device": false,
47
+ "seed": 42,
48
+ "data_seed": 42,
49
+ "jit_mode_eval": false,
50
+ "use_ipex": false,
51
+ "bf16": true,
52
+ "fp16": false,
53
+ "fp16_opt_level": "O1",
54
+ "half_precision_backend": "auto",
55
+ "bf16_full_eval": false,
56
+ "fp16_full_eval": false,
57
+ "tf32": null,
58
+ "local_rank": -1,
59
+ "ddp_backend": null,
60
+ "tpu_num_cores": null,
61
+ "tpu_metrics_debug": false,
62
+ "debug": null,
63
+ "dataloader_drop_last": false,
64
+ "eval_steps": 200.0,
65
+ "dataloader_num_workers": 8,
66
+ "dataloader_prefetch_factor": null,
67
+ "past_index": -1,
68
+ "run_name": "deepseek_ocr2_chartqa_stage3_joint_from_query_qwen2_with_lora_v1",
69
+ "disable_tqdm": null,
70
+ "remove_unused_columns": true,
71
+ "label_names": null,
72
+ "load_best_model_at_end": false,
73
+ "metric_for_best_model": "loss",
74
+ "greater_is_better": false,
75
+ "ignore_data_skip": false,
76
+ "fsdp": [],
77
+ "fsdp_min_num_params": 0,
78
+ "fsdp_config": null,
79
+ "fsdp_transformer_layer_cls_to_wrap": null,
80
+ "accelerator_config": {
81
+ "dispatch_batches": false
82
+ },
83
+ "deepspeed": null,
84
+ "label_smoothing_factor": 0.0,
85
+ "optim": "adamw_torch",
86
+ "optim_args": null,
87
+ "adafactor": false,
88
+ "group_by_length": false,
89
+ "length_column_name": "length",
90
+ "report_to": [
91
+ "wandb"
92
+ ],
93
+ "ddp_find_unused_parameters": null,
94
+ "ddp_bucket_cap_mb": null,
95
+ "ddp_broadcast_buffers": null,
96
+ "dataloader_pin_memory": true,
97
+ "dataloader_persistent_workers": false,
98
+ "skip_memory_metrics": true,
99
+ "use_legacy_prediction_loop": false,
100
+ "push_to_hub": false,
101
+ "resume_from_checkpoint": null,
102
+ "hub_model_id": null,
103
+ "hub_strategy": "every_save",
104
+ "hub_token": null,
105
+ "hub_private_repo": false,
106
+ "hub_always_push": false,
107
+ "gradient_checkpointing": false,
108
+ "gradient_checkpointing_kwargs": null,
109
+ "include_inputs_for_metrics": false,
110
+ "include_for_metrics": [],
111
+ "eval_do_concat_batches": true,
112
+ "fp16_backend": "auto",
113
+ "evaluation_strategy": "steps",
114
+ "push_to_hub_model_id": null,
115
+ "push_to_hub_organization": null,
116
+ "push_to_hub_token": null,
117
+ "mp_parameters": "",
118
+ "auto_find_batch_size": false,
119
+ "full_determinism": false,
120
+ "torchdynamo": null,
121
+ "ray_scope": "last",
122
+ "ddp_timeout": 18000000,
123
+ "torch_compile": false,
124
+ "torch_compile_backend": null,
125
+ "torch_compile_mode": null,
126
+ "dispatch_batches": null,
127
+ "split_batches": null,
128
+ "include_tokens_per_second": false,
129
+ "include_num_input_tokens_seen": false,
130
+ "neftune_noise_alpha": null,
131
+ "optim_target_modules": null,
132
+ "batch_eval_metrics": false,
133
+ "eval_on_start": false,
134
+ "use_liger_kernel": false,
135
+ "eval_use_gather_object": false,
136
+ "average_tokens_across_devices": false,
137
+ "sortish_sampler": false,
138
+ "predict_with_generate": false,
139
+ "generation_max_length": null,
140
+ "generation_num_beams": null,
141
+ "generation_config": null,
142
+ "tuner_backend": "peft",
143
+ "vit_gradient_checkpointing": null,
144
+ "router_aux_loss_coef": 0.0,
145
+ "enable_dft_loss": false,
146
+ "enable_channel_loss": false,
147
+ "safe_serialization": true,
148
+ "max_shard_size": "5GB",
149
+ "check_model": true,
150
+ "acc_strategy": "token",
151
+ "train_dataloader_shuffle": true,
152
+ "max_epochs": null,
153
+ "aligner_lr": null,
154
+ "vit_lr": null,
155
+ "use_logits_to_keep": null,
156
+ "ds3_gather_for_generation": true,
157
+ "resume_only_model": false,
158
+ "optimizer": null,
159
+ "loss_type": null,
160
+ "eval_metric": null,
161
+ "callbacks": [],
162
+ "early_stop_interval": null,
163
+ "eval_use_evalscope": false,
164
+ "eval_dataset": [],
165
+ "eval_dataset_args": null,
166
+ "eval_limit": null,
167
+ "eval_generation_config": null,
168
+ "extra_eval_args": null,
169
+ "tuner_type": "full",
170
+ "use_galore": false,
171
+ "galore_target_modules": null,
172
+ "galore_rank": 128,
173
+ "galore_update_proj_gap": 50,
174
+ "galore_scale": 1.0,
175
+ "galore_proj_type": "std",
176
+ "galore_optim_per_parameter": false,
177
+ "galore_with_embedding": false,
178
+ "galore_quantization": false,
179
+ "galore_proj_quant": false,
180
+ "galore_proj_bits": 4,
181
+ "galore_proj_group_size": 256,
182
+ "galore_cos_threshold": 0.4,
183
+ "galore_gamma_proj": 2,
184
+ "galore_queue_size": 5,
185
+ "lisa_activated_layers": 0,
186
+ "lisa_step_interval": 20,
187
+ "use_flash_ckpt": false,
188
+ "use_ray": false,
189
+ "ray_exp_name": null,
190
+ "device_groups": null,
191
+ "model": "/home/xzhan576/projects/aip-xli135/xzhan576/532G-project/ckpts/query_qwen2_with_lora_v1",
192
+ "model_type": "deepseek_ocr2",
193
+ "model_revision": null,
194
+ "task_type": "causal_lm",
195
+ "torch_dtype": "bfloat16",
196
+ "attn_impl": null,
197
+ "experts_impl": null,
198
+ "new_special_tokens": [],
199
+ "num_labels": null,
200
+ "problem_type": null,
201
+ "rope_scaling": null,
202
+ "device_map": null,
203
+ "max_memory": {},
204
+ "max_model_len": null,
205
+ "local_repo_path": null,
206
+ "init_strategy": null,
207
+ "template": "deepseek_ocr2",
208
+ "system": null,
209
+ "max_length": 2048,
210
+ "truncation_strategy": "delete",
211
+ "max_pixels": 602112,
212
+ "agent_template": null,
213
+ "norm_bbox": null,
214
+ "use_chat_template": true,
215
+ "padding_side": "right",
216
+ "padding_free": false,
217
+ "loss_scale": "default",
218
+ "sequence_parallel_size": 1,
219
+ "template_backend": "swift",
220
+ "response_prefix": null,
221
+ "enable_thinking": null,
222
+ "add_non_thinking_prefix": true,
223
+ "dataset": [
224
+ "HuggingFaceM4/ChartQA"
225
+ ],
226
+ "val_dataset": [],
227
+ "cached_dataset": [],
228
+ "cached_val_dataset": [],
229
+ "split_dataset_ratio": 0.0,
230
+ "dataset_num_proc": 8,
231
+ "load_from_cache_file": false,
232
+ "dataset_shuffle": true,
233
+ "val_dataset_shuffle": false,
234
+ "streaming": false,
235
+ "interleave_prob": null,
236
+ "stopping_strategy": "first_exhausted",
237
+ "shuffle_buffer_size": 1000,
238
+ "download_mode": "reuse_dataset_if_exists",
239
+ "columns": {},
240
+ "strict": false,
241
+ "model_name": null,
242
+ "model_author": null,
243
+ "custom_dataset_info": [],
244
+ "quant_method": null,
245
+ "quant_bits": null,
246
+ "hqq_axis": null,
247
+ "bnb_4bit_compute_dtype": "bfloat16",
248
+ "bnb_4bit_quant_type": "nf4",
249
+ "bnb_4bit_use_double_quant": true,
250
+ "bnb_4bit_quant_storage": null,
251
+ "max_new_tokens": 64,
252
+ "temperature": 0.0,
253
+ "top_k": null,
254
+ "top_p": null,
255
+ "repetition_penalty": null,
256
+ "num_beams": 1,
257
+ "stream": false,
258
+ "stop_words": [],
259
+ "logprobs": false,
260
+ "top_logprobs": null,
261
+ "structured_outputs_regex": null,
262
+ "adapters": [],
263
+ "external_plugins": [],
264
+ "custom_register_path": [],
265
+ "model_kwargs": {},
266
+ "load_args": false,
267
+ "load_data_args": false,
268
+ "packing": false,
269
+ "packing_length": null,
270
+ "packing_num_proc": 1,
271
+ "lazy_tokenize": true,
272
+ "use_hf": true,
273
+ "ignore_args_error": false,
274
+ "use_swift_lora": false,
275
+ "freeze_parameters": [
276
+ "model.layers",
277
+ "model.sam_model",
278
+ "model.qwen2_model",
279
+ "model.projector"
280
+ ],
281
+ "freeze_parameters_regex": null,
282
+ "freeze_parameters_ratio": 1.0,
283
+ "trainable_parameters": [
284
+ "model.projector",
285
+ "model.qwen2_model.model",
286
+ "model.qwen2_model.query_768",
287
+ "model.qwen2_model.query_1024",
288
+ "model.qwen2_model.text_context_proj",
289
+ "model.qwen2_model.text_query_mlp",
290
+ "model.qwen2_model.text_query_residual_scale"
291
+ ],
292
+ "trainable_parameters_regex": null,
293
+ "freeze_llm": true,
294
+ "freeze_vit": true,
295
+ "freeze_aligner": true,
296
+ "target_modules": [
297
+ "all-linear"
298
+ ],
299
+ "target_regex": null,
300
+ "target_parameters": null,
301
+ "modules_to_save": [],
302
+ "lora_rank": 8,
303
+ "lora_alpha": 32,
304
+ "lora_dropout": 0.05,
305
+ "lora_bias": "none",
306
+ "lora_dtype": null,
307
+ "lorap_lr_ratio": null,
308
+ "use_rslora": false,
309
+ "use_dora": false,
310
+ "lora_ga_batch_size": 2,
311
+ "lora_ga_iters": 2,
312
+ "lora_ga_max_length": 1024,
313
+ "lora_ga_direction": "ArB2r",
314
+ "lora_ga_scale": "stable",
315
+ "lora_ga_stable_gamma": 16,
316
+ "init_weights": true,
317
+ "fourier_n_frequency": 2000,
318
+ "fourier_scaling": 300.0,
319
+ "boft_block_size": 4,
320
+ "boft_block_num": 0,
321
+ "boft_n_butterfly_factor": 1,
322
+ "boft_dropout": 0.0,
323
+ "vera_rank": 256,
324
+ "vera_projection_prng_key": 0,
325
+ "vera_dropout": 0.0,
326
+ "vera_d_initial": 0.1,
327
+ "adapter_act": "gelu",
328
+ "adapter_length": 128,
329
+ "adalora_target_r": 8,
330
+ "adalora_init_r": 12,
331
+ "adalora_tinit": 0,
332
+ "adalora_tfinal": 0,
333
+ "adalora_deltaT": 1,
334
+ "adalora_beta1": 0.85,
335
+ "adalora_beta2": 0.85,
336
+ "adalora_orth_reg_weight": 0.5,
337
+ "llamapro_num_new_blocks": 4,
338
+ "llamapro_num_groups": null,
339
+ "reft_layer_key": null,
340
+ "reft_layers": null,
341
+ "reft_rank": 4,
342
+ "reft_intervention_type": "LoreftIntervention",
343
+ "reft_args": null,
344
+ "swanlab_token": null,
345
+ "swanlab_project": "ms-swift",
346
+ "swanlab_workspace": null,
347
+ "swanlab_exp_name": null,
348
+ "swanlab_notification_method": null,
349
+ "swanlab_webhook_url": null,
350
+ "swanlab_secret": null,
351
+ "swanlab_sender_email": null,
352
+ "swanlab_receiver_email": null,
353
+ "swanlab_smtp_server": null,
354
+ "swanlab_smtp_port": null,
355
+ "swanlab_email_language": "zh",
356
+ "swanlab_mode": "cloud",
357
+ "add_version": true,
358
+ "create_checkpoint_symlink": false,
359
+ "zero_hpz_partition_size": null,
360
+ "deepspeed_autotp_size": null,
361
+ "swift_version": "4.1.0.dev0",
362
+ "ckpt_dir": "/home/xzhan576/projects/aip-xli135/xzhan576/532G-project/ckpts/query_qwen2_with_lora_v1",
363
+ "rank": -1,
364
+ "global_world_size": 1,
365
+ "local_world_size": 1,
366
+ "model_suffix": "query_qwen2_with_lora_v1",
367
+ "model_info": "ModelInfo(model_type='deepseek_ocr2', model_dir='/home/xzhan576/projects/aip-xli135/xzhan576/532G-project/ckpts/query_qwen2_with_lora_v1', torch_dtype=torch.bfloat16, max_model_len=8192, quant_method=None, quant_bits=None, rope_scaling=None, is_moe_model=True, is_multimodal=True, config=None, task_type='causal_lm', num_labels=None)",
368
+ "model_meta": "ModelMeta(model_type='deepseek_ocr2', model_groups=[ModelGroup(models=[Model(ms_model_id='deepseek-ai/DeepSeek-OCR-2', hf_model_id='deepseek-ai/DeepSeek-OCR-2', model_path=None, ms_revision=None, hf_revision=None)], template=None, ignore_patterns=None, requires=None, tags=[])], loader=<class 'swift.model.models.deepseek.DeepseekOCR2Loader'>, template='deepseek_ocr2', model_arch=MultiModelKeys(arch_name='deepseek_ocr2', embedding=None, module_list=None, lm_head=None, q_proj=None, k_proj=None, v_proj=None, o_proj=None, attention=None, mlp=None, down_proj=None, qkv_proj=None, qk_proj=None, qa_proj=None, qb_proj=None, kv_proj=None, kva_proj=None, kvb_proj=None, language_model=['model.layers'], aligner=['model.projector'], vision_tower=['model.sam_model', 'model.qwen2_model'], generator=[]), architectures=['DeepseekOCR2ForCausalLM'], additional_saved_files=[], torch_dtype=None, is_multimodal=True, is_reward=False, task_type=None, ignore_patterns=None, requires=['transformers==4.46.3', 'easydict'], tags=['vision'])",
369
+ "model_dir": "/home/xzhan576/projects/aip-xli135/xzhan576/532G-project/ckpts/query_qwen2_with_lora_v1",
370
+ "template_meta": "TemplateMeta(template_type='deepseek_ocr2', prefix=['<|begin▁of▁sentence|>'], prompt=['{{QUERY}}'], chat_sep=None, suffix=[['eos_token_id']], template_cls=<class 'swift.template.templates.deepseek.DeepseekOCR2'>, system_prefix=None, default_system=None, auto_add_bos=False, stop_words=[], agent_template='react_en', is_thinking=False, thinking_prefix='', non_thinking_prefix='', history_thinking_prefix='')",
371
+ "_val_dataset_exists": false,
372
+ "hub": "<class 'swift.hub.hub.HFHub'>",
373
+ "training_args": "Seq2SeqTrainingArguments(output_dir='/project/6101776/xzhan576/532G-project/output/deepseek_ocr2_chartqa_stage3_joint_from_query_qwen2_with_lora_v1/v0-20260409-152815', 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=8, eval_accumulation_steps=None, eval_delay=0, torch_empty_cache_steps=None, learning_rate=3e-05, weight_decay=0.0, adam_beta1=0.9, adam_beta2=0.95, adam_epsilon=1e-08, max_grad_norm=1.0, num_train_epochs=1.0, max_steps=-1, lr_scheduler_type=<SchedulerType.COSINE_WITH_MIN_LR: 'cosine_with_min_lr'>, lr_scheduler_kwargs={'min_lr': 3e-06}, warmup_ratio=0.1, warmup_steps=0, log_level='passive', log_level_replica='warning', log_on_each_node=True, logging_dir='/project/6101776/xzhan576/532G-project/output/deepseek_ocr2_chartqa_stage3_joint_from_query_qwen2_with_lora_v1/v0-20260409-152815/runs', logging_strategy=<IntervalStrategy.STEPS: 'steps'>, logging_first_step=True, logging_steps=5, logging_nan_inf_filter=True, save_strategy=<IntervalStrategy.STEPS: 'steps'>, save_steps=200, 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=200, dataloader_num_workers=8, dataloader_prefetch_factor=2, past_index=-1, run_name='deepseek_ocr2_chartqa_stage3_joint_from_query_qwen2_with_lora_v1', disable_tqdm=False, remove_unused_columns=False, label_names=None, load_best_model_at_end=False, metric_for_best_model='loss', greater_is_better=False, 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=['wandb'], 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=False, hub_always_push=False, gradient_checkpointing=False, 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=18000000, 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, sortish_sampler=False, predict_with_generate=False, generation_max_length=None, generation_num_beams=None, generation_config=None, tuner_backend='peft', vit_gradient_checkpointing=False, router_aux_loss_coef=0.0, enable_dft_loss=False, enable_channel_loss=False, safe_serialization=True, max_shard_size='5GB', check_model=True, acc_strategy='token', train_dataloader_shuffle=True, max_epochs=None, aligner_lr=None, vit_lr=None, use_logits_to_keep=None, ds3_gather_for_generation=True, resume_only_model=False, optimizer=None, loss_type=None, eval_metric=None, callbacks=[], early_stop_interval=None, eval_use_evalscope=False, eval_dataset=[], eval_dataset_args=None, eval_limit=None, eval_generation_config=None, extra_eval_args=None, tuner_type='full', use_galore=False, galore_target_modules=None, galore_rank=128, galore_update_proj_gap=50, galore_scale=1.0, galore_proj_type='std', galore_optim_per_parameter=False, galore_with_embedding=False, galore_quantization=False, galore_proj_quant=False, galore_proj_bits=4, galore_proj_group_size=256, galore_cos_threshold=0.4, galore_gamma_proj=2, galore_queue_size=5, lisa_activated_layers=0, lisa_step_interval=20, use_flash_ckpt=False)"
374
+ }
config.json ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/home/xzhan576/projects/aip-xli135/xzhan576/532G-project/ckpts/query_qwen2_with_lora_v1",
3
+ "architectures": [
4
+ "DeepseekOCR2ForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "modeling_deepseekocr2.DeepseekOCR2Config",
10
+ "AutoModel": "modeling_deepseekocr2.DeepseekOCR2ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.001,
13
+ "bos_token_id": 0,
14
+ "candidate_resolutions": [
15
+ [
16
+ 1024,
17
+ 1024
18
+ ]
19
+ ],
20
+ "eos_token_id": 1,
21
+ "ep_size": 1,
22
+ "first_k_dense_replace": 1,
23
+ "global_view_pos": "head",
24
+ "hidden_act": "silu",
25
+ "hidden_size": 1280,
26
+ "initializer_range": 0.02,
27
+ "intermediate_size": 6848,
28
+ "kv_lora_rank": null,
29
+ "language_config": {
30
+ "architectures": [
31
+ "DeepseekV2ForCausalLM"
32
+ ],
33
+ "auto_map": {
34
+ "AutoConfig": "configuration_deepseekv2.DeepseekV2Config",
35
+ "AutoModel": "modeling_deepseek.DeepseekV2Model",
36
+ "AutoModelForCausalLM": "modeling_deepseek.DeepseekV2ForCausalLM"
37
+ },
38
+ "bos_token_id": 0,
39
+ "eos_token_id": 1,
40
+ "first_k_dense_replace": 1,
41
+ "hidden_size": 1280,
42
+ "intermediate_size": 6848,
43
+ "kv_lora_rank": null,
44
+ "lm_head": true,
45
+ "max_position_embeddings": 8192,
46
+ "moe_intermediate_size": 896,
47
+ "n_group": 1,
48
+ "n_routed_experts": 64,
49
+ "n_shared_experts": 2,
50
+ "num_attention_heads": 10,
51
+ "num_experts_per_tok": 6,
52
+ "num_hidden_layers": 12,
53
+ "num_key_value_heads": 10,
54
+ "q_lora_rank": null,
55
+ "qk_nope_head_dim": 0,
56
+ "qk_rope_head_dim": 0,
57
+ "rm_head": false,
58
+ "topk_group": 1,
59
+ "topk_method": "greedy",
60
+ "torch_dtype": "bfloat16",
61
+ "use_mla": false,
62
+ "v_head_dim": 0,
63
+ "vocab_size": 129280
64
+ },
65
+ "lm_head": true,
66
+ "max_position_embeddings": 8192,
67
+ "model_type": "DeepseekOCR2",
68
+ "moe_intermediate_size": 896,
69
+ "moe_layer_freq": 1,
70
+ "n_group": 1,
71
+ "n_routed_experts": 64,
72
+ "n_shared_experts": 2,
73
+ "norm_topk_prob": false,
74
+ "num_attention_heads": 10,
75
+ "num_experts_per_tok": 6,
76
+ "num_hidden_layers": 12,
77
+ "num_key_value_heads": 10,
78
+ "pad_token_id": 2,
79
+ "pretraining_tp": 1,
80
+ "projector_config": {
81
+ "input_dim": 896,
82
+ "model_type": "mlp_projector",
83
+ "n_embed": 1280,
84
+ "projector_type": "linear"
85
+ },
86
+ "q_lora_rank": null,
87
+ "qk_nope_head_dim": 0,
88
+ "qk_rope_head_dim": 0,
89
+ "rm_head": false,
90
+ "rms_norm_eps": 1e-06,
91
+ "rope_scaling": null,
92
+ "rope_theta": 10000.0,
93
+ "routed_scaling_factor": 1.0,
94
+ "scoring_func": "softmax",
95
+ "seq_aux": true,
96
+ "tie_word_embeddings": false,
97
+ "tile_tag": "2D",
98
+ "topk_group": 1,
99
+ "topk_method": "greedy",
100
+ "torch_dtype": "bfloat16",
101
+ "transformers_version": "4.46.3",
102
+ "use_cache": false,
103
+ "use_mla": false,
104
+ "v_head_dim": 0,
105
+ "vision_config": {
106
+ "image_size": 1024,
107
+ "mlp_ratio": 3.7362,
108
+ "model_name": "deepencoderv2",
109
+ "model_type": "vision",
110
+ "width": {
111
+ "qwen2-0-5b": {
112
+ "dim": 896
113
+ },
114
+ "sam_vit_b": {
115
+ "downsample_channels": [
116
+ 512,
117
+ 1024
118
+ ],
119
+ "global_attn_indexes": [
120
+ 2,
121
+ 5,
122
+ 8,
123
+ 11
124
+ ],
125
+ "heads": 12,
126
+ "layers": 12,
127
+ "width": 768
128
+ }
129
+ }
130
+ },
131
+ "vocab_size": 129280
132
+ }
configuration_deepseek_v2.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ logger = logging.get_logger(__name__)
5
+
6
+ DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
7
+ class DeepseekV2Config(PretrainedConfig):
8
+ r"""
9
+ This is the configuration class to store the configuration of a [`DeepseekV2Model`]. It is used to instantiate an DeepSeek
10
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
11
+ defaults will yield a similar configuration to that of the DeepSeek-V2 with multi-latent attention.
12
+
13
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
14
+ documentation from [`PretrainedConfig`] for more information.
15
+
16
+
17
+ Args:
18
+ vocab_size (`int`, *optional*, defaults to 102400):
19
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
20
+ `inputs_ids` passed when calling [`DeepseekV2Model`]
21
+ hidden_size (`int`, *optional*, defaults to 4096):
22
+ Dimension of the hidden representations.
23
+ intermediate_size (`int`, *optional*, defaults to 11008):
24
+ Dimension of the MLP representations.
25
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
26
+ Dimension of the MoE representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer decoder.
29
+ num_attention_heads (`int`, *optional*, defaults to 32):
30
+ Number of attention heads for each attention layer in the Transformer decoder.
31
+ n_shared_experts (`int`, *optional*, defaults to None):
32
+ Number of shared experts, None means dense model.
33
+ n_routed_experts (`int`, *optional*, defaults to None):
34
+ Number of routed experts, None means dense model.
35
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
36
+ Scaling factor or routed experts.
37
+ topk_method (`str`, *optional*, defaults to `gready`):
38
+ Topk method used in routed gate.
39
+ n_group (`int`, *optional*, defaults to None):
40
+ Number of groups for routed experts.
41
+ topk_group (`int`, *optional*, defaults to None):
42
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
43
+ num_experts_per_tok (`int`, *optional*, defaults to None):
44
+ Number of selected experts, None means dense model.
45
+ moe_layer_freq (`int`, *optional*, defaults to 1):
46
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
47
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
48
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
49
+ \--k dense layers--/
50
+ norm_topk_prob (`bool`, *optional*, defaults to False):
51
+ Whether to normalize the weights of the routed experts.
52
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
53
+ Method of computing expert weights.
54
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
55
+ Auxiliary loss weight coefficient.
56
+ seq_aux = (`bool`, *optional*, defaults to True):
57
+ Whether to compute the auxiliary loss for each individual sample.
58
+ num_key_value_heads (`int`, *optional*):
59
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
60
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
61
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
62
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
63
+ by meanpooling all the original heads within that group. For more details checkout [this
64
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
65
+ `num_attention_heads`.
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with.
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
73
+ The epsilon used by the rms normalization layers.
74
+ use_cache (`bool`, *optional*, defaults to `True`):
75
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
76
+ relevant if `config.is_decoder=True`.
77
+ pad_token_id (`int`, *optional*):
78
+ Padding token id.
79
+ bos_token_id (`int`, *optional*, defaults to 1):
80
+ Beginning of stream token id.
81
+ eos_token_id (`int`, *optional*, defaults to 2):
82
+ End of stream token id.
83
+ pretraining_tp (`int`, *optional*, defaults to 1):
84
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
85
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
86
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
87
+ issue](https://github.com/pytorch/pytorch/issues/76232).
88
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
89
+ Whether to tie weight embeddings
90
+ rope_theta (`float`, *optional*, defaults to 10000.0):
91
+ The base period of the RoPE embeddings.
92
+ rope_scaling (`Dict`, *optional*):
93
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
94
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
95
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
96
+ `max_position_embeddings` to the expected new maximum.
97
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
98
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
99
+ attention_dropout (`float`, *optional*, defaults to 0.0):
100
+ The dropout ratio for the attention probabilities.
101
+ use_mla (`bool`, *optional*, defaults to `True`): Use multi-latent attention or multi-head attention. If True,
102
+ the model will use multi-latent attention, otherwise, it will use multi-head attention.
103
+
104
+ ```python
105
+ >>> from transformers import DeepseekV2Model, DeepseekV2Config
106
+
107
+ >>> # Initializing a Deepseek-V2 style configuration
108
+ >>> configuration = DeepseekV2Config()
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "deepseek_v2"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=102400,
120
+ hidden_size=4096,
121
+ intermediate_size=11008,
122
+ moe_intermediate_size = 1407,
123
+ num_hidden_layers=30,
124
+ num_attention_heads=32,
125
+ num_key_value_heads=32,
126
+ n_shared_experts = None,
127
+ n_routed_experts = None,
128
+ ep_size = 1,
129
+ routed_scaling_factor = 1.0,
130
+ kv_lora_rank = 512,
131
+ q_lora_rank = 1536,
132
+ qk_rope_head_dim = 64,
133
+ v_head_dim = 128,
134
+ qk_nope_head_dim = 128,
135
+ topk_method = 'gready',
136
+ n_group = None,
137
+ topk_group = None,
138
+ num_experts_per_tok = None,
139
+ moe_layer_freq = 1,
140
+ first_k_dense_replace = 0,
141
+ norm_topk_prob = False,
142
+ scoring_func = 'softmax',
143
+ aux_loss_alpha = 0.001,
144
+ seq_aux = True,
145
+ hidden_act="silu",
146
+ max_position_embeddings=2048,
147
+ initializer_range=0.02,
148
+ rms_norm_eps=1e-6,
149
+ use_cache=True,
150
+ pad_token_id=None,
151
+ bos_token_id=100000,
152
+ eos_token_id=100001,
153
+ pretraining_tp=1,
154
+ tie_word_embeddings=False,
155
+ rope_theta=10000.0,
156
+ rope_scaling=None,
157
+ attention_bias=False,
158
+ attention_dropout=0.0,
159
+ use_mla=True,
160
+ **kwargs,
161
+ ):
162
+ self.vocab_size = vocab_size
163
+ self.max_position_embeddings = max_position_embeddings
164
+ self.hidden_size = hidden_size
165
+ self.intermediate_size = intermediate_size
166
+ self.moe_intermediate_size = moe_intermediate_size
167
+ self.num_hidden_layers = num_hidden_layers
168
+ self.num_attention_heads = num_attention_heads
169
+ self.n_shared_experts = n_shared_experts
170
+ self.n_routed_experts = n_routed_experts
171
+ self.ep_size = ep_size
172
+ self.routed_scaling_factor = routed_scaling_factor
173
+ self.kv_lora_rank = kv_lora_rank
174
+ self.q_lora_rank = q_lora_rank
175
+ self.qk_rope_head_dim = qk_rope_head_dim
176
+ self.v_head_dim = v_head_dim
177
+ self.qk_nope_head_dim = qk_nope_head_dim
178
+ self.topk_method = topk_method
179
+ self.n_group = n_group
180
+ self.topk_group = topk_group
181
+ self.num_experts_per_tok = num_experts_per_tok
182
+ self.moe_layer_freq = moe_layer_freq
183
+ self.first_k_dense_replace = first_k_dense_replace
184
+ self.norm_topk_prob = norm_topk_prob
185
+ self.scoring_func = scoring_func
186
+ self.aux_loss_alpha = aux_loss_alpha
187
+ self.seq_aux = seq_aux
188
+ # for backward compatibility
189
+ if num_key_value_heads is None:
190
+ num_key_value_heads = num_attention_heads
191
+
192
+ self.num_key_value_heads = num_key_value_heads
193
+ self.hidden_act = hidden_act
194
+ self.initializer_range = initializer_range
195
+ self.rms_norm_eps = float(rms_norm_eps)
196
+ self.pretraining_tp = pretraining_tp
197
+ self.use_cache = use_cache
198
+ self.rope_theta = rope_theta
199
+ self.rope_scaling = rope_scaling
200
+ self.attention_bias = attention_bias
201
+ self.attention_dropout = attention_dropout
202
+ self.use_mla = use_mla
203
+
204
+ super().__init__(
205
+ pad_token_id=pad_token_id,
206
+ bos_token_id=bos_token_id,
207
+ eos_token_id=eos_token_id,
208
+ tie_word_embeddings=tie_word_embeddings,
209
+ **kwargs,
210
+ )
conversation.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ From https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
3
+ """
4
+
5
+ import dataclasses
6
+ from enum import IntEnum, auto
7
+ from typing import Any, Dict, List
8
+
9
+
10
+ class SeparatorStyle(IntEnum):
11
+ """Separator styles."""
12
+
13
+ DeepSeek = auto()
14
+ DeepSeekV2 = auto()
15
+ PLAIN = auto()
16
+ ALIGNMENT = auto()
17
+
18
+
19
+ @dataclasses.dataclass
20
+ class Conversation:
21
+ """A class that manages prompt templates and keeps all conversation history."""
22
+
23
+ # The name of this template
24
+ name: str
25
+ # The template of the system prompt
26
+ system_template: str = "{system_message}"
27
+ # The system message
28
+ system_message: str = ""
29
+ # The names of two roles
30
+ roles: List[str] = (("USER", "ASSISTANT"),)
31
+ # All messages. Each item is (role, message).
32
+ messages: List[List[str]] = ()
33
+ # The number of few shot examples
34
+ offset: int = 0
35
+ # The separator style and configurations
36
+ sep_style: SeparatorStyle = SeparatorStyle.DeepSeek
37
+ sep: str = "\n"
38
+ sep2: str = None
39
+ # Stop criteria (the default one is EOS token)
40
+ stop_str: str = None
41
+ # Stops generation if meeting any token in this list
42
+ stop_token_ids: List[int] = None
43
+
44
+ def get_prompt(self) -> str:
45
+ """Get the prompt for generation."""
46
+ system_prompt = self.system_template.format(system_message=self.system_message)
47
+ if self.sep_style == SeparatorStyle.DeepSeek:
48
+ seps = [self.sep, self.sep2]
49
+ if system_prompt == "" or system_prompt is None:
50
+ ret = ""
51
+ else:
52
+ ret = system_prompt + seps[0]
53
+ for i, (role, message) in enumerate(self.messages):
54
+ if message:
55
+ ret += role + ": " + message + seps[i % 2]
56
+ else:
57
+ ret += role + ":"
58
+ return ret
59
+ elif self.sep_style == SeparatorStyle.DeepSeekV2:
60
+ seps = [self.sep, self.sep2]
61
+ if system_prompt == "" or system_prompt is None:
62
+ ret = ""
63
+ else:
64
+ ret = system_prompt + seps[0]
65
+ for i, (role, message) in enumerate(self.messages):
66
+ if message:
67
+ if role == "User":
68
+ ret += "<|sft▁begin|>\n" + message + self.sep #<|sft▁begin|>User Input<|sft▁end|>\nResponse<|end▁of▁sentence|>
69
+ else:
70
+ ret += message + self.sep2
71
+ else:
72
+ ret = ret
73
+ return ret
74
+
75
+ elif self.sep_style == SeparatorStyle.PLAIN:
76
+ seps = [self.sep, self.sep2]
77
+ ret = ""
78
+ for i, (role, message) in enumerate(self.messages):
79
+ if message:
80
+ if type(message) is tuple:
81
+ message, _, _ = message
82
+ if i % 2 == 0:
83
+ ret += message + seps[i % 2]
84
+ else:
85
+ ret += message + seps[i % 2]
86
+ else:
87
+ ret += ""
88
+ return ret
89
+ elif self.sep_style == SeparatorStyle.ALIGNMENT:
90
+ seps = [self.sep, self.sep2]
91
+ ret = ""
92
+ for i, (role, message) in enumerate(self.messages):
93
+ if message:
94
+ if type(message) is tuple:
95
+ message, _, _ = message
96
+ if i % 2 == 0:
97
+ ret += '<image>\n' + seps[i % 2]
98
+ else:
99
+ ret += message + seps[i % 2]
100
+ else:
101
+ ret += ""
102
+ return ret
103
+ else:
104
+ raise ValueError(f"Invalid style: {self.sep_style}")
105
+
106
+ def set_system_message(self, system_message: str):
107
+ """Set the system message."""
108
+ self.system_message = system_message
109
+
110
+ def append_message(self, role: str, message: str):
111
+ """Append a new message."""
112
+ self.messages.append([role, message])
113
+
114
+ def update_last_message(self, message: str):
115
+ """Update the last output.
116
+
117
+ The last message is typically set to be None when constructing the prompt,
118
+ so we need to update it in-place after getting the response from a model.
119
+ """
120
+ self.messages[-1][1] = message
121
+
122
+ def reset_message(self):
123
+ """Reset a new message."""
124
+ self.messages = []
125
+
126
+ def to_gradio_chatbot(self):
127
+ """Convert the conversation to gradio chatbot format."""
128
+ ret = []
129
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
130
+ if i % 2 == 0:
131
+ ret.append([msg, None])
132
+ else:
133
+ ret[-1][-1] = msg
134
+ return ret
135
+
136
+ def to_openai_api_messages(self):
137
+ """Convert the conversation to OpenAI chat completion format."""
138
+ system_prompt = self.system_template.format(system_message=self.system_message)
139
+ ret = [{"role": "system", "content": system_prompt}]
140
+
141
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
142
+ if i % 2 == 0:
143
+ ret.append({"role": "user", "content": msg})
144
+ else:
145
+ if msg is not None:
146
+ ret.append({"role": "assistant", "content": msg})
147
+ return ret
148
+
149
+ def copy(self):
150
+ return Conversation(
151
+ name=self.name,
152
+ system_template=self.system_template,
153
+ system_message=self.system_message,
154
+ roles=self.roles,
155
+ messages=[[x, y] for x, y in self.messages],
156
+ offset=self.offset,
157
+ sep_style=self.sep_style,
158
+ sep=self.sep,
159
+ sep2=self.sep2,
160
+ stop_str=self.stop_str,
161
+ stop_token_ids=self.stop_token_ids,
162
+ )
163
+
164
+ def dict(self):
165
+ return {
166
+ "template_name": self.name,
167
+ "system_message": self.system_message,
168
+ "roles": self.roles,
169
+ "messages": self.messages,
170
+ "offset": self.offset,
171
+ }
172
+
173
+
174
+ # A global registry for all conversation templates
175
+ conv_templates: Dict[str, Conversation] = {}
176
+
177
+
178
+ def register_conv_template(template: Conversation, override: bool = False):
179
+ """Register a new conversation template."""
180
+ if not override:
181
+ assert template.name not in conv_templates, f"{template.name} has been registered."
182
+
183
+ conv_templates[template.name] = template
184
+
185
+
186
+ def get_conv_template(name: str) -> Conversation:
187
+ """Get a conversation template."""
188
+ return conv_templates[name].copy()
189
+
190
+
191
+ register_conv_template(
192
+ Conversation(
193
+ name="deepseek",
194
+ system_template="{system_message}",
195
+ # system_message="You are a helpful assistant. Please answer truthfully and write out your "
196
+ # "thinking step by step to be sure you get the right answer.",
197
+ system_message="",
198
+ roles=("<|User|>", "<|Assistant|>"),
199
+ messages=(),
200
+ offset=0,
201
+ sep_style=SeparatorStyle.DeepSeek,
202
+ sep="\n\n",
203
+ sep2="<|end▁of▁sentence|>",
204
+ stop_token_ids=[100001],
205
+ stop_str=["User:", "<|end▁of▁sentence|>"]
206
+ )
207
+ )
208
+ register_conv_template(
209
+ Conversation(
210
+ name="deepseekv2",
211
+ system_template="{system_message}",
212
+ # system_message="You are a helpful assistant. Please answer truthfully and write out your "
213
+ # "thinking step by step to be sure you get the right answer.",
214
+ system_message="",
215
+ roles=("<|User|>", "<|Assistant|>"),
216
+ messages=(),
217
+ offset=0,
218
+ sep_style=SeparatorStyle.DeepSeek,
219
+ sep="",
220
+ sep2="<|end▁of▁sentence|>",
221
+ stop_token_ids=[100001],
222
+ stop_str=["User:", "<|end▁of▁sentence|>"]
223
+ )
224
+ )
225
+
226
+
227
+ register_conv_template(
228
+ Conversation(
229
+ name="plain",
230
+ system_template="",
231
+ system_message="",
232
+ roles=("", ""),
233
+ messages=(),
234
+ offset=0,
235
+ sep_style=SeparatorStyle.PLAIN,
236
+ sep="",
237
+ sep2="",
238
+ stop_token_ids=[100001],
239
+ stop_str=['</s>'],
240
+ )
241
+ )
242
+
243
+
244
+ register_conv_template(
245
+ Conversation(
246
+ name="alignment",
247
+ system_template="",
248
+ system_message="",
249
+ roles=("", ""),
250
+ messages=(),
251
+ offset=0,
252
+ sep_style=SeparatorStyle.ALIGNMENT,
253
+ sep="",
254
+ sep2="",
255
+ stop_token_ids=[100001],
256
+ stop_str=['</s>'],
257
+ )
258
+ )
259
+
260
+
261
+ if __name__ == "__main__":
262
+ print("deepseek template:")
263
+ conv = get_conv_template("deepseek")
264
+ conv.append_message(conv.roles[0], "Hello!")
265
+ conv.append_message(conv.roles[1], "Hi! This is Tony.")
266
+ conv.append_message(conv.roles[0], "Who are you?")
267
+ conv.append_message(conv.roles[1], "I am a helpful assistant.")
268
+ conv.append_message(conv.roles[0], "How are you?")
269
+ conv.append_message(conv.roles[1], None)
270
+ print(conv.get_prompt())
271
+
272
+ print("deepseekv2 template:")
273
+ conv = get_conv_template("deepseekv2")
274
+ conv.append_message(conv.roles[0], "Hello!")
275
+ conv.append_message(conv.roles[1], "Hi! This is Tony.")
276
+ conv.append_message(conv.roles[0], "Who are you?")
277
+ conv.append_message(conv.roles[1], "I am a helpful assistant.")
278
+ conv.append_message(conv.roles[0], "How are you?")
279
+ conv.append_message(conv.roles[1], None)
280
+ print(conv.get_prompt())
deepencoderv2.py ADDED
@@ -0,0 +1,1039 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+ import torch.nn.functional as F
4
+ import copy
5
+ import os
6
+
7
+
8
+ from typing import Optional, Tuple
9
+
10
+ # from megatron.model import LayerNorm
11
+
12
+ import transformers
13
+
14
+
15
+ from typing import Optional, Tuple, Type
16
+ from functools import partial
17
+
18
+
19
+
20
+ class MlpProjector(nn.Module):
21
+
22
+ def __init__(self, cfg):
23
+
24
+ super().__init__()
25
+
26
+ self.cfg = cfg
27
+
28
+ if cfg.projector_type == "identity":
29
+ modules = nn.Identity()
30
+
31
+ elif cfg.projector_type == "linear":
32
+ modules = nn.Linear(cfg.input_dim, cfg.n_embed)
33
+
34
+ elif cfg.projector_type == "mlp_gelu":
35
+ mlp_depth = cfg.get("depth", 1)
36
+ modules = [nn.Linear(cfg.input_dim, cfg.n_embed)]
37
+ for _ in range(1, mlp_depth):
38
+ modules.append(nn.GELU())
39
+ modules.append(nn.Linear(cfg.n_embed, cfg.n_embed))
40
+ modules = nn.Sequential(*modules)
41
+
42
+ elif cfg.projector_type == "normlayer_downsample_mlp_gelu":
43
+ mlp_depth = cfg.get("depth", 1)
44
+ mlp_ratio = cfg.get("mlp_ratio", 1)
45
+ modules = [
46
+ nn.LayerNorm(cfg.input_dim * cfg.downsample_ratio * cfg.downsample_ratio),
47
+ nn.Linear(cfg.input_dim * cfg.downsample_ratio * cfg.downsample_ratio, cfg.n_embed * mlp_ratio)
48
+ ]
49
+ for _ in range(1, mlp_depth - 1):
50
+ modules.append(nn.GELU())
51
+ modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed * mlp_ratio))
52
+ modules.append(nn.GELU())
53
+ modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed))
54
+ modules = nn.Sequential(*modules)
55
+
56
+ elif cfg.projector_type == "downsample_mlp_gelu":
57
+ mlp_depth = cfg.get("depth", 1)
58
+ mlp_ratio = cfg.get("mlp_ratio", 1)
59
+ modules = [nn.Linear(cfg.input_dim * cfg.downsample_ratio * cfg.downsample_ratio, cfg.n_embed * mlp_ratio)]
60
+ for _ in range(1, mlp_depth - 1):
61
+ modules.append(nn.GELU())
62
+ modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed * mlp_ratio))
63
+ modules.append(nn.GELU())
64
+ modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed))
65
+ modules = nn.Sequential(*modules)
66
+
67
+ elif cfg.projector_type == "low_high_hybrid_split_mlp_gelu":
68
+ mlp_depth = cfg.get("depth", 1)
69
+ self.high_up_proj = nn.Linear(cfg.input_dim, cfg.n_embed // 2)
70
+ self.low_up_proj = nn.Linear(cfg.input_dim, cfg.n_embed // 2)
71
+
72
+ modules = []
73
+ for _ in range(1, mlp_depth):
74
+ modules.append(nn.GELU())
75
+ modules.append(nn.Linear(cfg.n_embed, cfg.n_embed))
76
+ modules = nn.Sequential(*modules)
77
+
78
+ elif cfg.projector_type == "hybrid_split_feature_mlp_gelu":
79
+ mlp_depth = cfg.get("depth", 1)
80
+ channel_div = cfg.get("channel_div", 0.5)
81
+ self.high_up_proj = nn.Linear(cfg.input_dim[0], int(cfg.n_embed * channel_div))
82
+ self.low_up_proj = nn.Linear(cfg.input_dim[1], cfg.n_embed - int(cfg.n_embed * channel_div))
83
+
84
+ modules = []
85
+ for _ in range(1, mlp_depth):
86
+ modules.append(nn.GELU())
87
+ modules.append(nn.Linear(cfg.n_embed, cfg.n_embed))
88
+ modules = nn.Sequential(*modules)
89
+
90
+ elif cfg.projector_type == "low_high_split_mlp_gelu":
91
+ mlp_depth = cfg.get("depth", 1)
92
+ modules = []
93
+ for _ in range(1, mlp_depth):
94
+ modules.append(nn.GELU())
95
+ modules.append(nn.Linear(cfg.n_embed // 2, cfg.n_embed // 2))
96
+ modules = nn.Sequential(*modules)
97
+ self.high_layers = nn.Sequential(*modules)
98
+ self.low_layers = copy.deepcopy(modules)
99
+
100
+ else:
101
+ raise ValueError(f"Unknown projector type: {cfg.projector_type}")
102
+
103
+ if cfg.get("token_pooling", False):
104
+ self.token_pooling_layer = nn.Linear(cfg.input_dim * 4, cfg.input_dim)
105
+
106
+ if cfg.get("conv_fusion_high_low_features", False):
107
+ self.fusion_layer = nn.Linear(cfg.input_dim, cfg.input_dim)
108
+ self.layers = modules
109
+
110
+ def forward(self, x):
111
+ if self.cfg.get("token_pooling", False):
112
+ batch_size, wxh, channels = x.shape
113
+ w = h = int(wxh**0.5)
114
+ x = x.view(batch_size, w, h, channels)
115
+ x = x.permute(0, 3, 1, 2)
116
+ # import ipdb; ipdb.set_trace()
117
+ patches = x.unfold(2, 2, 2).unfold(3, 2, 2)
118
+ batch_size, channels, h_patches, w_patches, _, _ = patches.size()
119
+ # 在通道维度上拼接
120
+ patches = patches.contiguous().view(batch_size, channels, h_patches * w_patches, -1)
121
+
122
+ # 通过线性层
123
+ patches = patches.permute(0, 2, 1, 3).contiguous()
124
+ patches = patches.view(batch_size, h_patches * w_patches, channels * 4)
125
+
126
+ x = self.token_pooling_layer(patches)
127
+
128
+ if self.cfg.get("conv_fusion_high_low_features", False):
129
+ x = self.fusion_layer(x[:, 0]) + x[:, 1]
130
+
131
+ if self.cfg.projector_type == 'low_high_hybrid_split_mlp_gelu':
132
+ high_x, low_x = x[0], x[1]
133
+ high_x = self.high_up_proj(high_x)
134
+ low_x = self.low_up_proj(low_x)
135
+ x = torch.concat([high_x, low_x], dim=-1)
136
+
137
+ if self.cfg.projector_type == 'hybrid_split_feature_mlp_gelu':
138
+ high_x = x[...,:self.cfg.input_dim[0]]
139
+ low_x = x[...,self.cfg.input_dim[0]:]
140
+ high_x = self.high_up_proj(high_x)
141
+ low_x = self.low_up_proj(low_x)
142
+ x = torch.concat([high_x, low_x], dim=-1)
143
+
144
+ if self.cfg.projector_type == 'low_high_split_mlp_gelu':
145
+ high_x, low_x = x[0], x[1]
146
+ high_x = self.high_layers(high_x)
147
+ low_x = self.low_layers(low_x)
148
+ x = torch.concat([high_x, low_x], dim=-1)
149
+ return x
150
+
151
+ if self.cfg.projector_type == 'downsample_mlp_gelu' or self.cfg.projector_type == 'normlayer_downsample_mlp_gelu':
152
+ bs, hw, input_dim = x.shape
153
+ h = w = int((hw) ** 0.5)
154
+
155
+ """compute padding"""
156
+ if h % self.cfg.downsample_ratio:
157
+ pad = self.cfg.downsample_ratio - h % self.cfg.downsample_ratio
158
+ else:
159
+ pad = 0
160
+ x = x.reshape(bs, h, w, input_dim)
161
+ if pad > 0:
162
+ x = F.pad(x, (0, 0, 0, pad, 0, pad), "constant", 0)
163
+
164
+ """4 to 1 concat"""
165
+ x = x.permute(0, 3, 1, 2) # B, C, H, W
166
+ x = F.unfold(x, kernel_size=self.cfg.downsample_ratio, stride=self.cfg.downsample_ratio, padding=0) # B, C*4, HW // 4
167
+ x = x.permute(0, 2, 1)
168
+
169
+ return self.layers(x)
170
+
171
+ @staticmethod
172
+ def get_flops_per_sample(cfg):
173
+ if cfg.projector_type == "linear":
174
+ fwd = 2 * cfg.input_dim * cfg.n_embed
175
+
176
+ elif "mlp_gelu" in cfg.projector_type :
177
+ mlp_depth = cfg.get("depth", 1)
178
+ downsample_ratio = cfg.get("downsample_ratio", 1)
179
+ input_dim = sum(cfg.input_dim) if isinstance(cfg.input_dim, list) else cfg.input_dim
180
+ input_dim = input_dim * downsample_ratio * downsample_ratio
181
+ fwd = 2 * input_dim * cfg.n_embed + (mlp_depth - 1) * 2 * cfg.n_embed * cfg.n_embed
182
+ else:
183
+ fwd = 0
184
+
185
+ return fwd * 3
186
+
187
+
188
+ #===================qwen2================================
189
+
190
+ class CustomQwen2Decoder(nn.Module):
191
+ """
192
+ Qwen2 visual encoder
193
+ non-causal attention + causal attention
194
+ token_type_ids :0=non-causal, 1=causal
195
+ """
196
+
197
+ def __init__(
198
+ self,
199
+ decoder_layer: int = 24,
200
+ max_position_embeddings: int = 131072,
201
+ hidden_dimension: int = 896,
202
+ num_attention_heads: int = 14,
203
+ num_key_value_heads: int = 2,
204
+ intermediate_size: int = 4864,
205
+ vocab_size: int = 151936,
206
+ attn_implementation: str = "sdpa", # ⭐
207
+ rms_norm_eps: float = 1e-06,
208
+ rope_theta: float = 1000000.0,
209
+ attention_dropout: float = 0.0,
210
+ hidden_act: str = "silu",
211
+ initializer_range: float = 0.02,
212
+ ):
213
+ super().__init__()
214
+
215
+ # attn_implementation check
216
+ if attn_implementation == "flash_attention_2":
217
+ raise ValueError(
218
+ "CustomQwen2Decoder do not support flash_attention_2,"
219
+ "new attention mask needs 'sdpa' or 'eager'"
220
+ )
221
+
222
+ # load
223
+ Qwen2Model = getattr(transformers.models.qwen2.modeling_qwen2, 'Qwen2Model')
224
+ Qwen2Config = getattr(transformers, 'Qwen2Config')
225
+
226
+ # config
227
+ config = Qwen2Config(
228
+ hidden_size=hidden_dimension,
229
+ num_hidden_layers=decoder_layer,
230
+ num_attention_heads=num_attention_heads,
231
+ num_key_value_heads=num_key_value_heads,
232
+ intermediate_size=intermediate_size,
233
+ max_position_embeddings=max_position_embeddings,
234
+ vocab_size=vocab_size,
235
+ rms_norm_eps=rms_norm_eps,
236
+ rope_theta=rope_theta,
237
+ attention_dropout=attention_dropout,
238
+ hidden_act=hidden_act,
239
+ initializer_range=initializer_range,
240
+ _attn_implementation=attn_implementation, # ⭐
241
+ )
242
+
243
+ #
244
+ self.model = self._create_custom_model(Qwen2Model, config)
245
+
246
+ del self.model.embed_tokens
247
+
248
+ def _create_custom_model(self, Qwen2Model, config):
249
+ """ Qwen2Model """
250
+
251
+ class CustomQwen2ModelInner(Qwen2Model):
252
+
253
+
254
+ def forward(
255
+ self,
256
+ input_ids=None,
257
+ attention_mask=None,
258
+ position_ids=None,
259
+ past_key_values=None,
260
+ inputs_embeds=None,
261
+ token_type_ids=None, # ⭐
262
+ use_cache=None,
263
+ output_attentions=None,
264
+ output_hidden_states=None,
265
+ return_dict=None,
266
+ cache_position=None,
267
+ ):
268
+ # token_type_ids
269
+ self._current_token_type_ids = token_type_ids
270
+
271
+ outputs = super().forward(
272
+ input_ids=input_ids,
273
+ attention_mask=attention_mask,
274
+ position_ids=position_ids,
275
+ past_key_values=past_key_values,
276
+ inputs_embeds=inputs_embeds,
277
+ use_cache=use_cache,
278
+ output_attentions=output_attentions,
279
+ output_hidden_states=output_hidden_states,
280
+ return_dict=return_dict,
281
+ cache_position=cache_position,
282
+ )
283
+
284
+ return outputs
285
+
286
+ def _update_causal_mask(
287
+ self,
288
+ attention_mask,
289
+ input_tensor,
290
+ cache_position,
291
+ past_key_values,
292
+ output_attentions,
293
+ ):
294
+ dtype, device = input_tensor.dtype, input_tensor.device
295
+ min_dtype = torch.finfo(dtype).min
296
+ batch_size, sequence_length = input_tensor.shape[0], input_tensor.shape[1]
297
+
298
+ token_type_ids = self._current_token_type_ids
299
+
300
+ # attention mask
301
+ causal_mask = self._create_custom_4d_mask(
302
+ sequence_length=sequence_length,
303
+ dtype=dtype,
304
+ device=device,
305
+ batch_size=batch_size,
306
+ token_type_ids=token_type_ids,
307
+ )
308
+
309
+ # padding mask
310
+ if attention_mask is not None and attention_mask.dim() == 2:
311
+ padding_mask = attention_mask[:, None, None, :].to(dtype=dtype)
312
+ padding_mask = (1.0 - padding_mask) * min_dtype
313
+ causal_mask = causal_mask + padding_mask
314
+
315
+ return causal_mask
316
+
317
+ def _create_custom_4d_mask(
318
+ self,
319
+ sequence_length,
320
+ dtype,
321
+ device,
322
+ batch_size,
323
+ token_type_ids,
324
+ ):
325
+ min_dtype = torch.finfo(dtype).min
326
+
327
+ masks = []
328
+ for b in range(batch_size):
329
+ mask = torch.full(
330
+ (sequence_length, sequence_length),
331
+ fill_value=min_dtype,
332
+ dtype=dtype,
333
+ device=device
334
+ )
335
+
336
+ type_ids = token_type_ids[b]
337
+
338
+ image_positions = (type_ids == 0).nonzero(as_tuple=True)[0]
339
+ text_positions = (type_ids == 1).nonzero(as_tuple=True)[0]
340
+
341
+ # non-casual
342
+ if len(image_positions) > 0:
343
+ mask[image_positions[:, None], image_positions] = 0.0
344
+
345
+ # causal
346
+ for i, text_pos in enumerate(text_positions):
347
+ if len(image_positions) > 0:
348
+ mask[text_pos, image_positions] = 0.0
349
+ mask[text_pos, text_positions[:i+1]] = 0.0
350
+
351
+ masks.append(mask)
352
+
353
+ mask = torch.stack(masks, dim=0).unsqueeze(1)
354
+ return mask
355
+
356
+ return CustomQwen2ModelInner(config)
357
+
358
+ def forward(
359
+ self,
360
+ inputs_embeds,
361
+ token_type_ids,
362
+ attention_mask=None,
363
+ **kwargs
364
+ ):
365
+ """
366
+ Args:
367
+ inputs_embeds: [batch_size, seq_len, hidden_dim]
368
+ token_type_ids: [batch_size, seq_len], 0=non-causal, 1=causal
369
+ attention_mask: [batch_size, seq_len], optional
370
+ """
371
+ return self.model(
372
+ inputs_embeds=inputs_embeds,
373
+ token_type_ids=token_type_ids,
374
+ attention_mask=attention_mask,
375
+ **kwargs
376
+ )
377
+
378
+
379
+
380
+
381
+
382
+ # batch_size = 2
383
+ # inputs_embeds = torch.randn(batch_size, 512, 896).cuda()
384
+
385
+ # inputs_embeds = torch.randn(batch_size, 512, 896).cuda()
386
+ # token_type_ids = torch.cat([
387
+ # torch.zeros(batch_size, 256, dtype=torch.long),
388
+ # torch.ones(batch_size, 256, dtype=torch.long),
389
+ # ], dim=1).cuda()
390
+
391
+ # # start = time.time()
392
+ # with torch.no_grad():
393
+ # outputs_sdpa = decoder_sdpa(inputs_embeds, token_type_ids)
394
+ # print(outputs_sdpa[0].shape)
395
+ # print(f"SDPA time: {time.time() - start:.4f}s")
396
+
397
+
398
+
399
+ class Qwen2Decoder2Encoder(nn.Module):
400
+ """
401
+ Decoder based on Multilingual BART
402
+ Set the initial weights and configuration with a pretrained multilingual BART model,
403
+ and modify the detailed configurations as a Nougat decoder
404
+ """
405
+
406
+ def __init__(
407
+ self,
408
+ decoder_layer: int,
409
+ hidden_dimension: int,
410
+ num_attention_heads: int,
411
+ num_key_value_heads: int,
412
+ intermediate_size: int,
413
+ max_query: int,
414
+ text_hidden_dim: int = 1280,
415
+ ):
416
+ super().__init__()
417
+
418
+ self.model = CustomQwen2Decoder(
419
+ decoder_layer=decoder_layer,
420
+ hidden_dimension=hidden_dimension,
421
+ num_attention_heads=num_attention_heads,
422
+ num_key_value_heads=num_key_value_heads,
423
+ intermediate_size=intermediate_size,
424
+ attn_implementation="sdpa",
425
+ )
426
+
427
+
428
+
429
+
430
+ self.query_768 = nn.Embedding(144, hidden_dimension)
431
+ self.query_1024 = nn.Embedding(256, hidden_dimension)
432
+ self.enable_text_query_residual = os.getenv('DEEPSEEK_OCR2_ENABLE_TEXT_QUERY_RESIDUAL', '0') == '1'
433
+ self.text_context_proj = nn.Linear(text_hidden_dim, hidden_dimension)
434
+ self.text_query_mlp = nn.Sequential(
435
+ nn.Linear(hidden_dimension, hidden_dimension),
436
+ nn.SiLU(),
437
+ nn.Linear(hidden_dimension, hidden_dimension * 2),
438
+ )
439
+ self.text_query_residual_scale = nn.Parameter(torch.zeros(1))
440
+ nn.init.zeros_(self.text_query_mlp[-1].weight)
441
+ nn.init.zeros_(self.text_query_mlp[-1].bias)
442
+
443
+
444
+ # self.query_refixation = nn.Embedding(int(math.sqrt(max_query)), hidden_dimension)
445
+
446
+
447
+ def _apply_text_context(self, base_query_imgs: torch.Tensor, text_context: Optional[torch.Tensor]) -> torch.Tensor:
448
+ if not self.enable_text_query_residual or text_context is None:
449
+ return base_query_imgs
450
+
451
+ text_context = self.text_context_proj(text_context).to(base_query_imgs.dtype)
452
+ delta, gate = self.text_query_mlp(text_context).chunk(2, dim=-1)
453
+ residual = torch.sigmoid(gate).unsqueeze(1) * delta.unsqueeze(1)
454
+ return base_query_imgs + self.text_query_residual_scale * residual
455
+
456
+ def forward(self, x: torch.Tensor, text_context: Optional[torch.Tensor] = None) -> torch.Tensor:
457
+ x = x.flatten(2).transpose(1, 2)
458
+
459
+ bs, n_query, _ = x.shape
460
+
461
+ if n_query == 144:
462
+ param_img = self.query_768.weight
463
+ elif n_query == 256:
464
+ param_img = self.query_1024.weight
465
+
466
+ batch_query_imgs = param_img.unsqueeze(0).expand(
467
+ bs, -1, -1
468
+ ) # (batch_size, num_queries, hidden_size)
469
+ batch_query_imgs = self._apply_text_context(batch_query_imgs, text_context)
470
+
471
+
472
+
473
+ x_combined = torch.cat([x, batch_query_imgs], dim=1)
474
+
475
+ token_type_ids = torch.cat([
476
+ torch.zeros(bs, n_query, dtype=torch.long),
477
+ torch.ones(bs, n_query, dtype=torch.long),
478
+ ], dim=1)
479
+
480
+
481
+ y = self.model(x_combined, token_type_ids)[0]
482
+
483
+
484
+ y = y[:, n_query:, :] # causal flow query
485
+
486
+
487
+ return y
488
+
489
+
490
+ def build_qwen2_decoder_as_encoder(
491
+ decoder_layer=24,
492
+ hidden_dimension=896,
493
+ num_attention_heads=14,
494
+ num_key_value_heads=2,
495
+ intermediate_size=4864,
496
+ max_query = 400,
497
+ text_hidden_dim=1280,
498
+ checkpoint=None,
499
+ ):
500
+
501
+ decoder_as_encoder = Qwen2Decoder2Encoder(
502
+ decoder_layer=decoder_layer,
503
+ hidden_dimension = hidden_dimension,
504
+ num_attention_heads = num_attention_heads,
505
+ num_key_value_heads = num_key_value_heads,
506
+ intermediate_size = intermediate_size,
507
+ max_query = max_query,
508
+ text_hidden_dim=text_hidden_dim
509
+ )
510
+
511
+
512
+
513
+
514
+ if checkpoint is not None:
515
+ # with open(checkpoint, "rb") as f:
516
+ state_dict = torch.load(checkpoint)
517
+
518
+ decoder_as_encoder.load_state_dict(state_dict, strict=True)
519
+ # tob
520
+ print(checkpoint)
521
+ return decoder_as_encoder
522
+
523
+
524
+
525
+
526
+ #=========================Sam-Vary=================================
527
+
528
+
529
+ def get_abs_pos_sam(abs_pos, tgt_size):
530
+
531
+ dtype = abs_pos.dtype
532
+
533
+ src_size = abs_pos.size(1)
534
+
535
+ if src_size != tgt_size:
536
+ old_pos_embed = abs_pos.permute(0, 3, 1, 2)
537
+ old_pos_embed = old_pos_embed.to(torch.float32)
538
+ new_pos_embed = F.interpolate(
539
+ old_pos_embed,
540
+ size=(tgt_size, tgt_size),
541
+ mode='bicubic',
542
+ antialias=True,
543
+ align_corners=False,
544
+ ).to(dtype)
545
+ new_pos_embed = new_pos_embed.permute(0, 2, 3, 1)
546
+ return new_pos_embed
547
+ else:
548
+ return abs_pos
549
+
550
+
551
+
552
+
553
+ class MLPBlock(nn.Module):
554
+ def __init__(
555
+ self,
556
+ embedding_dim: int,
557
+ mlp_dim: int,
558
+ act: Type[nn.Module] = nn.GELU,
559
+ ) -> None:
560
+ super().__init__()
561
+ self.lin1 = nn.Linear(embedding_dim, mlp_dim)
562
+ self.lin2 = nn.Linear(mlp_dim, embedding_dim)
563
+ self.act = act()
564
+
565
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
566
+ return self.lin2(self.act(self.lin1(x)))
567
+
568
+
569
+ # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
570
+ # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
571
+ class LayerNorm2d(nn.Module):
572
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
573
+ super().__init__()
574
+ self.weight = nn.Parameter(torch.ones(num_channels))
575
+ self.bias = nn.Parameter(torch.zeros(num_channels))
576
+ self.eps = eps
577
+
578
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
579
+ u = x.mean(1, keepdim=True)
580
+ s = (x - u).pow(2).mean(1, keepdim=True)
581
+ x = (x - u) / torch.sqrt(s + self.eps)
582
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
583
+ return x
584
+
585
+
586
+ # This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
587
+ class ImageEncoderViT(nn.Module):
588
+ def __init__(
589
+ self,
590
+ img_size: int = 1024,
591
+ patch_size: int = 16,
592
+ in_chans: int = 3,
593
+ embed_dim: int = 768,
594
+ depth: int = 12,
595
+ num_heads: int = 12,
596
+ mlp_ratio: float = 4.0,
597
+ out_chans: int = 256,
598
+ qkv_bias: bool = True,
599
+ norm_layer: Type[nn.Module] = nn.LayerNorm,
600
+ act_layer: Type[nn.Module] = nn.GELU,
601
+ use_abs_pos: bool = True,
602
+ use_rel_pos: bool = False,
603
+ rel_pos_zero_init: bool = True,
604
+ window_size: int = 0,
605
+ global_attn_indexes: Tuple[int, ...] = (),
606
+ ) -> None:
607
+ """
608
+ Args:
609
+ img_size (int): Input image size.
610
+ patch_size (int): Patch size.
611
+ in_chans (int): Number of input image channels.
612
+ embed_dim (int): Patch embedding dimension.
613
+ depth (int): Depth of ViT.
614
+ num_heads (int): Number of attention heads in each ViT block.
615
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
616
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
617
+ norm_layer (nn.Module): Normalization layer.
618
+ act_layer (nn.Module): Activation layer.
619
+ use_abs_pos (bool): If True, use absolute positional embeddings.
620
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
621
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
622
+ window_size (int): Window size for window attention blocks.
623
+ global_attn_indexes (list): Indexes for blocks using global attention.
624
+ """
625
+ super().__init__()
626
+ self.img_size = img_size
627
+
628
+ self.patch_embed = PatchEmbed(
629
+ kernel_size=(patch_size, patch_size),
630
+ stride=(patch_size, patch_size),
631
+ in_chans=in_chans,
632
+ embed_dim=embed_dim,
633
+ )
634
+
635
+ self.pos_embed: Optional[nn.Parameter] = None
636
+ if use_abs_pos:
637
+ # Initialize absolute positional embedding with pretrain image size.
638
+ self.pos_embed = nn.Parameter(
639
+ torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim)
640
+ )
641
+
642
+ self.blocks = nn.ModuleList()
643
+ for i in range(depth):
644
+ block = Block(
645
+ dim=embed_dim,
646
+ num_heads=num_heads,
647
+ mlp_ratio=mlp_ratio,
648
+ qkv_bias=qkv_bias,
649
+ norm_layer=norm_layer,
650
+ act_layer=act_layer,
651
+ use_rel_pos=use_rel_pos,
652
+ rel_pos_zero_init=rel_pos_zero_init,
653
+ window_size=window_size if i not in global_attn_indexes else 0,
654
+ input_size=(img_size // patch_size, img_size // patch_size),
655
+ )
656
+ self.blocks.append(block)
657
+
658
+ self.neck = nn.Sequential(
659
+ nn.Conv2d(
660
+ embed_dim,
661
+ out_chans,
662
+ kernel_size=1,
663
+ bias=False,
664
+ ),
665
+ LayerNorm2d(out_chans),
666
+ nn.Conv2d(
667
+ out_chans,
668
+ out_chans,
669
+ kernel_size=3,
670
+ padding=1,
671
+ bias=False,
672
+ ),
673
+ LayerNorm2d(out_chans),
674
+ )
675
+
676
+ self.net_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1, bias=False)
677
+ self.net_3 = nn.Conv2d(512, 896, kernel_size=3, stride=2, padding=1, bias=False)
678
+
679
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
680
+ x = self.patch_embed(x)
681
+ if self.pos_embed is not None:
682
+ # x = x + self.pos_embed
683
+ x = x + get_abs_pos_sam(self.pos_embed, x.size(1))
684
+
685
+ for blk in self.blocks:
686
+ x = blk(x)
687
+
688
+ x = self.neck(x.permute(0, 3, 1, 2))
689
+ x2 = self.net_2(x)
690
+ x3 = self.net_3(x2.clone())
691
+
692
+ return x3
693
+
694
+
695
+ class Block(nn.Module):
696
+ """Transformer blocks with support of window attention and residual propagation blocks"""
697
+
698
+ def __init__(
699
+ self,
700
+ dim: int,
701
+ num_heads: int,
702
+ mlp_ratio: float = 4.0,
703
+ qkv_bias: bool = True,
704
+ norm_layer: Type[nn.Module] = nn.LayerNorm,
705
+ act_layer: Type[nn.Module] = nn.GELU,
706
+ use_rel_pos: bool = False,
707
+ rel_pos_zero_init: bool = True,
708
+ window_size: int = 0,
709
+ input_size: Optional[Tuple[int, int]] = None,
710
+ ) -> None:
711
+ """
712
+ Args:
713
+ dim (int): Number of input channels.
714
+ num_heads (int): Number of attention heads in each ViT block.
715
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
716
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
717
+ norm_layer (nn.Module): Normalization layer.
718
+ act_layer (nn.Module): Activation layer.
719
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
720
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
721
+ window_size (int): Window size for window attention blocks. If it equals 0, then
722
+ use global attention.
723
+ input_size (tuple(int, int) or None): Input resolution for calculating the relative
724
+ positional parameter size.
725
+ """
726
+ super().__init__()
727
+ self.norm1 = norm_layer(dim)
728
+ self.attn = Attention(
729
+ dim,
730
+ num_heads=num_heads,
731
+ qkv_bias=qkv_bias,
732
+ use_rel_pos=use_rel_pos,
733
+ rel_pos_zero_init=rel_pos_zero_init,
734
+ input_size=input_size if window_size == 0 else (window_size, window_size),
735
+ )
736
+
737
+ self.norm2 = norm_layer(dim)
738
+ self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer)
739
+
740
+ self.window_size = window_size
741
+
742
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
743
+ shortcut = x
744
+ x = self.norm1(x)
745
+ # Window partition
746
+ if self.window_size > 0:
747
+ H, W = x.shape[1], x.shape[2]
748
+ x, pad_hw = window_partition(x, self.window_size)
749
+
750
+ x = self.attn(x)
751
+ # Reverse window partition
752
+ if self.window_size > 0:
753
+ x = window_unpartition(x, self.window_size, pad_hw, (H, W))
754
+
755
+ x = shortcut + x
756
+ x = x + self.mlp(self.norm2(x))
757
+
758
+ return x
759
+
760
+
761
+ class Attention(nn.Module):
762
+ """Multi-head Attention block with relative position embeddings."""
763
+
764
+ def __init__(
765
+ self,
766
+ dim: int,
767
+ num_heads: int = 8,
768
+ qkv_bias: bool = True,
769
+ use_rel_pos: bool = False,
770
+ rel_pos_zero_init: bool = True,
771
+ input_size: Optional[Tuple[int, int]] = None,
772
+ ) -> None:
773
+ """
774
+ Args:
775
+ dim (int): Number of input channels.
776
+ num_heads (int): Number of attention heads.
777
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
778
+ rel_pos (bool): If True, add relative positional embeddings to the attention map.
779
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
780
+ input_size (tuple(int, int) or None): Input resolution for calculating the relative
781
+ positional parameter size.
782
+ """
783
+ super().__init__()
784
+ self.num_heads = num_heads
785
+ head_dim = dim // num_heads
786
+ self.scale = head_dim**-0.5
787
+
788
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
789
+ self.proj = nn.Linear(dim, dim)
790
+
791
+ self.use_rel_pos = use_rel_pos
792
+ if self.use_rel_pos:
793
+ assert (
794
+ input_size is not None
795
+ ), "Input size must be provided if using relative positional encoding."
796
+ # initialize relative positional embeddings
797
+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
798
+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
799
+
800
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
801
+ B, H, W, _ = x.shape
802
+ # qkv with shape (3, B, nHead, H * W, C)
803
+ qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
804
+ # q, k, v with shape (B * nHead, H * W, C)
805
+ q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
806
+
807
+ rel_h, rel_w = None, None
808
+ if self.use_rel_pos:
809
+ rel_h, rel_w = add_decomposed_rel_pos(q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))
810
+
811
+ q = q.view(B, self.num_heads, H * W, -1)
812
+ k = k.view(B, self.num_heads, H * W, -1)
813
+ v = v.view(B, self.num_heads, H * W, -1)
814
+
815
+ if self.use_rel_pos:
816
+ rel_h = rel_h.view(B, self.num_heads, rel_h.size(1), rel_h.size(2), rel_h.size(3))
817
+ rel_w = rel_w.view(B, self.num_heads, rel_w.size(1), rel_w.size(2), rel_w.size(3))
818
+ attn_bias = (rel_h + rel_w).view(B, self.num_heads, rel_h.size(2), rel_h.size(3) * rel_w.size(4))
819
+ x = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=attn_bias)
820
+ # x = _attention_rel_h_rel_w(q, k, v, rel_h, rel_w)
821
+ else:
822
+ x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
823
+
824
+ x = x.view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
825
+
826
+ x = self.proj(x)
827
+
828
+ return x
829
+
830
+
831
+ def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]:
832
+ """
833
+ Partition into non-overlapping windows with padding if needed.
834
+ Args:
835
+ x (tensor): input tokens with [B, H, W, C].
836
+ window_size (int): window size.
837
+
838
+ Returns:
839
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
840
+ (Hp, Wp): padded height and width before partition
841
+ """
842
+ B, H, W, C = x.shape
843
+
844
+ pad_h = (window_size - H % window_size) % window_size
845
+ pad_w = (window_size - W % window_size) % window_size
846
+ if pad_h > 0 or pad_w > 0:
847
+ x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
848
+ Hp, Wp = H + pad_h, W + pad_w
849
+
850
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
851
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
852
+ return windows, (Hp, Wp)
853
+
854
+
855
+ def window_unpartition(
856
+ windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int]
857
+ ) -> torch.Tensor:
858
+ """
859
+ Window unpartition into original sequences and removing padding.
860
+ Args:
861
+ windows (tensor): input tokens with [B * num_windows, window_size, window_size, C].
862
+ window_size (int): window size.
863
+ pad_hw (Tuple): padded height and width (Hp, Wp).
864
+ hw (Tuple): original height and width (H, W) before padding.
865
+
866
+ Returns:
867
+ x: unpartitioned sequences with [B, H, W, C].
868
+ """
869
+ Hp, Wp = pad_hw
870
+ H, W = hw
871
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
872
+ x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
873
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
874
+
875
+ if Hp > H or Wp > W:
876
+ x = x[:, :H, :W, :].contiguous()
877
+ return x
878
+
879
+
880
+ def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
881
+ """
882
+ Get relative positional embeddings according to the relative positions of
883
+ query and key sizes.
884
+ Args:
885
+ q_size (int): size of query q.
886
+ k_size (int): size of key k.
887
+ rel_pos (Tensor): relative position embeddings (L, C).
888
+
889
+ Returns:
890
+ Extracted positional embeddings according to relative positions.
891
+ """
892
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
893
+ # Interpolate rel pos if needed.
894
+ if rel_pos.shape[0] != max_rel_dist:
895
+ # Interpolate rel pos.
896
+ dtype = rel_pos.dtype
897
+ rel_pos = rel_pos.to(torch.float32)
898
+ rel_pos_resized = F.interpolate(
899
+ rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
900
+ size=max_rel_dist,
901
+ mode="linear",
902
+ ).to(dtype)
903
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
904
+ else:
905
+ rel_pos_resized = rel_pos
906
+
907
+ # Scale the coords with short length if shapes for q and k are different.
908
+ q_coords = torch.arange(q_size, device=rel_pos.device)[:, None] * max(k_size / q_size, 1.0)
909
+ k_coords = torch.arange(k_size, device=rel_pos.device)[None, :] * max(q_size / k_size, 1.0)
910
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
911
+
912
+ return rel_pos_resized[relative_coords.long()]
913
+
914
+
915
+ def add_decomposed_rel_pos(
916
+ q: torch.Tensor,
917
+ rel_pos_h: torch.Tensor,
918
+ rel_pos_w: torch.Tensor,
919
+ q_size: Tuple[int, int],
920
+ k_size: Tuple[int, int],
921
+ ) -> torch.Tensor:
922
+ """
923
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
924
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950
925
+ Args:
926
+ q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).
927
+ rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.
928
+ rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.
929
+ q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
930
+ k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
931
+
932
+ Returns:
933
+ attn (Tensor): attention map with added relative positional embeddings.
934
+ """
935
+ q_h, q_w = q_size
936
+ k_h, k_w = k_size
937
+ Rh = get_rel_pos(q_h, k_h, rel_pos_h)
938
+ Rw = get_rel_pos(q_w, k_w, rel_pos_w)
939
+
940
+ B, _, dim = q.shape
941
+ r_q = q.reshape(B, q_h, q_w, dim)
942
+ rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
943
+ rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
944
+ rel_h = rel_h.unsqueeze(-1)
945
+ rel_w = rel_w.unsqueeze(-2)
946
+ rel_h = rel_h.reshape(B, q_h * q_w, k_h, 1)
947
+ rel_w = rel_w.reshape(B, q_h * q_w, 1, k_w)
948
+
949
+ return rel_h, rel_w
950
+
951
+
952
+ class PatchEmbed(nn.Module):
953
+ """
954
+ Image to Patch Embedding.
955
+ """
956
+
957
+ def __init__(
958
+ self,
959
+ kernel_size: Tuple[int, int] = (16, 16),
960
+ stride: Tuple[int, int] = (16, 16),
961
+ padding: Tuple[int, int] = (0, 0),
962
+ in_chans: int = 3,
963
+ embed_dim: int = 768,
964
+ ) -> None:
965
+ """
966
+ Args:
967
+ kernel_size (Tuple): kernel size of the projection layer.
968
+ stride (Tuple): stride of the projection layer.
969
+ padding (Tuple): padding size of the projection layer.
970
+ in_chans (int): Number of input image channels.
971
+ embed_dim (int): Patch embedding dimension.
972
+ """
973
+ super().__init__()
974
+
975
+ self.proj = nn.Conv2d(
976
+ in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
977
+ )
978
+
979
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
980
+ x = self.proj(x)
981
+ # B C H W -> B H W C
982
+ x = x.permute(0, 2, 3, 1)
983
+ return x
984
+
985
+
986
+ def build_sam_vit_b(checkpoint=None):
987
+ return _build_sam(
988
+ encoder_embed_dim=768,
989
+ encoder_depth=12,
990
+ encoder_num_heads=12,
991
+ encoder_global_attn_indexes=[2, 5, 8, 11],
992
+ checkpoint=checkpoint,
993
+ )
994
+
995
+ def build_sam_fast_vit_b(checkpoint=None, compile_mode='max-autotune', dtype=torch.bfloat16):
996
+ image_encoder = build_sam_vit_b(checkpoint).eval().to(dtype)
997
+ # sam = _apply_eval_dtype_sam(sam, dtype)
998
+ image_encoder = torch.compile(image_encoder, mode=compile_mode)
999
+ return image_encoder
1000
+
1001
+
1002
+ def _build_sam(
1003
+ encoder_embed_dim,
1004
+ encoder_depth,
1005
+ encoder_num_heads,
1006
+ encoder_global_attn_indexes,
1007
+ checkpoint=None,
1008
+ ):
1009
+ prompt_embed_dim = 256
1010
+ image_size = 1024
1011
+ vit_patch_size = 16
1012
+ image_embedding_size = image_size // vit_patch_size
1013
+ image_encoder=ImageEncoderViT(
1014
+ depth=encoder_depth,
1015
+ embed_dim=encoder_embed_dim,
1016
+ img_size=image_size,
1017
+ mlp_ratio=4,
1018
+ norm_layer=partial(torch.nn.LayerNorm, eps=1e-6),
1019
+ num_heads=encoder_num_heads,
1020
+ patch_size=vit_patch_size,
1021
+ qkv_bias=True,
1022
+ use_rel_pos=True,
1023
+ global_attn_indexes=encoder_global_attn_indexes,
1024
+ window_size=14,
1025
+ out_chans=prompt_embed_dim,
1026
+ )
1027
+ image_encoder.eval()
1028
+ if checkpoint is not None:
1029
+ # with open(checkpoint, "rb") as f:
1030
+ state_dict = torch.load(checkpoint)
1031
+ # print(state_dict.keys())
1032
+ # for key in state_dict:
1033
+ # image_encoder.load_state_dict({k[14:]: v for k, v in state_dict.items() if 'image_encoder' in k}, strict=False)
1034
+ # ocr-anyting
1035
+ # image_encoder.load_state_dict(state_dict, strict=True)
1036
+ # tob
1037
+ image_encoder.load_state_dict({k[30:]: v for k, v in state_dict.items() if 'vision_tower_high' in k}, strict=True)
1038
+ print(checkpoint)
1039
+ return image_encoder
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "transformers_version": "4.46.3"
6
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4d4e57f129c2c045963661f26cc79bf2cacf6dc2f015145317ff4d38a4e8432
3
+ size 5000040704
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1bbe38202705c569f8135d76e29240187eaae4cb4dc1242828f4fb5059af9a7f
3
+ size 1785650986
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_deepseekocr2.py ADDED
@@ -0,0 +1,1064 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .modeling_deepseekv2 import DeepseekV2Model, DeepseekV2ForCausalLM
2
+ from .configuration_deepseek_v2 import DeepseekV2Config
3
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
4
+ from typing import List, Optional, Tuple, Union
5
+ from transformers.cache_utils import Cache
6
+ import requests
7
+ from PIL import Image, ImageOps, ImageDraw, ImageFont
8
+ from io import BytesIO
9
+ import torch
10
+ import torch.nn as nn
11
+ from torch.nn import CrossEntropyLoss
12
+ from torchvision import transforms
13
+ # from torchvision.transforms.functional import InterpolationMode
14
+ import os
15
+ from .deepencoderv2 import build_sam_vit_b, build_qwen2_decoder_as_encoder, MlpProjector
16
+ from addict import Dict
17
+ from transformers import TextStreamer
18
+ from .conversation import get_conv_template
19
+ from abc import ABC
20
+ import math
21
+ import re
22
+ from tqdm import tqdm
23
+ import numpy as np
24
+ # import time
25
+
26
+
27
+
28
+ def load_image(image_path):
29
+
30
+ try:
31
+ image = Image.open(image_path)
32
+
33
+ corrected_image = ImageOps.exif_transpose(image)
34
+
35
+ return corrected_image
36
+
37
+ except Exception as e:
38
+ print(f"error: {e}")
39
+ try:
40
+ return Image.open(image_path)
41
+ except:
42
+ return None
43
+
44
+
45
+ def re_match(text):
46
+ pattern = r'(<\|ref\|>(.*?)<\|/ref\|><\|det\|>(.*?)<\|/det\|>)'
47
+ matches = re.findall(pattern, text, re.DOTALL)
48
+
49
+ # pattern1 = r'<\|ref\|>.*?<\|/ref\|>\n'
50
+ # new_text1 = re.sub(pattern1, '', text, flags=re.DOTALL)
51
+
52
+ mathes_image = []
53
+ mathes_other = []
54
+ for a_match in matches:
55
+ if '<|ref|>image<|/ref|>' in a_match[0]:
56
+ mathes_image.append(a_match[0])
57
+ else:
58
+ mathes_other.append(a_match[0])
59
+ return matches, mathes_image, mathes_other
60
+
61
+
62
+ def extract_coordinates_and_label(ref_text, image_width, image_height):
63
+
64
+ try:
65
+ label_type = ref_text[1]
66
+ cor_list = eval(ref_text[2])
67
+ except Exception as e:
68
+ print(e)
69
+ return None
70
+
71
+ return (label_type, cor_list)
72
+
73
+
74
+ def draw_bounding_boxes(image, refs, ouput_path):
75
+
76
+ image_width, image_height = image.size
77
+
78
+ img_draw = image.copy()
79
+ draw = ImageDraw.Draw(img_draw)
80
+
81
+ overlay = Image.new('RGBA', img_draw.size, (0, 0, 0, 0))
82
+ draw2 = ImageDraw.Draw(overlay)
83
+
84
+ # try:
85
+ # except IOError:
86
+ # try:
87
+ # font = ImageFont.truetype("DejaVuSans.ttf", 20)
88
+ # except IOError:
89
+ font = ImageFont.load_default()
90
+
91
+ img_idx = 0
92
+
93
+ for i, ref in enumerate(refs):
94
+ try:
95
+ result = extract_coordinates_and_label(ref, image_width, image_height)
96
+ if result:
97
+ label_type, points_list = result
98
+
99
+ color = (np.random.randint(0, 200), np.random.randint(0, 200), np.random.randint(0, 255))
100
+
101
+ color_a = color + (20, )
102
+ for points in points_list:
103
+ x1, y1, x2, y2 = points
104
+
105
+ x1 = int(x1 / 999 * image_width)
106
+ y1 = int(y1 / 999 * image_height)
107
+
108
+ x2 = int(x2 / 999 * image_width)
109
+ y2 = int(y2 / 999 * image_height)
110
+
111
+ if label_type == 'image':
112
+ try:
113
+ cropped = image.crop((x1, y1, x2, y2))
114
+ cropped.save(f"{ouput_path}/images/{img_idx}.jpg")
115
+ except Exception as e:
116
+ print(e)
117
+ pass
118
+ img_idx += 1
119
+
120
+ try:
121
+ if label_type == 'title':
122
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=4)
123
+ draw2.rectangle([x1, y1, x2, y2], fill=color_a, outline=(0, 0, 0, 0), width=1)
124
+ else:
125
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=2)
126
+ draw2.rectangle([x1, y1, x2, y2], fill=color_a, outline=(0, 0, 0, 0), width=1)
127
+ text_x = x1
128
+ text_y = max(0, y1 - 15)
129
+
130
+
131
+ text_bbox = draw.textbbox((0, 0), label_type, font=font)
132
+ text_width = text_bbox[2] - text_bbox[0]
133
+ text_height = text_bbox[3] - text_bbox[1]
134
+ draw.rectangle([text_x, text_y, text_x + text_width, text_y + text_height],
135
+ fill=(255, 255, 255, 30))
136
+
137
+ draw.text((text_x, text_y), label_type, font=font, fill=color)
138
+ except:
139
+ pass
140
+ except:
141
+ continue
142
+ img_draw.paste(overlay, (0, 0), overlay)
143
+ return img_draw
144
+
145
+
146
+ def process_image_with_refs(image, ref_texts, output_path):
147
+
148
+ result_image = draw_bounding_boxes(image, ref_texts, output_path)
149
+
150
+ return result_image
151
+
152
+
153
+
154
+
155
+
156
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
157
+ best_ratio_diff = float('inf')
158
+ best_ratio = (1, 1)
159
+ area = width * height
160
+ for ratio in target_ratios:
161
+ target_aspect_ratio = ratio[0] / ratio[1]
162
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
163
+ if ratio_diff < best_ratio_diff:
164
+ best_ratio_diff = ratio_diff
165
+ best_ratio = ratio
166
+ elif ratio_diff == best_ratio_diff:
167
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
168
+ best_ratio = ratio
169
+ # print(f'width: {width}, height: {height}, best_ratio: {best_ratio}')
170
+ return best_ratio
171
+
172
+
173
+ def dynamic_preprocess(image, min_num=2, max_num=6, image_size=768, use_thumbnail=False):
174
+ orig_width, orig_height = image.size
175
+ aspect_ratio = orig_width / orig_height
176
+
177
+ # calculate the existing image aspect ratio
178
+ target_ratios = set(
179
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
180
+ i * j <= max_num and i * j >= min_num)
181
+ # print(target_ratios)
182
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
183
+
184
+ # find the closest aspect ratio to the target
185
+ target_aspect_ratio = find_closest_aspect_ratio(
186
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
187
+
188
+ # print(target_aspect_ratio)
189
+ # calculate the target width and height
190
+ target_width = image_size * target_aspect_ratio[0]
191
+ target_height = image_size * target_aspect_ratio[1]
192
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
193
+
194
+ # resize the image
195
+ resized_img = image.resize((target_width, target_height))
196
+ processed_images = []
197
+ for i in range(blocks):
198
+ box = (
199
+ (i % (target_width // image_size)) * image_size,
200
+ (i // (target_width // image_size)) * image_size,
201
+ ((i % (target_width // image_size)) + 1) * image_size,
202
+ ((i // (target_width // image_size)) + 1) * image_size
203
+ )
204
+ # split the image
205
+ split_img = resized_img.crop(box)
206
+ processed_images.append(split_img)
207
+ assert len(processed_images) == blocks
208
+ if use_thumbnail and len(processed_images) != 1:
209
+ thumbnail_img = image.resize((image_size, image_size))
210
+ processed_images.append(thumbnail_img)
211
+ return processed_images, target_aspect_ratio
212
+
213
+
214
+
215
+ def normalize_transform(mean, std):
216
+ if mean is None and std is None:
217
+ transform = None
218
+ elif mean is None and std is not None:
219
+ mean = [0.] * len(std)
220
+ transform = transforms.Normalize(mean=mean, std=std)
221
+ elif mean is not None and std is None:
222
+ std = [1.] * len(mean)
223
+ transform = transforms.Normalize(mean=mean, std=std)
224
+ else:
225
+ transform = transforms.Normalize(mean=mean, std=std)
226
+
227
+ return transform
228
+
229
+
230
+
231
+ def format_messages(
232
+ conversations: List[Dict[str, str]],
233
+ sft_format: str = "deepseek",
234
+ system_prompt: str = "",
235
+ ):
236
+ """
237
+ Applies the SFT template to conversation.
238
+
239
+ Args:
240
+ conversations (List[Dict]): A List of messages.
241
+ sft_format (str, optional): The format of the SFT template to use. Defaults to "deepseek".
242
+ system_prompt (str, optional): The system prompt to use in the SFT template. Defaults to "".
243
+
244
+ Returns:
245
+ sft_prompt (str): The formatted text.
246
+ """
247
+
248
+ conv = get_conv_template(sft_format)
249
+ conv.set_system_message(system_prompt)
250
+ for message in conversations:
251
+ conv.append_message(message["role"], message["content"].strip())
252
+ sft_prompt = conv.get_prompt().strip()
253
+
254
+ return sft_prompt
255
+
256
+
257
+ def text_encode(tokenizer, text: str, bos: bool = True, eos: bool = False):
258
+ t = tokenizer.encode(text, add_special_tokens=False)
259
+ bos_id = 0
260
+ eos_id = 1
261
+ if bos:
262
+ t = [bos_id] + t
263
+ if eos:
264
+ t = t + [eos_id]
265
+
266
+ return t
267
+
268
+ def load_pil_images(conversations: List[Dict[str, str]]) -> List[Image.Image]:
269
+ """
270
+
271
+ Args:
272
+ conversations (List[Dict[str, str]]): the conversations with a list of messages. An example is :
273
+ [
274
+ {
275
+ "role": "User",
276
+ "content": "<image_placeholder>\nExtract all information from this image and convert them into markdown format.",
277
+ "images": ["./examples/table_datasets.png"]
278
+ },
279
+ {"role": "Assistant", "content": ""},
280
+ ]
281
+
282
+ Returns:
283
+ pil_images (List[PIL.Image.Image]): the list of PIL images.
284
+
285
+ """
286
+
287
+ pil_images = []
288
+
289
+ for message in conversations:
290
+ if "images" not in message:
291
+ continue
292
+
293
+ for image_path in message["images"]:
294
+ # print('----------------')
295
+ # print(image_path)
296
+ # print('----------------')
297
+ # exit()
298
+
299
+ # pil_img = Image.open(image_path)
300
+ pil_img = load_image(image_path)
301
+ pil_img = pil_img.convert("RGB")
302
+ pil_images.append(pil_img)
303
+
304
+ return pil_images
305
+
306
+
307
+ class BaseTransform(ABC):
308
+
309
+ def set_rng(self, *args, **kwargs):
310
+ pass
311
+
312
+ def __call__(self, *args, **kwargs) -> torch.Tensor:
313
+ pass
314
+
315
+ @property
316
+ def default_shape(self):
317
+ raise NotImplementedError
318
+
319
+
320
+ class BasicImageTransform(BaseTransform):
321
+ def __init__(
322
+ self,
323
+ mean: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
324
+ std: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
325
+ normalize: bool = True
326
+ ):
327
+ self.mean = mean
328
+ self.std = std
329
+
330
+ transform_pipelines = [
331
+ transforms.ToTensor()
332
+ ]
333
+
334
+ normalize = normalize_transform(mean, std) if normalize else nn.Identity()
335
+ if normalize is not None:
336
+ transform_pipelines.append(normalize)
337
+
338
+ self.transform = transforms.Compose(transform_pipelines)
339
+
340
+ def __call__(self, x):
341
+ x = self.transform(x)
342
+ return x
343
+
344
+ class NoEOSTextStreamer(TextStreamer):
345
+ def on_finalized_text(self, text: str, stream_end: bool = False):
346
+
347
+ eos_text = self.tokenizer.decode([self.tokenizer.eos_token_id], skip_special_tokens=False)
348
+ text = text.replace(eos_text, "\n")
349
+ print(text, flush=True, end="")
350
+
351
+
352
+ class DeepseekOCR2Config(DeepseekV2Config):
353
+ model_type = "DeepseekOCR2"
354
+
355
+ class DeepseekOCR2Model(DeepseekV2Model):
356
+ config_class = DeepseekOCR2Config
357
+
358
+ def __init__(self, config: DeepseekV2Config):
359
+ super(DeepseekOCR2Model, self).__init__(config)
360
+
361
+ self.sam_model = build_sam_vit_b()
362
+ self.qwen2_model = build_qwen2_decoder_as_encoder()
363
+ # self.conv_2 = nn.Conv2d(in_channels=1024, out_channels=2048, kernel_size=2, stride=2)
364
+ n_embed = 1280
365
+ self.projector = MlpProjector(Dict(projector_type="linear", input_dim=896, n_embed=n_embed))
366
+ embed_std = 1 / torch.sqrt(torch.tensor(n_embed, dtype=torch.float32))
367
+ # self.image_newline = nn.Parameter(torch.randn(n_embed) * embed_std)
368
+ self.view_seperator = nn.Parameter(torch.randn(n_embed) * embed_std)
369
+ self.enable_text_query_residual = getattr(self.qwen2_model, 'enable_text_query_residual', False)
370
+
371
+ def _pool_text_context(
372
+ self,
373
+ inputs_embeds: torch.Tensor,
374
+ attention_mask: Optional[torch.Tensor] = None,
375
+ labels: Optional[torch.Tensor] = None,
376
+ images_seq_mask: Optional[torch.Tensor] = None,
377
+ ) -> torch.Tensor:
378
+ pooled_source = inputs_embeds.detach()
379
+ mask = torch.ones(pooled_source.shape[:2], dtype=torch.bool, device=pooled_source.device)
380
+ if attention_mask is not None:
381
+ mask = mask & attention_mask.bool()
382
+ if images_seq_mask is not None:
383
+ mask = mask & (~images_seq_mask.bool())
384
+
385
+ if labels is not None:
386
+ prompt_mask = mask & labels.eq(-100)
387
+ empty_prompt_rows = prompt_mask.sum(dim=1) == 0
388
+ if empty_prompt_rows.any():
389
+ prompt_mask[empty_prompt_rows] = mask[empty_prompt_rows]
390
+ mask = prompt_mask
391
+
392
+ weights = mask.unsqueeze(-1).to(pooled_source.dtype)
393
+ denom = weights.sum(dim=1).clamp_min(1.0)
394
+ return (pooled_source * weights).sum(dim=1) / denom
395
+
396
+
397
+
398
+ def forward(
399
+ self,
400
+ input_ids: torch.LongTensor = None,
401
+ attention_mask: Optional[torch.Tensor] = None,
402
+ position_ids: Optional[torch.LongTensor] = None,
403
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
404
+ inputs_embeds: Optional[torch.FloatTensor] = None,
405
+ use_cache: Optional[bool] = None,
406
+ output_attentions: Optional[bool] = None,
407
+ output_hidden_states: Optional[bool] = None,
408
+ images: Optional[torch.FloatTensor] = None,
409
+ images_seq_mask: Optional[torch.FloatTensor] = None,
410
+ images_spatial_crop: Optional[torch.FloatTensor] = None,
411
+ labels: Optional[torch.LongTensor] = None,
412
+ return_dict: Optional[bool] = None,
413
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
414
+
415
+
416
+
417
+
418
+ if inputs_embeds is None:
419
+ # inputs_embeds = self.embed_tokens(input_ids)
420
+ inputs_embeds = self.get_input_embeddings()(input_ids)
421
+
422
+
423
+
424
+ sam_model = getattr(self, 'sam_model', None)
425
+ # sam_model = self.sam_model
426
+ qwen2_model = getattr(self, 'qwen2_model', None)
427
+ text_context = None
428
+ if qwen2_model is not None and self.enable_text_query_residual:
429
+ text_context = self._pool_text_context(
430
+ inputs_embeds,
431
+ attention_mask=attention_mask,
432
+ labels=labels,
433
+ images_seq_mask=images_seq_mask)
434
+
435
+
436
+
437
+ if sam_model is not None and (input_ids.shape[1] != 1 or self.training) and torch.sum(images[0][1]).item() != 0:
438
+
439
+ idx = 0
440
+
441
+ # sam_model = torch.jit.script(sam_model)
442
+
443
+ # start_time = time.time()
444
+ for image, crop_shape in zip(images, images_spatial_crop):
445
+ images_in_this_batch = []
446
+
447
+ patches = image[0]
448
+ image_ori = image[1]
449
+ sample_text_context = text_context[idx:idx + 1] if text_context is not None else None
450
+
451
+ if torch.sum(patches).item() != 0:
452
+ # P, C, H, W = patches.shape
453
+ crop_flag = 1
454
+ with torch.no_grad():
455
+ local_features_1 = sam_model(patches)
456
+ global_features_1 = sam_model(image_ori)
457
+
458
+ local_text_context = (
459
+ sample_text_context.expand(local_features_1.shape[0], -1)
460
+ if sample_text_context is not None else None
461
+ )
462
+ global_text_context = (
463
+ sample_text_context.expand(global_features_1.shape[0], -1)
464
+ if sample_text_context is not None else None
465
+ )
466
+
467
+ local_features_2 = qwen2_model(local_features_1, text_context=local_text_context)
468
+ # vit_time = time.time()
469
+ local_features = local_features_2
470
+ local_features = self.projector(local_features)
471
+
472
+ global_features_2 = qwen2_model(global_features_1, text_context=global_text_context)
473
+ global_features = global_features_2
474
+ global_features = self.projector(global_features)
475
+
476
+ _, hw, n_dim = global_features.shape
477
+ # h = w = int(hw ** 0.5)
478
+
479
+ _2, hw2, n_dim2 = local_features.shape
480
+ # h2 = w2 = int(hw2 ** 0.5)
481
+
482
+ global_features = global_features.view(-1, n_dim)
483
+
484
+ local_features = local_features.view(-1, n_dim2)
485
+
486
+ global_local_features = torch.cat([local_features, global_features, self.view_seperator[None, :]], dim=0)
487
+
488
+ # end_time = time.time()
489
+
490
+ # print('sam: ', sam_time - start_time)
491
+ # print('vit: ', vit_time - sam_time)
492
+ # print('all: ', end_time - start_time)
493
+
494
+ # exit()
495
+
496
+ else:
497
+ with torch.no_grad():
498
+ global_features_1 = sam_model(image_ori)
499
+
500
+ global_text_context = (
501
+ sample_text_context.expand(global_features_1.shape[0], -1)
502
+ if sample_text_context is not None else None
503
+ )
504
+ global_features_2 = qwen2_model(global_features_1, text_context=global_text_context)
505
+ global_features = global_features_2
506
+ global_features = self.projector(global_features)
507
+ _, hw, n_dim = global_features.shape
508
+ # h = w = int(hw ** 0.5)
509
+
510
+ # global_features = global_features.view(h, w, n_dim)
511
+
512
+ # global_features = torch.cat(
513
+ # [global_features, self.image_newline[None, None, :].expand(h, 1, n_dim)], dim=1
514
+ # )
515
+
516
+ global_features = global_features.view(-1, n_dim)
517
+
518
+ global_local_features = torch.cat([global_features, self.view_seperator[None, :]], dim=0)
519
+
520
+ images_in_this_batch.append(global_local_features)
521
+
522
+
523
+ # print(inputs_embeds.shape)
524
+
525
+ if images_in_this_batch:
526
+ images_in_this_batch = torch.cat(images_in_this_batch, dim=0)
527
+ # exit()
528
+
529
+ inputs_embeds[idx].masked_scatter_(images_seq_mask[idx].unsqueeze(-1).cuda(), images_in_this_batch)
530
+
531
+ idx += 1
532
+
533
+
534
+ return super(DeepseekOCR2Model, self).forward(
535
+ input_ids=None, attention_mask=attention_mask, past_key_values=past_key_values,
536
+ inputs_embeds=inputs_embeds, use_cache=use_cache, position_ids = position_ids,
537
+ output_attentions=output_attentions, output_hidden_states=output_hidden_states,
538
+ return_dict=return_dict
539
+ )
540
+
541
+
542
+ class DeepseekOCR2ForCausalLM(DeepseekV2ForCausalLM):
543
+
544
+ config_class = DeepseekOCR2Config
545
+ # supports_gradient_checkpointing = True
546
+
547
+ def __init__(self, config):
548
+ super(DeepseekV2ForCausalLM, self).__init__(config)
549
+ self.model = DeepseekOCR2Model(config)
550
+
551
+ self.vocab_size = config.vocab_size
552
+
553
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
554
+
555
+ # self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
556
+
557
+ # Initialize weights and apply final processing
558
+ self.post_init()
559
+
560
+ def get_model(self):
561
+ return self.model
562
+
563
+
564
+ def forward(
565
+ self,
566
+ input_ids: torch.LongTensor = None,
567
+ attention_mask: Optional[torch.Tensor] = None,
568
+ position_ids: Optional[torch.LongTensor] = None,
569
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
570
+ inputs_embeds: Optional[torch.FloatTensor] = None,
571
+ labels: Optional[torch.LongTensor] = None,
572
+ use_cache: Optional[bool] = None,
573
+ output_attentions: Optional[bool] = None,
574
+ output_hidden_states: Optional[bool] = None,
575
+ images: Optional[torch.FloatTensor] = None,
576
+ images_seq_mask: Optional[torch.FloatTensor] = None,
577
+ images_spatial_crop: Optional[torch.FloatTensor] = None,
578
+ return_dict: Optional[bool] = None,
579
+
580
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
581
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
582
+ output_hidden_states = (
583
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
584
+ )
585
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
586
+
587
+
588
+
589
+ outputs = self.model(
590
+ input_ids=input_ids,
591
+ past_key_values=past_key_values,
592
+ attention_mask=attention_mask,
593
+ position_ids=position_ids,
594
+ inputs_embeds=inputs_embeds,
595
+ use_cache=use_cache,
596
+ output_attentions=output_attentions,
597
+ output_hidden_states=output_hidden_states,
598
+ images=images,
599
+ images_seq_mask = images_seq_mask,
600
+ images_spatial_crop = images_spatial_crop,
601
+ labels=labels,
602
+ return_dict=return_dict
603
+
604
+ )
605
+
606
+
607
+
608
+ # print(transformer_outputs)
609
+
610
+ hidden_states = outputs[0]
611
+ logits = self.lm_head(hidden_states)
612
+ logits = logits.float()
613
+
614
+ # logits
615
+
616
+ loss = None
617
+ if labels is not None:
618
+ # Shift so that tokens < n predict n
619
+ shift_logits = logits[..., :-1, :].contiguous()
620
+ shift_labels = labels[..., 1:].contiguous()
621
+ # Flatten the tokens
622
+ loss_fct = CrossEntropyLoss()
623
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
624
+ shift_labels = shift_labels.view(-1)
625
+ # Enable model parallelism
626
+ shift_labels = shift_labels.to(shift_logits.device)
627
+ loss = loss_fct(shift_logits, shift_labels)
628
+
629
+ if not return_dict:
630
+ output = (logits,) + outputs[1:]
631
+ return (loss,) + output if loss is not None else output
632
+
633
+ return CausalLMOutputWithPast(
634
+ loss=loss,
635
+ logits=logits,
636
+ past_key_values=outputs.past_key_values,
637
+ hidden_states=outputs.hidden_states,
638
+ attentions=outputs.attentions,
639
+ )
640
+
641
+
642
+ def prepare_inputs_for_generation(
643
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
644
+ ):
645
+ # Omit tokens covered by past_key_values
646
+ past_length = 0
647
+ if past_key_values is not None:
648
+ if isinstance(past_key_values, Cache):
649
+ cache_length = past_key_values.get_seq_length()
650
+ past_length = past_key_values.seen_tokens
651
+ max_cache_length = past_key_values.get_max_length()
652
+ else:
653
+ cache_length = past_length = past_key_values[0][0].shape[2]
654
+ max_cache_length = None
655
+
656
+ # Keep only the unprocessed tokens:
657
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
658
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
659
+ # input)
660
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
661
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
662
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
663
+ # input_ids based on the past_length.
664
+ elif past_length < input_ids.shape[1]:
665
+ input_ids = input_ids[:, past_length:]
666
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
667
+
668
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
669
+ if (
670
+ max_cache_length is not None
671
+ and attention_mask is not None
672
+ and cache_length + input_ids.shape[1] > max_cache_length
673
+ ):
674
+ attention_mask = attention_mask[:, -max_cache_length:]
675
+
676
+ position_ids = kwargs.get("position_ids", None)
677
+ if attention_mask is not None and position_ids is None:
678
+ # create position_ids on the fly for batch generation
679
+ position_ids = attention_mask.long().cumsum(-1) - 1
680
+ position_ids.masked_fill_(attention_mask == 0, 1)
681
+ if past_key_values:
682
+ position_ids = position_ids[:, -input_ids.shape[1] :]
683
+
684
+ # if self.generation_config.cache_implementation == "static":
685
+ # # generation with static cache
686
+ # cache_position = kwargs.get("cache_position", None)
687
+ # if cache_position is None:
688
+ # past_length = 0
689
+ # else:
690
+ # past_length = cache_position[-1] + 1
691
+ # input_ids = input_ids[:, past_length:]
692
+ # position_ids = position_ids[:, past_length:]
693
+
694
+ # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
695
+ # same goes for position ids. Could also help with continued generation.
696
+ cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
697
+
698
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
699
+ if inputs_embeds is not None and past_key_values is None:
700
+ model_inputs = {"inputs_embeds": inputs_embeds}
701
+ else:
702
+ model_inputs = {"input_ids": input_ids}
703
+
704
+ model_inputs.update(
705
+ {
706
+ "position_ids": position_ids,
707
+ "past_key_values": past_key_values,
708
+ "use_cache": kwargs.get("use_cache"),
709
+ "attention_mask": attention_mask,
710
+ "images": kwargs.get("images", None),
711
+ "images_seq_mask": kwargs.get("images_seq_mask", None),
712
+ "images_spatial_crop": kwargs.get("images_spatial_crop", None),
713
+ }
714
+ )
715
+ return model_inputs
716
+
717
+
718
+ def disable_torch_init(self):
719
+ """
720
+ Disable the redundant torch default initialization to accelerate model creation.
721
+ """
722
+ import torch
723
+ setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
724
+ setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
725
+
726
+
727
+
728
+ def infer(self, tokenizer, prompt='', image_file='', output_path = '', base_size=1024, image_size=640, crop_mode=True, test_compress=False, save_results=False, eval_mode=False):
729
+ self.disable_torch_init()
730
+
731
+ os.makedirs(output_path, exist_ok=True)
732
+ os.makedirs(f'{output_path}/images', exist_ok=True)
733
+
734
+ if prompt and image_file:
735
+ conversation = [
736
+ {
737
+ "role": "<|User|>",
738
+ # "content": "<image>\n<|grounding|>Given the layout of the image. ",
739
+ "content": f'{prompt}',
740
+ # "content": "君不见黄河之水天上来的下一句是什么?",
741
+ # "content": "<image>\nFree OCR. ",
742
+ # "content": "<image>\nParse the figure. ",
743
+ # "content": "<image>\nExtract the text in the image. ",
744
+ "images": [f'{image_file}'],
745
+ },
746
+ {"role": "<|Assistant|>", "content": ""},
747
+ ]
748
+
749
+ elif prompt:
750
+ conversation = [
751
+ {
752
+ "role": "<|User|>",
753
+ # "content": "<image>\n<|grounding|>Given the layout of the image. ",
754
+ "content": f'{prompt}',
755
+ # "content": "君不见黄河之水天上来的下一句是什么?",
756
+ # "content": "<image>\nFree OCR. ",
757
+ # "content": "<image>\nParse the figure. ",
758
+ # "content": "<image>\nExtract the text in the image. ",
759
+ # "images": [f'{image_file}'],
760
+ },
761
+ {"role": "<|Assistant|>", "content": ""},
762
+ ]
763
+ else:
764
+ assert False, f'prompt is none!'
765
+
766
+ prompt = format_messages(conversations=conversation, sft_format='plain', system_prompt='')
767
+
768
+ patch_size = 16
769
+ downsample_ratio = 4
770
+ images = load_pil_images(conversation)
771
+
772
+ valid_img_tokens = 0
773
+ ratio = 1
774
+
775
+ image_draw = images[0].copy()
776
+
777
+ w,h = image_draw.size
778
+ # print(w, h)
779
+ ratio = 1 - ((max(w, h) - min(w, h)) / (max(w, h)))
780
+
781
+
782
+ image_transform=BasicImageTransform(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), normalize=True)
783
+ images_seq_mask = []
784
+
785
+ image_token = '<image>'
786
+ image_token_id = 128815
787
+ text_splits = prompt.split(image_token)
788
+
789
+ images_list, images_crop_list, images_seq_mask = [], [], []
790
+ tokenized_str = []
791
+ images_spatial_crop = []
792
+ for text_sep, image in zip(text_splits, images):
793
+
794
+ tokenized_sep = text_encode(tokenizer, text_sep, bos=False, eos=False)
795
+ tokenized_str += tokenized_sep
796
+ images_seq_mask += [False] * len(tokenized_sep)
797
+
798
+ if crop_mode:
799
+
800
+ if image.size[0] <= 768 and image.size[1] <= 768:
801
+ crop_ratio = [1, 1]
802
+
803
+ else:
804
+ if crop_mode:
805
+ # best_width, best_height = select_best_resolution(image.size, self.candidate_resolutions)
806
+ images_crop_raw, crop_ratio = dynamic_preprocess(image)
807
+ else:
808
+ # best_width, best_height = self.image_size, self.image_size
809
+ crop_ratio = [1, 1]
810
+
811
+ """process the global view"""
812
+ # image = image.resize((base_size, base_size))
813
+ global_view = ImageOps.pad(image, (base_size, base_size),
814
+ color=tuple(int(x * 255) for x in image_transform.mean))
815
+
816
+ if base_size == 1024:
817
+ valid_img_tokens += int(256 * ratio)
818
+ elif base_size == 1280:
819
+ valid_img_tokens += int(400 * ratio)
820
+ # elif base_size == 640:
821
+ # valid_img_tokens += int(100 * ratio)
822
+
823
+
824
+
825
+
826
+
827
+ images_list.append(image_transform(global_view).to(torch.bfloat16))
828
+
829
+ # global_view_tensor = image_transform(global_view).to(torch.bfloat16)
830
+
831
+ width_crop_num, height_crop_num = crop_ratio
832
+
833
+ images_spatial_crop.append([width_crop_num, height_crop_num])
834
+
835
+
836
+ if width_crop_num > 1 or height_crop_num > 1:
837
+ """process the local views"""
838
+
839
+ for i in range(len(images_crop_raw)):
840
+ images_crop_list.append(image_transform(images_crop_raw[i]).to(torch.bfloat16))
841
+
842
+ if image_size == 768:
843
+ valid_img_tokens += len(images_crop_list) * 144
844
+
845
+ num_queries = math.ceil((image_size // patch_size) / downsample_ratio)
846
+ num_queries_base = math.ceil((base_size // patch_size) / downsample_ratio)
847
+
848
+
849
+
850
+ """add image tokens"""
851
+
852
+
853
+
854
+ tokenized_image = ([image_token_id] * num_queries_base) * num_queries_base
855
+ tokenized_image += [image_token_id]
856
+ if width_crop_num > 1 or height_crop_num > 1:
857
+ tokenized_image += ([image_token_id] * (num_queries * width_crop_num)) * (
858
+ num_queries * height_crop_num)
859
+ tokenized_str += tokenized_image
860
+ images_seq_mask += [True] * len(tokenized_image)
861
+ # num_image_tokens.append(len(tokenized_image))
862
+
863
+ else:
864
+ # best_width, best_height = self.image_size, self.image_size
865
+ # print(image.size, (best_width, best_height)) # check the select_best_resolutions func
866
+
867
+ """process the global view"""
868
+ if image_size <= 768:
869
+ print('directly resize')
870
+ image = image.resize((image_size, image_size))
871
+ # else:
872
+ global_view = ImageOps.pad(image, (image_size, image_size),
873
+ color=tuple(int(x * 255) for x in image_transform.mean))
874
+ images_list.append(image_transform(global_view).to(torch.bfloat16))
875
+
876
+ if base_size == 1024:
877
+ valid_img_tokens += int(256 * ratio)
878
+ elif base_size == 1280:
879
+ valid_img_tokens += int(400 * ratio)
880
+ elif base_size == 640:
881
+ valid_img_tokens += int(100 * 1)
882
+ elif base_size == 512:
883
+ valid_img_tokens += int(64 * 1)
884
+ elif base_size == 768:
885
+ valid_img_tokens += int(144 * 1)
886
+
887
+ width_crop_num, height_crop_num = 1, 1
888
+
889
+ images_spatial_crop.append([width_crop_num, height_crop_num])
890
+
891
+
892
+ """add image tokens"""
893
+ num_queries = math.ceil((image_size // patch_size) / downsample_ratio)
894
+
895
+ tokenized_image = ([image_token_id] * num_queries) * num_queries
896
+ tokenized_image += [image_token_id]
897
+ # tokenized_image += ([self.image_token_id] * (num_queries * width_crop_num) + [self.image_token_id]) * (
898
+ # num_queries * height_crop_num)
899
+ tokenized_str += tokenized_image
900
+ images_seq_mask += [True] * len(tokenized_image)
901
+ # num_image_tokens.append(len(tokenized_image))
902
+
903
+
904
+ """process the last text split"""
905
+ tokenized_sep = text_encode(tokenizer, text_splits[-1], bos=False, eos=False)
906
+ tokenized_str += tokenized_sep
907
+ images_seq_mask += [False] * len(tokenized_sep)
908
+
909
+ """add the bos tokens"""
910
+ bos_id = 0
911
+ tokenized_str = [bos_id] + tokenized_str
912
+ images_seq_mask = [False] + images_seq_mask
913
+
914
+
915
+
916
+ input_ids = torch.LongTensor(tokenized_str)
917
+
918
+
919
+
920
+
921
+ images_seq_mask = torch.tensor(images_seq_mask, dtype=torch.bool)
922
+
923
+
924
+ if len(images_list) == 0:
925
+ images_ori = torch.zeros((1, 3, image_size, image_size))
926
+ images_spatial_crop = torch.zeros((1, 2), dtype=torch.long)
927
+ images_crop = torch.zeros((1, 3, base_size, base_size))
928
+
929
+ else:
930
+ images_ori = torch.stack(images_list, dim=0)
931
+ images_spatial_crop = torch.tensor(images_spatial_crop, dtype=torch.long)
932
+ if images_crop_list:
933
+ images_crop = torch.stack(images_crop_list, dim=0)
934
+ else:
935
+ images_crop = torch.zeros((1, 3, base_size, base_size))
936
+
937
+
938
+
939
+ if not eval_mode:
940
+ streamer = NoEOSTextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=False)
941
+ with torch.autocast("cuda", dtype=torch.bfloat16):
942
+ with torch.no_grad():
943
+ output_ids = self.generate(
944
+ input_ids.unsqueeze(0).cuda(),
945
+ images=[(images_crop.cuda(), images_ori.cuda())],
946
+ images_seq_mask = images_seq_mask.unsqueeze(0).cuda(),
947
+ images_spatial_crop = images_spatial_crop,
948
+ # do_sample=False,
949
+ # num_beams = 1,
950
+ temperature=0.0,
951
+ eos_token_id=tokenizer.eos_token_id,
952
+ streamer=streamer,
953
+ max_new_tokens=8192,
954
+ no_repeat_ngram_size = 20,
955
+ use_cache = True
956
+ )
957
+
958
+ else:
959
+ with torch.autocast("cuda", dtype=torch.bfloat16):
960
+ with torch.no_grad():
961
+ output_ids = self.generate(
962
+ input_ids.unsqueeze(0).cuda(),
963
+ images=[(images_crop.cuda(), images_ori.cuda())],
964
+ images_seq_mask = images_seq_mask.unsqueeze(0).cuda(),
965
+ images_spatial_crop = images_spatial_crop,
966
+ # do_sample=False,
967
+ # num_beams = 1,
968
+ temperature=0.0,
969
+ eos_token_id=tokenizer.eos_token_id,
970
+ max_new_tokens=8192,
971
+ no_repeat_ngram_size = 35,
972
+ use_cache = True
973
+ )
974
+
975
+
976
+ if '<image>' in conversation[0]['content'] and eval_mode:
977
+ outputs = tokenizer.decode(output_ids[0, input_ids.unsqueeze(0).cuda().shape[1]:])
978
+ stop_str = '<|end▁of▁sentence|>'
979
+ if outputs.endswith(stop_str):
980
+ outputs = outputs[:-len(stop_str)]
981
+ # re_match
982
+ outputs = outputs.strip()
983
+
984
+ return outputs
985
+
986
+ if '<image>' in conversation[0]['content'] and test_compress:
987
+ outputs = tokenizer.decode(output_ids[0, input_ids.unsqueeze(0).cuda().shape[1]:])
988
+ pure_texts_outputs_token_length = len(text_encode(tokenizer, outputs, bos=False, eos=False))
989
+ print('='*50)
990
+ print('image size: ', (w, h))
991
+ print('valid image tokens: ', int(valid_img_tokens))
992
+ print('output texts tokens (valid): ', pure_texts_outputs_token_length)
993
+ print('compression ratio: ', round(pure_texts_outputs_token_length/valid_img_tokens, 2))
994
+ print('='*50)
995
+
996
+
997
+ if '<image>' in conversation[0]['content'] and save_results:
998
+ outputs = tokenizer.decode(output_ids[0, input_ids.unsqueeze(0).cuda().shape[1]:])
999
+ stop_str = '<|end▁of▁sentence|>'
1000
+
1001
+ print('='*15 + 'save results:' + '='*15)
1002
+
1003
+ # # # # conv.messages[-1][-1] = outputs
1004
+ if outputs.endswith(stop_str):
1005
+ outputs = outputs[:-len(stop_str)]
1006
+ outputs = outputs.strip()
1007
+
1008
+ matches_ref, matches_images, mathes_other = re_match(outputs)
1009
+ # print(matches_ref)
1010
+ result = process_image_with_refs(image_draw, matches_ref, output_path)
1011
+
1012
+
1013
+ for idx, a_match_image in enumerate(tqdm(matches_images, desc="image")):
1014
+ outputs = outputs.replace(a_match_image, '![](images/' + str(idx) + '.jpg)\n')
1015
+
1016
+ for idx, a_match_other in enumerate(tqdm(mathes_other, desc="other")):
1017
+ outputs = outputs.replace(a_match_other, '').replace('\\coloneqq', ':=').replace('\\eqqcolon', '=:')
1018
+
1019
+
1020
+ # if 'structural formula' in conversation[0]['content']:
1021
+ # outputs = '<smiles>' + outputs + '</smiles>'
1022
+ with open(f'{output_path}/result.mmd', 'w', encoding = 'utf-8') as afile:
1023
+ afile.write(outputs)
1024
+
1025
+ if 'line_type' in outputs:
1026
+ import matplotlib.pyplot as plt
1027
+ lines = eval(outputs)['Line']['line']
1028
+
1029
+ line_type = eval(outputs)['Line']['line_type']
1030
+ # print(lines)
1031
+
1032
+ endpoints = eval(outputs)['Line']['line_endpoint']
1033
+
1034
+ fig, ax = plt.subplots(figsize=(3,3), dpi=200)
1035
+ ax.set_xlim(-15, 15)
1036
+ ax.set_ylim(-15, 15)
1037
+
1038
+ for idx, line in enumerate(lines):
1039
+ try:
1040
+ p0 = eval(line.split(' -- ')[0])
1041
+ p1 = eval(line.split(' -- ')[-1])
1042
+
1043
+ if line_type[idx] == '--':
1044
+ ax.plot([p0[0], p1[0]], [p0[1], p1[1]], linewidth=0.8, color='k')
1045
+ else:
1046
+ ax.plot([p0[0], p1[0]], [p0[1], p1[1]], linewidth = 0.8, color = 'k')
1047
+
1048
+ ax.scatter(p0[0], p0[1], s=5, color = 'k')
1049
+ ax.scatter(p1[0], p1[1], s=5, color = 'k')
1050
+ except:
1051
+ pass
1052
+
1053
+ for endpoint in endpoints:
1054
+
1055
+ label = endpoint.split(': ')[0]
1056
+ (x, y) = eval(endpoint.split(': ')[1])
1057
+ ax.annotate(label, (x, y), xytext=(1, 1), textcoords='offset points',
1058
+ fontsize=5, fontweight='light')
1059
+
1060
+
1061
+ plt.savefig(f'{output_path}/geo.jpg')
1062
+ plt.close()
1063
+
1064
+ result.save(f"{output_path}/result_with_boxes.jpg")
modeling_deepseekv2.py ADDED
@@ -0,0 +1,1992 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch DeepSeek model and compatible with both DeepSeekV2 and DeepSeekV3"""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+ import numpy as np
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ import torch.distributed as dist
30
+ from einops import repeat
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.cache_utils import Cache, DynamicCache
36
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
37
+ from transformers.models.llama.modeling_llama import (
38
+ LlamaAttention,
39
+ LlamaFlashAttention2
40
+ )
41
+ from transformers.modeling_outputs import (
42
+ BaseModelOutputWithPast,
43
+ CausalLMOutputWithPast,
44
+ SequenceClassifierOutputWithPast,
45
+ )
46
+ from transformers.modeling_utils import PreTrainedModel
47
+ from transformers.pytorch_utils import (
48
+ ALL_LAYERNORM_LAYERS,
49
+ is_torch_greater_or_equal_than_1_13,
50
+ )
51
+ from transformers.utils import (
52
+ add_start_docstrings,
53
+ add_start_docstrings_to_model_forward,
54
+ is_flash_attn_2_available,
55
+ is_flash_attn_greater_or_equal_2_10,
56
+ logging,
57
+ replace_return_docstrings,
58
+ )
59
+ from transformers.utils.import_utils import is_torch_fx_available
60
+
61
+ from .configuration_deepseek_v2 import DeepseekV2Config
62
+
63
+ if is_flash_attn_2_available():
64
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
65
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
66
+
67
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
68
+ # It means that the function will not be traced through and simply appear as a node in the graph.
69
+ if is_torch_fx_available():
70
+ if not is_torch_greater_or_equal_than_1_13:
71
+ import torch.fx
72
+
73
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
74
+
75
+ logger = logging.get_logger(__name__)
76
+
77
+ _CONFIG_FOR_DOC = "DeepseekV2Config"
78
+
79
+
80
+ def _get_unpad_data(attention_mask):
81
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
82
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
83
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
84
+ cu_seqlens = F.pad(
85
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
86
+ )
87
+ return (
88
+ indices,
89
+ cu_seqlens,
90
+ max_seqlen_in_batch,
91
+ )
92
+
93
+
94
+ class DeepseekV2RMSNorm(nn.Module):
95
+ def __init__(self, hidden_size, eps=1e-6):
96
+ """
97
+ DeepseekV2RMSNorm is equivalent to T5LayerNorm
98
+ """
99
+ super().__init__()
100
+ self.weight = nn.Parameter(torch.ones(hidden_size))
101
+ self.variance_epsilon = eps
102
+
103
+ def forward(self, hidden_states):
104
+ input_dtype = hidden_states.dtype
105
+ hidden_states = hidden_states.to(torch.float32)
106
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
107
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
108
+ return self.weight * hidden_states.to(input_dtype)
109
+
110
+
111
+ ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
112
+
113
+
114
+
115
+
116
+ class DeepseekV2RotaryEmbedding(nn.Module):
117
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
118
+ super().__init__()
119
+
120
+ self.dim = dim
121
+ self.max_position_embeddings = max_position_embeddings
122
+ self.base = base
123
+ inv_freq = 1.0 / (
124
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
125
+ )
126
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
127
+
128
+ # Build here to make `torch.jit.trace` work.
129
+ self._set_cos_sin_cache(
130
+ seq_len=max_position_embeddings,
131
+ device=self.inv_freq.device,
132
+ dtype=torch.get_default_dtype(),
133
+ )
134
+ self.max_seq_len_cached = None
135
+
136
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
137
+ self.max_seq_len_cached = seq_len
138
+ t = torch.arange(
139
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
140
+ )
141
+
142
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
143
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
144
+ emb = torch.cat((freqs, freqs), dim=-1)
145
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
146
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
147
+
148
+ def forward(self, x, seq_len=None):
149
+ # x: [bs, num_attention_heads, seq_len, head_size]
150
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
151
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
152
+
153
+ return (
154
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
155
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
156
+ )
157
+
158
+
159
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2
160
+ class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
161
+ """DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
162
+
163
+ def __init__(
164
+ self,
165
+ dim,
166
+ max_position_embeddings=2048,
167
+ base=10000,
168
+ device=None,
169
+ scaling_factor=1.0,
170
+ ):
171
+ self.scaling_factor = scaling_factor
172
+ super().__init__(dim, max_position_embeddings, base, device)
173
+
174
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
175
+ self.max_seq_len_cached = seq_len
176
+ t = torch.arange(
177
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
178
+ )
179
+ t = t / self.scaling_factor
180
+
181
+ freqs = torch.outer(t, self.inv_freq)
182
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
183
+ emb = torch.cat((freqs, freqs), dim=-1)
184
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
185
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
186
+
187
+
188
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2
189
+ class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding):
190
+ """DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
191
+
192
+ def __init__(
193
+ self,
194
+ dim,
195
+ max_position_embeddings=2048,
196
+ base=10000,
197
+ device=None,
198
+ scaling_factor=1.0,
199
+ ):
200
+ self.scaling_factor = scaling_factor
201
+ super().__init__(dim, max_position_embeddings, base, device)
202
+
203
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
204
+ self.max_seq_len_cached = seq_len
205
+
206
+ if seq_len > self.max_position_embeddings:
207
+ base = self.base * (
208
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
209
+ - (self.scaling_factor - 1)
210
+ ) ** (self.dim / (self.dim - 2))
211
+ inv_freq = 1.0 / (
212
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
213
+ )
214
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
215
+
216
+ t = torch.arange(
217
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
218
+ )
219
+
220
+ freqs = torch.outer(t, self.inv_freq)
221
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
222
+ emb = torch.cat((freqs, freqs), dim=-1)
223
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
224
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
225
+
226
+
227
+ # Inverse dim formula to find dim based on number of rotations
228
+ def yarn_find_correction_dim(
229
+ num_rotations, dim, base=10000, max_position_embeddings=2048
230
+ ):
231
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
232
+ 2 * math.log(base)
233
+ )
234
+
235
+
236
+ # Find dim range bounds based on rotations
237
+ def yarn_find_correction_range(
238
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
239
+ ):
240
+ low = math.floor(
241
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
242
+ )
243
+ high = math.ceil(
244
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
245
+ )
246
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
247
+
248
+
249
+ def yarn_get_mscale(scale=1, mscale=1):
250
+ if scale <= 1:
251
+ return 1.0
252
+ return 0.1 * mscale * math.log(scale) + 1.0
253
+
254
+
255
+ def yarn_linear_ramp_mask(min, max, dim):
256
+ if min == max:
257
+ max += 0.001 # Prevent singularity
258
+
259
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
260
+ ramp_func = torch.clamp(linear_func, 0, 1)
261
+ return ramp_func
262
+
263
+
264
+ class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
265
+
266
+ def __init__(
267
+ self,
268
+ dim,
269
+ max_position_embeddings=2048,
270
+ base=10000,
271
+ device=None,
272
+ scaling_factor=1.0,
273
+ original_max_position_embeddings=4096,
274
+ beta_fast=32,
275
+ beta_slow=1,
276
+ mscale=1,
277
+ mscale_all_dim=0,
278
+ ):
279
+ self.scaling_factor = scaling_factor
280
+ self.original_max_position_embeddings = original_max_position_embeddings
281
+ self.beta_fast = beta_fast
282
+ self.beta_slow = beta_slow
283
+ self.mscale = mscale
284
+ self.mscale_all_dim = mscale_all_dim
285
+ super().__init__(dim, max_position_embeddings, base, device)
286
+
287
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
288
+ self.max_seq_len_cached = seq_len
289
+ dim = self.dim
290
+
291
+ freq_extra = 1.0 / (
292
+ self.base
293
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
294
+ )
295
+ freq_inter = 1.0 / (
296
+ self.scaling_factor
297
+ * self.base
298
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
299
+ )
300
+
301
+ low, high = yarn_find_correction_range(
302
+ self.beta_fast,
303
+ self.beta_slow,
304
+ dim,
305
+ self.base,
306
+ self.original_max_position_embeddings,
307
+ )
308
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
309
+ device=device, dtype=torch.float32
310
+ )
311
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
312
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
313
+
314
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
315
+
316
+ freqs = torch.outer(t, inv_freq)
317
+
318
+ _mscale = float(
319
+ yarn_get_mscale(self.scaling_factor, self.mscale)
320
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
321
+ )
322
+
323
+ emb = torch.cat((freqs, freqs), dim=-1)
324
+ self.register_buffer(
325
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
326
+ )
327
+ self.register_buffer(
328
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
329
+ )
330
+
331
+
332
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
333
+ def rotate_half(x):
334
+ """Rotates half the hidden dims of the input."""
335
+ x1 = x[..., : x.shape[-1] // 2]
336
+ x2 = x[..., x.shape[-1] // 2 :]
337
+ return torch.cat((-x2, x1), dim=-1)
338
+
339
+
340
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
341
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
342
+ """Applies Rotary Position Embedding to the query and key tensors.
343
+
344
+ Args:
345
+ q (`torch.Tensor`): The query tensor.
346
+ k (`torch.Tensor`): The key tensor.
347
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
348
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
349
+ position_ids (`torch.Tensor`):
350
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
351
+ used to pass offsetted position ids when working with a KV-cache.
352
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
353
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
354
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
355
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
356
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
357
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
358
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
359
+ Returns:
360
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
361
+ """
362
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
363
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
364
+
365
+
366
+ # print()
367
+
368
+ b, h, s, d = q.shape
369
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
370
+
371
+ b, h, s, d = k.shape
372
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
373
+
374
+ q_embed = (q * cos) + (rotate_half(q) * sin)
375
+ k_embed = (k * cos) + (rotate_half(k) * sin)
376
+
377
+
378
+ return q_embed, k_embed
379
+
380
+
381
+ class DeepseekV2MLP(nn.Module):
382
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
383
+ super().__init__()
384
+ self.config = config
385
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
386
+ self.intermediate_size = (
387
+ config.intermediate_size if intermediate_size is None else intermediate_size
388
+ )
389
+
390
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
391
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
392
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
393
+ self.act_fn = ACT2FN[config.hidden_act]
394
+
395
+ def forward(self, x):
396
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
397
+ return down_proj
398
+
399
+
400
+ class MoEGate(nn.Module):
401
+ def __init__(self, config):
402
+ super().__init__()
403
+ self.config = config
404
+ self.top_k = config.num_experts_per_tok
405
+ self.n_routed_experts = config.n_routed_experts
406
+ self.routed_scaling_factor = config.routed_scaling_factor
407
+ self.scoring_func = config.scoring_func
408
+ self.alpha = config.aux_loss_alpha
409
+ self.seq_aux = config.seq_aux
410
+ self.topk_method = config.topk_method
411
+ self.n_group = config.n_group
412
+ self.topk_group = config.topk_group
413
+
414
+ # topk selection algorithm
415
+ self.norm_topk_prob = config.norm_topk_prob
416
+ self.gating_dim = config.hidden_size
417
+ self.weight = nn.Parameter(
418
+ torch.empty((self.n_routed_experts, self.gating_dim))
419
+ )
420
+ if self.topk_method == "noaux_tc":
421
+ self.e_score_correction_bias = nn.Parameter(
422
+ torch.empty((self.n_routed_experts))
423
+ )
424
+ self.reset_parameters()
425
+
426
+ def reset_parameters(self) -> None:
427
+ import torch.nn.init as init
428
+
429
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
430
+
431
+ def forward(self, hidden_states):
432
+ bsz, seq_len, h = hidden_states.shape
433
+ ### compute gating score
434
+ hidden_states = hidden_states.view(-1, h)
435
+ logits = F.linear(
436
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
437
+ )
438
+ if self.scoring_func == "softmax":
439
+ scores = logits.softmax(dim=-1, dtype=torch.float32)
440
+ elif self.scoring_func == "sigmoid":
441
+ scores = logits.sigmoid()
442
+ else:
443
+ raise NotImplementedError(
444
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
445
+ )
446
+
447
+ ### select top-k experts
448
+ if self.topk_method == "greedy":
449
+ topk_weight, topk_idx = torch.topk(
450
+ scores, k=self.top_k, dim=-1, sorted=False
451
+ )
452
+ elif self.topk_method == "group_limited_greedy":
453
+ group_scores = (
454
+ scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values
455
+ ) # [n, n_group]
456
+ group_idx = torch.topk(
457
+ group_scores, k=self.topk_group, dim=-1, sorted=False
458
+ )[
459
+ 1
460
+ ] # [n, top_k_group]
461
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
462
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
463
+ score_mask = (
464
+ group_mask.unsqueeze(-1)
465
+ .expand(
466
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
467
+ )
468
+ .reshape(bsz * seq_len, -1)
469
+ ) # [n, e]
470
+ tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e]
471
+ topk_weight, topk_idx = torch.topk(
472
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
473
+ )
474
+ elif self.topk_method == "noaux_tc":
475
+ assert not self.training
476
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
477
+ group_scores = (
478
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
479
+ ) # [n, n_group]
480
+ group_idx = torch.topk(
481
+ group_scores, k=self.topk_group, dim=-1, sorted=False
482
+ )[
483
+ 1
484
+ ] # [n, top_k_group]
485
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
486
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
487
+ score_mask = (
488
+ group_mask.unsqueeze(-1)
489
+ .expand(
490
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
491
+ )
492
+ .reshape(bsz * seq_len, -1)
493
+ ) # [n, e]
494
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
495
+ _, topk_idx = torch.topk(
496
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
497
+ )
498
+ topk_weight = scores.gather(1, topk_idx)
499
+
500
+ ### norm gate to sum 1
501
+ if self.top_k > 1 and self.norm_topk_prob:
502
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
503
+ topk_weight = topk_weight / denominator * self.routed_scaling_factor
504
+ else:
505
+ topk_weight = topk_weight * self.routed_scaling_factor
506
+ ### expert-level computation auxiliary loss
507
+ if self.training and self.alpha > 0.0:
508
+ scores_for_aux = scores
509
+ aux_topk = self.top_k
510
+ # always compute aux loss based on the naive greedy topk method
511
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
512
+ if self.seq_aux:
513
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
514
+ ce = torch.zeros(
515
+ bsz, self.n_routed_experts, device=hidden_states.device
516
+ )
517
+ ce.scatter_add_(
518
+ 1,
519
+ topk_idx_for_aux_loss,
520
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device),
521
+ ).div_(seq_len * aux_topk / self.n_routed_experts)
522
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(
523
+ dim=1
524
+ ).mean() * self.alpha
525
+ else:
526
+ mask_ce = F.one_hot(
527
+ topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts
528
+ )
529
+ ce = mask_ce.float().mean(0)
530
+ Pi = scores_for_aux.mean(0)
531
+ fi = ce * self.n_routed_experts
532
+ aux_loss = (Pi * fi).sum() * self.alpha
533
+ else:
534
+ aux_loss = None
535
+ return topk_idx, topk_weight, aux_loss
536
+
537
+
538
+ class AddAuxiliaryLoss(torch.autograd.Function):
539
+ """
540
+ The trick function of adding auxiliary (aux) loss,
541
+ which includes the gradient of the aux loss during backpropagation.
542
+ """
543
+
544
+ @staticmethod
545
+ def forward(ctx, x, loss):
546
+ assert loss.numel() == 1
547
+ ctx.dtype = loss.dtype
548
+ ctx.required_aux_loss = loss.requires_grad
549
+ return x
550
+
551
+ @staticmethod
552
+ def backward(ctx, grad_output):
553
+ grad_loss = None
554
+ if ctx.required_aux_loss:
555
+ grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
556
+ return grad_output, grad_loss
557
+
558
+
559
+ class DeepseekV2MoE(nn.Module):
560
+ """
561
+ A mixed expert module containing shared experts.
562
+ """
563
+
564
+ def __init__(self, config):
565
+ super().__init__()
566
+ self.config = config
567
+ self.num_experts_per_tok = config.num_experts_per_tok
568
+
569
+ if hasattr(config, "ep_size") and config.ep_size > 1:
570
+ assert config.ep_size == dist.get_world_size()
571
+ self.ep_size = config.ep_size
572
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
573
+ self.ep_rank = dist.get_rank()
574
+ self.experts = nn.ModuleList(
575
+ [
576
+ (
577
+ DeepseekV2MLP(
578
+ config, intermediate_size=config.moe_intermediate_size
579
+ )
580
+ if i >= self.ep_rank * self.experts_per_rank
581
+ and i < (self.ep_rank + 1) * self.experts_per_rank
582
+ else None
583
+ )
584
+ for i in range(config.n_routed_experts)
585
+ ]
586
+ )
587
+ else:
588
+ self.ep_size = 1
589
+ self.experts_per_rank = config.n_routed_experts
590
+ self.ep_rank = 0
591
+ self.experts = nn.ModuleList(
592
+ [
593
+ DeepseekV2MLP(
594
+ config, intermediate_size=config.moe_intermediate_size
595
+ )
596
+ for i in range(config.n_routed_experts)
597
+ ]
598
+ )
599
+ self.gate = MoEGate(config)
600
+ if config.n_shared_experts is not None:
601
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
602
+ self.shared_experts = DeepseekV2MLP(
603
+ config=config, intermediate_size=intermediate_size
604
+ )
605
+
606
+ def forward(self, hidden_states):
607
+ identity = hidden_states
608
+ orig_shape = hidden_states.shape
609
+ topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
610
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
611
+ flat_topk_idx = topk_idx.view(-1)
612
+ if self.training:
613
+ hidden_states = hidden_states.repeat_interleave(
614
+ self.num_experts_per_tok, dim=0
615
+ )
616
+ y = torch.empty_like(hidden_states)
617
+ for i, expert in enumerate(self.experts):
618
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
619
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
620
+ y = y.to(hidden_states.dtype).view(*orig_shape)
621
+ y = AddAuxiliaryLoss.apply(y, aux_loss)
622
+ else:
623
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
624
+ if self.config.n_shared_experts is not None:
625
+ y = y + self.shared_experts(identity)
626
+ return y
627
+
628
+ @torch.no_grad()
629
+ def moe_infer(self, x, topk_ids, topk_weight):
630
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
631
+ cnts.scatter_(1, topk_ids, 1)
632
+ tokens_per_expert = cnts.sum(dim=0)
633
+ idxs = topk_ids.view(-1).argsort()
634
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
635
+ sorted_tokens_shape = sorted_tokens.shape
636
+ if self.ep_size > 1:
637
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
638
+ tokens_per_expert_group = tokens_per_expert.new_empty(
639
+ tokens_per_expert.shape[0]
640
+ )
641
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
642
+ output_splits = (
643
+ tokens_per_expert_group.view(self.ep_size, -1)
644
+ .sum(1)
645
+ .cpu()
646
+ .numpy()
647
+ .tolist()
648
+ )
649
+ gathered_tokens = sorted_tokens.new_empty(
650
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
651
+ )
652
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
653
+ dist.all_to_all(
654
+ list(gathered_tokens.split(output_splits)),
655
+ list(sorted_tokens.split(input_split_sizes)),
656
+ )
657
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
658
+ self.ep_size, self.experts_per_rank
659
+ ).sum(dim=0)
660
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
661
+ s = 0
662
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
663
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
664
+ s += k
665
+ gatherd_idxs = gatherd_idxs.argsort()
666
+ sorted_tokens = gathered_tokens[gatherd_idxs]
667
+ tokens_per_expert = tokens_per_expert_post_gather
668
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
669
+
670
+ outputs = []
671
+ start_idx = 0
672
+ for i, num_tokens in enumerate(tokens_per_expert):
673
+ end_idx = start_idx + num_tokens
674
+ if num_tokens == 0:
675
+ continue
676
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
677
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
678
+ expert_out = expert(tokens_for_this_expert)
679
+ outputs.append(expert_out)
680
+ start_idx = end_idx
681
+
682
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
683
+ if self.ep_size > 1:
684
+ new_x = torch.empty_like(outs)
685
+ new_x[gatherd_idxs] = outs
686
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
687
+ dist.all_to_all(
688
+ list(gathered_tokens.split(input_split_sizes)),
689
+ list(new_x.split(output_splits)),
690
+ )
691
+ outs = gathered_tokens
692
+
693
+ new_x = torch.empty_like(outs)
694
+ new_x[idxs] = outs
695
+ final_out = (
696
+ new_x.view(*topk_ids.shape, -1)
697
+ .type(topk_weight.dtype)
698
+ .mul_(topk_weight.unsqueeze(dim=-1))
699
+ .sum(dim=1)
700
+ .type(new_x.dtype)
701
+ )
702
+ return final_out
703
+
704
+
705
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
706
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
707
+ """
708
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
709
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
710
+ """
711
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
712
+ if n_rep == 1:
713
+ return hidden_states
714
+ hidden_states = hidden_states[:, :, None, :, :].expand(
715
+ batch, num_key_value_heads, n_rep, slen, head_dim
716
+ )
717
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
718
+
719
+
720
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2
721
+ class DeepseekV2Attention(nn.Module):
722
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
723
+
724
+ def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None):
725
+ super().__init__()
726
+ self.config = config
727
+ self.layer_idx = layer_idx
728
+ if layer_idx is None:
729
+ logger.warning_once(
730
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
731
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
732
+ "when creating this class."
733
+ )
734
+
735
+ self.attention_dropout = config.attention_dropout
736
+ self.hidden_size = config.hidden_size
737
+ self.num_heads = config.num_attention_heads
738
+
739
+ self.max_position_embeddings = config.max_position_embeddings
740
+ self.rope_theta = config.rope_theta
741
+ self.q_lora_rank = config.q_lora_rank
742
+ self.qk_rope_head_dim = config.qk_rope_head_dim
743
+ self.kv_lora_rank = config.kv_lora_rank
744
+ self.v_head_dim = config.v_head_dim
745
+ self.qk_nope_head_dim = config.qk_nope_head_dim
746
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
747
+
748
+ self.is_causal = True
749
+
750
+ if self.q_lora_rank is None:
751
+ self.q_proj = nn.Linear(
752
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
753
+ )
754
+ else:
755
+ self.q_a_proj = nn.Linear(
756
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
757
+ )
758
+ self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank)
759
+ self.q_b_proj = nn.Linear(
760
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
761
+ )
762
+ # config.kv_lora_rank + config.qk_rope_head_dim,
763
+ self.kv_a_proj_with_mqa = nn.Linear(
764
+ self.hidden_size,
765
+ config.kv_lora_rank + config.qk_rope_head_dim,
766
+ bias=config.attention_bias,
767
+ )
768
+ self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank)
769
+ self.kv_b_proj = nn.Linear(
770
+ config.kv_lora_rank,
771
+ self.num_heads
772
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
773
+ bias=False,
774
+ )
775
+
776
+ self.o_proj = nn.Linear(
777
+ self.num_heads * self.v_head_dim,
778
+ self.hidden_size,
779
+ bias=config.attention_bias,
780
+ )
781
+ self._init_rope()
782
+
783
+ self.softmax_scale = self.q_head_dim ** (-0.5)
784
+ if self.config.rope_scaling is not None:
785
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
786
+ scaling_factor = self.config.rope_scaling["factor"]
787
+ if mscale_all_dim:
788
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
789
+ self.softmax_scale = self.softmax_scale * mscale * mscale
790
+
791
+ def _init_rope(self):
792
+ if self.config.rope_scaling is None:
793
+ self.rotary_emb = DeepseekV2RotaryEmbedding(
794
+ self.qk_rope_head_dim,
795
+ max_position_embeddings=self.max_position_embeddings,
796
+ base=self.rope_theta,
797
+ )
798
+ # self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
799
+ # self.qk_rope_head_dim,
800
+ # max_position_embeddings=self.max_position_embeddings,
801
+ # scaling_factor=scaling_factor,
802
+ # base=self.rope_theta,
803
+ # )
804
+ else:
805
+ scaling_type = self.config.rope_scaling["type"]
806
+ scaling_factor = self.config.rope_scaling["factor"]
807
+ if scaling_type == "linear":
808
+ self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding(
809
+ self.qk_rope_head_dim,
810
+ max_position_embeddings=self.max_position_embeddings,
811
+ scaling_factor=scaling_factor,
812
+ base=self.rope_theta,
813
+ )
814
+ elif scaling_type == "dynamic":
815
+ self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding(
816
+ self.qk_rope_head_dim,
817
+ max_position_embeddings=self.max_position_embeddings,
818
+ scaling_factor=scaling_factor,
819
+ base=self.rope_theta,
820
+ )
821
+ elif scaling_type == "yarn":
822
+ kwargs = {
823
+ key: self.config.rope_scaling[key]
824
+ for key in [
825
+ "original_max_position_embeddings",
826
+ "beta_fast",
827
+ "beta_slow",
828
+ "mscale",
829
+ "mscale_all_dim",
830
+ ]
831
+ if key in self.config.rope_scaling
832
+ }
833
+ self.rotary_emb = DeepseekV2YarnRotaryEmbedding(
834
+ self.qk_rope_head_dim,
835
+ max_position_embeddings=self.max_position_embeddings,
836
+ scaling_factor=scaling_factor,
837
+ base=self.rope_theta,
838
+ **kwargs,
839
+ )
840
+ else:
841
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
842
+
843
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
844
+ return (
845
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
846
+ .transpose(1, 2)
847
+ .contiguous()
848
+ )
849
+
850
+ def forward(
851
+ self,
852
+ hidden_states: torch.Tensor,
853
+ attention_mask: Optional[torch.Tensor] = None,
854
+ position_ids: Optional[torch.LongTensor] = None,
855
+ past_key_value: Optional[Cache] = None,
856
+ output_attentions: bool = False,
857
+ use_cache: bool = False,
858
+ **kwargs,
859
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
860
+ if "padding_mask" in kwargs:
861
+ warnings.warn(
862
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
863
+ )
864
+ bsz, q_len, _ = hidden_states.size()
865
+
866
+ if self.q_lora_rank is None:
867
+ q = self.q_proj(hidden_states)
868
+ else:
869
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
870
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
871
+
872
+
873
+ q_nope, q_pe = torch.split(
874
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
875
+ )
876
+
877
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
878
+ compressed_kv, k_pe = torch.split(
879
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
880
+ )
881
+ compressed_kv = self.kv_a_layernorm(compressed_kv)
882
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
883
+
884
+ kv_seq_len = k_pe.shape[-2]
885
+ if past_key_value is not None:
886
+ if self.layer_idx is None:
887
+ raise ValueError(
888
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
889
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
890
+ "with a layer index."
891
+ )
892
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
893
+
894
+ cos, sin = self.rotary_emb(q_pe, seq_len=kv_seq_len)
895
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
896
+
897
+ if past_key_value is not None:
898
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
899
+ compressed_kv = compressed_kv.unsqueeze(1)
900
+ k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs)
901
+ compressed_kv = compressed_kv.squeeze(1)
902
+
903
+ kv_b_proj = self.kv_b_proj.weight.view(self.num_heads, -1, self.kv_lora_rank)
904
+ q_absorb = kv_b_proj[:, :self.qk_nope_head_dim, :]
905
+ out_absorb = kv_b_proj[:, self.qk_nope_head_dim:, :]
906
+
907
+ q_nope = torch.matmul(q_nope, q_absorb)
908
+ attn_weights = (torch.matmul(q_pe, k_pe.mT) +
909
+ torch.matmul(q_nope, compressed_kv.unsqueeze(-3).mT)) * self.softmax_scale
910
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
911
+ raise ValueError(
912
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
913
+ f" {attn_weights.size()}"
914
+ )
915
+ assert attention_mask is not None
916
+ if attention_mask is not None:
917
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
918
+ raise ValueError(
919
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
920
+ )
921
+ attn_weights = attn_weights + attention_mask
922
+
923
+ # upcast attention to fp32
924
+ attn_weights = nn.functional.softmax(
925
+ attn_weights, dim=-1, dtype=torch.float32
926
+ ).to(q_pe.dtype)
927
+ attn_weights = nn.functional.dropout(
928
+ attn_weights, p=self.attention_dropout, training=self.training
929
+ )
930
+ attn_output = torch.einsum('bhql,blc->bhqc', attn_weights, compressed_kv)
931
+
932
+ attn_output = torch.matmul(attn_output, out_absorb.mT)
933
+
934
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
935
+ raise ValueError(
936
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
937
+ f" {attn_output.size()}"
938
+ )
939
+
940
+ attn_output = attn_output.transpose(1, 2).contiguous()
941
+
942
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
943
+
944
+ attn_output = self.o_proj(attn_output)
945
+
946
+ if not output_attentions:
947
+ attn_weights = None
948
+
949
+ return attn_output, attn_weights, past_key_value
950
+
951
+
952
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2
953
+ class DeepseekV2FlashAttention2(DeepseekV2Attention):
954
+ """
955
+ DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays
956
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
957
+ flash attention and deal with padding tokens in case the input contains any of them.
958
+ """
959
+
960
+ def __init__(self, *args, **kwargs):
961
+ super().__init__(*args, **kwargs)
962
+
963
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
964
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
965
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
966
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
967
+
968
+ def forward(
969
+ self,
970
+ hidden_states: torch.Tensor,
971
+ attention_mask: Optional[torch.LongTensor] = None,
972
+ position_ids: Optional[torch.LongTensor] = None,
973
+ past_key_value: Optional[Cache] = None,
974
+ output_attentions: bool = False,
975
+ use_cache: bool = False,
976
+ **kwargs,
977
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
978
+ # DeepseekV2FlashAttention2 attention does not support output_attentions
979
+ if "padding_mask" in kwargs:
980
+ warnings.warn(
981
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
982
+ )
983
+
984
+ # overwrite attention_mask with padding_mask
985
+ attention_mask = kwargs.pop("padding_mask")
986
+
987
+ output_attentions = False
988
+
989
+ bsz, q_len, _ = hidden_states.size()
990
+
991
+ if self.q_lora_rank is None:
992
+ q = self.q_proj(hidden_states)
993
+ else:
994
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
995
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
996
+ q_nope, q_pe = torch.split(
997
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
998
+ )
999
+
1000
+ # Flash attention requires the input to have the shape
1001
+ # batch_size x seq_length x head_dim x hidden_dim
1002
+ # therefore we just need to keep the original shape
1003
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1004
+ compressed_kv, k_pe = torch.split(
1005
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1006
+ )
1007
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1008
+ kv = (
1009
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1010
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1011
+ .transpose(1, 2)
1012
+ )
1013
+
1014
+ k_nope, value_states = torch.split(
1015
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1016
+ )
1017
+ kv_seq_len = value_states.shape[-2]
1018
+
1019
+ kv_seq_len = value_states.shape[-2]
1020
+ if past_key_value is not None:
1021
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1022
+
1023
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1024
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1025
+
1026
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1027
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1028
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1029
+
1030
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1031
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1032
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1033
+
1034
+ if self.q_head_dim != self.v_head_dim:
1035
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1036
+
1037
+ # TODO: support compressed_kv for kv_cache (instead of key_states, value_states) in flash_attention version
1038
+ if past_key_value is not None:
1039
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1040
+ key_states, value_states = past_key_value.update(
1041
+ key_states, value_states, self.layer_idx, cache_kwargs
1042
+ )
1043
+
1044
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
1045
+ # to be able to avoid many of these transpose/reshape/view.
1046
+ query_states = query_states.transpose(1, 2)
1047
+ key_states = key_states.transpose(1, 2)
1048
+ value_states = value_states.transpose(1, 2)
1049
+
1050
+ dropout_rate = self.attention_dropout if self.training else 0.0
1051
+
1052
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1053
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1054
+ # cast them back in the correct dtype just to be sure everything works as expected.
1055
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1056
+ # in fp32. (DeepseekV2RMSNorm handles it correctly)
1057
+
1058
+ input_dtype = query_states.dtype
1059
+ if input_dtype == torch.float32:
1060
+ # Handle the case where the model is quantized
1061
+ if hasattr(self.config, "_pre_quantization_dtype"):
1062
+ target_dtype = self.config._pre_quantization_dtype
1063
+ elif torch.is_autocast_enabled():
1064
+ target_dtype = torch.get_autocast_gpu_dtype()
1065
+ else:
1066
+ target_dtype = (
1067
+ self.q_proj.weight.dtype
1068
+ if self.q_lora_rank is None
1069
+ else self.q_a_proj.weight.dtype
1070
+ )
1071
+
1072
+ logger.warning_once(
1073
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1074
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1075
+ f" {target_dtype}."
1076
+ )
1077
+
1078
+ query_states = query_states.to(target_dtype)
1079
+ key_states = key_states.to(target_dtype)
1080
+ value_states = value_states.to(target_dtype)
1081
+
1082
+ attn_output = self._flash_attention_forward(
1083
+ query_states,
1084
+ key_states,
1085
+ value_states,
1086
+ attention_mask,
1087
+ q_len,
1088
+ dropout=dropout_rate,
1089
+ softmax_scale=self.softmax_scale,
1090
+ )
1091
+ if self.q_head_dim != self.v_head_dim:
1092
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1093
+
1094
+ attn_output = attn_output.reshape(
1095
+ bsz, q_len, self.num_heads * self.v_head_dim
1096
+ ).contiguous()
1097
+ attn_output = self.o_proj(attn_output)
1098
+
1099
+ if not output_attentions:
1100
+ attn_weights = None
1101
+
1102
+ return attn_output, attn_weights, past_key_value
1103
+
1104
+ def _flash_attention_forward(
1105
+ self,
1106
+ query_states,
1107
+ key_states,
1108
+ value_states,
1109
+ attention_mask,
1110
+ query_length,
1111
+ dropout=0.0,
1112
+ softmax_scale=None,
1113
+ ):
1114
+ """
1115
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1116
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1117
+
1118
+ Args:
1119
+ query_states (`torch.Tensor`):
1120
+ Input query states to be passed to Flash Attention API
1121
+ key_states (`torch.Tensor`):
1122
+ Input key states to be passed to Flash Attention API
1123
+ value_states (`torch.Tensor`):
1124
+ Input value states to be passed to Flash Attention API
1125
+ attention_mask (`torch.Tensor`):
1126
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1127
+ position of padding tokens and 1 for the position of non-padding tokens.
1128
+ dropout (`int`, *optional*):
1129
+ Attention dropout
1130
+ softmax_scale (`float`, *optional*):
1131
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1132
+ """
1133
+ if not self._flash_attn_uses_top_left_mask:
1134
+ causal = self.is_causal
1135
+ else:
1136
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__.
1137
+ causal = self.is_causal and query_length != 1
1138
+
1139
+ # Contains at least one padding token in the sequence
1140
+ if attention_mask is not None:
1141
+ batch_size = query_states.shape[0]
1142
+ (
1143
+ query_states,
1144
+ key_states,
1145
+ value_states,
1146
+ indices_q,
1147
+ cu_seq_lens,
1148
+ max_seq_lens,
1149
+ ) = self._upad_input(
1150
+ query_states, key_states, value_states, attention_mask, query_length
1151
+ )
1152
+
1153
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1154
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1155
+
1156
+ attn_output_unpad = flash_attn_varlen_func(
1157
+ query_states,
1158
+ key_states,
1159
+ value_states,
1160
+ cu_seqlens_q=cu_seqlens_q,
1161
+ cu_seqlens_k=cu_seqlens_k,
1162
+ max_seqlen_q=max_seqlen_in_batch_q,
1163
+ max_seqlen_k=max_seqlen_in_batch_k,
1164
+ dropout_p=dropout,
1165
+ softmax_scale=softmax_scale,
1166
+ causal=causal,
1167
+ )
1168
+
1169
+ attn_output = pad_input(
1170
+ attn_output_unpad, indices_q, batch_size, query_length
1171
+ )
1172
+ else:
1173
+ attn_output = flash_attn_func(
1174
+ query_states,
1175
+ key_states,
1176
+ value_states,
1177
+ dropout,
1178
+ softmax_scale=softmax_scale,
1179
+ causal=causal,
1180
+ )
1181
+
1182
+ return attn_output
1183
+
1184
+ def _upad_input(
1185
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1186
+ ):
1187
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1188
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1189
+
1190
+ key_layer = index_first_axis(
1191
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1192
+ indices_k,
1193
+ )
1194
+ value_layer = index_first_axis(
1195
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1196
+ indices_k,
1197
+ )
1198
+ if query_length == kv_seq_len:
1199
+ query_layer = index_first_axis(
1200
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1201
+ indices_k,
1202
+ )
1203
+ cu_seqlens_q = cu_seqlens_k
1204
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1205
+ indices_q = indices_k
1206
+ elif query_length == 1:
1207
+ max_seqlen_in_batch_q = 1
1208
+ cu_seqlens_q = torch.arange(
1209
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1210
+ ) # There is a memcpy here, that is very bad.
1211
+ indices_q = cu_seqlens_q[:-1]
1212
+ query_layer = query_layer.squeeze(1)
1213
+ else:
1214
+ # The -q_len: slice assumes left padding.
1215
+ attention_mask = attention_mask[:, -query_length:]
1216
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1217
+ query_layer, attention_mask
1218
+ )
1219
+
1220
+ return (
1221
+ query_layer,
1222
+ key_layer,
1223
+ value_layer,
1224
+ indices_q,
1225
+ (cu_seqlens_q, cu_seqlens_k),
1226
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1227
+ )
1228
+
1229
+
1230
+ ATTENTION_CLASSES = {
1231
+ "eager": DeepseekV2Attention,
1232
+ "flash_attention_2": DeepseekV2FlashAttention2,
1233
+
1234
+ "mla_eager": DeepseekV2Attention,
1235
+ "mla_flash_attention_2": DeepseekV2FlashAttention2,
1236
+
1237
+ "mha_eager": LlamaAttention,
1238
+ "mha_flash_attention_2": LlamaFlashAttention2
1239
+ }
1240
+
1241
+
1242
+ class DeepseekV2DecoderLayer(nn.Module):
1243
+ def __init__(self, config: DeepseekV2Config, layer_idx: int):
1244
+ super().__init__()
1245
+ self.hidden_size = config.hidden_size
1246
+
1247
+
1248
+ if config.use_mla:
1249
+ attn_implementation = "mla_" + config._attn_implementation
1250
+ else:
1251
+ attn_implementation = "mha_" + config._attn_implementation
1252
+
1253
+ self.self_attn = ATTENTION_CLASSES[attn_implementation](
1254
+ config=config, layer_idx=layer_idx
1255
+ )
1256
+
1257
+ self.mlp = (
1258
+ DeepseekV2MoE(config)
1259
+ if (
1260
+ config.n_routed_experts is not None
1261
+ and layer_idx >= config.first_k_dense_replace
1262
+ and layer_idx % config.moe_layer_freq == 0
1263
+ )
1264
+ else DeepseekV2MLP(config)
1265
+ )
1266
+ self.input_layernorm = DeepseekV2RMSNorm(
1267
+ config.hidden_size, eps=config.rms_norm_eps
1268
+ )
1269
+ self.post_attention_layernorm = DeepseekV2RMSNorm(
1270
+ config.hidden_size, eps=config.rms_norm_eps
1271
+ )
1272
+
1273
+ def forward(
1274
+ self,
1275
+ hidden_states: torch.Tensor,
1276
+ attention_mask: Optional[torch.Tensor] = None,
1277
+ position_ids: Optional[torch.LongTensor] = None,
1278
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1279
+ output_attentions: Optional[bool] = False,
1280
+ use_cache: Optional[bool] = False,
1281
+ **kwargs,
1282
+ ) -> Tuple[
1283
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1284
+ ]:
1285
+ """
1286
+ Args:
1287
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1288
+ attention_mask (`torch.FloatTensor`, *optional*):
1289
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1290
+ query_sequence_length, key_sequence_length)` if default attention is used.
1291
+ output_attentions (`bool`, *optional*):
1292
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1293
+ returned tensors for more detail.
1294
+ use_cache (`bool`, *optional*):
1295
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1296
+ (see `past_key_values`).
1297
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1298
+ """
1299
+ if "padding_mask" in kwargs:
1300
+ warnings.warn(
1301
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1302
+ )
1303
+ residual = hidden_states
1304
+
1305
+ hidden_states = self.input_layernorm(hidden_states)
1306
+
1307
+ # Self Attention
1308
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1309
+ hidden_states=hidden_states,
1310
+ attention_mask=attention_mask,
1311
+ position_ids=position_ids,
1312
+ past_key_value=past_key_value,
1313
+ output_attentions=output_attentions,
1314
+ use_cache=use_cache,
1315
+ **kwargs,
1316
+ )
1317
+ hidden_states = residual + hidden_states
1318
+
1319
+ # Fully Connected
1320
+ residual = hidden_states
1321
+ hidden_states = self.post_attention_layernorm(hidden_states)
1322
+ hidden_states = self.mlp(hidden_states)
1323
+ hidden_states = residual + hidden_states
1324
+
1325
+ outputs = (hidden_states,)
1326
+
1327
+ if output_attentions:
1328
+ outputs += (self_attn_weights,)
1329
+
1330
+ if use_cache:
1331
+ outputs += (present_key_value,)
1332
+
1333
+ return outputs
1334
+
1335
+
1336
+ DeepseekV2_START_DOCSTRING = r"""
1337
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1338
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1339
+ etc.)
1340
+
1341
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1342
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1343
+ and behavior.
1344
+
1345
+ Parameters:
1346
+ config ([`DeepseekV2Config`]):
1347
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1348
+ load the weights associated with the model, only the configuration. Check out the
1349
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1350
+ """
1351
+
1352
+
1353
+ @add_start_docstrings(
1354
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1355
+ DeepseekV2_START_DOCSTRING,
1356
+ )
1357
+ class DeepseekV2PreTrainedModel(PreTrainedModel):
1358
+ config_class = DeepseekV2Config
1359
+ base_model_prefix = "model"
1360
+ supports_gradient_checkpointing = True
1361
+ _no_split_modules = ["DeepseekV2DecoderLayer"]
1362
+ _skip_keys_device_placement = "past_key_values"
1363
+ _supports_flash_attn_2 = True
1364
+ _supports_cache_class = True
1365
+
1366
+ def _init_weights(self, module):
1367
+ std = self.config.initializer_range
1368
+ if isinstance(module, nn.Linear):
1369
+ module.weight.data.normal_(mean=0.0, std=std)
1370
+ if module.bias is not None:
1371
+ module.bias.data.zero_()
1372
+ elif isinstance(module, nn.Embedding):
1373
+ module.weight.data.normal_(mean=0.0, std=std)
1374
+ if module.padding_idx is not None:
1375
+ module.weight.data[module.padding_idx].zero_()
1376
+
1377
+
1378
+ DeepseekV2_INPUTS_DOCSTRING = r"""
1379
+ Args:
1380
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1381
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1382
+ it.
1383
+
1384
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1385
+ [`PreTrainedTokenizer.__call__`] for details.
1386
+
1387
+ [What are input IDs?](../glossary#input-ids)
1388
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1389
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1390
+
1391
+ - 1 for tokens that are **not masked**,
1392
+ - 0 for tokens that are **masked**.
1393
+
1394
+ [What are attention masks?](../glossary#attention-mask)
1395
+
1396
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1397
+ [`PreTrainedTokenizer.__call__`] for details.
1398
+
1399
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1400
+ `past_key_values`).
1401
+
1402
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1403
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1404
+ information on the default strategy.
1405
+
1406
+ - 1 indicates the head is **not masked**,
1407
+ - 0 indicates the head is **masked**.
1408
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1409
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1410
+ config.n_positions - 1]`.
1411
+
1412
+ [What are position IDs?](../glossary#position-ids)
1413
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1414
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1415
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1416
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1417
+
1418
+ Two formats are allowed:
1419
+ - a [`~cache_utils.Cache`] instance;
1420
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1421
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1422
+ cache format.
1423
+
1424
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1425
+ legacy cache format will be returned.
1426
+
1427
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1428
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1429
+ of shape `(batch_size, sequence_length)`.
1430
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1431
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1432
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1433
+ model's internal embedding lookup matrix.
1434
+ use_cache (`bool`, *optional*):
1435
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1436
+ `past_key_values`).
1437
+ output_attentions (`bool`, *optional*):
1438
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1439
+ tensors for more detail.
1440
+ output_hidden_states (`bool`, *optional*):
1441
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1442
+ more detail.
1443
+ return_dict (`bool`, *optional*):
1444
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1445
+ """
1446
+
1447
+
1448
+ @add_start_docstrings(
1449
+ "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.",
1450
+ DeepseekV2_START_DOCSTRING,
1451
+ )
1452
+ class DeepseekV2Model(DeepseekV2PreTrainedModel):
1453
+ """
1454
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
1455
+
1456
+ Args:
1457
+ config: DeepseekV2Config
1458
+ """
1459
+
1460
+ def __init__(self, config: DeepseekV2Config):
1461
+ super().__init__(config)
1462
+ self.padding_idx = config.pad_token_id
1463
+ self.vocab_size = config.vocab_size
1464
+
1465
+ self.embed_tokens = nn.Embedding(
1466
+ config.vocab_size, config.hidden_size, self.padding_idx
1467
+ )
1468
+ self.layers = nn.ModuleList(
1469
+ [
1470
+ DeepseekV2DecoderLayer(config, layer_idx)
1471
+ for layer_idx in range(config.num_hidden_layers)
1472
+ ]
1473
+ )
1474
+ # print(config._attn_implementation)
1475
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1476
+ self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1477
+
1478
+ self.gradient_checkpointing = False
1479
+ # Initialize weights and apply final processing
1480
+ self.post_init()
1481
+
1482
+ def get_input_embeddings(self):
1483
+ return self.embed_tokens
1484
+
1485
+ def set_input_embeddings(self, value):
1486
+ self.embed_tokens = value
1487
+
1488
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1489
+ def forward(
1490
+ self,
1491
+ input_ids: torch.LongTensor = None,
1492
+ attention_mask: Optional[torch.Tensor] = None,
1493
+ position_ids: Optional[torch.LongTensor] = None,
1494
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1495
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1496
+ use_cache: Optional[bool] = None,
1497
+ output_attentions: Optional[bool] = None,
1498
+ output_hidden_states: Optional[bool] = None,
1499
+ return_dict: Optional[bool] = None,
1500
+ cache_position: Optional[torch.LongTensor] = None
1501
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1502
+ output_attentions = (
1503
+ output_attentions
1504
+ if output_attentions is not None
1505
+ else self.config.output_attentions
1506
+ )
1507
+ output_hidden_states = (
1508
+ output_hidden_states
1509
+ if output_hidden_states is not None
1510
+ else self.config.output_hidden_states
1511
+ )
1512
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1513
+
1514
+ return_dict = (
1515
+ return_dict if return_dict is not None else self.config.use_return_dict
1516
+ )
1517
+
1518
+ # retrieve input_ids and inputs_embeds
1519
+ if input_ids is not None and inputs_embeds is not None:
1520
+ raise ValueError(
1521
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1522
+ )
1523
+ elif input_ids is not None:
1524
+ batch_size, seq_length = input_ids.shape[:2]
1525
+ elif inputs_embeds is not None:
1526
+ batch_size, seq_length = inputs_embeds.shape[:2]
1527
+ else:
1528
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1529
+
1530
+ if self.gradient_checkpointing and self.training:
1531
+ if use_cache:
1532
+ logger.warning_once(
1533
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1534
+ )
1535
+ use_cache = False
1536
+
1537
+ past_key_values_length = 0
1538
+ if use_cache:
1539
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1540
+ if use_legacy_cache:
1541
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1542
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1543
+
1544
+ if position_ids is None:
1545
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1546
+ position_ids = torch.arange(
1547
+ past_key_values_length,
1548
+ seq_length + past_key_values_length,
1549
+ dtype=torch.long,
1550
+ device=device,
1551
+ )
1552
+ position_ids = position_ids.unsqueeze(0)
1553
+
1554
+ if inputs_embeds is None:
1555
+ inputs_embeds = self.embed_tokens(input_ids)
1556
+
1557
+ if self._use_flash_attention_2:
1558
+ # 2d mask is passed through the layers
1559
+ attention_mask = (
1560
+ attention_mask
1561
+ if (attention_mask is not None and 0 in attention_mask)
1562
+ else None
1563
+ )
1564
+ else:
1565
+ # 4d mask is passed through the layers
1566
+ attention_mask = _prepare_4d_causal_attention_mask(
1567
+ attention_mask,
1568
+ (batch_size, seq_length),
1569
+ inputs_embeds,
1570
+ past_key_values_length,
1571
+ )
1572
+
1573
+ # embed positions
1574
+ hidden_states = inputs_embeds
1575
+
1576
+ # decoder layers
1577
+ all_hidden_states = () if output_hidden_states else None
1578
+ all_self_attns = () if output_attentions else None
1579
+ next_decoder_cache = None
1580
+
1581
+ for decoder_layer in self.layers:
1582
+ if output_hidden_states:
1583
+ all_hidden_states += (hidden_states,)
1584
+
1585
+ if self.gradient_checkpointing and self.training:
1586
+ layer_outputs = self._gradient_checkpointing_func(
1587
+ decoder_layer.__call__,
1588
+ hidden_states,
1589
+ attention_mask,
1590
+ position_ids,
1591
+ past_key_values,
1592
+ output_attentions,
1593
+ use_cache,
1594
+ )
1595
+ else:
1596
+ layer_outputs = decoder_layer(
1597
+ hidden_states,
1598
+ attention_mask=attention_mask,
1599
+ position_ids=position_ids,
1600
+ past_key_value=past_key_values,
1601
+ output_attentions=output_attentions,
1602
+ use_cache=use_cache,
1603
+ )
1604
+
1605
+ hidden_states = layer_outputs[0]
1606
+
1607
+ if use_cache:
1608
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1609
+
1610
+ if output_attentions:
1611
+ all_self_attns += (layer_outputs[1],)
1612
+
1613
+ hidden_states = self.norm(hidden_states)
1614
+
1615
+ # add hidden states from the last decoder layer
1616
+ if output_hidden_states:
1617
+ all_hidden_states += (hidden_states,)
1618
+
1619
+ next_cache = None
1620
+ if use_cache:
1621
+ next_cache = (
1622
+ next_decoder_cache.to_legacy_cache()
1623
+ if use_legacy_cache
1624
+ else next_decoder_cache
1625
+ )
1626
+ if not return_dict:
1627
+ return tuple(
1628
+ v
1629
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1630
+ if v is not None
1631
+ )
1632
+ return BaseModelOutputWithPast(
1633
+ last_hidden_state=hidden_states,
1634
+ past_key_values=next_cache,
1635
+ hidden_states=all_hidden_states,
1636
+ attentions=all_self_attns,
1637
+ )
1638
+
1639
+
1640
+ class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel):
1641
+ _tied_weights_keys = ["lm_head.weight"]
1642
+
1643
+ def __init__(self, config):
1644
+ super().__init__(config)
1645
+ self.model = DeepseekV2Model(config)
1646
+ self.vocab_size = config.vocab_size
1647
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1648
+
1649
+ # Initialize weights and apply final processing
1650
+ self.post_init()
1651
+
1652
+ def get_input_embeddings(self):
1653
+ return self.model.embed_tokens
1654
+
1655
+ def set_input_embeddings(self, value):
1656
+ self.model.embed_tokens = value
1657
+
1658
+ def get_output_embeddings(self):
1659
+ return self.lm_head
1660
+
1661
+ def set_output_embeddings(self, new_embeddings):
1662
+ self.lm_head = new_embeddings
1663
+
1664
+ def set_decoder(self, decoder):
1665
+ self.model = decoder
1666
+
1667
+ def get_decoder(self):
1668
+ return self.model
1669
+
1670
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1671
+ @replace_return_docstrings(
1672
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1673
+ )
1674
+ def forward(
1675
+ self,
1676
+ input_ids: torch.LongTensor = None,
1677
+ attention_mask: Optional[torch.Tensor] = None,
1678
+ position_ids: Optional[torch.LongTensor] = None,
1679
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1680
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1681
+ labels: Optional[torch.LongTensor] = None,
1682
+ use_cache: Optional[bool] = None,
1683
+ output_attentions: Optional[bool] = None,
1684
+ output_hidden_states: Optional[bool] = None,
1685
+ return_dict: Optional[bool] = None,
1686
+ cache_position: Optional[torch.LongTensor] = None
1687
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1688
+ r"""
1689
+ Args:
1690
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1691
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1692
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1693
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1694
+
1695
+ Returns:
1696
+
1697
+ Example:
1698
+
1699
+ ```python
1700
+ >>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
1701
+
1702
+ >>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1703
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1704
+
1705
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1706
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1707
+
1708
+ >>> # Generate
1709
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1710
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1711
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1712
+ ```"""
1713
+ output_attentions = (
1714
+ output_attentions
1715
+ if output_attentions is not None
1716
+ else self.config.output_attentions
1717
+ )
1718
+ output_hidden_states = (
1719
+ output_hidden_states
1720
+ if output_hidden_states is not None
1721
+ else self.config.output_hidden_states
1722
+ )
1723
+ return_dict = (
1724
+ return_dict if return_dict is not None else self.config.use_return_dict
1725
+ )
1726
+
1727
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1728
+ outputs = self.model(
1729
+ input_ids=input_ids,
1730
+ attention_mask=attention_mask,
1731
+ position_ids=position_ids,
1732
+ past_key_values=past_key_values,
1733
+ inputs_embeds=inputs_embeds,
1734
+ use_cache=use_cache,
1735
+ output_attentions=output_attentions,
1736
+ output_hidden_states=output_hidden_states,
1737
+ return_dict=return_dict,
1738
+ cache_position=cache_position
1739
+ )
1740
+
1741
+ hidden_states = outputs[0]
1742
+ logits = self.lm_head(hidden_states)
1743
+ logits = logits.float()
1744
+
1745
+ loss = None
1746
+ if labels is not None:
1747
+ # Shift so that tokens < n predict n
1748
+ shift_logits = logits[..., :-1, :].contiguous()
1749
+ shift_labels = labels[..., 1:].contiguous()
1750
+ # Flatten the tokens
1751
+ loss_fct = CrossEntropyLoss()
1752
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1753
+ shift_labels = shift_labels.view(-1)
1754
+ # Enable model parallelism
1755
+ shift_labels = shift_labels.to(shift_logits.device)
1756
+ loss = loss_fct(shift_logits, shift_labels)
1757
+
1758
+ if not return_dict:
1759
+ output = (logits,) + outputs[1:]
1760
+ return (loss,) + output if loss is not None else output
1761
+
1762
+ return CausalLMOutputWithPast(
1763
+ loss=loss,
1764
+ logits=logits,
1765
+ past_key_values=outputs.past_key_values,
1766
+ hidden_states=outputs.hidden_states,
1767
+ attentions=outputs.attentions,
1768
+ )
1769
+
1770
+ def prepare_inputs_for_generation(
1771
+ self,
1772
+ input_ids,
1773
+ past_key_values=None,
1774
+ attention_mask=None,
1775
+ inputs_embeds=None,
1776
+ **kwargs,
1777
+ ):
1778
+ past_length = 0
1779
+ if past_key_values is not None:
1780
+ if isinstance(past_key_values, Cache):
1781
+ cache_length = past_key_values.get_seq_length()
1782
+ past_length = past_key_values.seen_tokens
1783
+ max_cache_length = past_key_values.get_max_length()
1784
+ else:
1785
+ cache_length = past_length = past_key_values[0][0].shape[2]
1786
+ max_cache_length = None
1787
+
1788
+ # Keep only the unprocessed tokens:
1789
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1790
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1791
+ # input)
1792
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1793
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1794
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1795
+ # input_ids based on the past_length.
1796
+ elif past_length < input_ids.shape[1]:
1797
+ input_ids = input_ids[:, past_length:]
1798
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1799
+
1800
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1801
+ if (
1802
+ max_cache_length is not None
1803
+ and attention_mask is not None
1804
+ and cache_length + input_ids.shape[1] > max_cache_length
1805
+ ):
1806
+ attention_mask = attention_mask[:, -max_cache_length:]
1807
+
1808
+ position_ids = kwargs.get("position_ids", None)
1809
+ if attention_mask is not None and position_ids is None:
1810
+ # create position_ids on the fly for batch generation
1811
+ position_ids = attention_mask.long().cumsum(-1) - 1
1812
+ position_ids.masked_fill_(attention_mask == 0, 1)
1813
+ if past_key_values:
1814
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1815
+
1816
+ if self.generation_config.cache_implementation == "static":
1817
+ # generation with static cache
1818
+ cache_position = kwargs.get("cache_position", None)
1819
+ if cache_position is None:
1820
+ past_length = 0
1821
+ else:
1822
+ past_length = cache_position[-1] + 1
1823
+ input_ids = input_ids[:, past_length:]
1824
+ position_ids = position_ids[:, past_length:]
1825
+
1826
+ # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
1827
+ # same goes for position ids. Could also help with continued generation.
1828
+ cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
1829
+
1830
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1831
+ if inputs_embeds is not None and past_key_values is None:
1832
+ model_inputs = {"inputs_embeds": inputs_embeds}
1833
+ else:
1834
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1835
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1836
+ # TODO: use `next_tokens` directly instead.
1837
+ model_inputs = {"input_ids": input_ids.contiguous()}
1838
+
1839
+ model_inputs.update(
1840
+ {
1841
+ "position_ids": position_ids.contiguous(),
1842
+ "cache_position": cache_position,
1843
+ "past_key_values": past_key_values,
1844
+ "use_cache": kwargs.get("use_cache"),
1845
+ "attention_mask": attention_mask,
1846
+ }
1847
+ )
1848
+ return model_inputs
1849
+
1850
+ @staticmethod
1851
+ def _reorder_cache(past_key_values, beam_idx):
1852
+ reordered_past = ()
1853
+ for layer_past in past_key_values:
1854
+ reordered_past += (
1855
+ tuple(
1856
+ past_state.index_select(0, beam_idx.to(past_state.device))
1857
+ for past_state in layer_past
1858
+ ),
1859
+ )
1860
+ return reordered_past
1861
+
1862
+
1863
+ @add_start_docstrings(
1864
+ """
1865
+ The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
1866
+
1867
+ [`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1868
+ (e.g. GPT-2) do.
1869
+
1870
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1871
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1872
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1873
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1874
+ each row of the batch).
1875
+ """,
1876
+ DeepseekV2_START_DOCSTRING,
1877
+ )
1878
+ class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel):
1879
+ def __init__(self, config):
1880
+ super().__init__(config)
1881
+ self.num_labels = config.num_labels
1882
+ self.model = DeepseekV2Model(config)
1883
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1884
+
1885
+ # Initialize weights and apply final processing
1886
+ self.post_init()
1887
+
1888
+ def get_input_embeddings(self):
1889
+ return self.model.embed_tokens
1890
+
1891
+ def set_input_embeddings(self, value):
1892
+ self.model.embed_tokens = value
1893
+
1894
+ @add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING)
1895
+ def forward(
1896
+ self,
1897
+ input_ids: torch.LongTensor = None,
1898
+ attention_mask: Optional[torch.Tensor] = None,
1899
+ position_ids: Optional[torch.LongTensor] = None,
1900
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1901
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1902
+ labels: Optional[torch.LongTensor] = None,
1903
+ use_cache: Optional[bool] = None,
1904
+ output_attentions: Optional[bool] = None,
1905
+ output_hidden_states: Optional[bool] = None,
1906
+ return_dict: Optional[bool] = None,
1907
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1908
+ r"""
1909
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1910
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1911
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1912
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1913
+ """
1914
+ return_dict = (
1915
+ return_dict if return_dict is not None else self.config.use_return_dict
1916
+ )
1917
+
1918
+ transformer_outputs = self.model(
1919
+ input_ids,
1920
+ attention_mask=attention_mask,
1921
+ position_ids=position_ids,
1922
+ past_key_values=past_key_values,
1923
+ inputs_embeds=inputs_embeds,
1924
+ use_cache=use_cache,
1925
+ output_attentions=output_attentions,
1926
+ output_hidden_states=output_hidden_states,
1927
+ return_dict=return_dict,
1928
+ )
1929
+ hidden_states = transformer_outputs[0]
1930
+ logits = self.score(hidden_states)
1931
+
1932
+ if input_ids is not None:
1933
+ batch_size = input_ids.shape[0]
1934
+ else:
1935
+ batch_size = inputs_embeds.shape[0]
1936
+
1937
+ if self.config.pad_token_id is None and batch_size != 1:
1938
+ raise ValueError(
1939
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1940
+ )
1941
+ if self.config.pad_token_id is None:
1942
+ sequence_lengths = -1
1943
+ else:
1944
+ if input_ids is not None:
1945
+ sequence_lengths = (
1946
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1947
+ ).to(logits.device)
1948
+ else:
1949
+ sequence_lengths = -1
1950
+
1951
+ pooled_logits = logits[
1952
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1953
+ ]
1954
+
1955
+ loss = None
1956
+ if labels is not None:
1957
+ labels = labels.to(logits.device)
1958
+ if self.config.problem_type is None:
1959
+ if self.num_labels == 1:
1960
+ self.config.problem_type = "regression"
1961
+ elif self.num_labels > 1 and (
1962
+ labels.dtype == torch.long or labels.dtype == torch.int
1963
+ ):
1964
+ self.config.problem_type = "single_label_classification"
1965
+ else:
1966
+ self.config.problem_type = "multi_label_classification"
1967
+
1968
+ if self.config.problem_type == "regression":
1969
+ loss_fct = MSELoss()
1970
+ if self.num_labels == 1:
1971
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1972
+ else:
1973
+ loss = loss_fct(pooled_logits, labels)
1974
+ elif self.config.problem_type == "single_label_classification":
1975
+ loss_fct = CrossEntropyLoss()
1976
+ loss = loss_fct(
1977
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1978
+ )
1979
+ elif self.config.problem_type == "multi_label_classification":
1980
+ loss_fct = BCEWithLogitsLoss()
1981
+ loss = loss_fct(pooled_logits, labels)
1982
+ if not return_dict:
1983
+ output = (pooled_logits,) + transformer_outputs[1:]
1984
+ return ((loss,) + output) if loss is not None else output
1985
+
1986
+ return SequenceClassifierOutputWithPast(
1987
+ loss=loss,
1988
+ logits=pooled_logits,
1989
+ past_key_values=transformer_outputs.past_key_values,
1990
+ hidden_states=transformer_outputs.hidden_states,
1991
+ attentions=transformer_outputs.attentions,
1992
+ )
optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:593c0477a6cbaa0303f96c0d090ae77faad4a86c1db9f5bbb848b6ddc34f75bd
3
+ size 1452106315
rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61c19bab1174704a4a4441475683bf1270277af15d2e2c95e964789128e482c4
3
+ size 14645
scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:948facafbb9566e0b2b7727fcb77963fe02735f49bd022ab883fd5c464266ac8
3
+ size 1465
special_tokens_map.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|User|>",
4
+ "<|Assistant|>"
5
+ ],
6
+ "bos_token": {
7
+ "content": "<|begin▁of▁sentence|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "eos_token": {
14
+ "content": "<|end▁of▁sentence|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "pad_token": {
21
+ "content": "<|▁pad▁|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ }
27
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff
 
trainer_state.json ADDED
@@ -0,0 +1,1449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 0.9995759717314487,
5
+ "eval_steps": 200,
6
+ "global_step": 884,
7
+ "is_hyper_param_search": false,
8
+ "is_local_process_zero": true,
9
+ "is_world_process_zero": true,
10
+ "log_history": [
11
+ {
12
+ "epoch": 0.0011307420494699647,
13
+ "grad_norm": 8.3125,
14
+ "learning_rate": 3.3707865168539325e-07,
15
+ "loss": 0.493535578250885,
16
+ "step": 1,
17
+ "token_acc": 0.8620689655172413
18
+ },
19
+ {
20
+ "epoch": 0.005653710247349823,
21
+ "grad_norm": 10.0625,
22
+ "learning_rate": 1.6853932584269663e-06,
23
+ "loss": 0.4733062982559204,
24
+ "step": 5,
25
+ "token_acc": 0.8886255924170616
26
+ },
27
+ {
28
+ "epoch": 0.011307420494699646,
29
+ "grad_norm": 7.8125,
30
+ "learning_rate": 3.3707865168539327e-06,
31
+ "loss": 0.575874137878418,
32
+ "step": 10,
33
+ "token_acc": 0.8524590163934426
34
+ },
35
+ {
36
+ "epoch": 0.01696113074204947,
37
+ "grad_norm": 10.625,
38
+ "learning_rate": 5.056179775280899e-06,
39
+ "loss": 0.5115116596221924,
40
+ "step": 15,
41
+ "token_acc": 0.8833652007648184
42
+ },
43
+ {
44
+ "epoch": 0.022614840989399292,
45
+ "grad_norm": 9.1875,
46
+ "learning_rate": 6.741573033707865e-06,
47
+ "loss": 0.5164161682128906,
48
+ "step": 20,
49
+ "token_acc": 0.858195211786372
50
+ },
51
+ {
52
+ "epoch": 0.028268551236749116,
53
+ "grad_norm": 7.28125,
54
+ "learning_rate": 8.426966292134832e-06,
55
+ "loss": 0.500755786895752,
56
+ "step": 25,
57
+ "token_acc": 0.8675623800383877
58
+ },
59
+ {
60
+ "epoch": 0.03392226148409894,
61
+ "grad_norm": 11.4375,
62
+ "learning_rate": 1.0112359550561798e-05,
63
+ "loss": 0.45065789222717284,
64
+ "step": 30,
65
+ "token_acc": 0.8818011257035647
66
+ },
67
+ {
68
+ "epoch": 0.039575971731448764,
69
+ "grad_norm": 9.375,
70
+ "learning_rate": 1.1797752808988765e-05,
71
+ "loss": 0.5452223300933838,
72
+ "step": 35,
73
+ "token_acc": 0.8604651162790697
74
+ },
75
+ {
76
+ "epoch": 0.045229681978798585,
77
+ "grad_norm": 12.0,
78
+ "learning_rate": 1.348314606741573e-05,
79
+ "loss": 0.46700444221496584,
80
+ "step": 40,
81
+ "token_acc": 0.8830188679245283
82
+ },
83
+ {
84
+ "epoch": 0.05088339222614841,
85
+ "grad_norm": 8.4375,
86
+ "learning_rate": 1.5168539325842698e-05,
87
+ "loss": 0.4567443370819092,
88
+ "step": 45,
89
+ "token_acc": 0.8964879852125693
90
+ },
91
+ {
92
+ "epoch": 0.05653710247349823,
93
+ "grad_norm": 13.5,
94
+ "learning_rate": 1.6853932584269665e-05,
95
+ "loss": 0.5110898494720459,
96
+ "step": 50,
97
+ "token_acc": 0.864406779661017
98
+ },
99
+ {
100
+ "epoch": 0.06219081272084806,
101
+ "grad_norm": 5.0,
102
+ "learning_rate": 1.853932584269663e-05,
103
+ "loss": 0.4209805965423584,
104
+ "step": 55,
105
+ "token_acc": 0.8962264150943396
106
+ },
107
+ {
108
+ "epoch": 0.06784452296819787,
109
+ "grad_norm": 8.125,
110
+ "learning_rate": 2.0224719101123596e-05,
111
+ "loss": 0.4727331638336182,
112
+ "step": 60,
113
+ "token_acc": 0.891941391941392
114
+ },
115
+ {
116
+ "epoch": 0.0734982332155477,
117
+ "grad_norm": 11.125,
118
+ "learning_rate": 2.1910112359550563e-05,
119
+ "loss": 0.390924072265625,
120
+ "step": 65,
121
+ "token_acc": 0.8983364140480592
122
+ },
123
+ {
124
+ "epoch": 0.07915194346289753,
125
+ "grad_norm": 7.09375,
126
+ "learning_rate": 2.359550561797753e-05,
127
+ "loss": 0.3485325813293457,
128
+ "step": 70,
129
+ "token_acc": 0.9133709981167608
130
+ },
131
+ {
132
+ "epoch": 0.08480565371024736,
133
+ "grad_norm": 9.875,
134
+ "learning_rate": 2.5280898876404494e-05,
135
+ "loss": 0.4826796531677246,
136
+ "step": 75,
137
+ "token_acc": 0.8802946593001841
138
+ },
139
+ {
140
+ "epoch": 0.09045936395759717,
141
+ "grad_norm": 8.5,
142
+ "learning_rate": 2.696629213483146e-05,
143
+ "loss": 0.4428101539611816,
144
+ "step": 80,
145
+ "token_acc": 0.8783269961977186
146
+ },
147
+ {
148
+ "epoch": 0.096113074204947,
149
+ "grad_norm": 9.375,
150
+ "learning_rate": 2.865168539325843e-05,
151
+ "loss": 0.48508028984069823,
152
+ "step": 85,
153
+ "token_acc": 0.886654478976234
154
+ },
155
+ {
156
+ "epoch": 0.10176678445229682,
157
+ "grad_norm": 13.5,
158
+ "learning_rate": 2.999989459318379e-05,
159
+ "loss": 0.4538856506347656,
160
+ "step": 90,
161
+ "token_acc": 0.9044943820224719
162
+ },
163
+ {
164
+ "epoch": 0.10742049469964664,
165
+ "grad_norm": 8.4375,
166
+ "learning_rate": 2.999620552744515e-05,
167
+ "loss": 0.4510812282562256,
168
+ "step": 95,
169
+ "token_acc": 0.9045801526717557
170
+ },
171
+ {
172
+ "epoch": 0.11307420494699646,
173
+ "grad_norm": 16.5,
174
+ "learning_rate": 2.998724776679495e-05,
175
+ "loss": 0.49095354080200193,
176
+ "step": 100,
177
+ "token_acc": 0.8860294117647058
178
+ },
179
+ {
180
+ "epoch": 0.11872791519434629,
181
+ "grad_norm": 9.875,
182
+ "learning_rate": 2.997302480819445e-05,
183
+ "loss": 0.41774497032165525,
184
+ "step": 105,
185
+ "token_acc": 0.8880597014925373
186
+ },
187
+ {
188
+ "epoch": 0.12438162544169612,
189
+ "grad_norm": 7.15625,
190
+ "learning_rate": 2.9953542204050917e-05,
191
+ "loss": 0.30308961868286133,
192
+ "step": 110,
193
+ "token_acc": 0.9306049822064056
194
+ },
195
+ {
196
+ "epoch": 0.13003533568904593,
197
+ "grad_norm": 16.0,
198
+ "learning_rate": 2.9928807560050043e-05,
199
+ "loss": 0.5130989074707031,
200
+ "step": 115,
201
+ "token_acc": 0.8803738317757009
202
+ },
203
+ {
204
+ "epoch": 0.13568904593639575,
205
+ "grad_norm": 6.84375,
206
+ "learning_rate": 2.9898830532186824e-05,
207
+ "loss": 0.4366453647613525,
208
+ "step": 120,
209
+ "token_acc": 0.886654478976234
210
+ },
211
+ {
212
+ "epoch": 0.1413427561837456,
213
+ "grad_norm": 10.875,
214
+ "learning_rate": 2.9863622822996006e-05,
215
+ "loss": 0.5397056102752685,
216
+ "step": 125,
217
+ "token_acc": 0.8822429906542056
218
+ },
219
+ {
220
+ "epoch": 0.1469964664310954,
221
+ "grad_norm": 12.5,
222
+ "learning_rate": 2.982319817698363e-05,
223
+ "loss": 0.5331222534179687,
224
+ "step": 130,
225
+ "token_acc": 0.8604651162790697
226
+ },
227
+ {
228
+ "epoch": 0.15265017667844524,
229
+ "grad_norm": 12.1875,
230
+ "learning_rate": 2.977757237526136e-05,
231
+ "loss": 0.343440842628479,
232
+ "step": 135,
233
+ "token_acc": 0.9131238447319778
234
+ },
235
+ {
236
+ "epoch": 0.15830388692579506,
237
+ "grad_norm": 12.625,
238
+ "learning_rate": 2.9726763229385863e-05,
239
+ "loss": 0.47114005088806155,
240
+ "step": 140,
241
+ "token_acc": 0.886654478976234
242
+ },
243
+ {
244
+ "epoch": 0.16395759717314487,
245
+ "grad_norm": 8.625,
246
+ "learning_rate": 2.9670790574405432e-05,
247
+ "loss": 0.4388119697570801,
248
+ "step": 145,
249
+ "token_acc": 0.8894927536231884
250
+ },
251
+ {
252
+ "epoch": 0.1696113074204947,
253
+ "grad_norm": 6.6875,
254
+ "learning_rate": 2.9609676261116703e-05,
255
+ "loss": 0.558556079864502,
256
+ "step": 150,
257
+ "token_acc": 0.8729582577132486
258
+ },
259
+ {
260
+ "epoch": 0.17526501766784452,
261
+ "grad_norm": 10.375,
262
+ "learning_rate": 2.9543444147534497e-05,
263
+ "loss": 0.4793074131011963,
264
+ "step": 155,
265
+ "token_acc": 0.8905660377358491
266
+ },
267
+ {
268
+ "epoch": 0.18091872791519434,
269
+ "grad_norm": 8.3125,
270
+ "learning_rate": 2.947212008957803e-05,
271
+ "loss": 0.48024735450744627,
272
+ "step": 160,
273
+ "token_acc": 0.8924528301886793
274
+ },
275
+ {
276
+ "epoch": 0.18657243816254418,
277
+ "grad_norm": 19.875,
278
+ "learning_rate": 2.9395731930977187e-05,
279
+ "loss": 0.36183197498321534,
280
+ "step": 165,
281
+ "token_acc": 0.9111969111969112
282
+ },
283
+ {
284
+ "epoch": 0.192226148409894,
285
+ "grad_norm": 16.5,
286
+ "learning_rate": 2.9314309492402806e-05,
287
+ "loss": 0.5196819305419922,
288
+ "step": 170,
289
+ "token_acc": 0.8822393822393823
290
+ },
291
+ {
292
+ "epoch": 0.1978798586572438,
293
+ "grad_norm": 11.5625,
294
+ "learning_rate": 2.922788455982516e-05,
295
+ "loss": 0.46062512397766114,
296
+ "step": 175,
297
+ "token_acc": 0.8813559322033898
298
+ },
299
+ {
300
+ "epoch": 0.20353356890459365,
301
+ "grad_norm": 4.65625,
302
+ "learning_rate": 2.9136490872105272e-05,
303
+ "loss": 0.35768780708312986,
304
+ "step": 180,
305
+ "token_acc": 0.9044943820224719
306
+ },
307
+ {
308
+ "epoch": 0.20918727915194346,
309
+ "grad_norm": 9.5625,
310
+ "learning_rate": 2.904016410782379e-05,
311
+ "loss": 0.49846739768981935,
312
+ "step": 185,
313
+ "token_acc": 0.875
314
+ },
315
+ {
316
+ "epoch": 0.21484098939929328,
317
+ "grad_norm": 9.625,
318
+ "learning_rate": 2.8938941871352683e-05,
319
+ "loss": 0.5851227760314941,
320
+ "step": 190,
321
+ "token_acc": 0.8588007736943907
322
+ },
323
+ {
324
+ "epoch": 0.22049469964664312,
325
+ "grad_norm": 14.3125,
326
+ "learning_rate": 2.883286367817511e-05,
327
+ "loss": 0.4418447017669678,
328
+ "step": 195,
329
+ "token_acc": 0.8899253731343284
330
+ },
331
+ {
332
+ "epoch": 0.22614840989399293,
333
+ "grad_norm": 11.4375,
334
+ "learning_rate": 2.872197093945924e-05,
335
+ "loss": 0.7016141414642334,
336
+ "step": 200,
337
+ "token_acc": 0.8148148148148148
338
+ },
339
+ {
340
+ "epoch": 0.23180212014134274,
341
+ "grad_norm": 17.875,
342
+ "learning_rate": 2.860630694589199e-05,
343
+ "loss": 0.3626969337463379,
344
+ "step": 205,
345
+ "token_acc": 0.9100917431192661
346
+ },
347
+ {
348
+ "epoch": 0.23745583038869258,
349
+ "grad_norm": 12.9375,
350
+ "learning_rate": 2.8485916850779088e-05,
351
+ "loss": 0.4723252296447754,
352
+ "step": 210,
353
+ "token_acc": 0.8835978835978836
354
+ },
355
+ {
356
+ "epoch": 0.2431095406360424,
357
+ "grad_norm": 11.4375,
358
+ "learning_rate": 2.8360847652417973e-05,
359
+ "loss": 0.5085994720458984,
360
+ "step": 215,
361
+ "token_acc": 0.893048128342246
362
+ },
363
+ {
364
+ "epoch": 0.24876325088339224,
365
+ "grad_norm": 9.9375,
366
+ "learning_rate": 2.82311481757504e-05,
367
+ "loss": 0.4896233081817627,
368
+ "step": 220,
369
+ "token_acc": 0.8727272727272727
370
+ },
371
+ {
372
+ "epoch": 0.254416961130742,
373
+ "grad_norm": 11.375,
374
+ "learning_rate": 2.8096869053302046e-05,
375
+ "loss": 0.4948256492614746,
376
+ "step": 225,
377
+ "token_acc": 0.8743068391866913
378
+ },
379
+ {
380
+ "epoch": 0.26007067137809187,
381
+ "grad_norm": 8.5625,
382
+ "learning_rate": 2.7958062705416376e-05,
383
+ "loss": 0.4669034481048584,
384
+ "step": 230,
385
+ "token_acc": 0.8822463768115942
386
+ },
387
+ {
388
+ "epoch": 0.2657243816254417,
389
+ "grad_norm": 9.8125,
390
+ "learning_rate": 2.7814783319790595e-05,
391
+ "loss": 0.4465358734130859,
392
+ "step": 235,
393
+ "token_acc": 0.8836772983114447
394
+ },
395
+ {
396
+ "epoch": 0.2713780918727915,
397
+ "grad_norm": 10.9375,
398
+ "learning_rate": 2.766708683032173e-05,
399
+ "loss": 0.4827105522155762,
400
+ "step": 240,
401
+ "token_acc": 0.8766859344894027
402
+ },
403
+ {
404
+ "epoch": 0.27703180212014133,
405
+ "grad_norm": 9.4375,
406
+ "learning_rate": 2.75150308952709e-05,
407
+ "loss": 0.40639634132385255,
408
+ "step": 245,
409
+ "token_acc": 0.9010791366906474
410
+ },
411
+ {
412
+ "epoch": 0.2826855123674912,
413
+ "grad_norm": 11.4375,
414
+ "learning_rate": 2.735867487475452e-05,
415
+ "loss": 0.5378179550170898,
416
+ "step": 250,
417
+ "token_acc": 0.874766355140187
418
+ },
419
+ {
420
+ "epoch": 0.28833922261484096,
421
+ "grad_norm": 19.125,
422
+ "learning_rate": 2.7198079807571094e-05,
423
+ "loss": 0.42697606086730955,
424
+ "step": 255,
425
+ "token_acc": 0.8934579439252337
426
+ },
427
+ {
428
+ "epoch": 0.2939929328621908,
429
+ "grad_norm": 7.625,
430
+ "learning_rate": 2.7033308387372666e-05,
431
+ "loss": 0.45955357551574705,
432
+ "step": 260,
433
+ "token_acc": 0.888045540796964
434
+ },
435
+ {
436
+ "epoch": 0.29964664310954064,
437
+ "grad_norm": 8.875,
438
+ "learning_rate": 2.6864424938190263e-05,
439
+ "loss": 0.51542067527771,
440
+ "step": 265,
441
+ "token_acc": 0.8812260536398467
442
+ },
443
+ {
444
+ "epoch": 0.3053003533568905,
445
+ "grad_norm": 10.25,
446
+ "learning_rate": 2.6691495389322878e-05,
447
+ "loss": 0.49557199478149416,
448
+ "step": 270,
449
+ "token_acc": 0.8658536585365854
450
+ },
451
+ {
452
+ "epoch": 0.31095406360424027,
453
+ "grad_norm": 7.125,
454
+ "learning_rate": 2.651458724959973e-05,
455
+ "loss": 0.4124931812286377,
456
+ "step": 275,
457
+ "token_acc": 0.8986615678776291
458
+ },
459
+ {
460
+ "epoch": 0.3166077738515901,
461
+ "grad_norm": 8.9375,
462
+ "learning_rate": 2.633376958102597e-05,
463
+ "loss": 0.6442465782165527,
464
+ "step": 280,
465
+ "token_acc": 0.8523364485981308
466
+ },
467
+ {
468
+ "epoch": 0.32226148409893995,
469
+ "grad_norm": 9.875,
470
+ "learning_rate": 2.614911297182199e-05,
471
+ "loss": 0.43247137069702146,
472
+ "step": 285,
473
+ "token_acc": 0.8936567164179104
474
+ },
475
+ {
476
+ "epoch": 0.32791519434628974,
477
+ "grad_norm": 8.1875,
478
+ "learning_rate": 2.596068950886699e-05,
479
+ "loss": 0.40369553565979005,
480
+ "step": 290,
481
+ "token_acc": 0.9065934065934066
482
+ },
483
+ {
484
+ "epoch": 0.3335689045936396,
485
+ "grad_norm": 6.75,
486
+ "learning_rate": 2.5768572749557398e-05,
487
+ "loss": 0.35304784774780273,
488
+ "step": 295,
489
+ "token_acc": 0.9064885496183206
490
+ },
491
+ {
492
+ "epoch": 0.3392226148409894,
493
+ "grad_norm": 10.625,
494
+ "learning_rate": 2.5572837693091338e-05,
495
+ "loss": 0.42280235290527346,
496
+ "step": 300,
497
+ "token_acc": 0.8916518650088809
498
+ },
499
+ {
500
+ "epoch": 0.3448763250883392,
501
+ "grad_norm": 15.3125,
502
+ "learning_rate": 2.5373560751190164e-05,
503
+ "loss": 0.41590089797973634,
504
+ "step": 305,
505
+ "token_acc": 0.8983050847457628
506
+ },
507
+ {
508
+ "epoch": 0.35053003533568905,
509
+ "grad_norm": 15.5625,
510
+ "learning_rate": 2.517081971826858e-05,
511
+ "loss": 0.5931228637695313,
512
+ "step": 310,
513
+ "token_acc": 0.8493408662900188
514
+ },
515
+ {
516
+ "epoch": 0.3561837455830389,
517
+ "grad_norm": 16.0,
518
+ "learning_rate": 2.4964693741065e-05,
519
+ "loss": 0.3908259630203247,
520
+ "step": 315,
521
+ "token_acc": 0.8956043956043956
522
+ },
523
+ {
524
+ "epoch": 0.3618374558303887,
525
+ "grad_norm": 6.9375,
526
+ "learning_rate": 2.4755263287743982e-05,
527
+ "loss": 0.533808708190918,
528
+ "step": 320,
529
+ "token_acc": 0.8736842105263158
530
+ },
531
+ {
532
+ "epoch": 0.3674911660777385,
533
+ "grad_norm": 11.75,
534
+ "learning_rate": 2.4542610116482777e-05,
535
+ "loss": 0.43399462699890134,
536
+ "step": 325,
537
+ "token_acc": 0.8923076923076924
538
+ },
539
+ {
540
+ "epoch": 0.37314487632508836,
541
+ "grad_norm": 16.375,
542
+ "learning_rate": 2.43268172435543e-05,
543
+ "loss": 0.5363679885864258,
544
+ "step": 330,
545
+ "token_acc": 0.8554006968641115
546
+ },
547
+ {
548
+ "epoch": 0.37879858657243815,
549
+ "grad_norm": 6.46875,
550
+ "learning_rate": 2.4107968910918943e-05,
551
+ "loss": 0.4685643196105957,
552
+ "step": 335,
553
+ "token_acc": 0.8926553672316384
554
+ },
555
+ {
556
+ "epoch": 0.384452296819788,
557
+ "grad_norm": 11.25,
558
+ "learning_rate": 2.3886150553337925e-05,
559
+ "loss": 0.4552040100097656,
560
+ "step": 340,
561
+ "token_acc": 0.8849557522123894
562
+ },
563
+ {
564
+ "epoch": 0.3901060070671378,
565
+ "grad_norm": 9.375,
566
+ "learning_rate": 2.366144876502097e-05,
567
+ "loss": 0.41571660041809083,
568
+ "step": 345,
569
+ "token_acc": 0.8919925512104283
570
+ },
571
+ {
572
+ "epoch": 0.3957597173144876,
573
+ "grad_norm": 16.75,
574
+ "learning_rate": 2.3433951265821347e-05,
575
+ "loss": 0.48478131294250487,
576
+ "step": 350,
577
+ "token_acc": 0.8825688073394495
578
+ },
579
+ {
580
+ "epoch": 0.40141342756183745,
581
+ "grad_norm": 12.875,
582
+ "learning_rate": 2.320374686699154e-05,
583
+ "loss": 0.48756847381591795,
584
+ "step": 355,
585
+ "token_acc": 0.8759398496240601
586
+ },
587
+ {
588
+ "epoch": 0.4070671378091873,
589
+ "grad_norm": 10.25,
590
+ "learning_rate": 2.2970925436512743e-05,
591
+ "loss": 0.5582265853881836,
592
+ "step": 360,
593
+ "token_acc": 0.8727272727272727
594
+ },
595
+ {
596
+ "epoch": 0.4127208480565371,
597
+ "grad_norm": 7.125,
598
+ "learning_rate": 2.2735577864011946e-05,
599
+ "loss": 0.40789146423339845,
600
+ "step": 365,
601
+ "token_acc": 0.903954802259887
602
+ },
603
+ {
604
+ "epoch": 0.4183745583038869,
605
+ "grad_norm": 9.0625,
606
+ "learning_rate": 2.2497796025280097e-05,
607
+ "loss": 0.4335779666900635,
608
+ "step": 370,
609
+ "token_acc": 0.8895027624309392
610
+ },
611
+ {
612
+ "epoch": 0.42402826855123676,
613
+ "grad_norm": 8.6875,
614
+ "learning_rate": 2.2257672746405337e-05,
615
+ "loss": 0.5792682647705079,
616
+ "step": 375,
617
+ "token_acc": 0.8518518518518519
618
+ },
619
+ {
620
+ "epoch": 0.42968197879858655,
621
+ "grad_norm": 9.125,
622
+ "learning_rate": 2.201530176753521e-05,
623
+ "loss": 0.5717463016510009,
624
+ "step": 380,
625
+ "token_acc": 0.8565965583173997
626
+ },
627
+ {
628
+ "epoch": 0.4353356890459364,
629
+ "grad_norm": 6.9375,
630
+ "learning_rate": 2.17707777062821e-05,
631
+ "loss": 0.3671257972717285,
632
+ "step": 385,
633
+ "token_acc": 0.9074410163339383
634
+ },
635
+ {
636
+ "epoch": 0.44098939929328623,
637
+ "grad_norm": 12.125,
638
+ "learning_rate": 2.1524196020786038e-05,
639
+ "loss": 0.5280078887939453,
640
+ "step": 390,
641
+ "token_acc": 0.8771929824561403
642
+ },
643
+ {
644
+ "epoch": 0.446643109540636,
645
+ "grad_norm": 21.25,
646
+ "learning_rate": 2.127565297244947e-05,
647
+ "loss": 0.4925088882446289,
648
+ "step": 395,
649
+ "token_acc": 0.8908765652951699
650
+ },
651
+ {
652
+ "epoch": 0.45229681978798586,
653
+ "grad_norm": 10.3125,
654
+ "learning_rate": 2.1025245588358365e-05,
655
+ "loss": 0.4084740161895752,
656
+ "step": 400,
657
+ "token_acc": 0.8884758364312267
658
+ },
659
+ {
660
+ "epoch": 0.4579505300353357,
661
+ "grad_norm": 11.1875,
662
+ "learning_rate": 2.0773071623404486e-05,
663
+ "loss": 0.6456653594970703,
664
+ "step": 405,
665
+ "token_acc": 0.8585461689587426
666
+ },
667
+ {
668
+ "epoch": 0.4636042402826855,
669
+ "grad_norm": 6.6875,
670
+ "learning_rate": 2.0519229522123453e-05,
671
+ "loss": 0.6197998046875,
672
+ "step": 410,
673
+ "token_acc": 0.8672727272727273
674
+ },
675
+ {
676
+ "epoch": 0.46925795053003533,
677
+ "grad_norm": 8.8125,
678
+ "learning_rate": 2.026381838026368e-05,
679
+ "loss": 0.4290182113647461,
680
+ "step": 415,
681
+ "token_acc": 0.8931860036832413
682
+ },
683
+ {
684
+ "epoch": 0.47491166077738517,
685
+ "grad_norm": 9.9375,
686
+ "learning_rate": 2.0006937906100998e-05,
687
+ "loss": 0.4530322551727295,
688
+ "step": 420,
689
+ "token_acc": 0.9066901408450704
690
+ },
691
+ {
692
+ "epoch": 0.48056537102473496,
693
+ "grad_norm": 14.5625,
694
+ "learning_rate": 1.9748688381514224e-05,
695
+ "loss": 0.4739545345306396,
696
+ "step": 425,
697
+ "token_acc": 0.8712121212121212
698
+ },
699
+ {
700
+ "epoch": 0.4862190812720848,
701
+ "grad_norm": 14.1875,
702
+ "learning_rate": 1.9489170622836754e-05,
703
+ "loss": 0.5166975498199463,
704
+ "step": 430,
705
+ "token_acc": 0.8643122676579925
706
+ },
707
+ {
708
+ "epoch": 0.49187279151943464,
709
+ "grad_norm": 7.25,
710
+ "learning_rate": 1.922848594149955e-05,
711
+ "loss": 0.41360926628112793,
712
+ "step": 435,
713
+ "token_acc": 0.8875968992248062
714
+ },
715
+ {
716
+ "epoch": 0.4975265017667845,
717
+ "grad_norm": 8.1875,
718
+ "learning_rate": 1.896673610448085e-05,
719
+ "loss": 0.3576143741607666,
720
+ "step": 440,
721
+ "token_acc": 0.9126559714795008
722
+ },
723
+ {
724
+ "epoch": 0.5031802120141343,
725
+ "grad_norm": 9.8125,
726
+ "learning_rate": 1.8704023294578e-05,
727
+ "loss": 0.4304816246032715,
728
+ "step": 445,
729
+ "token_acc": 0.8942486085343229
730
+ },
731
+ {
732
+ "epoch": 0.508833922261484,
733
+ "grad_norm": 9.3125,
734
+ "learning_rate": 1.8440450070517e-05,
735
+ "loss": 0.40277585983276365,
736
+ "step": 450,
737
+ "token_acc": 0.8975791433891993
738
+ },
739
+ {
740
+ "epoch": 0.5144876325088339,
741
+ "grad_norm": 11.25,
742
+ "learning_rate": 1.817611932691528e-05,
743
+ "loss": 0.4203328609466553,
744
+ "step": 455,
745
+ "token_acc": 0.8958333333333334
746
+ },
747
+ {
748
+ "epoch": 0.5201413427561837,
749
+ "grad_norm": 15.375,
750
+ "learning_rate": 1.791113425411332e-05,
751
+ "loss": 0.4957026481628418,
752
+ "step": 460,
753
+ "token_acc": 0.869811320754717
754
+ },
755
+ {
756
+ "epoch": 0.5257950530035336,
757
+ "grad_norm": 12.5,
758
+ "learning_rate": 1.7645598297890914e-05,
759
+ "loss": 0.38120887279510496,
760
+ "step": 465,
761
+ "token_acc": 0.8954372623574145
762
+ },
763
+ {
764
+ "epoch": 0.5314487632508834,
765
+ "grad_norm": 12.5625,
766
+ "learning_rate": 1.7379615119083562e-05,
767
+ "loss": 0.46092791557312013,
768
+ "step": 470,
769
+ "token_acc": 0.9040590405904059
770
+ },
771
+ {
772
+ "epoch": 0.5371024734982333,
773
+ "grad_norm": 8.875,
774
+ "learning_rate": 1.7113288553115094e-05,
775
+ "loss": 0.35474748611450196,
776
+ "step": 475,
777
+ "token_acc": 0.9045045045045045
778
+ },
779
+ {
780
+ "epoch": 0.542756183745583,
781
+ "grad_norm": 11.5,
782
+ "learning_rate": 1.6846722569461957e-05,
783
+ "loss": 0.6311816215515137,
784
+ "step": 480,
785
+ "token_acc": 0.864376130198915
786
+ },
787
+ {
788
+ "epoch": 0.5484098939929328,
789
+ "grad_norm": 7.46875,
790
+ "learning_rate": 1.658002123106531e-05,
791
+ "loss": 0.4077010154724121,
792
+ "step": 485,
793
+ "token_acc": 0.8971428571428571
794
+ },
795
+ {
796
+ "epoch": 0.5540636042402827,
797
+ "grad_norm": 9.25,
798
+ "learning_rate": 1.6313288653706577e-05,
799
+ "loss": 0.5004054546356201,
800
+ "step": 490,
801
+ "token_acc": 0.8745173745173745
802
+ },
803
+ {
804
+ "epoch": 0.5597173144876325,
805
+ "grad_norm": 10.875,
806
+ "learning_rate": 1.6046628965362325e-05,
807
+ "loss": 0.49433560371398927,
808
+ "step": 495,
809
+ "token_acc": 0.8756660746003553
810
+ },
811
+ {
812
+ "epoch": 0.5653710247349824,
813
+ "grad_norm": 13.625,
814
+ "learning_rate": 1.5780146265554462e-05,
815
+ "loss": 0.5154177188873291,
816
+ "step": 500,
817
+ "token_acc": 0.8778359511343804
818
+ },
819
+ {
820
+ "epoch": 0.5710247349823322,
821
+ "grad_norm": 16.0,
822
+ "learning_rate": 1.5513944584711537e-05,
823
+ "loss": 0.5768596172332764,
824
+ "step": 505,
825
+ "token_acc": 0.8682170542635659
826
+ },
827
+ {
828
+ "epoch": 0.5766784452296819,
829
+ "grad_norm": 11.5,
830
+ "learning_rate": 1.5248127843556906e-05,
831
+ "loss": 0.542631196975708,
832
+ "step": 510,
833
+ "token_acc": 0.8648148148148148
834
+ },
835
+ {
836
+ "epoch": 0.5823321554770318,
837
+ "grad_norm": 9.3125,
838
+ "learning_rate": 1.4982799812539898e-05,
839
+ "loss": 0.44904112815856934,
840
+ "step": 515,
841
+ "token_acc": 0.8768656716417911
842
+ },
843
+ {
844
+ "epoch": 0.5879858657243816,
845
+ "grad_norm": 12.0,
846
+ "learning_rate": 1.471806407132547e-05,
847
+ "loss": 0.4998485088348389,
848
+ "step": 520,
849
+ "token_acc": 0.8848920863309353
850
+ },
851
+ {
852
+ "epoch": 0.5936395759717314,
853
+ "grad_norm": 14.9375,
854
+ "learning_rate": 1.445402396835848e-05,
855
+ "loss": 0.4888237476348877,
856
+ "step": 525,
857
+ "token_acc": 0.8878676470588235
858
+ },
859
+ {
860
+ "epoch": 0.5992932862190813,
861
+ "grad_norm": 11.875,
862
+ "learning_rate": 1.4190782580518134e-05,
863
+ "loss": 0.4358950614929199,
864
+ "step": 530,
865
+ "token_acc": 0.8945454545454545
866
+ },
867
+ {
868
+ "epoch": 0.6049469964664311,
869
+ "grad_norm": 13.4375,
870
+ "learning_rate": 1.3928442672878498e-05,
871
+ "loss": 0.3919216632843018,
872
+ "step": 535,
873
+ "token_acc": 0.9005424954792043
874
+ },
875
+ {
876
+ "epoch": 0.610600706713781,
877
+ "grad_norm": 14.625,
878
+ "learning_rate": 1.3667106658590713e-05,
879
+ "loss": 0.4299191474914551,
880
+ "step": 540,
881
+ "token_acc": 0.8834586466165414
882
+ },
883
+ {
884
+ "epoch": 0.6162544169611307,
885
+ "grad_norm": 11.0,
886
+ "learning_rate": 1.3406876558902596e-05,
887
+ "loss": 0.4752546787261963,
888
+ "step": 545,
889
+ "token_acc": 0.8946395563770795
890
+ },
891
+ {
892
+ "epoch": 0.6219081272084805,
893
+ "grad_norm": 8.0,
894
+ "learning_rate": 1.3147853963331226e-05,
895
+ "loss": 0.462324857711792,
896
+ "step": 550,
897
+ "token_acc": 0.8884892086330936
898
+ },
899
+ {
900
+ "epoch": 0.6275618374558304,
901
+ "grad_norm": 14.125,
902
+ "learning_rate": 1.2890139990004112e-05,
903
+ "loss": 0.4813478946685791,
904
+ "step": 555,
905
+ "token_acc": 0.8781818181818182
906
+ },
907
+ {
908
+ "epoch": 0.6332155477031802,
909
+ "grad_norm": 10.375,
910
+ "learning_rate": 1.2633835246184317e-05,
911
+ "loss": 0.4766115188598633,
912
+ "step": 560,
913
+ "token_acc": 0.8956692913385826
914
+ },
915
+ {
916
+ "epoch": 0.6388692579505301,
917
+ "grad_norm": 13.75,
918
+ "learning_rate": 1.2379039788995068e-05,
919
+ "loss": 0.555994701385498,
920
+ "step": 565,
921
+ "token_acc": 0.8626692456479691
922
+ },
923
+ {
924
+ "epoch": 0.6445229681978799,
925
+ "grad_norm": 11.4375,
926
+ "learning_rate": 1.2125853086359117e-05,
927
+ "loss": 0.554969596862793,
928
+ "step": 570,
929
+ "token_acc": 0.864406779661017
930
+ },
931
+ {
932
+ "epoch": 0.6501766784452296,
933
+ "grad_norm": 9.375,
934
+ "learning_rate": 1.1874373978168092e-05,
935
+ "loss": 0.48480896949768065,
936
+ "step": 575,
937
+ "token_acc": 0.8574144486692015
938
+ },
939
+ {
940
+ "epoch": 0.6558303886925795,
941
+ "grad_norm": 10.75,
942
+ "learning_rate": 1.1624700637697078e-05,
943
+ "loss": 0.6284814357757569,
944
+ "step": 580,
945
+ "token_acc": 0.8512241054613936
946
+ },
947
+ {
948
+ "epoch": 0.6614840989399293,
949
+ "grad_norm": 10.1875,
950
+ "learning_rate": 1.1376930533279357e-05,
951
+ "loss": 0.38442087173461914,
952
+ "step": 585,
953
+ "token_acc": 0.9003690036900369
954
+ },
955
+ {
956
+ "epoch": 0.6671378091872792,
957
+ "grad_norm": 10.3125,
958
+ "learning_rate": 1.1131160390256417e-05,
959
+ "loss": 0.5038439750671386,
960
+ "step": 590,
961
+ "token_acc": 0.8627819548872181
962
+ },
963
+ {
964
+ "epoch": 0.672791519434629,
965
+ "grad_norm": 14.3125,
966
+ "learning_rate": 1.0887486153217962e-05,
967
+ "loss": 0.45342187881469725,
968
+ "step": 595,
969
+ "token_acc": 0.8917910447761194
970
+ },
971
+ {
972
+ "epoch": 0.6784452296819788,
973
+ "grad_norm": 10.3125,
974
+ "learning_rate": 1.064600294854675e-05,
975
+ "loss": 0.5414403915405274,
976
+ "step": 600,
977
+ "token_acc": 0.8771266540642723
978
+ },
979
+ {
980
+ "epoch": 0.6840989399293286,
981
+ "grad_norm": 12.1875,
982
+ "learning_rate": 1.0406805047282826e-05,
983
+ "loss": 0.44243249893188474,
984
+ "step": 605,
985
+ "token_acc": 0.8971428571428571
986
+ },
987
+ {
988
+ "epoch": 0.6897526501766784,
989
+ "grad_norm": 9.4375,
990
+ "learning_rate": 1.0169985828321664e-05,
991
+ "loss": 0.4240866661071777,
992
+ "step": 610,
993
+ "token_acc": 0.900562851782364
994
+ },
995
+ {
996
+ "epoch": 0.6954063604240283,
997
+ "grad_norm": 17.0,
998
+ "learning_rate": 9.935637741960595e-06,
999
+ "loss": 0.5268006324768066,
1000
+ "step": 615,
1001
+ "token_acc": 0.8721804511278195
1002
+ },
1003
+ {
1004
+ "epoch": 0.7010600706713781,
1005
+ "grad_norm": 13.75,
1006
+ "learning_rate": 9.703852273807745e-06,
1007
+ "loss": 0.5309527397155762,
1008
+ "step": 620,
1009
+ "token_acc": 0.864963503649635
1010
+ },
1011
+ {
1012
+ "epoch": 0.7067137809187279,
1013
+ "grad_norm": 10.625,
1014
+ "learning_rate": 9.474719909067592e-06,
1015
+ "loss": 0.46470232009887696,
1016
+ "step": 625,
1017
+ "token_acc": 0.8984674329501916
1018
+ },
1019
+ {
1020
+ "epoch": 0.7123674911660778,
1021
+ "grad_norm": 10.75,
1022
+ "learning_rate": 9.248330097216998e-06,
1023
+ "loss": 0.3585221290588379,
1024
+ "step": 630,
1025
+ "token_acc": 0.9072356215213359
1026
+ },
1027
+ {
1028
+ "epoch": 0.7180212014134275,
1029
+ "grad_norm": 10.8125,
1030
+ "learning_rate": 9.024771217085648e-06,
1031
+ "loss": 0.45208401679992677,
1032
+ "step": 635,
1033
+ "token_acc": 0.9046728971962616
1034
+ },
1035
+ {
1036
+ "epoch": 0.7236749116607774,
1037
+ "grad_norm": 9.0,
1038
+ "learning_rate": 8.804130542354423e-06,
1039
+ "loss": 0.40645594596862794,
1040
+ "step": 640,
1041
+ "token_acc": 0.8970588235294118
1042
+ },
1043
+ {
1044
+ "epoch": 0.7293286219081272,
1045
+ "grad_norm": 11.1875,
1046
+ "learning_rate": 8.586494207485173e-06,
1047
+ "loss": 0.5020310878753662,
1048
+ "step": 645,
1049
+ "token_acc": 0.8729582577132486
1050
+ },
1051
+ {
1052
+ "epoch": 0.734982332155477,
1053
+ "grad_norm": 26.25,
1054
+ "learning_rate": 8.371947174095276e-06,
1055
+ "loss": 0.5611002445220947,
1056
+ "step": 650,
1057
+ "token_acc": 0.8490566037735849
1058
+ },
1059
+ {
1060
+ "epoch": 0.7406360424028269,
1061
+ "grad_norm": 14.8125,
1062
+ "learning_rate": 8.160573197790034e-06,
1063
+ "loss": 0.504447078704834,
1064
+ "step": 655,
1065
+ "token_acc": 0.8843416370106761
1066
+ },
1067
+ {
1068
+ "epoch": 0.7462897526501767,
1069
+ "grad_norm": 18.375,
1070
+ "learning_rate": 7.952454795465847e-06,
1071
+ "loss": 0.41913480758666993,
1072
+ "step": 660,
1073
+ "token_acc": 0.8958333333333334
1074
+ },
1075
+ {
1076
+ "epoch": 0.7519434628975264,
1077
+ "grad_norm": 8.75,
1078
+ "learning_rate": 7.747673213097013e-06,
1079
+ "loss": 0.4940896511077881,
1080
+ "step": 665,
1081
+ "token_acc": 0.8772893772893773
1082
+ },
1083
+ {
1084
+ "epoch": 0.7575971731448763,
1085
+ "grad_norm": 13.5625,
1086
+ "learning_rate": 7.5463083940186235e-06,
1087
+ "loss": 0.47562193870544434,
1088
+ "step": 670,
1089
+ "token_acc": 0.8994614003590664
1090
+ },
1091
+ {
1092
+ "epoch": 0.7632508833922261,
1093
+ "grad_norm": 10.0625,
1094
+ "learning_rate": 7.3484389477180245e-06,
1095
+ "loss": 0.48333349227905276,
1096
+ "step": 675,
1097
+ "token_acc": 0.8953488372093024
1098
+ },
1099
+ {
1100
+ "epoch": 0.768904593639576,
1101
+ "grad_norm": 8.5,
1102
+ "learning_rate": 7.154142119146981e-06,
1103
+ "loss": 0.41202802658081056,
1104
+ "step": 680,
1105
+ "token_acc": 0.9003831417624522
1106
+ },
1107
+ {
1108
+ "epoch": 0.7745583038869258,
1109
+ "grad_norm": 12.9375,
1110
+ "learning_rate": 6.9634937585665066e-06,
1111
+ "loss": 0.47983555793762206,
1112
+ "step": 685,
1113
+ "token_acc": 0.8998211091234347
1114
+ },
1115
+ {
1116
+ "epoch": 0.7802120141342757,
1117
+ "grad_norm": 8.6875,
1118
+ "learning_rate": 6.776568291936193e-06,
1119
+ "loss": 0.4969668388366699,
1120
+ "step": 690,
1121
+ "token_acc": 0.8790786948176583
1122
+ },
1123
+ {
1124
+ "epoch": 0.7858657243816255,
1125
+ "grad_norm": 10.375,
1126
+ "learning_rate": 6.593438691859566e-06,
1127
+ "loss": 0.44586987495422364,
1128
+ "step": 695,
1129
+ "token_acc": 0.884469696969697
1130
+ },
1131
+ {
1132
+ "epoch": 0.7915194346289752,
1133
+ "grad_norm": 11.875,
1134
+ "learning_rate": 6.414176449096749e-06,
1135
+ "loss": 0.5935549736022949,
1136
+ "step": 700,
1137
+ "token_acc": 0.8718929254302104
1138
+ },
1139
+ {
1140
+ "epoch": 0.7971731448763251,
1141
+ "grad_norm": 16.75,
1142
+ "learning_rate": 6.238851544655688e-06,
1143
+ "loss": 0.5915599822998047,
1144
+ "step": 705,
1145
+ "token_acc": 0.8622641509433963
1146
+ },
1147
+ {
1148
+ "epoch": 0.8028268551236749,
1149
+ "grad_norm": 13.4375,
1150
+ "learning_rate": 6.067532422472728e-06,
1151
+ "loss": 0.45562114715576174,
1152
+ "step": 710,
1153
+ "token_acc": 0.8954372623574145
1154
+ },
1155
+ {
1156
+ "epoch": 0.8084805653710248,
1157
+ "grad_norm": 9.5625,
1158
+ "learning_rate": 5.9002859626932115e-06,
1159
+ "loss": 0.44912257194519045,
1160
+ "step": 715,
1161
+ "token_acc": 0.8789571694599627
1162
+ },
1163
+ {
1164
+ "epoch": 0.8141342756183746,
1165
+ "grad_norm": 12.6875,
1166
+ "learning_rate": 5.7371774555625925e-06,
1167
+ "loss": 0.4588914394378662,
1168
+ "step": 720,
1169
+ "token_acc": 0.8875638841567292
1170
+ },
1171
+ {
1172
+ "epoch": 0.8197879858657244,
1173
+ "grad_norm": 10.5625,
1174
+ "learning_rate": 5.578270575938212e-06,
1175
+ "loss": 0.42406349182128905,
1176
+ "step": 725,
1177
+ "token_acc": 0.9009009009009009
1178
+ },
1179
+ {
1180
+ "epoch": 0.8254416961130742,
1181
+ "grad_norm": 13.875,
1182
+ "learning_rate": 5.423627358431671e-06,
1183
+ "loss": 0.49872541427612305,
1184
+ "step": 730,
1185
+ "token_acc": 0.8799249530956847
1186
+ },
1187
+ {
1188
+ "epoch": 0.831095406360424,
1189
+ "grad_norm": 17.0,
1190
+ "learning_rate": 5.273308173191575e-06,
1191
+ "loss": 0.48893170356750487,
1192
+ "step": 735,
1193
+ "token_acc": 0.8968105065666041
1194
+ },
1195
+ {
1196
+ "epoch": 0.8367491166077738,
1197
+ "grad_norm": 10.3125,
1198
+ "learning_rate": 5.127371702336002e-06,
1199
+ "loss": 0.5636299133300782,
1200
+ "step": 740,
1201
+ "token_acc": 0.860236220472441
1202
+ },
1203
+ {
1204
+ "epoch": 0.8424028268551237,
1205
+ "grad_norm": 12.0,
1206
+ "learning_rate": 4.985874917043985e-06,
1207
+ "loss": 0.41251296997070314,
1208
+ "step": 745,
1209
+ "token_acc": 0.8983364140480592
1210
+ },
1211
+ {
1212
+ "epoch": 0.8480565371024735,
1213
+ "grad_norm": 12.3125,
1214
+ "learning_rate": 4.848873055314914e-06,
1215
+ "loss": 0.5803286552429199,
1216
+ "step": 750,
1217
+ "token_acc": 0.8612612612612612
1218
+ },
1219
+ {
1220
+ "epoch": 0.8537102473498234,
1221
+ "grad_norm": 9.75,
1222
+ "learning_rate": 4.7164196004045305e-06,
1223
+ "loss": 0.5717785835266114,
1224
+ "step": 755,
1225
+ "token_acc": 0.8810408921933085
1226
+ },
1227
+ {
1228
+ "epoch": 0.8593639575971731,
1229
+ "grad_norm": 8.9375,
1230
+ "learning_rate": 4.588566259945948e-06,
1231
+ "loss": 0.545508623123169,
1232
+ "step": 760,
1233
+ "token_acc": 0.8704761904761905
1234
+ },
1235
+ {
1236
+ "epoch": 0.8650176678445229,
1237
+ "grad_norm": 11.5,
1238
+ "learning_rate": 4.465362945763868e-06,
1239
+ "loss": 0.40853538513183596,
1240
+ "step": 765,
1241
+ "token_acc": 0.9005424954792043
1242
+ },
1243
+ {
1244
+ "epoch": 0.8706713780918728,
1245
+ "grad_norm": 15.1875,
1246
+ "learning_rate": 4.3468577543898026e-06,
1247
+ "loss": 0.469269323348999,
1248
+ "step": 770,
1249
+ "token_acc": 0.8923357664233577
1250
+ },
1251
+ {
1252
+ "epoch": 0.8763250883392226,
1253
+ "grad_norm": 14.875,
1254
+ "learning_rate": 4.233096948286008e-06,
1255
+ "loss": 0.485385799407959,
1256
+ "step": 775,
1257
+ "token_acc": 0.8886792452830189
1258
+ },
1259
+ {
1260
+ "epoch": 0.8819787985865725,
1261
+ "grad_norm": 10.25,
1262
+ "learning_rate": 4.124124937785375e-06,
1263
+ "loss": 0.5617117404937744,
1264
+ "step": 780,
1265
+ "token_acc": 0.8745318352059925
1266
+ },
1267
+ {
1268
+ "epoch": 0.8876325088339223,
1269
+ "grad_norm": 14.625,
1270
+ "learning_rate": 4.019984263754374e-06,
1271
+ "loss": 0.5018572807312012,
1272
+ "step": 785,
1273
+ "token_acc": 0.8718861209964412
1274
+ },
1275
+ {
1276
+ "epoch": 0.893286219081272,
1277
+ "grad_norm": 20.25,
1278
+ "learning_rate": 3.920715580985813e-06,
1279
+ "loss": 0.5424814224243164,
1280
+ "step": 790,
1281
+ "token_acc": 0.8679245283018868
1282
+ },
1283
+ {
1284
+ "epoch": 0.8989399293286219,
1285
+ "grad_norm": 7.375,
1286
+ "learning_rate": 3.8263576423278684e-06,
1287
+ "loss": 0.3595900058746338,
1288
+ "step": 795,
1289
+ "token_acc": 0.9087591240875912
1290
+ },
1291
+ {
1292
+ "epoch": 0.9045936395759717,
1293
+ "grad_norm": 13.9375,
1294
+ "learning_rate": 3.736947283555621e-06,
1295
+ "loss": 0.5959813117980957,
1296
+ "step": 800,
1297
+ "token_acc": 0.8745019920318725
1298
+ },
1299
+ {
1300
+ "epoch": 0.9102473498233216,
1301
+ "grad_norm": 9.6875,
1302
+ "learning_rate": 3.6525194089909827e-06,
1303
+ "loss": 0.6750380039215088,
1304
+ "step": 805,
1305
+ "token_acc": 0.8412098298676749
1306
+ },
1307
+ {
1308
+ "epoch": 0.9159010600706714,
1309
+ "grad_norm": 14.4375,
1310
+ "learning_rate": 3.5731069778766223e-06,
1311
+ "loss": 0.680885648727417,
1312
+ "step": 810,
1313
+ "token_acc": 0.8374291115311909
1314
+ },
1315
+ {
1316
+ "epoch": 0.9215547703180212,
1317
+ "grad_norm": 9.0,
1318
+ "learning_rate": 3.498740991509231e-06,
1319
+ "loss": 0.5743994235992431,
1320
+ "step": 815,
1321
+ "token_acc": 0.8820224719101124
1322
+ },
1323
+ {
1324
+ "epoch": 0.927208480565371,
1325
+ "grad_norm": 17.5,
1326
+ "learning_rate": 3.4294504811371234e-06,
1327
+ "loss": 0.5227997779846192,
1328
+ "step": 820,
1329
+ "token_acc": 0.887189292543021
1330
+ },
1331
+ {
1332
+ "epoch": 0.9328621908127208,
1333
+ "grad_norm": 12.8125,
1334
+ "learning_rate": 3.3652624966269193e-06,
1335
+ "loss": 0.41265015602111815,
1336
+ "step": 825,
1337
+ "token_acc": 0.8854545454545455
1338
+ },
1339
+ {
1340
+ "epoch": 0.9385159010600707,
1341
+ "grad_norm": 17.125,
1342
+ "learning_rate": 3.306202095903728e-06,
1343
+ "loss": 0.5101790428161621,
1344
+ "step": 830,
1345
+ "token_acc": 0.891588785046729
1346
+ },
1347
+ {
1348
+ "epoch": 0.9441696113074205,
1349
+ "grad_norm": 12.5,
1350
+ "learning_rate": 3.252292335168949e-06,
1351
+ "loss": 0.48482298851013184,
1352
+ "step": 835,
1353
+ "token_acc": 0.8655616942909761
1354
+ },
1355
+ {
1356
+ "epoch": 0.9498233215547703,
1357
+ "grad_norm": 11.0,
1358
+ "learning_rate": 3.2035542598995146e-06,
1359
+ "loss": 0.5188216209411621,
1360
+ "step": 840,
1361
+ "token_acc": 0.8686679174484052
1362
+ },
1363
+ {
1364
+ "epoch": 0.9554770318021202,
1365
+ "grad_norm": 16.625,
1366
+ "learning_rate": 3.1600068966320774e-06,
1367
+ "loss": 0.5178674697875977,
1368
+ "step": 845,
1369
+ "token_acc": 0.8787878787878788
1370
+ },
1371
+ {
1372
+ "epoch": 0.9611307420494699,
1373
+ "grad_norm": 9.375,
1374
+ "learning_rate": 3.1216672455353746e-06,
1375
+ "loss": 0.3571352958679199,
1376
+ "step": 850,
1377
+ "token_acc": 0.9163636363636364
1378
+ },
1379
+ {
1380
+ "epoch": 0.9667844522968198,
1381
+ "grad_norm": 19.75,
1382
+ "learning_rate": 3.0885502737736366e-06,
1383
+ "loss": 0.5291311740875244,
1384
+ "step": 855,
1385
+ "token_acc": 0.8817829457364341
1386
+ },
1387
+ {
1388
+ "epoch": 0.9724381625441696,
1389
+ "grad_norm": 10.625,
1390
+ "learning_rate": 3.0606689096636604e-06,
1391
+ "loss": 0.7415075778961182,
1392
+ "step": 860,
1393
+ "token_acc": 0.8426763110307414
1394
+ },
1395
+ {
1396
+ "epoch": 0.9780918727915194,
1397
+ "grad_norm": 11.125,
1398
+ "learning_rate": 3.0380340376278078e-06,
1399
+ "loss": 0.4753167152404785,
1400
+ "step": 865,
1401
+ "token_acc": 0.8872180451127819
1402
+ },
1403
+ {
1404
+ "epoch": 0.9837455830388693,
1405
+ "grad_norm": 13.75,
1406
+ "learning_rate": 3.0206544939449e-06,
1407
+ "loss": 0.5666730403900146,
1408
+ "step": 870,
1409
+ "token_acc": 0.8776595744680851
1410
+ },
1411
+ {
1412
+ "epoch": 0.9893992932862191,
1413
+ "grad_norm": 14.1875,
1414
+ "learning_rate": 3.0085370633006945e-06,
1415
+ "loss": 0.5065449714660645,
1416
+ "step": 875,
1417
+ "token_acc": 0.8717948717948718
1418
+ },
1419
+ {
1420
+ "epoch": 0.995053003533569,
1421
+ "grad_norm": 12.8125,
1422
+ "learning_rate": 3.0016864761392417e-06,
1423
+ "loss": 0.5106320858001709,
1424
+ "step": 880,
1425
+ "token_acc": 0.874031007751938
1426
+ }
1427
+ ],
1428
+ "logging_steps": 5,
1429
+ "max_steps": 884,
1430
+ "num_input_tokens_seen": 0,
1431
+ "num_train_epochs": 1,
1432
+ "save_steps": 200,
1433
+ "stateful_callbacks": {
1434
+ "TrainerControl": {
1435
+ "args": {
1436
+ "should_epoch_stop": false,
1437
+ "should_evaluate": false,
1438
+ "should_log": false,
1439
+ "should_save": true,
1440
+ "should_training_stop": true
1441
+ },
1442
+ "attributes": {}
1443
+ }
1444
+ },
1445
+ "total_flos": 6.272720385457565e+17,
1446
+ "train_batch_size": 4,
1447
+ "trial_name": null,
1448
+ "trial_params": null
1449
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:046f76cf1cc1ef8e176a3d3d47a44960a7c80058f6c2ac992f5029250a9491f5
3
+ size 7377