GuoruiSong commited on
Commit
f01711d
·
verified ·
1 Parent(s): 6c2c0d5

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step10.json +0 -0
  2. rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step6.json +0 -0
  3. rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step9.json +0 -0
  4. rl_lladav_video_reversal_wo_ub_reward/config.yaml +102 -0
  5. rl_lladav_video_reversal_wo_ub_reward/results/all_rewards.csv +62 -0
  6. rl_lladav_video_reversal_wo_ub_reward/results/results-eval-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train.txt +0 -0
  7. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step10.txt +2 -0
  8. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step11.txt +2 -0
  9. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step12.txt +2 -0
  10. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step13.txt +2 -0
  11. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step14.txt +2 -0
  12. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step16.txt +2 -0
  13. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step17.txt +2 -0
  14. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step18.txt +2 -0
  15. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step19.txt +2 -0
  16. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step20.txt +2 -0
  17. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step21.txt +2 -0
  18. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step23.txt +2 -0
  19. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step24.txt +2 -0
  20. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step25.txt +2 -0
  21. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step27.txt +2 -0
  22. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step28.txt +2 -0
  23. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step3.txt +2 -0
  24. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step30.txt +2 -0
  25. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step4.txt +2 -0
  26. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step5.txt +2 -0
  27. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step6.txt +2 -0
  28. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step7.txt +2 -0
  29. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step8.txt +2 -0
  30. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step9.txt +2 -0
  31. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train.txt +0 -0
  32. rl_lladav_video_reversal_wo_ub_reward/results/results-rl-.data4.runqing.dLLM-RL.sft_lladav_video_reversal_3_21.ckpt.optimized-video_reversal_rl_train-step1.txt +2 -0
  33. train/eval_lavida_revvideo.py +390 -0
  34. train/eval_llava_next_revvideo.py +325 -0
  35. train/init_lladav_value_model.py +164 -0
  36. train/init_mmada_v_value_model.py +162 -0
  37. train/init_sdar_value_model.py +194 -0
  38. train/init_trado_value_model.py +194 -0
  39. train/llava/__init__.py +0 -0
  40. train/llava/cache/Cache.py +83 -0
  41. train/llava/cache/Config.py +9 -0
  42. train/llava/cache/__init__.py +4 -0
  43. train/llava/constants.py +12 -0
  44. train/llava/conversation.py +624 -0
  45. train/llava/hooks/__init__.py +6 -0
  46. train/llava/hooks/cache_hook_LLaDA_V.py +619 -0
  47. train/llava/hooks/fast_dllm_hook.py +507 -0
  48. train/llava/mm_utils.py +396 -0
  49. train/llava/model/__init__.py +11 -0
  50. train/llava/model/apply_delta.py +47 -0
rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step10.json ADDED
The diff for this file is too large to render. See raw diff
 
rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step6.json ADDED
The diff for this file is too large to render. See raw diff
 
rl_lavida_revvideo_orig10k_4gpu_len128/temp_data/outputs-rl-...rl_lavida_revvideo_orig10k_4gpu_len128.ckpt.optimized-video_reversal_sft_train_cleaned_10k-step9.json ADDED
The diff for this file is too large to render. See raw diff
 
rl_lladav_video_reversal_wo_ub_reward/config.yaml ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ wandb:
2
+ entity: null
3
+ resume: auto
4
+ run_id: lzqtg4q4
5
+ system:
6
+ HTTP_PROXY: null
7
+ HF_HOME: null
8
+ env_name: /data8/runqing/miniconda/envs/dllm-rl
9
+ envs_dir: /data8/runqing/miniconda/envs/dllm-rl
10
+ base_dir: /data4/runqing/dLLM-RL
11
+ experiment:
12
+ project: rl_lladav_video_reversal_wo_ub_reward
13
+ function: train
14
+ start_from_scratch: true
15
+ total_step: 30
16
+ save_every: 10
17
+ eval_every: 5
18
+ current_epoch: 30
19
+ deepspeed_file: 1_node_8_gpus_deepspeed_zero2_rl
20
+ num_node: 1
21
+ node_index: 0
22
+ logging_dir: rl_lladav_video_reversal_wo_ub_reward/logs
23
+ model:
24
+ pretrained_model: /data4/runqing/dLLM-RL/sft_lladav_video_reversal_3_21/ckpt/optimized
25
+ optimized_name: optimized
26
+ model_base: lladav
27
+ vq_model_path: /data4/runqing/hf/magvitv2
28
+ image_resolution: 512
29
+ dataset:
30
+ train_dataset: video_reversal_rl_train
31
+ data_type: video_reverse
32
+ optimization_data: rl_data
33
+ rollout:
34
+ num_task_per_step: 128
35
+ num_response_per_task: 8
36
+ temperature: 0.8
37
+ steps: 128
38
+ max_gen_length: 128
39
+ batch_size: 1
40
+ remasking_strategy: low_confidence_dynamic
41
+ target: confidence
42
+ dynamic_threshold: 0.9
43
+ block_size: 32
44
+ further_horizon: 128
45
+ use_cache: true
46
+ reward:
47
+ answer_must_in_box: true
48
+ strict_len_check: false
49
+ execute:
50
+ num_chunk: 128
51
+ training:
52
+ gradient_accumulation_steps: 2
53
+ batch_size_lm: 1
54
+ mixed_precision: bf16
55
+ enable_tf32: true
56
+ seed: 10086
57
+ num_train_epochs: 1
58
+ max_grad_norm: 1.0
59
+ method: random_masking
60
+ lower_p: 0.35
61
+ upper_p: 0.9
62
+ shrink: 8
63
+ post_num: 1
64
+ mask_times_per_sample: 2
65
+ max_gen_length: ${rollout.max_gen_length}
66
+ max_prompt_len: 512
67
+ eps: 0.2
68
+ beta: 0.01
69
+ use_kl_estimator_k3: true
70
+ optimizer:
71
+ name: adamw
72
+ params:
73
+ learning_rate: 1.0e-06
74
+ scale_lr: false
75
+ beta1: 0.9
76
+ beta2: 0.999
77
+ weight_decay: 0.0
78
+ epsilon: 1.0e-08
79
+ lr_scheduler:
80
+ scheduler: cosine
81
+ params:
82
+ learning_rate: ${optimizer.params.learning_rate}
83
+ warmup_steps: 0
84
+ min_lr_scale: 1.0
85
+ evaluation:
86
+ if_eval: false
87
+ eval_dataset: video_reversal_rl_eval
88
+ data_type: video_reverse
89
+ num_response_per_task: 3
90
+ temperature: 0.1
91
+ steps: 128
92
+ max_gen_length: 128
93
+ batch_size: 1
94
+ remasking_strategy:
95
+ - low_confidence_static
96
+ - low_confidence_dynamic
97
+ target: confidence
98
+ dynamic_threshold: 0.9
99
+ block_size: 32
100
+ further_horizon: 128
101
+ use_cache: true
102
+ config: configs/rl_lladav_video_reversal_wo_ub_reward.yaml
rl_lladav_video_reversal_wo_ub_reward/results/all_rewards.csv ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ step,acc_reward,t_grpo_reward,unbiased_reward,response_length
2
+ 1,0.5293,0.2578,0.0000,128.00
3
+ step,acc_reward,t_grpo_reward,unbiased_reward,response_length
4
+ 1,0.5293,0.2578,0.0000,128.00
5
+ 2,0.5762,0.2672,0.0000,127.99
6
+ 2,0.5762,0.2672,0.0000,127.99
7
+ 3,0.5254,0.2625,0.0000,128.00
8
+ 3,0.5254,0.2625,0.0000,128.00
9
+ 4,0.5566,0.2484,0.0000,127.99
10
+ 4,0.5566,0.2484,0.0000,127.99
11
+ 5,0.5098,0.2344,0.0000,128.00
12
+ 5,0.5098,0.2344,0.0000,128.00
13
+ 6,0.6113,0.2578,0.0000,128.00
14
+ 6,0.6113,0.2578,0.0000,128.00
15
+ 7,0.6113,0.2578,0.0000,127.99
16
+ 7,0.6113,0.2578,0.0000,127.99
17
+ 8,0.5566,0.2438,0.0000,127.99
18
+ 8,0.5566,0.2438,0.0000,127.99
19
+ 9,0.5801,0.2250,0.0000,127.93
20
+ 9,0.5801,0.2250,0.0000,127.93
21
+ 10,0.5898,0.2297,0.0000,128.00
22
+ 10,0.5898,0.2297,0.0000,128.00
23
+ 11,0.5469,0.2438,0.0000,128.00
24
+ 11,0.5469,0.2438,0.0000,128.00
25
+ 12,0.5840,0.2531,0.0000,128.00
26
+ 12,0.5840,0.2531,0.0000,128.00
27
+ 13,0.6387,0.2625,0.0000,128.00
28
+ 13,0.6387,0.2625,0.0000,128.00
29
+ 14,0.4512,0.2438,0.0000,127.99
30
+ 14,0.4512,0.2438,0.0000,127.99
31
+ 15,0.5645,0.2578,0.0000,127.99
32
+ 15,0.5645,0.2578,0.0000,127.99
33
+ 16,0.5762,0.2672,0.0000,127.99
34
+ 16,0.5762,0.2672,0.0000,127.99
35
+ 17,0.5664,0.2672,0.0000,128.00
36
+ 17,0.5664,0.2672,0.0000,128.00
37
+ 18,0.5391,0.2484,0.0000,128.00
38
+ 18,0.5391,0.2484,0.0000,128.00
39
+ 19,0.4863,0.2250,0.0000,128.00
40
+ 19,0.4863,0.2250,0.0000,128.00
41
+ 20,0.4902,0.2531,0.0000,128.00
42
+ 20,0.4902,0.2531,0.0000,128.00
43
+ 21,0.5449,0.2625,0.0000,127.99
44
+ 21,0.5449,0.2625,0.0000,127.99
45
+ 22,0.5410,0.2484,0.0000,128.00
46
+ 22,0.5410,0.2484,0.0000,128.00
47
+ 23,0.5840,0.2484,0.0000,127.99
48
+ 23,0.5840,0.2484,0.0000,127.99
49
+ 24,0.5039,0.2391,0.0000,127.99
50
+ 24,0.5039,0.2391,0.0000,127.99
51
+ 25,0.5723,0.2531,0.0000,128.00
52
+ 25,0.5723,0.2531,0.0000,128.00
53
+ 26,0.6133,0.2531,0.0000,127.99
54
+ 26,0.6133,0.2531,0.0000,127.99
55
+ 27,0.5039,0.2531,0.0000,127.99
56
+ 27,0.5039,0.2531,0.0000,127.99
57
+ 28,0.5000,0.2484,0.0000,128.00
58
+ 28,0.5000,0.2484,0.0000,128.00
59
+ 29,0.5449,0.2391,0.0000,127.99
60
+ 29,0.5449,0.2391,0.0000,127.99
61
+ 30,0.5684,0.2672,0.0000,127.99
62
+ 30,0.5684,0.2672,0.0000,127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-eval-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train.txt ADDED
File without changes
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step10.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 10 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5898 avg length: 128.00
2
+ train step: 10 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5898 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step11.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 11 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5469 avg length: 128.00
2
+ train step: 11 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5469 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step12.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 12 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5840 avg length: 128.00
2
+ train step: 12 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5840 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step13.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 13 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6387 avg length: 128.00
2
+ train step: 13 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6387 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step14.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 14 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4512 avg length: 127.99
2
+ train step: 14 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4512 avg length: 127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step16.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 16 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5762 avg length: 127.99
2
+ train step: 16 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5762 avg length: 127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step17.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 17 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5664 avg length: 128.00
2
+ train step: 17 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5664 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step18.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 18 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5391 avg length: 128.00
2
+ train step: 18 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5391 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step19.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 19 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4863 avg length: 128.00
2
+ train step: 19 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4863 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step20.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 20 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4902 avg length: 128.00
2
+ train step: 20 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.4902 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step21.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 21 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5449 avg length: 127.99
2
+ train step: 21 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5449 avg length: 127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step23.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 23 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5840 avg length: 127.99
2
+ train step: 23 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5840 avg length: 127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step24.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 24 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5039 avg length: 127.99
2
+ train step: 24 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5039 avg length: 127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step25.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 25 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5723 avg length: 128.00
2
+ train step: 25 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5723 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step27.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 27 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5039 avg length: 127.99
2
+ train step: 27 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5039 avg length: 127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step28.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 28 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5000 avg length: 128.00
2
+ train step: 28 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5000 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step3.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 3 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5254 avg length: 128.00
2
+ train step: 3 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5254 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step30.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 30 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5684 avg length: 127.99
2
+ train step: 30 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5684 avg length: 127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step4.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 4 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5566 avg length: 127.99
2
+ train step: 4 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5566 avg length: 127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step5.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 5 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5098 avg length: 128.00
2
+ train step: 5 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5098 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step6.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 6 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6113 avg length: 128.00
2
+ train step: 6 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6113 avg length: 128.00
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step7.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 7 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6113 avg length: 127.99
2
+ train step: 7 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.6113 avg length: 127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step8.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 8 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5566 avg length: 127.99
2
+ train step: 8 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5566 avg length: 127.99
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train-step9.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 9 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5801 avg length: 127.93
2
+ train step: 9 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5801 avg length: 127.93
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-...rl_lladav_video_reversal_wo_ub_reward.ckpt.optimized-video_reversal_rl_train.txt ADDED
File without changes
rl_lladav_video_reversal_wo_ub_reward/results/results-rl-.data4.runqing.dLLM-RL.sft_lladav_video_reversal_3_21.ckpt.optimized-video_reversal_rl_train-step1.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ train step: 1 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5293 avg length: 128.00
2
+ train step: 1 remasking_strategy: low_confidence_dynamic block_size: 32 acc: 0.5293 avg length: 128.00
train/eval_lavida_revvideo.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import math
4
+ import os
5
+ import random
6
+ import re
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ os.environ.setdefault("HF_HUB_OFFLINE", "1")
11
+ os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
12
+ os.environ.setdefault("HF_DATASETS_OFFLINE", "1")
13
+
14
+ import torch
15
+ from transformers import AutoConfig
16
+
17
+ try:
18
+ from decord import VideoReader, cpu
19
+ except ImportError:
20
+ VideoReader = None
21
+ cpu = None
22
+ try:
23
+ import cv2
24
+ except ImportError:
25
+ cv2 = None
26
+
27
+
28
+ REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29
+ LAVIDA_ROOT = os.path.join(REPO_ROOT, "LaViDa")
30
+ sys.path.insert(0, LAVIDA_ROOT)
31
+ sys.path.insert(1, REPO_ROOT)
32
+
33
+ from llava.constants import DEFAULT_IMAGE_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, IMAGE_TOKEN_INDEX
34
+ from llava.conversation import SeparatorStyle, conv_templates
35
+ from llava.mm_utils import KeywordsStoppingCriteria, tokenizer_image_token
36
+ from llava.model.builder import load_pretrained_model
37
+
38
+
39
+ SYS_PROMPT = (
40
+ "Carefully watch the video and pay attention to the cause and sequence of events, "
41
+ "the detail and movement of objects, and the action and pose of persons. "
42
+ "Based on your observations, select the best option that accurately addresses the question.\n"
43
+ )
44
+ QUESTION_PROMPT = "\nOnly give the best option."
45
+ MCQ_PROMPT = " Please provide only the single option letter (e.g., A, B, C, D, etc.) within the <answer> </answer> tags."
46
+ LETTER_RE = re.compile(r"<answer>\s*([A-Z])\s*</answer>|(?:^|[^A-Z])([A-Z])(?:[\.\)\s]|$)")
47
+
48
+
49
+ def parse_args():
50
+ parser = argparse.ArgumentParser()
51
+ parser.add_argument("--model-path", required=True)
52
+ parser.add_argument("--dataset-json", default="/data4/runqing/dLLM-RL/data/video_reversal_sft_test.json")
53
+ parser.add_argument("--output-dir", required=True)
54
+ parser.add_argument("--device", default="cuda:1")
55
+ parser.add_argument("--device-map", default=None)
56
+ parser.add_argument("--conv-mode", default="llada")
57
+ parser.add_argument("--max-samples", type=int, default=None)
58
+ parser.add_argument("--start-index", type=int, default=0)
59
+ parser.add_argument("--frames", type=int, default=16)
60
+ parser.add_argument("--force-sample", action="store_true")
61
+ parser.add_argument("--mm-spatial-pool-stride", type=int, default=4)
62
+ parser.add_argument("--mm-spatial-pool-mode", default="average")
63
+ parser.add_argument("--mm-newline-position", default="grid")
64
+ parser.add_argument("--temperature", type=float, default=0.0)
65
+ parser.add_argument("--max-new-tokens", type=int, default=12)
66
+ parser.add_argument("--block-length", type=int, default=12)
67
+ parser.add_argument("--step-per-block", type=int, default=4)
68
+ parser.add_argument("--top-p", type=float, default=0.1)
69
+ parser.add_argument("--num-beams", type=int, default=1)
70
+ parser.add_argument("--use-tvcd", action="store_true")
71
+ parser.add_argument("--cd-alpha", type=float, default=1.0)
72
+ parser.add_argument("--cd-beta", type=float, default=0.1)
73
+ parser.add_argument("--tvcd-shuffle-seed", type=int, default=42)
74
+ parser.add_argument("--resume", action="store_true")
75
+ return parser.parse_args()
76
+
77
+
78
+ def load_video(video_path, frames_num, force_sample):
79
+ if VideoReader is not None:
80
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
81
+ total_frame_num = len(vr)
82
+ fps = max(1, round(vr.get_avg_fps()))
83
+ frame_idx = [i for i in range(0, total_frame_num, fps)]
84
+ if len(frame_idx) > frames_num or force_sample:
85
+ frame_idx = np_linspace_int(0, total_frame_num - 1, frames_num)
86
+ return vr.get_batch(frame_idx).asnumpy()
87
+
88
+ if cv2 is None:
89
+ raise RuntimeError("Neither decord nor cv2 is available for video decoding.")
90
+ cap = cv2.VideoCapture(video_path)
91
+ total_frame_num = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
92
+ fps = cap.get(cv2.CAP_PROP_FPS)
93
+ fps = max(1, round(fps if fps and fps > 0 else 1))
94
+ frame_idx = [i for i in range(0, max(total_frame_num, 1), fps)]
95
+ if len(frame_idx) > frames_num or force_sample:
96
+ frame_idx = np_linspace_int(0, max(total_frame_num - 1, 0), frames_num)
97
+
98
+ wanted = set(frame_idx)
99
+ frames = []
100
+ idx = 0
101
+ while True:
102
+ ok, frame = cap.read()
103
+ if not ok:
104
+ break
105
+ if idx in wanted:
106
+ frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
107
+ idx += 1
108
+ cap.release()
109
+ if not frames:
110
+ raise RuntimeError(f"Failed to decode video: {video_path}")
111
+ return frames
112
+
113
+
114
+ def np_linspace_int(start, end, count):
115
+ if count <= 1:
116
+ return [start]
117
+ step = (end - start) / (count - 1)
118
+ return [int(round(start + i * step)) for i in range(count)]
119
+
120
+
121
+ def shuffle_video_tensor(video_tensor, seed):
122
+ if video_tensor.ndim < 1 or video_tensor.shape[0] <= 1:
123
+ return video_tensor.clone()
124
+ generator = torch.Generator(device="cpu").manual_seed(int(seed))
125
+ perm = torch.randperm(video_tensor.shape[0], generator=generator)
126
+ return video_tensor[perm.to(video_tensor.device)]
127
+
128
+
129
+ def build_prompt(sample):
130
+ return (
131
+ SYS_PROMPT
132
+ + "Question: "
133
+ + sample["prompt"]
134
+ + "Options: "
135
+ + str(sample["options"])
136
+ + QUESTION_PROMPT
137
+ + MCQ_PROMPT
138
+ )
139
+
140
+
141
+ def extract_letter(text):
142
+ if not text:
143
+ return None
144
+ match = LETTER_RE.search(text.strip().upper())
145
+ if not match:
146
+ return None
147
+ return match.group(1) or match.group(2)
148
+
149
+
150
+ def clean_generation_text(text):
151
+ if text is None:
152
+ return None
153
+ text = text.lstrip("!").strip()
154
+ return text
155
+
156
+
157
+ def load_samples(path, start_index, max_samples):
158
+ with open(path) as f:
159
+ data = json.load(f)
160
+ if start_index:
161
+ data = data[start_index:]
162
+ if max_samples is not None:
163
+ data = data[:max_samples]
164
+ return data
165
+
166
+
167
+ def maybe_load_done_ids(path):
168
+ done = set()
169
+ if not os.path.exists(path):
170
+ return done
171
+ with open(path) as f:
172
+ for line in f:
173
+ if not line.strip():
174
+ continue
175
+ try:
176
+ row = json.loads(line)
177
+ done.add(int(row["sample_idx"]))
178
+ except Exception:
179
+ continue
180
+ return done
181
+
182
+
183
+ def main():
184
+ args = parse_args()
185
+ print(f"[eval] args={vars(args)}", flush=True)
186
+ torch.backends.cuda.matmul.allow_tf32 = True
187
+ if hasattr(torch.backends, "cudnn"):
188
+ torch.backends.cudnn.allow_tf32 = True
189
+
190
+ os.makedirs(args.output_dir, exist_ok=True)
191
+ print(f"[eval] output_dir={args.output_dir}", flush=True)
192
+ pred_path = os.path.join(args.output_dir, "predictions.jsonl")
193
+ summary_path = os.path.join(args.output_dir, "summary.json")
194
+
195
+ model_name = "llava_llada"
196
+ overwrite_config = {
197
+ "mm_spatial_pool_mode": args.mm_spatial_pool_mode,
198
+ "mm_spatial_pool_stride": args.mm_spatial_pool_stride,
199
+ "mm_newline_position": args.mm_newline_position,
200
+ }
201
+
202
+ cfg_pretrained = AutoConfig.from_pretrained(args.model_path)
203
+ if "qwen" not in args.model_path.lower():
204
+ if hasattr(cfg_pretrained, "mm_vision_tower") and "224" in cfg_pretrained.mm_vision_tower:
205
+ least_token_number = args.frames * (16 // args.mm_spatial_pool_stride) ** 2 + 1000
206
+ else:
207
+ least_token_number = args.frames * (24 // args.mm_spatial_pool_stride) ** 2 + 1000
208
+ scaling_factor = math.ceil(least_token_number / 4096)
209
+ if scaling_factor >= 2:
210
+ if getattr(cfg_pretrained, "_name_or_path", "") and "vicuna" in cfg_pretrained._name_or_path.lower():
211
+ overwrite_config["rope_scaling"] = {"factor": float(scaling_factor), "type": "linear"}
212
+ overwrite_config["max_sequence_length"] = 4096 * scaling_factor
213
+ overwrite_config["tokenizer_model_max_length"] = 4096 * scaling_factor
214
+
215
+ load_device_map = args.device_map if args.device_map is not None else None
216
+ print(f"[eval] loading model from {args.model_path} with device_map={load_device_map}", flush=True)
217
+ tokenizer, model, image_processor, _ = load_pretrained_model(
218
+ args.model_path,
219
+ None,
220
+ model_name,
221
+ multimodal=True,
222
+ device_map=load_device_map,
223
+ torch_dtype="bfloat16",
224
+ overwrite_config=overwrite_config,
225
+ )
226
+ if args.device_map is None:
227
+ device = torch.device(args.device)
228
+ model = model.to(device)
229
+ else:
230
+ device = torch.device(args.device)
231
+ model = model.eval()
232
+ print("[eval] model loaded", flush=True)
233
+
234
+ if getattr(model.config, "force_sample", None) is not None:
235
+ args.force_sample = bool(model.config.force_sample)
236
+
237
+ samples = load_samples(args.dataset_json, args.start_index, args.max_samples)
238
+ print(f"[eval] loaded {len(samples)} samples from {args.dataset_json}", flush=True)
239
+ done_ids = maybe_load_done_ids(pred_path) if args.resume else set()
240
+
241
+ total = 0
242
+ baseline_correct = 0
243
+ tvcd_correct = 0
244
+ rng = random.Random(args.tvcd_shuffle_seed)
245
+
246
+ if done_ids:
247
+ with open(pred_path) as f:
248
+ for line in f:
249
+ if not line.strip():
250
+ continue
251
+ row = json.loads(line)
252
+ if row.get("baseline_correct"):
253
+ baseline_correct += 1
254
+ if row.get("tvcd_correct"):
255
+ tvcd_correct += 1
256
+ total += 1
257
+
258
+ with open(pred_path, "a", buffering=1) as fout:
259
+ for offset, sample in enumerate(samples):
260
+ sample_idx = args.start_index + offset
261
+ if sample_idx in done_ids:
262
+ continue
263
+ print(
264
+ f"[eval] sample_idx={sample_idx} reversal_type={sample.get('reversal_type')} "
265
+ f"video={sample.get('video_abs_path')}",
266
+ flush=True,
267
+ )
268
+
269
+ prompt = build_prompt(sample)
270
+ qs = prompt
271
+ if model.config.mm_use_im_start_end:
272
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + "\n" + qs
273
+ else:
274
+ qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
275
+
276
+ conv = conv_templates[args.conv_mode].copy()
277
+ if getattr(conv, "tokenizer", None) is None:
278
+ conv.tokenizer = tokenizer
279
+ conv.append_message(conv.roles[0], qs)
280
+ conv.append_message(conv.roles[1], None)
281
+ full_prompt = conv.get_prompt()
282
+
283
+ input_ids = tokenizer_image_token(full_prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device)
284
+ if tokenizer.pad_token_id is None and "qwen" in (tokenizer.name_or_path or "").lower():
285
+ tokenizer.pad_token_id = 151643
286
+ pad_token_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id
287
+ attention_mask = input_ids.ne(pad_token_id).long().to(device)
288
+
289
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
290
+ stopping_criteria = KeywordsStoppingCriteria([stop_str], tokenizer, input_ids)
291
+
292
+ frames = load_video(sample["video_abs_path"], args.frames, args.force_sample)
293
+ video_tensor = image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].to(device=device, dtype=torch.bfloat16)
294
+ video = [video_tensor]
295
+ video_cd = None
296
+ if args.use_tvcd:
297
+ video_cd = [shuffle_video_tensor(video_tensor, seed=rng.randint(0, 2**31 - 1))]
298
+
299
+ gen_kwargs = dict(
300
+ inputs=input_ids,
301
+ images=video,
302
+ attention_mask=attention_mask,
303
+ modalities="video",
304
+ do_sample=False,
305
+ temperature=args.temperature,
306
+ max_new_tokens=args.max_new_tokens,
307
+ block_length=args.block_length,
308
+ step_per_block=args.step_per_block,
309
+ top_p=args.top_p,
310
+ num_beams=args.num_beams,
311
+ use_cache=True,
312
+ stopping_criteria=[stopping_criteria],
313
+ )
314
+
315
+ with torch.inference_mode():
316
+ baseline_ids = model.generate(**gen_kwargs)
317
+ baseline_text = clean_generation_text(tokenizer.batch_decode(baseline_ids, skip_special_tokens=True)[0])
318
+ print(f"[eval] sample_idx={sample_idx} baseline={baseline_text}", flush=True)
319
+
320
+ tvcd_text = None
321
+ if args.use_tvcd:
322
+ tvcd_ids = model.generate(
323
+ **gen_kwargs,
324
+ images_cd=video_cd,
325
+ cd_alpha=args.cd_alpha,
326
+ cd_beta=args.cd_beta,
327
+ )
328
+ tvcd_text = clean_generation_text(tokenizer.batch_decode(tvcd_ids, skip_special_tokens=True)[0])
329
+ print(f"[eval] sample_idx={sample_idx} tvcd={tvcd_text}", flush=True)
330
+
331
+ gt_letter = extract_letter(sample["response"])
332
+ baseline_letter = extract_letter(baseline_text)
333
+ tvcd_letter = extract_letter(tvcd_text) if tvcd_text is not None else None
334
+
335
+ baseline_hit = baseline_letter == gt_letter
336
+ tvcd_hit = tvcd_letter == gt_letter if tvcd_text is not None else None
337
+
338
+ total += 1
339
+ baseline_correct += int(baseline_hit)
340
+ if tvcd_hit is True:
341
+ tvcd_correct += 1
342
+
343
+ row = {
344
+ "sample_idx": sample_idx,
345
+ "data_id": sample.get("data_id"),
346
+ "reversal_type": sample.get("reversal_type"),
347
+ "video_abs_path": sample.get("video_abs_path"),
348
+ "gt_response": sample.get("response"),
349
+ "gt_letter": gt_letter,
350
+ "baseline_text": baseline_text,
351
+ "baseline_letter": baseline_letter,
352
+ "baseline_correct": baseline_hit,
353
+ "tvcd_text": tvcd_text,
354
+ "tvcd_letter": tvcd_letter,
355
+ "tvcd_correct": tvcd_hit,
356
+ }
357
+ fout.write(json.dumps(row, ensure_ascii=False) + "\n")
358
+
359
+ if total % 10 == 0:
360
+ summary = {
361
+ "samples_done": total,
362
+ "baseline_acc": baseline_correct / total,
363
+ "tvcd_acc": (tvcd_correct / total) if args.use_tvcd else None,
364
+ "model_path": args.model_path,
365
+ "dataset_json": args.dataset_json,
366
+ "use_tvcd": args.use_tvcd,
367
+ "cd_alpha": args.cd_alpha if args.use_tvcd else None,
368
+ "cd_beta": args.cd_beta if args.use_tvcd else None,
369
+ }
370
+ with open(summary_path, "w") as f:
371
+ json.dump(summary, f, indent=2, ensure_ascii=False)
372
+ print(summary, flush=True)
373
+
374
+ summary = {
375
+ "samples_done": total,
376
+ "baseline_acc": baseline_correct / total if total else 0.0,
377
+ "tvcd_acc": (tvcd_correct / total) if args.use_tvcd and total else None,
378
+ "model_path": args.model_path,
379
+ "dataset_json": args.dataset_json,
380
+ "use_tvcd": args.use_tvcd,
381
+ "cd_alpha": args.cd_alpha if args.use_tvcd else None,
382
+ "cd_beta": args.cd_beta if args.use_tvcd else None,
383
+ }
384
+ with open(summary_path, "w") as f:
385
+ json.dump(summary, f, indent=2, ensure_ascii=False)
386
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
387
+
388
+
389
+ if __name__ == "__main__":
390
+ main()
train/eval_llava_next_revvideo.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import math
4
+ import os
5
+ import random
6
+ import re
7
+ import sys
8
+
9
+ os.environ.setdefault("HF_HUB_OFFLINE", "1")
10
+ os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
11
+ os.environ.setdefault("HF_DATASETS_OFFLINE", "1")
12
+
13
+ import torch
14
+ from transformers import AutoConfig
15
+
16
+ REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
+ LLAVA_NEXT_ROOT = os.path.join(REPO_ROOT, "LLaVA-NeXT")
18
+ sys.path.insert(0, LLAVA_NEXT_ROOT)
19
+ sys.path.insert(1, REPO_ROOT)
20
+
21
+ from llava.constants import DEFAULT_IMAGE_TOKEN, IMAGE_TOKEN_INDEX
22
+ from llava.conversation import conv_templates
23
+ from llava.mm_utils import tokenizer_image_token, get_model_name_from_path
24
+ from llava.model.builder import load_pretrained_model
25
+ from llava.utils import process_video_with_decord
26
+ from train.llava_next_video.common import build_video_mcq_prompt, resolve_media_abs_path
27
+
28
+
29
+ SYS_PROMPT = (
30
+ "Carefully watch the video and pay attention to the cause and sequence of events, "
31
+ "the detail and movement of objects, and the action and pose of persons. "
32
+ "Based on your observations, select the best option that accurately addresses the question.\n"
33
+ )
34
+ QUESTION_PROMPT = "\nOnly give the best option."
35
+ MCQ_PROMPT = " Please provide only the single option letter (e.g., A, B, C, D, etc.) within the <answer> </answer> tags."
36
+ LETTER_RE = re.compile(r"<answer>\s*([A-Z])\s*</answer>|(?:^|[^A-Z])([A-Z])(?:[\.\)\s]|$)")
37
+
38
+
39
+ def parse_args():
40
+ parser = argparse.ArgumentParser()
41
+ parser.add_argument("--model-path", required=True)
42
+ parser.add_argument("--dataset-json", default="/data4/runqing/dLLM-RL/data/video_reversal_sft_test.json")
43
+ parser.add_argument("--output-dir", required=True)
44
+ parser.add_argument("--device", default="cuda:0")
45
+ parser.add_argument("--conv-mode", default="vicuna_v1")
46
+ parser.add_argument("--max-samples", type=int, default=None)
47
+ parser.add_argument("--start-index", type=int, default=0)
48
+ parser.add_argument("--frames", type=int, default=16)
49
+ parser.add_argument("--force-sample", action="store_true")
50
+ parser.add_argument("--mm-spatial-pool-stride", type=int, default=2)
51
+ parser.add_argument("--mm-spatial-pool-mode", default="average")
52
+ parser.add_argument("--mm-newline-position", default=None)
53
+ parser.add_argument("--temperature", type=float, default=0.0)
54
+ parser.add_argument("--max-new-tokens", type=int, default=12)
55
+ parser.add_argument("--top-p", type=float, default=0.1)
56
+ parser.add_argument("--num-beams", type=int, default=1)
57
+ parser.add_argument("--use-tvcd", action="store_true")
58
+ parser.add_argument("--cd-alpha", type=float, default=1.0)
59
+ parser.add_argument("--cd-beta", type=float, default=0.1)
60
+ parser.add_argument("--tvcd-shuffle-seed", type=int, default=42)
61
+ parser.add_argument("--resume", action="store_true")
62
+ return parser.parse_args()
63
+
64
+
65
+ def shuffle_video_tensor(video_tensor, seed):
66
+ if video_tensor.ndim < 1 or video_tensor.shape[0] <= 1:
67
+ return video_tensor.clone()
68
+ generator = torch.Generator(device="cpu").manual_seed(int(seed))
69
+ perm = torch.randperm(video_tensor.shape[0], generator=generator)
70
+ return video_tensor[perm.to(video_tensor.device)]
71
+
72
+
73
+ def load_video_inputs(video_path, image_processor, model_cfg, device):
74
+ video, video_time, frame_time, num_frames_to_sample = process_video_with_decord(video_path, model_cfg)
75
+ video_tensor = image_processor.preprocess(video, return_tensors="pt")["pixel_values"].to(device=device, dtype=torch.bfloat16)
76
+ return [video_tensor], [video[0].size], video_time, frame_time, num_frames_to_sample
77
+
78
+
79
+ def clean_generation_text(text):
80
+ if text is None:
81
+ return None
82
+ return text.lstrip("!").strip()
83
+
84
+
85
+ def extract_letter(text):
86
+ if not text:
87
+ return None
88
+ match = LETTER_RE.search(text.strip().upper())
89
+ if not match:
90
+ return None
91
+ return match.group(1) or match.group(2)
92
+
93
+
94
+ def load_samples(path, start_index, max_samples):
95
+ with open(path) as f:
96
+ data = json.load(f)
97
+ if start_index:
98
+ data = data[start_index:]
99
+ if max_samples is not None:
100
+ data = data[:max_samples]
101
+ return data
102
+
103
+
104
+ def maybe_load_done_ids(path):
105
+ done = set()
106
+ if not os.path.exists(path):
107
+ return done
108
+ with open(path) as f:
109
+ for line in f:
110
+ if not line.strip():
111
+ continue
112
+ try:
113
+ done.add(int(json.loads(line)["sample_idx"]))
114
+ except Exception:
115
+ continue
116
+ return done
117
+
118
+
119
+ def extract_generated_ids(output_ids, prompt_ids):
120
+ if output_ids.shape[1] > prompt_ids.shape[1]:
121
+ return output_ids[:, prompt_ids.shape[1] :]
122
+ return output_ids
123
+
124
+
125
+ def main():
126
+ args = parse_args()
127
+ print(f"[eval] args={vars(args)}", flush=True)
128
+ torch.backends.cuda.matmul.allow_tf32 = True
129
+ if hasattr(torch.backends, "cudnn"):
130
+ torch.backends.cudnn.allow_tf32 = True
131
+
132
+ os.makedirs(args.output_dir, exist_ok=True)
133
+ pred_path = os.path.join(args.output_dir, "predictions.jsonl")
134
+ summary_path = os.path.join(args.output_dir, "summary.json")
135
+ print(f"[eval] output_dir={args.output_dir}", flush=True)
136
+
137
+ model_name = get_model_name_from_path(args.model_path)
138
+ cfg_pretrained = AutoConfig.from_pretrained(args.model_path, local_files_only=True)
139
+ overwrite_config = {
140
+ "mm_spatial_pool_mode": args.mm_spatial_pool_mode,
141
+ "mm_spatial_pool_stride": args.mm_spatial_pool_stride,
142
+ "mm_newline_position": args.mm_newline_position or getattr(cfg_pretrained, "mm_newline_position", "grid"),
143
+ }
144
+ if "qwen" not in args.model_path.lower():
145
+ if hasattr(cfg_pretrained, "mm_vision_tower") and "224" in cfg_pretrained.mm_vision_tower:
146
+ least_token_number = args.frames * (16 // args.mm_spatial_pool_stride) ** 2 + 1000
147
+ else:
148
+ least_token_number = args.frames * (24 // args.mm_spatial_pool_stride) ** 2 + 1000
149
+ scaling_factor = math.ceil(least_token_number / 4096)
150
+ if scaling_factor >= 2:
151
+ if "vicuna" in str(getattr(cfg_pretrained, "_name_or_path", "")).lower():
152
+ overwrite_config["rope_scaling"] = {"factor": float(scaling_factor), "type": "linear"}
153
+ overwrite_config["max_sequence_length"] = 4096 * scaling_factor
154
+ overwrite_config["tokenizer_model_max_length"] = 4096 * scaling_factor
155
+
156
+ print(f"[eval] loading model from {args.model_path}", flush=True)
157
+ tokenizer, model, image_processor, _ = load_pretrained_model(
158
+ args.model_path,
159
+ None,
160
+ model_name,
161
+ multimodal=True,
162
+ device_map=None,
163
+ torch_dtype="bfloat16",
164
+ overwrite_config=overwrite_config,
165
+ )
166
+ device = torch.device(args.device)
167
+ model = model.to(device).eval()
168
+ print("[eval] model loaded", flush=True)
169
+
170
+ if getattr(model.config, "force_sample", None) is not None:
171
+ args.force_sample = bool(model.config.force_sample)
172
+ if getattr(model.config, "frames_upbound", None) is not None and args.frames == 16:
173
+ args.frames = int(model.config.frames_upbound)
174
+ if getattr(model.config, "add_time_instruction", None) is not None:
175
+ add_time_instruction = bool(model.config.add_time_instruction)
176
+ else:
177
+ add_time_instruction = False
178
+
179
+ samples = load_samples(args.dataset_json, args.start_index, args.max_samples)
180
+ print(f"[eval] loaded {len(samples)} samples from {args.dataset_json}", flush=True)
181
+ done_ids = maybe_load_done_ids(pred_path) if args.resume else set()
182
+
183
+ total = 0
184
+ baseline_correct = 0
185
+ tvcd_correct = 0
186
+ rng = random.Random(args.tvcd_shuffle_seed)
187
+
188
+ if done_ids:
189
+ with open(pred_path) as f:
190
+ for line in f:
191
+ if not line.strip():
192
+ continue
193
+ row = json.loads(line)
194
+ baseline_correct += int(bool(row.get("baseline_correct")))
195
+ tvcd_correct += int(bool(row.get("tvcd_correct")))
196
+ total += 1
197
+
198
+ with open(pred_path, "a", buffering=1) as fout:
199
+ for offset, sample in enumerate(samples):
200
+ sample_idx = args.start_index + offset
201
+ if sample_idx in done_ids:
202
+ continue
203
+ print(f"[eval] sample_idx={sample_idx} reversal_type={sample.get('reversal_type')} video={sample.get('video_abs_path')}", flush=True)
204
+
205
+ video_path = resolve_media_abs_path(sample, None, media_type="video")
206
+ video, image_sizes, video_time, frame_time, num_frames = load_video_inputs(
207
+ video_path,
208
+ image_processor,
209
+ model.config,
210
+ device,
211
+ )
212
+ video_tensor = video[0]
213
+ prompt = build_video_mcq_prompt(sample)
214
+
215
+ if add_time_instruction:
216
+ prompt = (
217
+ f"The video lasts for {video_time:.2f} seconds, and {num_frames} frames are uniformly sampled from it. "
218
+ f"These frames are located at {frame_time}. Please answer the following questions related to this video.\n"
219
+ f"{prompt}"
220
+ )
221
+
222
+ qs = DEFAULT_IMAGE_TOKEN + "\n" + prompt
223
+
224
+ conv = conv_templates[args.conv_mode].copy()
225
+ conv.append_message(conv.roles[0], qs)
226
+ conv.append_message(conv.roles[1], None)
227
+ full_prompt = conv.get_prompt()
228
+
229
+ input_ids = tokenizer_image_token(full_prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device)
230
+ pad_token_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id
231
+ attention_mask = input_ids.ne(pad_token_id).long().to(device)
232
+
233
+ gen_kwargs = dict(
234
+ inputs=input_ids,
235
+ images=video,
236
+ image_sizes=image_sizes,
237
+ attention_mask=attention_mask,
238
+ modalities=["video"],
239
+ do_sample=False,
240
+ temperature=args.temperature,
241
+ max_new_tokens=args.max_new_tokens,
242
+ top_p=args.top_p,
243
+ num_beams=args.num_beams,
244
+ use_cache=True,
245
+ )
246
+
247
+ with torch.inference_mode():
248
+ baseline_ids = model.generate(**gen_kwargs)
249
+ baseline_ids = extract_generated_ids(baseline_ids, input_ids)
250
+ baseline_text = clean_generation_text(tokenizer.batch_decode(baseline_ids, skip_special_tokens=True)[0])
251
+ print(f"[eval] sample_idx={sample_idx} baseline={baseline_text}", flush=True)
252
+
253
+ tvcd_text = None
254
+ if args.use_tvcd:
255
+ video_cd = [shuffle_video_tensor(video_tensor, seed=rng.randint(0, 2**31 - 1))]
256
+ tvcd_ids = model.generate(
257
+ **gen_kwargs,
258
+ images_cd=video_cd,
259
+ image_sizes_cd=image_sizes,
260
+ cd_alpha=args.cd_alpha,
261
+ cd_beta=args.cd_beta,
262
+ )
263
+ tvcd_ids = extract_generated_ids(tvcd_ids, input_ids)
264
+ tvcd_text = clean_generation_text(tokenizer.batch_decode(tvcd_ids, skip_special_tokens=True)[0])
265
+ print(f"[eval] sample_idx={sample_idx} tvcd={tvcd_text}", flush=True)
266
+
267
+ gt_letter = extract_letter(sample["response"])
268
+ baseline_letter = extract_letter(baseline_text)
269
+ tvcd_letter = extract_letter(tvcd_text) if tvcd_text is not None else None
270
+ baseline_hit = baseline_letter == gt_letter
271
+ tvcd_hit = tvcd_letter == gt_letter if tvcd_text is not None else None
272
+
273
+ total += 1
274
+ baseline_correct += int(baseline_hit)
275
+ if tvcd_hit is True:
276
+ tvcd_correct += 1
277
+
278
+ row = {
279
+ "sample_idx": sample_idx,
280
+ "data_id": sample.get("data_id"),
281
+ "reversal_type": sample.get("reversal_type"),
282
+ "video_abs_path": video_path,
283
+ "gt_response": sample.get("response"),
284
+ "gt_letter": gt_letter,
285
+ "baseline_text": baseline_text,
286
+ "baseline_letter": baseline_letter,
287
+ "baseline_correct": baseline_hit,
288
+ "tvcd_text": tvcd_text,
289
+ "tvcd_letter": tvcd_letter,
290
+ "tvcd_correct": tvcd_hit,
291
+ }
292
+ fout.write(json.dumps(row, ensure_ascii=False) + "\n")
293
+
294
+ if total % 10 == 0:
295
+ summary = {
296
+ "samples_done": total,
297
+ "baseline_acc": baseline_correct / total,
298
+ "tvcd_acc": (tvcd_correct / total) if args.use_tvcd else None,
299
+ "model_path": args.model_path,
300
+ "dataset_json": args.dataset_json,
301
+ "use_tvcd": args.use_tvcd,
302
+ "cd_alpha": args.cd_alpha if args.use_tvcd else None,
303
+ "cd_beta": args.cd_beta if args.use_tvcd else None,
304
+ }
305
+ with open(summary_path, "w") as f:
306
+ json.dump(summary, f, indent=2, ensure_ascii=False)
307
+ print(summary, flush=True)
308
+
309
+ summary = {
310
+ "samples_done": total,
311
+ "baseline_acc": baseline_correct / total if total else 0.0,
312
+ "tvcd_acc": (tvcd_correct / total) if args.use_tvcd and total else None,
313
+ "model_path": args.model_path,
314
+ "dataset_json": args.dataset_json,
315
+ "use_tvcd": args.use_tvcd,
316
+ "cd_alpha": args.cd_alpha if args.use_tvcd else None,
317
+ "cd_beta": args.cd_beta if args.use_tvcd else None,
318
+ }
319
+ with open(summary_path, "w") as f:
320
+ json.dump(summary, f, indent=2, ensure_ascii=False)
321
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
322
+
323
+
324
+ if __name__ == "__main__":
325
+ main()
train/init_lladav_value_model.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
4
+ os.environ["TOKENIZERS_PARALLELISM"] = "true"
5
+
6
+ import json
7
+ import shutil
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ from omegaconf import OmegaConf
14
+ from transformers import AutoTokenizer, AutoConfig
15
+
16
+ from train.utils import get_config
17
+ from models import LlavaLLaDAModelLM
18
+
19
+
20
+
21
+ def _get_hidden_size(cfg):
22
+ for k in ["hidden_size", "d_model", "n_embd", "embedding_size"]:
23
+ if hasattr(cfg, k):
24
+ return int(getattr(cfg, k))
25
+ raise ValueError("Cannot infer hidden size from config (expected one of hidden_size/d_model/n_embd/embedding_size).")
26
+
27
+
28
+ def _get_value_model(base_llm_class, value_head_prefix="value_head"):
29
+ class ValueModel(base_llm_class):
30
+ def __init__(self, config: AutoConfig):
31
+ try:
32
+ import deepspeed
33
+ zero_off = deepspeed.zero.Init(enabled=False)
34
+ except Exception:
35
+ from contextlib import nullcontext
36
+ zero_off = nullcontext()
37
+
38
+ with zero_off:
39
+ super().__init__(config)
40
+
41
+ self.value_head_prefix = value_head_prefix
42
+ hs = _get_hidden_size(config)
43
+ vh = nn.Linear(hs, 1, bias=False)
44
+ setattr(self, value_head_prefix, vh)
45
+
46
+ def forward(self, input_ids=None, inputs_embeds=None, attention_mask=None, **kwargs):
47
+ kwargs.pop("labels", None)
48
+ kwargs.pop("position_ids", None)
49
+ outputs = self.model(
50
+ input_ids=input_ids,
51
+ inputs_embeds=inputs_embeds,
52
+ attention_mask=attention_mask,
53
+ output_hidden_states=True,
54
+ return_dict=True,
55
+ )
56
+ hidden = outputs.hidden_states[-1]
57
+ return getattr(self, self.value_head_prefix)(hidden).squeeze(-1)
58
+ return ValueModel
59
+
60
+
61
+
62
+ def save_checkpoint(model, tokenizer, config, name, accelerator=None):
63
+ from pathlib import Path
64
+ import json, shutil, os, glob, importlib, inspect, time
65
+
66
+ output_dir = Path(f"../{config.experiment.project}")
67
+ output_dir.mkdir(parents=True, exist_ok=True)
68
+
69
+ def _is_main():
70
+ if accelerator is not None:
71
+ return accelerator.is_main_process
72
+ import torch.distributed as dist
73
+ return (not dist.is_available()) or (not dist.is_initialized()) or dist.get_rank() == 0
74
+
75
+ is_main = _is_main()
76
+
77
+ checkpoints_total_limit = config.experiment.get("checkpoints_total_limit", None)
78
+ if is_main and checkpoints_total_limit is not None:
79
+ ckpts = sorted(
80
+ [d for d in output_dir.iterdir() if d.name.startswith("checkpoint")],
81
+ key=lambda p: int(p.name.split("-")[1]) if "-" in p.name else -1,
82
+ )
83
+ if len(ckpts) >= checkpoints_total_limit:
84
+ to_remove = ckpts[: len(ckpts) - checkpoints_total_limit + 1]
85
+ for p in to_remove:
86
+ shutil.rmtree(p, ignore_errors=True)
87
+
88
+ save_base = output_dir / "ckpt"
89
+ save_base.mkdir(exist_ok=True)
90
+
91
+ if accelerator is not None:
92
+ model_to_save = accelerator.unwrap_model(model)
93
+ state_dict = accelerator.get_state_dict(model)
94
+ save_function = accelerator.save
95
+ else:
96
+ model_to_save = model
97
+ state_dict = model.state_dict()
98
+ save_function = None
99
+
100
+ if is_main:
101
+ save_dir = save_base / name
102
+ model_to_save.save_pretrained(
103
+ save_dir,
104
+ state_dict=state_dict,
105
+ safe_serialization=True,
106
+ save_function=save_function,
107
+ )
108
+ tokenizer.save_pretrained(str(save_dir))
109
+
110
+ def _copy_dynamic_modules(dst_dir, model_obj, tok_obj):
111
+ copied = 0
112
+ modules = set()
113
+ for obj in [model_obj, getattr(model_obj, "config", None), tok_obj]:
114
+ if obj is None:
115
+ continue
116
+ modname = getattr(obj.__class__, "__module__", None)
117
+ if modname:
118
+ modules.add(modname)
119
+
120
+ for modname in modules:
121
+ try:
122
+ mod = importlib.import_module(modname)
123
+ src_file = inspect.getsourcefile(mod)
124
+ if not src_file or not os.path.exists(src_file):
125
+ continue
126
+ base_dir = os.path.dirname(src_file)
127
+ for pattern in ("modeling_*.py", "configuration_*.py", "tokenization_*.py", "processing_*.py"):
128
+ for fn in glob.glob(os.path.join(base_dir, pattern)):
129
+ dst = os.path.join(dst_dir, os.path.basename(fn))
130
+ if not os.path.exists(dst):
131
+ shutil.copy2(fn, dst)
132
+ copied += 1
133
+ except Exception:
134
+ pass
135
+
136
+ _copy_dynamic_modules(str(save_dir), model_to_save, tokenizer)
137
+
138
+ metadata = {"save_time": time.strftime("%Y-%m-%d %H:%M:%S")}
139
+ with (save_base / "metadata.json").open("w") as f:
140
+ json.dump(metadata, f, indent=2)
141
+
142
+ if accelerator is None:
143
+ import torch.distributed as dist
144
+ if dist.is_available() and dist.is_initialized():
145
+ dist.barrier()
146
+
147
+
148
+ def main():
149
+ config = get_config()
150
+ pretrained_model = config.model.value_base_model
151
+
152
+ value_model_class = _get_value_model(LlavaLLaDAModelLM, "value_head")
153
+
154
+ tokenizer = AutoTokenizer.from_pretrained(pretrained_model, trust_remote_code=True)
155
+ value_model = value_model_class.from_pretrained(pretrained_model, trust_remote_code=True, torch_dtype="auto")
156
+
157
+ with torch.no_grad():
158
+ getattr(value_model, "value_head").weight.zero_()
159
+
160
+ save_checkpoint(value_model, tokenizer, config, config.model.optimized_value_name)
161
+
162
+
163
+ if __name__ == "__main__":
164
+ main()
train/init_mmada_v_value_model.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
4
+ os.environ["TOKENIZERS_PARALLELISM"] = "true"
5
+
6
+ import json
7
+ import shutil
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ from omegaconf import OmegaConf
14
+ from transformers import AutoTokenizer, AutoConfig
15
+
16
+ from train.utils import get_config
17
+ from models import MMadaModelLM
18
+
19
+
20
+ def _get_hidden_size(cfg):
21
+ for k in ["hidden_size", "d_model", "n_embd", "embedding_size"]:
22
+ if hasattr(cfg, k):
23
+ return int(getattr(cfg, k))
24
+ raise ValueError("Cannot infer hidden size from config (expected one of hidden_size/d_model/n_embd/embedding_size).")
25
+
26
+
27
+ def _get_value_model(base_llm_class, value_head_prefix="value_head"):
28
+ class ValueModel(base_llm_class):
29
+ def __init__(self, config: AutoConfig):
30
+ try:
31
+ import deepspeed
32
+ zero_off = deepspeed.zero.Init(enabled=False)
33
+ except Exception:
34
+ from contextlib import nullcontext
35
+ zero_off = nullcontext()
36
+
37
+ with zero_off:
38
+ super().__init__(config)
39
+
40
+ self.value_head_prefix = value_head_prefix
41
+ hs = _get_hidden_size(config)
42
+ vh = nn.Linear(hs, 1, bias=False)
43
+ setattr(self, value_head_prefix, vh)
44
+
45
+ def forward(self, input_ids=None, attention_mask=None, **kwargs):
46
+ kwargs.pop("labels", None)
47
+ outputs = super().forward(
48
+ input_ids=input_ids,
49
+ output_hidden_states=True,
50
+ return_dict=True,
51
+ )
52
+ hidden = outputs.hidden_states[-1] # (B, T, H)
53
+ return getattr(self, self.value_head_prefix)(hidden).squeeze(-1) # (B, T)
54
+
55
+ return ValueModel
56
+
57
+
58
+
59
+ def save_checkpoint(model, tokenizer, config, name, accelerator=None):
60
+ from pathlib import Path
61
+ import json, shutil, os, glob, importlib, inspect, time
62
+
63
+ # train/ 下运行,向上一级保存到 ../{project}
64
+ output_dir = Path(f"../{config.experiment.project}")
65
+ output_dir.mkdir(parents=True, exist_ok=True)
66
+
67
+ def _is_main():
68
+ if accelerator is not None:
69
+ return accelerator.is_main_process
70
+ import torch.distributed as dist
71
+ return (not dist.is_available()) or (not dist.is_initialized()) or dist.get_rank() == 0
72
+
73
+ is_main = _is_main()
74
+
75
+ checkpoints_total_limit = config.experiment.get("checkpoints_total_limit", None)
76
+ if is_main and checkpoints_total_limit is not None:
77
+ ckpts = sorted(
78
+ [d for d in output_dir.iterdir() if d.name.startswith("checkpoint")],
79
+ key=lambda p: int(p.name.split("-")[1]) if "-" in p.name else -1,
80
+ )
81
+ if len(ckpts) >= checkpoints_total_limit:
82
+ to_remove = ckpts[: len(ckpts) - checkpoints_total_limit + 1]
83
+ for p in to_remove:
84
+ shutil.rmtree(p, ignore_errors=True)
85
+
86
+ save_base = output_dir / "ckpt"
87
+ save_base.mkdir(exist_ok=True)
88
+
89
+ if accelerator is not None:
90
+ model_to_save = accelerator.unwrap_model(model)
91
+ state_dict = accelerator.get_state_dict(model)
92
+ save_function = accelerator.save
93
+ else:
94
+ model_to_save = model
95
+ state_dict = model.state_dict()
96
+ save_function = None
97
+
98
+ if is_main:
99
+ save_dir = save_base / name
100
+ model_to_save.save_pretrained(
101
+ save_dir,
102
+ state_dict=state_dict,
103
+ safe_serialization=True,
104
+ save_function=save_function,
105
+ )
106
+ tokenizer.save_pretrained(str(save_dir))
107
+
108
+ def _copy_dynamic_modules(dst_dir, model_obj, tok_obj):
109
+ copied = 0
110
+ modules = set()
111
+ for obj in [model_obj, getattr(model_obj, "config", None), tok_obj]:
112
+ if obj is None:
113
+ continue
114
+ modname = getattr(obj.__class__, "__module__", None)
115
+ if modname:
116
+ modules.add(modname)
117
+
118
+ for modname in modules:
119
+ try:
120
+ mod = importlib.import_module(modname)
121
+ src_file = inspect.getsourcefile(mod)
122
+ if not src_file or not os.path.exists(src_file):
123
+ continue
124
+ base_dir = os.path.dirname(src_file)
125
+ for pattern in ("modeling_*.py", "configuration_*.py", "tokenization_*.py", "processing_*.py"):
126
+ for fn in glob.glob(os.path.join(base_dir, pattern)):
127
+ dst = os.path.join(dst_dir, os.path.basename(fn))
128
+ if not os.path.exists(dst):
129
+ shutil.copy2(fn, dst)
130
+ copied += 1
131
+ except Exception:
132
+ pass
133
+
134
+ _copy_dynamic_modules(str(save_dir), model_to_save, tokenizer)
135
+
136
+ metadata = {"save_time": time.strftime("%Y-%m-%d %H:%M:%S")}
137
+ with (save_base / "metadata.json").open("w") as f:
138
+ json.dump(metadata, f, indent=2)
139
+
140
+ if accelerator is None:
141
+ import torch.distributed as dist
142
+ if dist.is_available() and dist.is_initialized():
143
+ dist.barrier()
144
+
145
+
146
+ def main():
147
+ config = get_config()
148
+ pretrained_model = config.model.value_base_model
149
+
150
+ value_model_class = _get_value_model(MMadaModelLM, "value_head")
151
+
152
+ tokenizer = AutoTokenizer.from_pretrained(pretrained_model, trust_remote_code=True)
153
+ value_model = value_model_class.from_pretrained(pretrained_model, trust_remote_code=True, torch_dtype="auto")
154
+
155
+ with torch.no_grad():
156
+ getattr(value_model, "value_head").weight.zero_()
157
+
158
+ save_checkpoint(value_model, tokenizer, config, config.model.optimized_value_name)
159
+
160
+
161
+ if __name__ == "__main__":
162
+ main()
train/init_sdar_value_model.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
4
+ os.environ["TOKENIZERS_PARALLELISM"] = "true"
5
+ import json
6
+ import logging
7
+ import math
8
+ import shutil
9
+ import time
10
+ from pathlib import Path
11
+ from typing import Optional, Tuple, Union
12
+
13
+ import numpy as np
14
+ from PIL import Image
15
+ from omegaconf import OmegaConf
16
+ import wandb
17
+ import torch
18
+ from torch.optim import AdamW
19
+ import torch.nn as nn
20
+
21
+ from transformers import AutoTokenizer, AutoConfig
22
+ from accelerate import Accelerator
23
+ from accelerate.utils import DistributedType, set_seed
24
+
25
+
26
+
27
+ from transformers import AutoModelForCausalLM, AutoTokenizer
28
+ from train.prompting_utils import UniversalPrompting
29
+ from models.lr_schedulers import get_scheduler
30
+ from models.logging import set_verbosity_info, set_verbosity_error
31
+
32
+ from torch.utils.data import Dataset, DataLoader
33
+
34
+ SYSTEM_PROMPT_LEN = 28
35
+
36
+ from train.utils import get_config, flatten_omega_conf, AverageMeter
37
+
38
+ try:
39
+ import apex
40
+
41
+ is_apex_available = True
42
+ except ImportError:
43
+ is_apex_available = False
44
+
45
+
46
+
47
+ def _get_value_model(base_llm_class, value_head_prefix="value_head"):
48
+ class ValueModel(base_llm_class):
49
+ def __init__(self, config: AutoConfig):
50
+ try:
51
+ import deepspeed
52
+ zero_off = deepspeed.zero.Init(enabled=False)
53
+ except Exception:
54
+ from contextlib import nullcontext
55
+ zero_off = nullcontext()
56
+
57
+ with zero_off:
58
+ super().__init__(config)
59
+
60
+ self.value_head_prefix = value_head_prefix
61
+ vh = nn.Linear(config.hidden_size, 1, bias=False)
62
+ setattr(self, value_head_prefix, vh)
63
+
64
+ def forward(self, input_ids=None, attention_mask=None, position_ids=None, **kwargs):
65
+ outputs = self.model(
66
+ input_ids, attention_mask=attention_mask, position_ids=position_ids, **kwargs
67
+ )
68
+ last_hidden_states = outputs["last_hidden_state"]
69
+ return getattr(self, self.value_head_prefix)(last_hidden_states).squeeze(-1)
70
+
71
+ return ValueModel
72
+
73
+
74
+
75
+ def main():
76
+ config = get_config()
77
+
78
+ pretrained_model = config.model.value_base_model
79
+
80
+ from transformers import AutoConfig
81
+ from models import SDARForCausalLM
82
+ value_model_class = _get_value_model(SDARForCausalLM, "value_head")
83
+
84
+
85
+ tokenizer = AutoTokenizer.from_pretrained(pretrained_model, trust_remote_code=True)
86
+ value_model = value_model_class.from_pretrained(pretrained_model, trust_remote_code=True, torch_dtype="auto")
87
+
88
+ with torch.no_grad():
89
+ getattr(value_model, "value_head").weight.zero_()
90
+
91
+
92
+
93
+ save_checkpoint(value_model, tokenizer, config, config.model.optimized_value_name)
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+ def save_checkpoint(model, tokenizer, config, name, accelerator=None):
105
+ from pathlib import Path
106
+ import time, json, shutil, os, glob, importlib, inspect
107
+ import torch
108
+
109
+ output_dir = Path(f"../{config.experiment.project}")
110
+ output_dir.mkdir(parents=True, exist_ok=True)
111
+
112
+ def _is_main():
113
+ if accelerator is not None:
114
+ return accelerator.is_main_process
115
+ import torch.distributed as dist
116
+ return (not dist.is_available()) or (not dist.is_initialized()) or dist.get_rank() == 0
117
+
118
+ is_main = _is_main()
119
+
120
+ checkpoints_total_limit = config.experiment.get("checkpoints_total_limit", None)
121
+ if is_main and checkpoints_total_limit is not None:
122
+ ckpts = sorted(
123
+ [d for d in output_dir.iterdir() if d.name.startswith("checkpoint")],
124
+ key=lambda p: int(p.name.split("-")[1]) if "-" in p.name else -1,
125
+ )
126
+ if len(ckpts) >= checkpoints_total_limit:
127
+ to_remove = ckpts[: len(ckpts) - checkpoints_total_limit + 1]
128
+ for p in to_remove:
129
+ shutil.rmtree(p, ignore_errors=True)
130
+
131
+ save_base = output_dir / "ckpt"
132
+ save_base.mkdir(exist_ok=True)
133
+
134
+ if accelerator is not None:
135
+ model_to_save = accelerator.unwrap_model(model)
136
+ state_dict = accelerator.get_state_dict(model)
137
+ save_function = accelerator.save
138
+ else:
139
+ model_to_save = model
140
+ state_dict = model.state_dict()
141
+ save_function = None
142
+
143
+ if is_main:
144
+ save_dir = save_base / name
145
+ model_to_save.save_pretrained(
146
+ save_dir,
147
+ state_dict=state_dict,
148
+ safe_serialization=True,
149
+ save_function=save_function,
150
+ )
151
+ tokenizer.save_pretrained(str(save_dir))
152
+
153
+ def _copy_dynamic_modules(dst_dir, model_obj, tok_obj):
154
+ copied = 0
155
+ modules = set()
156
+ for obj in [model_obj, getattr(model_obj, "config", None), tok_obj]:
157
+ if obj is None:
158
+ continue
159
+ modname = getattr(obj.__class__, "__module__", None)
160
+ if modname:
161
+ modules.add(modname)
162
+
163
+ for modname in modules:
164
+ try:
165
+ mod = importlib.import_module(modname)
166
+ src_file = inspect.getsourcefile(mod)
167
+ if not src_file or not os.path.exists(src_file):
168
+ continue
169
+ base_dir = os.path.dirname(src_file)
170
+ for pattern in ("modeling_*.py", "configuration_*.py", "tokenization_*.py", "processing_*.py"):
171
+ for fn in glob.glob(os.path.join(base_dir, pattern)):
172
+ dst = os.path.join(dst_dir, os.path.basename(fn))
173
+ if not os.path.exists(dst):
174
+ shutil.copy2(fn, dst)
175
+ copied += 1
176
+ except Exception as e:
177
+ pass
178
+
179
+ _copy_dynamic_modules(str(save_dir), model_to_save, tokenizer)
180
+
181
+ metadata = {"save_time": time.strftime("%Y-%m-%d %H:%M:%S")}
182
+ with (save_base / "metadata.json").open("w") as f:
183
+ json.dump(metadata, f, indent=2)
184
+
185
+
186
+ if accelerator is None:
187
+ import torch.distributed as dist
188
+ if dist.is_available() and dist.is_initialized():
189
+ dist.barrier()
190
+
191
+
192
+
193
+ if __name__ == "__main__":
194
+ main()
train/init_trado_value_model.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
4
+ os.environ["TOKENIZERS_PARALLELISM"] = "true"
5
+ import json
6
+ import logging
7
+ import math
8
+ import shutil
9
+ import time
10
+ from pathlib import Path
11
+ from typing import Optional, Tuple, Union
12
+
13
+ import numpy as np
14
+ from PIL import Image
15
+ from omegaconf import OmegaConf
16
+ import wandb
17
+ import torch
18
+ from torch.optim import AdamW
19
+ import torch.nn as nn
20
+
21
+ from transformers import AutoTokenizer, AutoConfig
22
+ from accelerate import Accelerator
23
+ from accelerate.utils import DistributedType, set_seed
24
+
25
+
26
+
27
+ from transformers import AutoModelForCausalLM, AutoTokenizer
28
+ from train.prompting_utils import UniversalPrompting
29
+ from models.lr_schedulers import get_scheduler
30
+ from models.logging import set_verbosity_info, set_verbosity_error
31
+
32
+ from torch.utils.data import Dataset, DataLoader
33
+
34
+ SYSTEM_PROMPT_LEN = 28
35
+
36
+ from train.utils import get_config, flatten_omega_conf, AverageMeter
37
+
38
+ try:
39
+ import apex
40
+
41
+ is_apex_available = True
42
+ except ImportError:
43
+ is_apex_available = False
44
+
45
+
46
+
47
+ def _get_value_model(base_llm_class, value_head_prefix="value_head"):
48
+ class ValueModel(base_llm_class):
49
+ def __init__(self, config: AutoConfig):
50
+ try:
51
+ import deepspeed
52
+ zero_off = deepspeed.zero.Init(enabled=False)
53
+ except Exception:
54
+ from contextlib import nullcontext
55
+ zero_off = nullcontext()
56
+
57
+ with zero_off:
58
+ super().__init__(config)
59
+
60
+ self.value_head_prefix = value_head_prefix
61
+ vh = nn.Linear(config.hidden_size, 1, bias=False)
62
+ setattr(self, value_head_prefix, vh)
63
+
64
+ def forward(self, input_ids=None, attention_mask=None, position_ids=None, **kwargs):
65
+ outputs = self.model(
66
+ input_ids, attention_mask=attention_mask, position_ids=position_ids, **kwargs
67
+ )
68
+ last_hidden_states = outputs["last_hidden_state"]
69
+ return getattr(self, self.value_head_prefix)(last_hidden_states).squeeze(-1)
70
+
71
+ return ValueModel
72
+
73
+
74
+
75
+ def main():
76
+ config = get_config()
77
+
78
+ pretrained_model = config.model.value_base_model
79
+
80
+ from transformers import AutoConfig
81
+ from models import SDARForCausalLM
82
+ value_model_class = _get_value_model(SDARForCausalLM, "value_head")
83
+
84
+
85
+ tokenizer = AutoTokenizer.from_pretrained(pretrained_model, trust_remote_code=True)
86
+ value_model = value_model_class.from_pretrained(pretrained_model, trust_remote_code=True, torch_dtype="auto")
87
+
88
+ with torch.no_grad():
89
+ getattr(value_model, "value_head").weight.zero_()
90
+
91
+
92
+
93
+ save_checkpoint(value_model, tokenizer, config, config.model.optimized_value_name)
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+ def save_checkpoint(model, tokenizer, config, name, accelerator=None):
105
+ from pathlib import Path
106
+ import time, json, shutil, os, glob, importlib, inspect
107
+ import torch
108
+
109
+ output_dir = Path(f"../{config.experiment.project}")
110
+ output_dir.mkdir(parents=True, exist_ok=True)
111
+
112
+ def _is_main():
113
+ if accelerator is not None:
114
+ return accelerator.is_main_process
115
+ import torch.distributed as dist
116
+ return (not dist.is_available()) or (not dist.is_initialized()) or dist.get_rank() == 0
117
+
118
+ is_main = _is_main()
119
+
120
+ checkpoints_total_limit = config.experiment.get("checkpoints_total_limit", None)
121
+ if is_main and checkpoints_total_limit is not None:
122
+ ckpts = sorted(
123
+ [d for d in output_dir.iterdir() if d.name.startswith("checkpoint")],
124
+ key=lambda p: int(p.name.split("-")[1]) if "-" in p.name else -1,
125
+ )
126
+ if len(ckpts) >= checkpoints_total_limit:
127
+ to_remove = ckpts[: len(ckpts) - checkpoints_total_limit + 1]
128
+ for p in to_remove:
129
+ shutil.rmtree(p, ignore_errors=True)
130
+
131
+ save_base = output_dir / "ckpt"
132
+ save_base.mkdir(exist_ok=True)
133
+
134
+ if accelerator is not None:
135
+ model_to_save = accelerator.unwrap_model(model)
136
+ state_dict = accelerator.get_state_dict(model)
137
+ save_function = accelerator.save
138
+ else:
139
+ model_to_save = model
140
+ state_dict = model.state_dict()
141
+ save_function = None
142
+
143
+ if is_main:
144
+ save_dir = save_base / name
145
+ model_to_save.save_pretrained(
146
+ save_dir,
147
+ state_dict=state_dict,
148
+ safe_serialization=True,
149
+ save_function=save_function,
150
+ )
151
+ tokenizer.save_pretrained(str(save_dir))
152
+
153
+ def _copy_dynamic_modules(dst_dir, model_obj, tok_obj):
154
+ copied = 0
155
+ modules = set()
156
+ for obj in [model_obj, getattr(model_obj, "config", None), tok_obj]:
157
+ if obj is None:
158
+ continue
159
+ modname = getattr(obj.__class__, "__module__", None)
160
+ if modname:
161
+ modules.add(modname)
162
+
163
+ for modname in modules:
164
+ try:
165
+ mod = importlib.import_module(modname)
166
+ src_file = inspect.getsourcefile(mod)
167
+ if not src_file or not os.path.exists(src_file):
168
+ continue
169
+ base_dir = os.path.dirname(src_file)
170
+ for pattern in ("modeling_*.py", "configuration_*.py", "tokenization_*.py", "processing_*.py"):
171
+ for fn in glob.glob(os.path.join(base_dir, pattern)):
172
+ dst = os.path.join(dst_dir, os.path.basename(fn))
173
+ if not os.path.exists(dst):
174
+ shutil.copy2(fn, dst)
175
+ copied += 1
176
+ except Exception as e:
177
+ pass
178
+
179
+ _copy_dynamic_modules(str(save_dir), model_to_save, tokenizer)
180
+
181
+ metadata = {"save_time": time.strftime("%Y-%m-%d %H:%M:%S")}
182
+ with (save_base / "metadata.json").open("w") as f:
183
+ json.dump(metadata, f, indent=2)
184
+
185
+
186
+ if accelerator is None:
187
+ import torch.distributed as dist
188
+ if dist.is_available() and dist.is_initialized():
189
+ dist.barrier()
190
+
191
+
192
+
193
+ if __name__ == "__main__":
194
+ main()
train/llava/__init__.py ADDED
File without changes
train/llava/cache/Cache.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from collections import defaultdict
3
+
4
+
5
+ class Singleton(type):
6
+ _instances = {}
7
+
8
+ def __call__(cls, *args, **kwargs):
9
+ if cls not in cls._instances:
10
+ cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
11
+ return cls._instances[cls]
12
+
13
+
14
+ class dLLMCache(metaclass=Singleton):
15
+ gen_interval_steps: int
16
+ prompt_interval_steps: int
17
+ cfg_interval_steps: int
18
+ prompt_length: int
19
+ transfer_ratio: float
20
+ __cache: defaultdict
21
+ __step_counter: defaultdict
22
+
23
+ @classmethod
24
+ def new_instance(
25
+ cls,
26
+ prompt_interval_steps: int = 1,
27
+ gen_interval_steps: int = 1,
28
+ cfg_interval_steps: int = 1,
29
+ transfer_ratio: float = 0.0,
30
+ ) -> "dLLMCache":
31
+ ins = cls()
32
+ setattr(ins, "prompt_interval_steps", prompt_interval_steps)
33
+ setattr(ins, "gen_interval_steps", gen_interval_steps)
34
+ setattr(ins, "cfg_interval_steps", cfg_interval_steps)
35
+ setattr(ins, "transfer_ratio", transfer_ratio)
36
+ ins.init()
37
+ return ins
38
+
39
+ def init(self) -> None:
40
+ self.__cache = defaultdict(
41
+ lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(dict)))
42
+ )
43
+ self.__step_counter = defaultdict(lambda: defaultdict(lambda: 0))
44
+
45
+ def reset_cache(self, prompt_length: int = 0) -> None:
46
+ self.init()
47
+ torch.cuda.empty_cache()
48
+ self.prompt_length = prompt_length
49
+ self.cache_type = "no_cfg"
50
+
51
+ def set_cache(
52
+ self, layer_id: int, feature_name: str, features: torch.Tensor, cache_type: str
53
+ ) -> None:
54
+ self.__cache[self.cache_type][cache_type][layer_id][feature_name] = {
55
+ 0: features
56
+ }
57
+
58
+ def get_cache(
59
+ self, layer_id: int, feature_name: str, cache_type: str
60
+ ) -> torch.Tensor:
61
+ output = self.__cache[self.cache_type][cache_type][layer_id][feature_name][0]
62
+ return output
63
+
64
+ def update_step(self, layer_id: int) -> None:
65
+ self.__step_counter[self.cache_type][layer_id] += 1
66
+
67
+ def refresh_gen(self, layer_id: int = 0) -> bool:
68
+ return (self.current_step - 1) % self.gen_interval_steps == 0
69
+
70
+ def refresh_prompt(self, layer_id: int = 0) -> bool:
71
+ return (self.current_step - 1) % self.prompt_interval_steps == 0
72
+
73
+ def refresh_cfg(self, layer_id: int = 0) -> bool:
74
+ return (
75
+ self.current_step - 1
76
+ ) % self.cfg_interval_steps == 0 or self.current_step <= 5
77
+
78
+ @property
79
+ def current_step(self) -> int:
80
+ return max(list(self.__step_counter[self.cache_type].values()), default=1)
81
+
82
+ def __repr__(self):
83
+ return f"USE dLLMCache"
train/llava/cache/Config.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass
5
+ class dLLMCacheConfig:
6
+ prompt_interval_steps: int = 1
7
+ gen_interval_steps: int = 1
8
+ transfer_ratio: float = 0.0
9
+ cfg_interval_steps: int = 1
train/llava/cache/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .Cache import dLLMCache
2
+ from .Config import dLLMCacheConfig
3
+
4
+ __all__ = ["dLLMCache", "dLLMCacheConfig"]
train/llava/constants.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
2
+ WORKER_HEART_BEAT_INTERVAL = 15
3
+
4
+ LOGDIR = "."
5
+
6
+ # Model Constants
7
+ IGNORE_INDEX = -100
8
+ IMAGE_TOKEN_INDEX = -200
9
+ DEFAULT_IMAGE_TOKEN = "<image>"
10
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
11
+ DEFAULT_IM_START_TOKEN = "<im_start>"
12
+ DEFAULT_IM_END_TOKEN = "<im_end>"
train/llava/conversation.py ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from enum import auto, Enum
3
+ from typing import List, Any, Dict, Union, Tuple
4
+ import re
5
+ import base64
6
+ from io import BytesIO
7
+ from PIL import Image
8
+ from transformers import AutoTokenizer
9
+
10
+
11
+ class SeparatorStyle(Enum):
12
+ """Different separator style."""
13
+
14
+ SINGLE = auto()
15
+ TWO = auto()
16
+ MPT = auto()
17
+ PLAIN = auto()
18
+ CHATML = auto()
19
+ LLAMA_2 = auto()
20
+ LLAMA_3 = auto()
21
+ QWEN = auto()
22
+ GEMMA = auto()
23
+
24
+
25
+ @dataclasses.dataclass
26
+ class Conversation:
27
+ """A class that keeps all conversation history."""
28
+
29
+ system: str
30
+ roles: List[str]
31
+ messages: List[List[str]]
32
+ offset: int
33
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
34
+ sep: str = "###"
35
+ sep2: str = None
36
+ version: str = "Unknown"
37
+
38
+ tokenizer_id: str = ""
39
+ tokenizer: Any = None
40
+ # Stop criteria (the default one is EOS token)
41
+ stop_str: Union[str, List[str]] = None
42
+ # Stops generation if meeting any token in this list
43
+ stop_token_ids: List[int] = None
44
+
45
+ skip_next: bool = False
46
+
47
+ def get_prompt(self):
48
+ messages = self.messages
49
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
50
+ messages = self.messages.copy()
51
+ init_role, init_msg = messages[0].copy()
52
+ init_msg = init_msg[0]
53
+ if "mmtag" in self.version:
54
+ init_msg = init_msg.replace("<image>", "").strip()
55
+ messages[0] = (init_role, init_msg)
56
+ messages.insert(0, (self.roles[0], "<Image><image></Image>"))
57
+ messages.insert(1, (self.roles[1], "Received."))
58
+ elif not init_msg.startswith("<image>"):
59
+ init_msg = init_msg.replace("<image>", "").strip()
60
+ messages[0] = (init_role, "<image>\n" + init_msg)
61
+ else:
62
+ messages[0] = (init_role, init_msg)
63
+
64
+ if self.sep_style == SeparatorStyle.SINGLE:
65
+ ret = self.system + self.sep
66
+ for role, message in messages:
67
+ if message:
68
+ if type(message) is tuple:
69
+ message, _, _ = message
70
+ ret += role + ": " + message + self.sep
71
+ else:
72
+ ret += role + ":"
73
+
74
+ elif self.sep_style == SeparatorStyle.TWO:
75
+ seps = [self.sep, self.sep2]
76
+ ret = self.system + seps[0]
77
+ for i, (role, message) in enumerate(messages):
78
+ if message:
79
+ if type(message) is tuple:
80
+ message, _, _ = message
81
+ ret += role + ": " + message + seps[i % 2]
82
+ else:
83
+ ret += role + ":"
84
+
85
+ elif self.sep_style == SeparatorStyle.CHATML:
86
+ ret = "" if self.system == "" else self.system + self.sep + "\n"
87
+ for role, message in messages:
88
+ if message:
89
+ if type(message) is tuple:
90
+ message, images, _ = message
91
+ message = "<image>" * len(images) + message
92
+ ret += role + "\n" + message + self.sep + "\n"
93
+ else:
94
+ ret += role + "\n"
95
+ return ret
96
+
97
+ elif self.sep_style == SeparatorStyle.LLAMA_3:
98
+ if self.tokenizer is None:
99
+ if self.version == "llama_v3":
100
+ self.tokenizer = AutoTokenizer.from_pretrained('meta-llama/Meta-Llama-3-8B-Instruct', trust_remote_code=True)
101
+ elif self.version == "llava_llada":
102
+ self.tokenizer = AutoTokenizer.from_pretrained('/data4/runqing/dLLM-RL/LLaDA-V', trust_remote_code=True)
103
+ else:
104
+ raise ValueError("The tokenizer is not available. Make sure you have the necessary permissions.")
105
+ chat_template_messages = [{"role": "system", "content": self.system}]
106
+ for role, message in messages:
107
+ if message:
108
+ if type(message) is tuple:
109
+ message, images = message
110
+ message = "<image>" * len(images) + message
111
+ chat_template_messages.append({"role": role, "content": message})
112
+
113
+ # print(chat_template_messages)
114
+ return self.tokenizer.apply_chat_template(chat_template_messages, tokenize=False, add_generation_prompt=True)
115
+ # ret = "" if self.system == "" else self.system + self.sep + "\n"
116
+ # for role, message in messages:
117
+ # if message:
118
+ # if type(message) is tuple:
119
+ # message, images = message
120
+ # message = "<image>" * len(images) + message
121
+ # ret += role + "\n" + message + self.sep + "\n"
122
+ # else:
123
+ # ret += role + "\n"
124
+ # return ret
125
+
126
+ elif self.sep_style == SeparatorStyle.MPT:
127
+ ret = self.system + self.sep
128
+ for role, message in messages:
129
+ if message:
130
+ if type(message) is tuple:
131
+ message, _, _ = message
132
+ ret += role + message + self.sep
133
+ else:
134
+ ret += role
135
+
136
+ elif self.sep_style == SeparatorStyle.GEMMA:
137
+ ret = ""
138
+ for i, (role, message) in enumerate(messages):
139
+ assert role == self.roles[i % 2], "Conversation should alternate user/assistant/user/assistant/..."
140
+ if message:
141
+ if type(message) is tuple:
142
+ message, _, _ = message
143
+ ret += role + message + self.sep
144
+ else:
145
+ ret += role
146
+
147
+ elif self.sep_style == SeparatorStyle.LLAMA_2:
148
+ wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n" if len(msg) > 0 else msg
149
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
150
+ ret = ""
151
+
152
+ for i, (role, message) in enumerate(messages):
153
+ if i == 0:
154
+ assert message, "first message should not be none"
155
+ assert role == self.roles[0], "first message should come from user"
156
+ if message:
157
+ if type(message) is tuple:
158
+ message, _, _ = message
159
+ if i == 0:
160
+ message = wrap_sys(self.system) + message
161
+ if i % 2 == 0:
162
+ message = wrap_inst(message)
163
+ ret += self.sep + message
164
+ else:
165
+ ret += " " + message + " " + self.sep2
166
+ else:
167
+ ret += ""
168
+ ret = ret.lstrip(self.sep)
169
+
170
+ elif self.sep_style == SeparatorStyle.PLAIN:
171
+ seps = [self.sep, self.sep2]
172
+ ret = self.system
173
+ for i, (role, message) in enumerate(messages):
174
+ if message:
175
+ if type(message) is tuple:
176
+ message, _, _ = message
177
+ ret += message + seps[i % 2]
178
+ else:
179
+ ret += ""
180
+ else:
181
+ raise ValueError(f"Invalid style: {self.sep_style}")
182
+
183
+ return ret
184
+
185
+ def append_message(self, role, message):
186
+ self.messages.append([role, message])
187
+
188
+ def process_image(self, image, image_process_mode, return_pil=False, image_format="PNG"):
189
+ if image_process_mode == "Pad":
190
+
191
+ def expand2square(pil_img, background_color=(122, 116, 104)):
192
+ width, height = pil_img.size
193
+ if width == height:
194
+ return pil_img
195
+ elif width > height:
196
+ result = Image.new(pil_img.mode, (width, width), background_color)
197
+ result.paste(pil_img, (0, (width - height) // 2))
198
+ return result
199
+ else:
200
+ result = Image.new(pil_img.mode, (height, height), background_color)
201
+ result.paste(pil_img, ((height - width) // 2, 0))
202
+ return result
203
+
204
+ image = expand2square(image)
205
+ elif image_process_mode in ["Default", "Crop"]:
206
+ pass
207
+ elif image_process_mode == "Resize":
208
+ image = image.resize((336, 336))
209
+ else:
210
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
211
+
212
+ if type(image) is not Image.Image:
213
+ image = Image.open(image).convert("RGB")
214
+
215
+ max_hw, min_hw = max(image.size), min(image.size)
216
+ aspect_ratio = max_hw / min_hw
217
+ max_len, min_len = 672, 448
218
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
219
+ longest_edge = int(shortest_edge * aspect_ratio)
220
+ W, H = image.size
221
+ if H > W:
222
+ H, W = longest_edge, shortest_edge
223
+ else:
224
+ H, W = shortest_edge, longest_edge
225
+ image = image.resize((W, H))
226
+ if return_pil:
227
+ return image
228
+ else:
229
+ buffered = BytesIO()
230
+ image.save(buffered, format=image_format)
231
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
232
+ return img_b64_str
233
+
234
+ def get_images(self, return_pil=False, return_path=False):
235
+ images = []
236
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
237
+ if i % 2 == 0:
238
+ if type(msg) is tuple:
239
+ msg, image, image_process_mode = msg
240
+ if type(image) != list:
241
+ image = [image]
242
+ for img in image:
243
+ if not return_path and self.is_image_file(img):
244
+ img = self.process_image(img, image_process_mode, return_pil=return_pil)
245
+ else:
246
+ images.append(img)
247
+ return images
248
+
249
+ def is_image_file(self, filename):
250
+ image_extensions = [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".webp"]
251
+ return any(filename.lower().endswith(ext) for ext in image_extensions)
252
+
253
+ def is_video_file(self, filename):
254
+ video_extensions = [".mp4", ".mov", ".avi", ".mkv", ".wmv", ".flv", ".mpeg", ".mpg"]
255
+ return any(filename.lower().endswith(ext) for ext in video_extensions)
256
+
257
+ def to_gradio_chatbot(self):
258
+ ret = []
259
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
260
+ if i % 2 == 0:
261
+ if type(msg) is tuple:
262
+ msg, image, image_process_mode = msg
263
+ if type(image) != list:
264
+ image = [image]
265
+ if len(image) == 1:
266
+ msg = "<image>\n" + msg.replace("<image>", "").strip()
267
+ else:
268
+ msg = re.sub(r"(<image>)\n(?=<image>)", r"\1 ", msg)
269
+
270
+ img_str_list = []
271
+ for img in image:
272
+ if self.is_image_file(img):
273
+ img_b64_str = self.process_image(img, "Default", return_pil=False, image_format="JPEG")
274
+ img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" style="max-width: 256px; max-height: 256px; width: auto; height: auto; object-fit: contain;"/>'
275
+ img_str_list.append(img_str)
276
+ elif self.is_video_file(img):
277
+ ret.append(((img,), None))
278
+
279
+ msg = msg.strip()
280
+ img_place_holder = ""
281
+ for img_str in img_str_list:
282
+ img_place_holder += f"{img_str}\n\n"
283
+
284
+ if len(img_str_list) > 0:
285
+ msg = f"{img_place_holder}\n\n{msg}"
286
+
287
+ if len(msg) > 0:
288
+ ret.append([msg, None])
289
+ else:
290
+ ret.append([msg, None])
291
+ else:
292
+ ret[-1][-1] = msg
293
+ return ret
294
+
295
+ def copy(self):
296
+ return Conversation(system=self.system, roles=self.roles, messages=[[x, y] for x, y in self.messages], offset=self.offset, sep_style=self.sep_style, sep=self.sep, sep2=self.sep2, version=self.version)
297
+
298
+ def dict(self):
299
+ if len(self.get_images()) > 0:
300
+ return {
301
+ "system": self.system,
302
+ "roles": self.roles,
303
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
304
+ "offset": self.offset,
305
+ "sep": self.sep,
306
+ "sep2": self.sep2,
307
+ }
308
+ return {
309
+ "system": self.system,
310
+ "roles": self.roles,
311
+ "messages": self.messages,
312
+ "offset": self.offset,
313
+ "sep": self.sep,
314
+ "sep2": self.sep2,
315
+ }
316
+
317
+
318
+ conv_vicuna_v0 = Conversation(
319
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
320
+ roles=("Human", "Assistant"),
321
+ messages=[
322
+ ["Human", "What are the key differences between renewable and non-renewable energy sources?"],
323
+ [
324
+ "Assistant",
325
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
326
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
327
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
328
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
329
+ "renewable and non-renewable energy sources:\n"
330
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
331
+ "energy sources are finite and will eventually run out.\n"
332
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
333
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
334
+ "and other negative effects.\n"
335
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
336
+ "have lower operational costs than non-renewable sources.\n"
337
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
338
+ "locations than non-renewable sources.\n"
339
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
340
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
341
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
342
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n",
343
+ ],
344
+ ],
345
+ offset=2,
346
+ sep_style=SeparatorStyle.SINGLE,
347
+ sep="###",
348
+ )
349
+
350
+ conv_vicuna_v1 = Conversation(
351
+ system="A chat between a curious user and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the user's questions.",
352
+ roles=("USER", "ASSISTANT"),
353
+ version="v1",
354
+ messages=[],
355
+ offset=0,
356
+ sep_style=SeparatorStyle.TWO,
357
+ sep=" ",
358
+ sep2="</s>",
359
+ )
360
+
361
+ conv_llama_2 = Conversation(
362
+ system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
363
+
364
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
365
+ roles=("USER", "ASSISTANT"),
366
+ version="llama_v2",
367
+ messages=[],
368
+ offset=0,
369
+ sep_style=SeparatorStyle.LLAMA_2,
370
+ sep="<s>",
371
+ sep2="</s>",
372
+ )
373
+
374
+ conv_llava_llama_2 = Conversation(
375
+ system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
376
+ roles=("USER", "ASSISTANT"),
377
+ version="llama_v2",
378
+ messages=[],
379
+ offset=0,
380
+ sep_style=SeparatorStyle.LLAMA_2,
381
+ sep="<s>",
382
+ sep2="</s>",
383
+ )
384
+
385
+ def safe_load_tokenizer(tokenizer_id):
386
+ try:
387
+ return AutoTokenizer.from_pretrained(tokenizer_id)
388
+ except Exception:
389
+ return None
390
+
391
+ conv_llava_llama_3 = Conversation(
392
+ system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
393
+ roles=("user", "assistant"),
394
+ version="llama_v3",
395
+ messages=[],
396
+ offset=0,
397
+ sep="<|eot_id|>",
398
+ sep_style=SeparatorStyle.LLAMA_3,
399
+ tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct",
400
+ tokenizer=safe_load_tokenizer("/data_storage/lbw/shared/pretrained_models/Meta-Llama-3-8B-Instruct"),
401
+ stop_token_ids=[128009],
402
+ )
403
+
404
+ conv_mistral_instruct = Conversation(
405
+ system="",
406
+ roles=("USER", "ASSISTANT"),
407
+ version="llama_v2",
408
+ messages=[],
409
+ offset=0,
410
+ sep_style=SeparatorStyle.LLAMA_2,
411
+ sep="",
412
+ sep2="</s>",
413
+ )
414
+
415
+ conv_llava_llama_2_simple = Conversation(
416
+ system="Answer the questions about the visual content that the user provides.",
417
+ roles=("USER", "ASSISTANT"),
418
+ version="llama_v2",
419
+ messages=[],
420
+ offset=0,
421
+ sep_style=SeparatorStyle.LLAMA_2,
422
+ sep="<s>",
423
+ sep2="</s>",
424
+ )
425
+
426
+ conv_llava_llama_2_mmtag = Conversation(
427
+ system="Answer the questions about the visual content that the user provides." "The visual content will be provided with the following format: <Image>visual content</Image>.",
428
+ roles=("USER", "ASSISTANT"),
429
+ version="llama_v2_mmtag",
430
+ messages=[],
431
+ offset=0,
432
+ sep_style=SeparatorStyle.LLAMA_2,
433
+ sep="<s>",
434
+ sep2="</s>",
435
+ )
436
+
437
+ conv_mpt = Conversation(
438
+ system="""<|im_start|>system
439
+ A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
440
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
441
+ version="mpt",
442
+ messages=[],
443
+ offset=0,
444
+ sep_style=SeparatorStyle.MPT,
445
+ sep="<|im_end|>",
446
+ )
447
+
448
+ conv_qwen = Conversation(
449
+ system="""<|im_start|>system
450
+ You are a helpful assistant.""",
451
+ roles=("<|im_start|>user", "<|im_start|>assistant"),
452
+ version="qwen",
453
+ messages=[],
454
+ offset=0,
455
+ sep_style=SeparatorStyle.CHATML,
456
+ sep="<|im_end|>",
457
+ )
458
+
459
+ conv_qwen_2_5 = Conversation(
460
+ system="""<|im_start|>system
461
+ You are Qwen, created by Alibaba Cloud. You are a helpful assistant.""",
462
+ roles=("<|im_start|>user", "<|im_start|>assistant"),
463
+ version="qwen",
464
+ messages=[],
465
+ offset=0,
466
+ sep_style=SeparatorStyle.CHATML,
467
+ sep="<|im_end|>",
468
+ )
469
+
470
+ conv_gemma_instruct = Conversation(system="", roles=("<start_of_turn>user\n", "<start_of_turn>model\n"), version="gemma", messages=[], offset=0, sep_style=SeparatorStyle.GEMMA, sep="<end_of_turn>\n")
471
+
472
+ conv_llava_plain = Conversation(
473
+ system="",
474
+ roles=("", ""),
475
+ messages=[],
476
+ offset=0,
477
+ sep_style=SeparatorStyle.PLAIN,
478
+ sep="\n",
479
+ )
480
+
481
+ conv_llada_plain = Conversation(
482
+ system="",
483
+ roles=("", ""),
484
+ messages=[],
485
+ version="llada_plain",
486
+ offset=0,
487
+ sep_style=SeparatorStyle.LLAMA_3,
488
+ sep="\n",
489
+ )
490
+
491
+ conv_llava_llada = Conversation(
492
+ system="You are a helpful language and vision assistant. " "You are able to understand the visual content that the user provides, " "and assist the user with a variety of tasks using natural language.",
493
+ roles=("user", "assistant"),
494
+ version="llava_llada",
495
+ messages=[],
496
+ offset=0,
497
+ sep="<|eot_id|>",
498
+ sep_style=SeparatorStyle.LLAMA_3,
499
+ )
500
+
501
+ conv_llava_v0 = Conversation(
502
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
503
+ roles=("Human", "Assistant"),
504
+ messages=[],
505
+ offset=0,
506
+ sep_style=SeparatorStyle.SINGLE,
507
+ sep="###",
508
+ )
509
+
510
+ conv_llava_v0_mmtag = Conversation(
511
+ system="A chat between a curious user and an artificial intelligence assistant. "
512
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
513
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
514
+ roles=("Human", "Assistant"),
515
+ messages=[],
516
+ offset=0,
517
+ sep_style=SeparatorStyle.SINGLE,
518
+ sep="###",
519
+ version="v0_mmtag",
520
+ )
521
+
522
+ conv_llava_v1 = Conversation(
523
+ system="A chat between a curious human and an artificial intelligence assistant. " "The assistant gives helpful, detailed, and polite answers to the human's questions.",
524
+ roles=("USER", "ASSISTANT"),
525
+ version="v1",
526
+ messages=[],
527
+ offset=0,
528
+ sep_style=SeparatorStyle.TWO,
529
+ sep=" ",
530
+ sep2="</s>",
531
+ )
532
+
533
+ conv_llava_v1_mmtag = Conversation(
534
+ system="A chat between a curious user and an artificial intelligence assistant. "
535
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
536
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
537
+ roles=("USER", "ASSISTANT"),
538
+ messages=[],
539
+ offset=0,
540
+ sep_style=SeparatorStyle.TWO,
541
+ sep=" ",
542
+ sep2="</s>",
543
+ version="v1_mmtag",
544
+ )
545
+
546
+ conv_mistral_orca = Conversation(
547
+ system="""<|im_start|>system
548
+ You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!""",
549
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
550
+ version="mpt",
551
+ messages=[],
552
+ offset=0,
553
+ sep_style=SeparatorStyle.MPT,
554
+ sep="<|im_end|>",
555
+ )
556
+
557
+ conv_mistral_zephyr = Conversation(
558
+ system="""<|system|>
559
+ You are a helpful AI assistant.""",
560
+ roles=("<|user|>\n", "<|assistant|>\n"),
561
+ version="mpt",
562
+ messages=[],
563
+ offset=0,
564
+ sep_style=SeparatorStyle.MPT,
565
+ sep="</s>",
566
+ )
567
+
568
+ conv_mistral_direct = Conversation(
569
+ system="""<|im_start|>system
570
+ Answer the questions.""",
571
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
572
+ version="mpt",
573
+ messages=[],
574
+ offset=0,
575
+ sep_style=SeparatorStyle.MPT,
576
+ sep="<|im_end|>",
577
+ )
578
+
579
+ conv_chatml_direct = Conversation(
580
+ system="""<|im_start|>system
581
+ Answer the questions.""",
582
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
583
+ version="mpt",
584
+ messages=[],
585
+ offset=0,
586
+ sep_style=SeparatorStyle.MPT,
587
+ sep="<|im_end|>",
588
+ )
589
+
590
+ default_conversation = conv_vicuna_v0
591
+ conv_templates = {
592
+ "default": conv_vicuna_v0,
593
+ "v0": conv_vicuna_v0,
594
+ "v1": conv_vicuna_v1,
595
+ "vicuna_v1": conv_vicuna_v1,
596
+ "llama_2": conv_llama_2,
597
+ "mistral_instruct": conv_mistral_instruct,
598
+ "mistral_orca": conv_mistral_orca,
599
+ "mistral_zephyr": conv_mistral_zephyr,
600
+ "mistral_direct": conv_mistral_direct,
601
+ "plain": conv_llava_plain,
602
+ "llada_plain": conv_llada_plain,
603
+ "llava_llada": conv_llava_llada,
604
+ "v0_plain": conv_llava_plain,
605
+ "chatml_direct": conv_chatml_direct,
606
+ "llava_v0": conv_llava_v0,
607
+ "llava_v0_mmtag": conv_llava_v0_mmtag,
608
+ "llava_v1": conv_llava_v1,
609
+ "llava_v1_mmtag": conv_llava_v1_mmtag,
610
+ "llava_llama_2": conv_llava_llama_2,
611
+ "llava_llama_3": conv_llava_llama_3,
612
+ "llava_llama_2_simple": conv_llava_llama_2_simple,
613
+ "llava_llama_2_mmtag": conv_llava_llama_2_mmtag,
614
+ "llava_mistral_instruct": conv_mistral_instruct,
615
+ "mpt": conv_mpt,
616
+ "qwen_1_5": conv_qwen,
617
+ "qwen_2": conv_qwen,
618
+ "qwen_2_5": conv_qwen_2_5,
619
+ "gemma_instruct": conv_gemma_instruct,
620
+ }
621
+
622
+
623
+ if __name__ == "__main__":
624
+ print(default_conversation.get_prompt())
train/llava/hooks/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .cache_hook_LLaDA_V import register_cache_LLaDA_V
2
+
3
+ __all__ = [
4
+ "register_cache_LLaDA_V",
5
+ "logout_cache_LLaDA_V",
6
+ ]
train/llava/hooks/cache_hook_LLaDA_V.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Optional, Tuple, List
3
+ import torch.nn as nn
4
+ import types
5
+ from llava.cache import dLLMCache
6
+ import math
7
+
8
+ # Helper functions from the new LLADa model (need to be accessible)
9
+ def rotate_half(x):
10
+ """Rotates half the hidden dims of the input."""
11
+ x1 = x[..., : x.shape[-1] // 2]
12
+ x2 = x[..., x.shape[-1] // 2 :]
13
+ return torch.cat((-x2, x1), dim=-1)
14
+
15
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
16
+ cos = cos.unsqueeze(unsqueeze_dim)
17
+ sin = sin.unsqueeze(unsqueeze_dim)
18
+ q_embed = (q * cos) + (rotate_half(q) * sin)
19
+ k_embed = (k * cos) + (rotate_half(k) * sin)
20
+ return q_embed, k_embed
21
+ # --- End of imports/helpers from new LLaDA model ---
22
+
23
+
24
+ def register_cache_LLaDA_V(model: nn.Module, tf_block_module_key_name: str) -> None:
25
+ """
26
+ Registers cache hooks for a LLaDA-like model.
27
+ tf_block_module_key_name is typically 'model.layers' for LLaMA-style models.
28
+ """
29
+ target_module_path = tf_block_module_key_name.split('.')
30
+ current_module = model
31
+ for part in target_module_path:
32
+ current_module = getattr(current_module, part)
33
+
34
+ target_module: Optional[nn.ModuleList] = current_module
35
+ if target_module is None or not isinstance(target_module, nn.ModuleList):
36
+ raise ValueError(f"Could not find nn.ModuleList at {tf_block_module_key_name}")
37
+
38
+ for layer_index, tf_block in enumerate(target_module):
39
+ setattr(tf_block, "layer_idx", layer_index)
40
+
41
+ setattr(tf_block, "_old_forward", tf_block.forward)
42
+ tf_block.forward = types.MethodType(llada_cache_hook_feature, tf_block)
43
+
44
+ setattr(tf_block.self_attn, "_old_forward_main", tf_block.self_attn.forward)
45
+ tf_block.self_attn.attention_forward_for_cache = types.MethodType(
46
+ llada_attention_hook_for_cache, tf_block.self_attn
47
+ )
48
+
49
+ setattr(tf_block.self_attn.rotary_emb, "_old_forward", tf_block.self_attn.rotary_emb.forward)
50
+ tf_block.self_attn.rotary_emb.forward = types.MethodType(
51
+ llada_RoPe_forward_hook, tf_block.self_attn.rotary_emb
52
+ )
53
+
54
+
55
+ def llada_attention_hook_for_cache(
56
+ self, # self is LLaDAAttention instance
57
+ q_in_proj: torch.Tensor, # Renamed from q to clarify it's post-projection from cache_hook
58
+ k_in_proj: torch.Tensor, # Renamed from k
59
+ v_in_proj: torch.Tensor, # Renamed from v
60
+ attention_bias: Optional[torch.Tensor] = None,
61
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
62
+ use_cache: bool = False,
63
+ q_index: Optional[torch.Tensor] = None,
64
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
65
+
66
+ # q_in_proj, k_in_proj, v_in_proj are (Batch, SeqLen_specific_to_them, HiddenDim_model)
67
+ B, q_len_current_q = q_in_proj.shape[0], q_in_proj.shape[1] # q_len_current_q is the length of the Q for this specific call
68
+
69
+ q_num_heads = self.num_heads
70
+ k_num_heads = self.num_key_value_heads
71
+ v_num_heads = self.num_key_value_heads
72
+ head_dim = self.head_dim
73
+
74
+ # Reshape q, k, v to (Batch, NumHeads, SeqLen, HeadDim)
75
+ q = q_in_proj.view(B, q_len_current_q, q_num_heads, head_dim).transpose(1, 2)
76
+
77
+ k_seq_len_current_k = k_in_proj.shape[1] # k_seq_len_current_k is the length of K for this call (e.g., full context)
78
+ v_seq_len_current_v = v_in_proj.shape[1]
79
+
80
+ k = k_in_proj.view(B, k_seq_len_current_k, k_num_heads, head_dim).transpose(1, 2)
81
+ v = v_in_proj.view(B, v_seq_len_current_v, v_num_heads, head_dim).transpose(1, 2)
82
+
83
+ if hasattr(self, 'rotary_emb'):
84
+ # q_index passed here should be for q_in_proj
85
+ q, k = self.rotary_emb(q, k, q_index=q_index)
86
+
87
+ present = None
88
+
89
+ k_repeated = repeat_kv(k, self.num_key_value_groups)
90
+ v_repeated = repeat_kv(v, self.num_key_value_groups)
91
+
92
+ # q is (B, q_num_heads, q_len_current_q, head_dim)
93
+ # k_repeated is (B, q_num_heads, k_seq_len_current_k, head_dim)
94
+
95
+ attn_weights = torch.matmul(q, k_repeated.transpose(2, 3)) / math.sqrt(self.head_dim)
96
+
97
+ if attention_bias is not None:
98
+ bias_q_dim = attention_bias.shape[-2]
99
+ bias_k_dim = attention_bias.shape[-1]
100
+
101
+ sliced_attention_bias = attention_bias
102
+ if q_len_current_q < bias_q_dim : # Q is a segment, assume it's the latest tokens
103
+ # This assumes the q segment is the last part of the full query sequence represented by the bias
104
+ sliced_attention_bias = attention_bias[:, :, -q_len_current_q:, :]
105
+
106
+ if k_seq_len_current_k < bias_k_dim: # K is a segment (less likely for full KV cache but possible)
107
+ # This assumes K is the latest part of the full key sequence in the bias
108
+ sliced_attention_bias = sliced_attention_bias[:, :, :, -k_seq_len_current_k:]
109
+
110
+
111
+ # Final check on dimensions before adding
112
+ if attn_weights.shape[-2] == sliced_attention_bias.shape[-2] and \
113
+ attn_weights.shape[-1] == sliced_attention_bias.shape[-1]:
114
+ attn_weights = attn_weights + sliced_attention_bias
115
+ else:
116
+ if sliced_attention_bias.shape[1] == 1 and attn_weights.shape[1] == self.num_heads: # Mask has 1 head dim
117
+ attn_weights = attn_weights + sliced_attention_bias # Broadcast over heads
118
+ elif sliced_attention_bias.shape[1] == self.num_heads: # Mask has same num heads
119
+ attn_weights = attn_weights + sliced_attention_bias
120
+ else:
121
+ raise RuntimeError(
122
+ f"Attention bias shape {sliced_attention_bias.shape} incompatible with "
123
+ f"attn_weights shape {attn_weights.shape} after slicing."
124
+ )
125
+
126
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
127
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
128
+ att_output_heads = torch.matmul(attn_weights, v_repeated)
129
+
130
+ # Reshape to (B, q_len_current_q, ModelHiddenDim)
131
+ att_output_heads = att_output_heads.transpose(1, 2).contiguous().view(B, q_len_current_q, q_num_heads * head_dim)
132
+
133
+ output = self.o_proj(att_output_heads)
134
+
135
+ return output, present
136
+
137
+
138
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
139
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
140
+ if n_rep == 1:
141
+ return hidden_states
142
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
143
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
144
+
145
+
146
+ def llada_RoPe_forward_hook(
147
+ self_rope,
148
+ q_in: torch.Tensor,
149
+ k_in: torch.Tensor,
150
+ q_index: Optional[torch.Tensor] = None
151
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
152
+
153
+ input_dtype = q_in.dtype
154
+ q_, k_ = q_in.float(), k_in.float()
155
+
156
+ bs, _, query_len_current, head_dim_calc = q_.shape
157
+ _, _, key_len_current, _ = k_.shape
158
+
159
+ max_pos_needed = key_len_current
160
+ if q_index is not None:
161
+ max_pos_needed = max(max_pos_needed, int(q_index.max().item()) + 1 if q_index.numel() > 0 else 0)
162
+
163
+ max_pos_needed = max(max_pos_needed, query_len_current)
164
+
165
+ if max_pos_needed == 0:
166
+ return q_in, k_in
167
+
168
+ dim = self_rope.dim
169
+ inv_freq_to_use = self_rope.inv_freq.to(q_.device)
170
+ t = torch.arange(max_pos_needed, device=q_.device, dtype=torch.float32)
171
+ if hasattr(self_rope, 'scaling_factor'):
172
+ t = t / self_rope.scaling_factor
173
+
174
+ freqs = torch.outer(t, inv_freq_to_use.float())
175
+ emb = torch.cat((freqs, freqs), dim=-1)
176
+
177
+ pos_cos_table = emb.cos()
178
+ pos_sin_table = emb.sin()
179
+
180
+ if q_index is not None:
181
+ actual_q_indices = q_index[:, :query_len_current]
182
+ cos_q = pos_cos_table[actual_q_indices]
183
+ sin_q = pos_sin_table[actual_q_indices]
184
+ q_rotated = (q_ * cos_q.unsqueeze(1)) + (rotate_half(q_) * sin_q.unsqueeze(1))
185
+ else:
186
+ q_indices = torch.arange(query_len_current, device=q_.device)
187
+ cos_q = pos_cos_table[q_indices].unsqueeze(0)
188
+ sin_q = pos_sin_table[q_indices].unsqueeze(0)
189
+ q_rotated = (q_ * cos_q.unsqueeze(1)) + (rotate_half(q_) * sin_q.unsqueeze(1))
190
+
191
+ k_indices = torch.arange(key_len_current, device=q_.device)
192
+ cos_k = pos_cos_table[k_indices].unsqueeze(0)
193
+ sin_k = pos_sin_table[k_indices].unsqueeze(0)
194
+ k_rotated = (k_ * cos_k.unsqueeze(1)) + (rotate_half(k_) * sin_k.unsqueeze(1))
195
+
196
+ return q_rotated.type_as(q_in), k_rotated.type_as(k_in)
197
+
198
+
199
+ def refresh_index(
200
+ new_features: torch.Tensor,
201
+ cached_features: torch.Tensor = None,
202
+ transfer_ratio: float = 0.5,
203
+ layer_id: int = 0,
204
+ ) -> torch.Tensor:
205
+ batch_size, gen_len, d_model = new_features.shape
206
+ num_replace = int(gen_len * transfer_ratio)
207
+ if num_replace == 0 or gen_len == 0:
208
+ return torch.empty((batch_size, 0), dtype=torch.long, device=new_features.device)
209
+ if cached_features is None or cached_features.shape[1] == 0:
210
+ return torch.empty((batch_size, 0), dtype=torch.long, device=new_features.device)
211
+
212
+ cos_sim = torch.nn.functional.cosine_similarity(
213
+ new_features, cached_features, dim=-1
214
+ )
215
+ k_actual = min(num_replace, cos_sim.shape[1])
216
+ if k_actual == 0:
217
+ return torch.empty((batch_size, 0), dtype=torch.long, device=new_features.device)
218
+
219
+ transfer_index = torch.topk(cos_sim, largest=False, k=k_actual).indices
220
+ return transfer_index
221
+
222
+
223
+ def llada_cache_hook_feature(
224
+ self,
225
+ hidden_states: torch.Tensor,
226
+ attention_mask: Optional[torch.Tensor] = None, # This is the original mask for the full layer input
227
+ position_ids: Optional[torch.LongTensor] = None,
228
+ past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
229
+ use_cache: Optional[bool] = False,
230
+ output_attentions: Optional[bool] = False,
231
+ cache_position: Optional[torch.LongTensor] = None,
232
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]], Optional[Tuple[torch.Tensor, ...]]]:
233
+
234
+ current_layer_idx = self.layer_idx
235
+ feature_cache = dLLMCache()
236
+ feature_cache.update_step(current_layer_idx)
237
+
238
+ prompt_length = feature_cache.prompt_length
239
+ # x_prompt and x_gen are sub-segments of hidden_states
240
+ x_prompt = hidden_states[:, :prompt_length, :]
241
+ x_gen = hidden_states[:, prompt_length:, :]
242
+
243
+ refresh_gen = feature_cache.refresh_gen(layer_id=current_layer_idx)
244
+ refresh_prompt = feature_cache.refresh_prompt(layer_id=current_layer_idx)
245
+ transfer_ratio = feature_cache.transfer_ratio
246
+
247
+ bs, seq_len, dim = hidden_states.shape # seq_len is the length of hidden_states input to this layer
248
+ transfer = transfer_ratio > 0 and transfer_ratio <= 1
249
+
250
+ index_from_attn_transfer = None
251
+ index_expanded_from_attn_transfer = None
252
+
253
+ def project(x_input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
254
+ x_normed = self.input_layernorm(x_input)
255
+ q = self.self_attn.q_proj(x_normed)
256
+ k = self.self_attn.k_proj(x_normed)
257
+ v = self.self_attn.v_proj(x_normed)
258
+ return q, k, v
259
+
260
+ # This function needs to be smarter about the attention_bias it passes.
261
+ # q_tensor_origin_slice: A tuple (start_idx, length) indicating where q_tensor comes from
262
+ # relative to the original hidden_states/attention_mask.
263
+ def call_attention_on_qkv(q_tensor, k_tensor, v_tensor,
264
+ original_full_attention_bias,
265
+ q_tensor_start_idx: int, # Start index of q_tensor within the original sequence
266
+ q_index: Optional[torch.Tensor] = None):
267
+
268
+ q_len_for_this_call = q_tensor.shape[1]
269
+ k_len_for_this_call = k_tensor.shape[1] # This K is already the full K from dLLM cache
270
+
271
+ # Slice the original_full_attention_bias
272
+ # original_full_attention_bias is likely (B, 1 or H, S_full_layer_input, K_full_from_dllm_or_max)
273
+ # We need (B, 1 or H, q_len_for_this_call, k_len_for_this_call)
274
+ sliced_bias = original_full_attention_bias
275
+ if original_full_attention_bias is not None:
276
+ # Slice query dimension based on q_tensor_start_idx and its length
277
+ # Slice key dimension to match k_tensor's length (which is k_full from dLLM)
278
+ sliced_bias = original_full_attention_bias[
279
+ :, :, q_tensor_start_idx : q_tensor_start_idx + q_len_for_this_call, :k_len_for_this_call
280
+ ]
281
+ # Ensure num_heads dim is compatible (1 for broadcast, or matches self.self_attn.num_heads)
282
+ if sliced_bias.shape[1] != 1 and sliced_bias.shape[1] != self.self_attn.num_heads:
283
+ # This might indicate an issue with mask preparation upstream if it's not 1 or num_heads
284
+ # For now, assume it's (B,1,q,k) and will broadcast if num_heads > 1 in attention_hook
285
+ pass
286
+
287
+
288
+ att_output, _ = self.self_attn.attention_forward_for_cache(
289
+ q_tensor,
290
+ k_tensor,
291
+ v_tensor,
292
+ attention_bias=sliced_bias,
293
+ layer_past=None,
294
+ use_cache=False,
295
+ q_index=q_index,
296
+ )
297
+ return att_output
298
+
299
+ def compute_mlp(input_to_mlp: torch.Tensor) -> torch.Tensor:
300
+ if input_to_mlp.shape[1] == 0:
301
+ return torch.empty_like(input_to_mlp)
302
+ x_norm = self.post_attention_layernorm(input_to_mlp)
303
+ gate_proj_out = self.mlp.gate_proj(x_norm)
304
+ up_proj_out = self.mlp.up_proj(x_norm)
305
+ act_out = self.mlp.act_fn(gate_proj_out)
306
+ x = act_out * up_proj_out
307
+ return self.mlp.down_proj(x)
308
+
309
+ residual_pre_attn = hidden_states
310
+
311
+ if refresh_gen and refresh_prompt:
312
+ q_full, k_full, v_full = project(hidden_states)
313
+ feature_cache.set_cache(
314
+ layer_id=current_layer_idx, feature_name="kv_cache",
315
+ features={"k": k_full[:, :prompt_length, :], "v": v_full[:, :prompt_length, :]}, cache_type="prompt"
316
+ )
317
+ if hidden_states.shape[1] > prompt_length:
318
+ feature_cache.set_cache(
319
+ layer_id=current_layer_idx, feature_name="kv_cache",
320
+ features={"k": k_full[:, prompt_length:, :], "v": v_full[:, prompt_length:, :]}, cache_type="gen"
321
+ )
322
+
323
+ # Q is all of hidden_states, K,V also from all of hidden_states
324
+ # q_start_idx is 0 because q_full corresponds to the start of hidden_states
325
+ att = call_attention_on_qkv(q_full, k_full, v_full, attention_mask, q_tensor_start_idx=0, q_index=position_ids)
326
+ feature_cache.set_cache(
327
+ layer_id=current_layer_idx, feature_name="attn",
328
+ features=att[:, :prompt_length, :], cache_type="prompt"
329
+ )
330
+ if hidden_states.shape[1] > prompt_length:
331
+ feature_cache.set_cache(
332
+ layer_id=current_layer_idx, feature_name="attn",
333
+ features=att[:, prompt_length:, :], cache_type="gen"
334
+ )
335
+
336
+ elif refresh_gen and not refresh_prompt:
337
+ att_gen_part = torch.empty((bs, 0, dim), device=hidden_states.device)
338
+ if x_gen.shape[1] > 0:
339
+ q_gen, k_gen, v_gen = project(x_gen)
340
+ feature_cache.set_cache(
341
+ layer_id=current_layer_idx, feature_name="kv_cache",
342
+ features={"k": k_gen, "v": v_gen}, cache_type="gen"
343
+ )
344
+ kv_cache_prompt = feature_cache.get_cache(
345
+ layer_id=current_layer_idx, feature_name="kv_cache", cache_type="prompt"
346
+ )
347
+ k_prompt_val = kv_cache_prompt.get("k", torch.empty(bs,0,dim,device=hidden_states.device))
348
+ v_prompt_val = kv_cache_prompt.get("v", torch.empty(bs,0,dim,device=hidden_states.device))
349
+
350
+ k_full_ctx = torch.cat([k_prompt_val, k_gen], dim=1)
351
+ v_full_ctx = torch.cat([v_prompt_val, v_gen], dim=1)
352
+
353
+ q_gen_pos_ids = position_ids[:, prompt_length:] if position_ids is not None and position_ids.shape[1] > prompt_length else None
354
+
355
+ # q_gen starts at prompt_length in the original hidden_states sequence
356
+ att_gen_part = call_attention_on_qkv(q_gen, k_full_ctx, v_full_ctx, attention_mask,
357
+ q_tensor_start_idx=prompt_length, q_index=q_gen_pos_ids)
358
+
359
+ feature_cache.set_cache(
360
+ layer_id=current_layer_idx, feature_name="attn",
361
+ features=att_gen_part, cache_type="gen"
362
+ )
363
+
364
+ att_prompt_cache = feature_cache.get_cache(
365
+ layer_id=current_layer_idx, feature_name="attn", cache_type="prompt"
366
+ )
367
+ att = torch.cat([att_prompt_cache, att_gen_part], dim=1)
368
+
369
+ elif not refresh_gen and refresh_prompt:
370
+ q_prompt, k_prompt, v_prompt = project(x_prompt)
371
+ feature_cache.set_cache(
372
+ layer_id=current_layer_idx, feature_name="kv_cache",
373
+ features={"k": k_prompt, "v": v_prompt}, cache_type="prompt"
374
+ )
375
+ kv_cache_gen = feature_cache.get_cache(
376
+ layer_id=current_layer_idx, feature_name="kv_cache", cache_type="gen"
377
+ )
378
+ att_gen_cache = feature_cache.get_cache(
379
+ layer_id=current_layer_idx, feature_name="attn", cache_type="gen"
380
+ )
381
+
382
+ k_gen_current = kv_cache_gen.get("k", torch.empty(bs,0,dim, device=hidden_states.device))
383
+ v_gen_current = kv_cache_gen.get("v", torch.empty(bs,0,dim, device=hidden_states.device))
384
+
385
+ q_for_attn_segments = [q_prompt]
386
+ q_idx_for_attn_segments = [position_ids[:, :prompt_length]] if position_ids is not None else [None]
387
+ q_start_indices_segments = [0] # q_prompt starts at index 0 of hidden_states
388
+
389
+ if transfer and x_gen.shape[1] > 0 and k_gen_current.shape[1] > 0:
390
+ _, _, v_gen_for_transfer = project(x_gen)
391
+ index_from_attn_transfer = refresh_index(v_gen_for_transfer, v_gen_current, transfer_ratio, current_layer_idx)
392
+
393
+ if index_from_attn_transfer.numel() > 0:
394
+ index_expanded_from_attn_transfer = index_from_attn_transfer.unsqueeze(-1).expand(-1, -1, dim)
395
+
396
+ x_gen_normed_selected = torch.gather(self.input_layernorm(x_gen), dim=1, index=index_expanded_from_attn_transfer)
397
+ q_gen_index = self.self_attn.q_proj(x_gen_normed_selected)
398
+ k_gen_index = self.self_attn.k_proj(x_gen_normed_selected)
399
+ v_gen_index_part = self.self_attn.v_proj(x_gen_normed_selected)
400
+
401
+ k_gen_current = k_gen_current.scatter(dim=1, index=index_expanded_from_attn_transfer, src=k_gen_index)
402
+ v_gen_current = v_gen_current.scatter(dim=1, index=index_expanded_from_attn_transfer, src=v_gen_index_part)
403
+
404
+ feature_cache.set_cache(
405
+ layer_id=current_layer_idx, feature_name="kv_cache",
406
+ features={"k": k_gen_current, "v": v_gen_current}, cache_type="gen"
407
+ )
408
+
409
+ q_for_attn_segments.append(q_gen_index)
410
+ if position_ids is not None and position_ids.shape[1] > prompt_length:
411
+ gen_abs_positions_all = position_ids[:, prompt_length:]
412
+ gen_abs_positions_selected = torch.gather(gen_abs_positions_all, 1, index_from_attn_transfer)
413
+ q_idx_for_attn_segments.append(gen_abs_positions_selected)
414
+ else:
415
+ q_idx_for_attn_segments.append(None)
416
+
417
+ q_combined_for_attn = torch.cat(q_for_attn_segments, dim=1)
418
+ q_idx_combined_for_rope = torch.cat(q_idx_for_attn_segments, dim=1) if all(s is not None for s in q_idx_for_attn_segments) else None
419
+
420
+
421
+ k_full_ctx = torch.cat([k_prompt, k_gen_current], dim=1)
422
+ v_full_ctx = torch.cat([v_prompt, v_gen_current], dim=1)
423
+
424
+ # q_combined_for_attn effectively starts at index 0 of a conceptual sequence.
425
+ # Its RoPE is handled by q_idx_combined_for_rope.
426
+ att_for_q_combined = call_attention_on_qkv(q_combined_for_attn, k_full_ctx, v_full_ctx,
427
+ attention_mask, q_tensor_start_idx=0, # Since Q is combined and starts from effective 0
428
+ q_index=q_idx_combined_for_rope)
429
+
430
+ att_prompt_new = att_for_q_combined[:, :q_prompt.shape[1], :]
431
+ if transfer and index_from_attn_transfer is not None and index_from_attn_transfer.numel() > 0:
432
+ att_gen_index_new = att_for_q_combined[:, q_prompt.shape[1]:, :] # Segment for transferred Qs
433
+ if att_gen_cache.shape[1] > 0:
434
+ att_gen_cache = att_gen_cache.scatter(dim=1, index=index_expanded_from_attn_transfer, src=att_gen_index_new)
435
+ feature_cache.set_cache(
436
+ layer_id=current_layer_idx, feature_name="attn",
437
+ features=att_gen_cache, cache_type="gen"
438
+ )
439
+
440
+ feature_cache.set_cache(
441
+ layer_id=current_layer_idx, feature_name="attn",
442
+ features=att_prompt_new, cache_type="prompt"
443
+ )
444
+ att = torch.cat([att_prompt_new, att_gen_cache], dim=1)
445
+
446
+ else: # Not refresh gen, not refresh prompt
447
+ att_prompt_cache = feature_cache.get_cache(
448
+ layer_id=current_layer_idx, feature_name="attn", cache_type="prompt"
449
+ )
450
+ att_gen_cache = feature_cache.get_cache(
451
+ layer_id=current_layer_idx, feature_name="attn", cache_type="gen"
452
+ )
453
+ kv_cache_gen = feature_cache.get_cache(
454
+ layer_id=current_layer_idx, feature_name="kv_cache", cache_type="gen"
455
+ )
456
+ kv_cache_prompt = feature_cache.get_cache(
457
+ layer_id=current_layer_idx, feature_name="kv_cache", cache_type="prompt"
458
+ )
459
+
460
+ k_gen_current = kv_cache_gen.get("k", torch.empty(bs,0,dim, device=hidden_states.device))
461
+ v_gen_current = kv_cache_gen.get("v", torch.empty(bs,0,dim, device=hidden_states.device))
462
+ k_prompt_val = kv_cache_prompt.get("k", torch.empty(bs,0,dim,device=hidden_states.device))
463
+ v_prompt_val = kv_cache_prompt.get("v", torch.empty(bs,0,dim,device=hidden_states.device))
464
+
465
+ if transfer and x_gen.shape[1] > 0 and k_gen_current.shape[1] > 0:
466
+ x_gen_normed = self.input_layernorm(x_gen)
467
+ v_gen_for_transfer = self.self_attn.v_proj(x_gen_normed)
468
+ index_from_attn_transfer = refresh_index(v_gen_for_transfer, v_gen_current, transfer_ratio, current_layer_idx)
469
+
470
+ if index_from_attn_transfer.numel() > 0:
471
+ index_expanded_from_attn_transfer = index_from_attn_transfer.unsqueeze(-1).expand(-1, -1, dim)
472
+
473
+ x_gen_normed_selected = torch.gather(x_gen_normed, dim=1, index=index_expanded_from_attn_transfer)
474
+ q_gen_index_only = self.self_attn.q_proj(x_gen_normed_selected) # Q only for transferred items
475
+ k_gen_index = self.self_attn.k_proj(x_gen_normed_selected)
476
+ v_gen_index_part = self.self_attn.v_proj(x_gen_normed_selected)
477
+
478
+ k_gen_current = k_gen_current.scatter(dim=1, index=index_expanded_from_attn_transfer, src=k_gen_index)
479
+ v_gen_current = v_gen_current.scatter(dim=1, index=index_expanded_from_attn_transfer, src=v_gen_index_part)
480
+
481
+ feature_cache.set_cache(
482
+ layer_id=current_layer_idx, feature_name="kv_cache",
483
+ features={"k": k_gen_current, "v": v_gen_current}, cache_type="gen"
484
+ )
485
+
486
+ q_idx_for_transferred_rope = None
487
+ if position_ids is not None and position_ids.shape[1] > prompt_length:
488
+ gen_abs_positions_all = position_ids[:, prompt_length:]
489
+ q_idx_for_transferred_rope = torch.gather(gen_abs_positions_all, 1, index_from_attn_transfer)
490
+
491
+ k_full_ctx = torch.cat([k_prompt_val, k_gen_current], dim=1)
492
+ v_full_ctx = torch.cat([v_prompt_val, v_gen_current], dim=1)
493
+
494
+ att_gen_index_new = call_attention_on_qkv(q_gen_index_only, k_full_ctx, v_full_ctx, attention_mask,
495
+ q_tensor_start_idx=prompt_length, # Approximate for mask slicing
496
+ q_index=q_idx_for_transferred_rope)
497
+
498
+ if att_gen_cache.shape[1] > 0: # Make sure att_gen_cache has a gen part
499
+ att_gen_cache = att_gen_cache.scatter(dim=1, index=index_expanded_from_attn_transfer, src=att_gen_index_new)
500
+ elif x_gen.shape[1] > 0: # If original att_gen_cache was for an empty gen part, but x_gen is not empty
501
+ # Initialize att_gen_cache to be of x_gen's length before scattering
502
+ att_gen_cache = torch.zeros((bs, x_gen.shape[1], dim), device=hidden_states.device, dtype=att_gen_index_new.dtype)
503
+ att_gen_cache = att_gen_cache.scatter(dim=1, index=index_expanded_from_attn_transfer, src=att_gen_index_new)
504
+ # Else: if x_gen.shape[1] is 0, att_gen_cache remains empty, scatter won't happen.
505
+
506
+ feature_cache.set_cache(
507
+ layer_id=current_layer_idx, feature_name="attn",
508
+ features=att_gen_cache, cache_type="gen"
509
+ )
510
+
511
+ att = torch.cat([att_prompt_cache, att_gen_cache], dim=1)
512
+
513
+
514
+ # ... rest of the llada_cache_hook_feature (MLP part) remains the same ...
515
+ hidden_states_after_attn = residual_pre_attn + att
516
+ residual_pre_mlp = hidden_states_after_attn
517
+
518
+ x_prompt_mlp = hidden_states_after_attn[:, :prompt_length, :]
519
+ x_gen_mlp = hidden_states_after_attn[:, prompt_length:, :]
520
+
521
+ mlp_out_prompt_part = torch.empty((bs, prompt_length, dim), device=hidden_states.device, dtype=hidden_states_after_attn.dtype)
522
+ mlp_out_gen_part = torch.empty((bs, x_gen_mlp.shape[1], dim), device=hidden_states.device, dtype=hidden_states_after_attn.dtype)
523
+
524
+
525
+ if refresh_gen and refresh_prompt:
526
+ mlp_out_full = compute_mlp(hidden_states_after_attn)
527
+ mlp_out_prompt_part = mlp_out_full[:, :prompt_length, :]
528
+ if x_gen_mlp.shape[1] > 0:
529
+ mlp_out_gen_part = mlp_out_full[:, prompt_length:, :]
530
+
531
+ feature_cache.set_cache(
532
+ current_layer_idx, "mlp", mlp_out_prompt_part, cache_type="prompt"
533
+ )
534
+ if x_gen_mlp.shape[1] > 0:
535
+ feature_cache.set_cache(
536
+ current_layer_idx, "mlp", mlp_out_gen_part, cache_type="gen"
537
+ )
538
+ if mlp_out_gen_part.shape[1] > 0:
539
+ mlp_out = torch.cat([mlp_out_prompt_part, mlp_out_gen_part], dim=1)
540
+ else:
541
+ mlp_out = mlp_out_prompt_part
542
+
543
+
544
+ elif refresh_gen and not refresh_prompt:
545
+ mlp_out_prompt_part = feature_cache.get_cache(
546
+ current_layer_idx, "mlp", cache_type="prompt"
547
+ )
548
+ if x_gen_mlp.shape[1] > 0:
549
+ mlp_out_gen_part = compute_mlp(x_gen_mlp)
550
+ feature_cache.set_cache(current_layer_idx, "mlp", mlp_out_gen_part, cache_type="gen")
551
+
552
+ if mlp_out_gen_part.shape[1] > 0:
553
+ mlp_out = torch.cat([mlp_out_prompt_part, mlp_out_gen_part], dim=1)
554
+ else:
555
+ mlp_out = mlp_out_prompt_part
556
+
557
+
558
+ elif refresh_prompt and not refresh_gen:
559
+ mlp_gen_cache_data = feature_cache.get_cache(current_layer_idx, "mlp", cache_type="gen")
560
+ if x_gen_mlp.shape[1] > 0:
561
+ mlp_out_gen_part = mlp_gen_cache_data
562
+
563
+ mlp_input_for_prompt_path = x_prompt_mlp
564
+ # Use index_expanded_from_attn_transfer which was set in the attention block
565
+ if transfer and index_expanded_from_attn_transfer is not None and index_expanded_from_attn_transfer.numel() > 0 and x_gen_mlp.shape[1] > 0 :
566
+ x_gen_mlp_selected = torch.gather(x_gen_mlp, dim=1, index=index_expanded_from_attn_transfer)
567
+ mlp_input_for_prompt_path = torch.cat([x_prompt_mlp, x_gen_mlp_selected], dim=1)
568
+
569
+ mlp_out_prompt_path_processed = compute_mlp(mlp_input_for_prompt_path)
570
+ mlp_out_prompt_part = mlp_out_prompt_path_processed[:, :x_prompt_mlp.shape[1], :]
571
+
572
+ if transfer and index_expanded_from_attn_transfer is not None and index_expanded_from_attn_transfer.numel() > 0 and x_gen_mlp.shape[1] > 0:
573
+ mlp_gen_index_new = mlp_out_prompt_path_processed[:, x_prompt_mlp.shape[1]:, :]
574
+ if mlp_out_gen_part.shape[1] > 0: # If gen part exists
575
+ mlp_out_gen_part = mlp_out_gen_part.scatter(dim=1, index=index_expanded_from_attn_transfer, src=mlp_gen_index_new)
576
+
577
+
578
+ feature_cache.set_cache(current_layer_idx, "mlp", mlp_out_gen_part, cache_type="gen")
579
+
580
+ feature_cache.set_cache(current_layer_idx, "mlp", mlp_out_prompt_part, cache_type="prompt")
581
+ if mlp_out_gen_part.shape[1] > 0:
582
+ mlp_out = torch.cat([mlp_out_prompt_part, mlp_out_gen_part], dim=1)
583
+ else:
584
+ mlp_out = mlp_out_prompt_part
585
+
586
+
587
+ else:
588
+ mlp_out_prompt_part = feature_cache.get_cache(
589
+ current_layer_idx, "mlp", cache_type="prompt"
590
+ )
591
+ mlp_gen_cache_data = feature_cache.get_cache(current_layer_idx, "mlp", cache_type="gen")
592
+ if x_gen_mlp.shape[1] > 0:
593
+ mlp_out_gen_part = mlp_gen_cache_data
594
+
595
+ # Use index_expanded_from_attn_transfer
596
+ if transfer and index_expanded_from_attn_transfer is not None and index_expanded_from_attn_transfer.numel() > 0 and x_gen_mlp.shape[1] > 0:
597
+ x_gen_mlp_selected = torch.gather(x_gen_mlp, dim=1, index=index_expanded_from_attn_transfer)
598
+ mlp_out_gen_index = compute_mlp(x_gen_mlp_selected)
599
+ if mlp_out_gen_part.shape[1] > 0:
600
+ mlp_out_gen_part = mlp_out_gen_part.scatter(dim=1, index=index_expanded_from_attn_transfer, src=mlp_out_gen_index)
601
+
602
+ feature_cache.set_cache(current_layer_idx, "mlp", mlp_out_gen_part, cache_type="gen")
603
+
604
+ if mlp_out_gen_part.shape[1] > 0:
605
+ mlp_out = torch.cat([mlp_out_prompt_part, mlp_out_gen_part], dim=1)
606
+ else:
607
+ mlp_out = mlp_out_prompt_part
608
+
609
+
610
+ final_hidden_states = residual_pre_mlp + mlp_out
611
+
612
+ returned_outputs = (final_hidden_states,)
613
+ if output_attentions:
614
+ returned_outputs += (None,)
615
+ if use_cache:
616
+ returned_outputs += (None,)
617
+
618
+ return returned_outputs
619
+
train/llava/hooks/fast_dllm_hook.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Fast dLLM Cache Hook for LLaDA Model
3
+
4
+ This module contains hooks and utilities for implementing fast distributed LLM caching
5
+ in the LLaDA model architecture.
6
+ """
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ import math
12
+ from typing import Optional, Tuple, List, Sequence, Union
13
+ import numpy as np
14
+
15
+ class FastDLLMGenerationHook:
16
+ """
17
+ Hook class for implementing fast dLLM caching functionality in LLaDA model.
18
+ This class handles both attention-level caching and generation-level optimizations.
19
+ """
20
+
21
+ def __init__(self, model):
22
+ self.model = model
23
+ self.original_methods = {}
24
+ self.is_registered = False
25
+
26
+ def register_hooks(self):
27
+ """Register fast dLLM hooks to the model."""
28
+ if self.is_registered:
29
+ return
30
+
31
+ # Store original methods
32
+ self.original_methods['generate'] = self.model.generate # 新增:保存原始的generate方法
33
+
34
+ # Store original attention forwards
35
+ for layer_idx, layer in enumerate(self.model.model.layers):
36
+ self.original_methods[f'attention_{layer_idx}'] = layer.self_attn.forward
37
+ # Replace attention forward with fast cache version
38
+ layer.self_attn.forward = self._create_fast_attention_forward(layer.self_attn, layer_idx)
39
+
40
+ self.model.generate = self._fast_generate # 新增:替换generate方法
41
+
42
+ self.is_registered = True
43
+
44
+ def unregister_hooks(self):
45
+ """Unregister fast dLLM hooks from the model."""
46
+ if not self.is_registered:
47
+ return
48
+
49
+ # Restore original methods
50
+ self.model.generate = self.original_methods['generate'] # 新增:恢复原始的generate方法
51
+
52
+ # Restore original attention forwards
53
+ for layer_idx, layer in enumerate(self.model.model.layers):
54
+ layer.self_attn.forward = self.original_methods[f'attention_{layer_idx}']
55
+
56
+ self.is_registered = False
57
+
58
+ def _create_fast_attention_forward(self, attention_layer, layer_idx):
59
+ """Create fast attention forward method with caching support."""
60
+ def fast_attention_forward(
61
+ hidden_states: torch.Tensor,
62
+ attention_mask: Optional[torch.Tensor] = None,
63
+ position_ids: Optional[torch.LongTensor] = None,
64
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
65
+ output_attentions: bool = False,
66
+ use_cache: bool = False,
67
+ cache_position: Optional[torch.LongTensor] = None,
68
+ fast_dllm_cache: Optional[Sequence[Tuple[torch.Tensor, torch.Tensor]]] = None,
69
+ **kwargs,
70
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
71
+
72
+ # If not using fast cache or output_attentions is needed, use original method
73
+ if output_attentions:
74
+ return self.original_methods[f'attention_{layer_idx}'](
75
+ hidden_states=hidden_states,
76
+ attention_mask=attention_mask,
77
+ position_ids=position_ids,
78
+ past_key_value=past_key_value,
79
+ output_attentions=output_attentions,
80
+ use_cache=use_cache,
81
+ cache_position=cache_position,
82
+ **kwargs
83
+ )
84
+
85
+ bsz, q_len, _ = hidden_states.size()
86
+
87
+ query_states = attention_layer.q_proj(hidden_states)
88
+ key_states = attention_layer.k_proj(hidden_states)
89
+ value_states = attention_layer.v_proj(hidden_states)
90
+
91
+ query_states = query_states.view(bsz, q_len, attention_layer.num_heads, attention_layer.head_dim).transpose(1, 2)
92
+ key_states = key_states.view(bsz, q_len, attention_layer.num_key_value_heads, attention_layer.head_dim).transpose(1, 2)
93
+ value_states = value_states.view(bsz, q_len, attention_layer.num_key_value_heads, attention_layer.head_dim).transpose(1, 2)
94
+
95
+ # Apply rotary position embedding with fast cache consideration
96
+ cache_offset = 0
97
+ if fast_dllm_cache and len(fast_dllm_cache) > layer_idx:
98
+ cache_offset = fast_dllm_cache[layer_idx][0].shape[-2]
99
+
100
+ cos, sin = attention_layer.rotary_emb(value_states, position_ids + cache_offset if cache_offset > 0 else position_ids)
101
+ query_states, key_states = self._apply_rotary_pos_emb(query_states, key_states, cos, sin)
102
+
103
+ # Handle past key values
104
+ past_key_value = getattr(attention_layer, "past_key_value", past_key_value)
105
+ if past_key_value is not None:
106
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
107
+ key_states, value_states = past_key_value.update(key_states, value_states, layer_idx, cache_kwargs)
108
+
109
+ # Fast dLLM cache logic
110
+ if fast_dllm_cache is not None:
111
+ if len(fast_dllm_cache) <= layer_idx:
112
+ fast_dllm_cache.append((key_states, value_states))
113
+ else:
114
+ past_key, past_value = fast_dllm_cache[layer_idx]
115
+ key_states = torch.cat([past_key, key_states], dim=-2)
116
+ value_states = torch.cat([past_value, value_states], dim=-2)
117
+
118
+ # Repeat key-value pairs for multi-head attention
119
+ key_states = self._repeat_kv(key_states, attention_layer.num_key_value_groups)
120
+ value_states = self._repeat_kv(value_states, attention_layer.num_key_value_groups)
121
+
122
+ # Apply causal mask
123
+ causal_mask = attention_mask
124
+ if attention_mask is not None:
125
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
126
+
127
+ # Ensure contiguous tensors for CUDA
128
+ if query_states.device.type == "cuda" and causal_mask is not None:
129
+ query_states = query_states.contiguous()
130
+ key_states = key_states.contiguous()
131
+ value_states = value_states.contiguous()
132
+
133
+ # Scaled dot-product attention
134
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
135
+ query_states,
136
+ key_states,
137
+ value_states,
138
+ attn_mask=None,
139
+ is_causal=False,
140
+ dropout_p=attention_layer.attention_dropout if attention_layer.training else 0.0,
141
+ )
142
+
143
+ attn_output = attn_output.transpose(1, 2).contiguous()
144
+ attn_output = attn_output.view(bsz, q_len, attention_layer.hidden_size)
145
+ attn_output = attention_layer.o_proj(attn_output)
146
+
147
+ return attn_output, None, past_key_value
148
+
149
+ return fast_attention_forward
150
+
151
+ @torch.no_grad()
152
+ def _fast_generate(
153
+ self,
154
+ inputs: Optional[torch.Tensor] = None,
155
+ images: Optional[torch.Tensor] = None,
156
+ image_sizes: Optional[torch.Tensor] = None,
157
+ modalities: Optional[List[str]] = ["image"],
158
+ **kwargs,
159
+ ):
160
+ modalities = kwargs.pop("modalities", None) if "modalities" in kwargs and modalities is None else modalities
161
+ position_ids = kwargs.pop("position_ids", None)
162
+ attention_mask = kwargs.pop("attention_mask", None)
163
+ if "inputs_embeds" in kwargs:
164
+ raise NotImplementedError("`inputs_embeds` is not supported")
165
+
166
+ if images is not None:
167
+ (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.model.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes)
168
+ else:
169
+ inputs_embeds = self.model.get_model().embed_tokens(inputs)
170
+ output = self._fast_generate_with_embeds(inputs_embeds=inputs_embeds, **kwargs)
171
+ return output
172
+
173
+ @torch.no_grad()
174
+ def _fast_generate_with_embeds(
175
+ self,
176
+ inputs_embeds,
177
+ steps=128,
178
+ gen_length=128,
179
+ block_length=128,
180
+ temperature=0.0,
181
+ cfg_scale=0.0,
182
+ remasking='low_confidence',
183
+ mask_id=126336,
184
+ tokenizer=None,
185
+ stopping_criteria=None,
186
+ generation_suffix=None,
187
+ threshold=None,
188
+ prefix_refresh_interval=32,
189
+ **kwargs
190
+ ):
191
+ """
192
+ Fast generation with embeddings using dLLM cache optimization.
193
+ This method incorporates all fast dLLM related optimizations.
194
+ """
195
+ # Use mixed precision for faster computation
196
+ with torch.cuda.amp.autocast(enabled=True):
197
+ # Handle generation suffix
198
+ suffix_embeds = None
199
+ suffix_token_ids = None
200
+ suffix_len = 0
201
+ if generation_suffix is not None and tokenizer is not None and len(generation_suffix) > 0:
202
+ suffix_token_ids = tokenizer.encode(generation_suffix, add_special_tokens=False)
203
+ suffix_token_ids = torch.tensor(suffix_token_ids, dtype=torch.long, device=inputs_embeds.device).unsqueeze(0)
204
+ suffix_embeds = self.model.model.embed_tokens(suffix_token_ids)
205
+ suffix_len = suffix_embeds.shape[1]
206
+
207
+ # Create input in embedding space
208
+ total_length = inputs_embeds.shape[1] + gen_length + suffix_len
209
+ masked_embed = self.model.model.embed_tokens(torch.tensor([mask_id]).to(inputs_embeds.device))
210
+ x_embeds = masked_embed.repeat(1, total_length, 1).to(inputs_embeds.device)
211
+ x_embeds[:, :inputs_embeds.shape[1]] = inputs_embeds.clone()
212
+ if suffix_embeds is not None:
213
+ x_embeds[:, -suffix_len:] = suffix_embeds
214
+
215
+ # Create tracking tensor for token IDs
216
+ x = torch.full((1, total_length), mask_id, dtype=torch.long, device=inputs_embeds.device)
217
+ if suffix_token_ids is not None:
218
+ x[:, -suffix_len:] = suffix_token_ids
219
+
220
+ # Prompt index tracking
221
+ prompt_index = torch.zeros((1, total_length), dtype=torch.bool, device=inputs_embeds.device)
222
+ prompt_index[:, :inputs_embeds.shape[1]] = 1
223
+
224
+ assert gen_length % block_length == 0
225
+ num_blocks = gen_length // block_length
226
+ assert steps % num_blocks == 0
227
+ steps = steps // num_blocks
228
+
229
+ # Initialize stop tracking
230
+ stop_position = inputs_embeds.shape[1] + gen_length
231
+ found_stop_seq = False
232
+ stop_tokens = []
233
+
234
+ if stopping_criteria is not None:
235
+ assert tokenizer is not None, "tokenizer is required when stopping_criteria is not None"
236
+ for stop_str in stopping_criteria:
237
+ tokens = tokenizer.encode(stop_str, add_special_tokens=False)
238
+ stop_tokens.append(tokens)
239
+
240
+ # Process each block
241
+ for num_block in range(num_blocks):
242
+ block_start = inputs_embeds.shape[1] + num_block * block_length
243
+ block_end = inputs_embeds.shape[1] + (num_block + 1) * block_length
244
+
245
+ # Skip if stop found before current block
246
+ if found_stop_seq and stop_position <= block_start:
247
+ break
248
+
249
+ block_embeds = x_embeds[:, block_start:block_end]
250
+ block_mask_index = torch.all(torch.abs(block_embeds - masked_embed) < 1e-5, dim=2)
251
+ num_transfer_tokens = self._get_num_transfer_tokens(block_mask_index, steps)
252
+
253
+
254
+ i = 0
255
+
256
+ while True:
257
+ if threshold is None and i >= steps:
258
+ break
259
+
260
+ # Check mask state
261
+ mask_index = torch.all(torch.abs(x_embeds - masked_embed) < 1e-5, dim=2)
262
+
263
+ if found_stop_seq:
264
+ pre_stop_masks = mask_index[0, inputs_embeds.shape[1]:stop_position]
265
+ if not pre_stop_masks.any():
266
+ break
267
+
268
+ current_block_masks = mask_index[0, block_start:block_end]
269
+ if not current_block_masks.any():
270
+ break
271
+
272
+ # Handle CFG
273
+ if cfg_scale > 0.0:
274
+ un_embeds = x_embeds.clone()
275
+ un_mask = prompt_index.unsqueeze(-1).expand_as(x_embeds)
276
+ un_embeds[un_mask] = masked_embed.repeat(x_embeds.shape[0], x_embeds.shape[1], 1)[un_mask]
277
+ combined_embeds = torch.cat([x_embeds, un_embeds], dim=0)
278
+
279
+ outputs = self.model.model(
280
+ inputs_embeds=combined_embeds,
281
+ fast_dllm_cache=fast_dllm_cache
282
+ )
283
+ logits = self.model.lm_head(outputs[0]).float()
284
+ logits, un_logits = torch.chunk(logits, 2, dim=0)
285
+ logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
286
+ else:
287
+ if i % prefix_refresh_interval == 0:
288
+ fast_dllm_cache = []
289
+ outputs = self.model.model(
290
+ inputs_embeds=x_embeds,
291
+ fast_dllm_cache=fast_dllm_cache
292
+ )
293
+ # Slice cache to block start
294
+ fast_dllm_cache = self._create_cache_slice(fast_dllm_cache, block_start)
295
+ else:
296
+ # Incremental forward pass
297
+ outputs = self.model.model(
298
+ inputs_embeds=x_embeds[:, block_start:],
299
+ fast_dllm_cache=fast_dllm_cache
300
+ )
301
+ logits = self.model.lm_head(outputs[0]).float()
302
+
303
+ # Filter forbidden tokens
304
+ forbidden_tokens = [126081, 126080, 126346, 126347]
305
+ if i % prefix_refresh_interval == 0:
306
+ for token_id in forbidden_tokens:
307
+ logits[:, :, token_id] = torch.where(mask_index, -float('inf'), logits[:, :, token_id])
308
+ else:
309
+ for token_id in forbidden_tokens:
310
+ logits[:, :, token_id] = torch.where(mask_index[:, block_start:], -float('inf'), logits[:, :, token_id])
311
+
312
+ # Get transfer indices and update
313
+ if i % prefix_refresh_interval == 0:
314
+ x0, transfer_index = self._get_transfer_index(
315
+ logits, temperature, remasking, mask_index, x,
316
+ num_transfer_tokens[:, i] if threshold is None else None,
317
+ found_stop_seq, stop_position, block_end, suffix_len, threshold
318
+ )
319
+ x0_embeds = self.model.model.embed_tokens(x0)
320
+ x0_embeds = torch.where(mask_index.unsqueeze(-1).expand_as(x_embeds), x0_embeds, x_embeds)
321
+ x_embeds[transfer_index] = x0_embeds[transfer_index]
322
+ x[transfer_index] = x0[transfer_index]
323
+ else:
324
+ x0, transfer_index = self._get_transfer_index(
325
+ logits, temperature, remasking, mask_index[:, block_start:], x[:, block_start:],
326
+ num_transfer_tokens[:, i] if threshold is None else None,
327
+ found_stop_seq, stop_position - block_start, block_end - block_start, suffix_len, threshold
328
+ )
329
+ x0_embeds = self.model.model.embed_tokens(x0)
330
+ x0_embeds = torch.where(mask_index[:, block_start:].unsqueeze(-1).expand_as(x_embeds[:, block_start:]),
331
+ x0_embeds, x_embeds[:, block_start:])
332
+ x_embeds[:, block_start:][transfer_index] = x0_embeds[transfer_index]
333
+ x[:, block_start:][transfer_index] = x0[transfer_index]
334
+
335
+ # Check for stop words
336
+ if stopping_criteria is not None:
337
+ generated_part = x[0, inputs_embeds.shape[1]:inputs_embeds.shape[1] + gen_length]
338
+ for stop_seq in stop_tokens:
339
+ if not isinstance(stop_seq, list):
340
+ stop_seq = [stop_seq]
341
+ for start_idx in range(generated_part.size(0) - len(stop_seq) + 1):
342
+ if torch.all(generated_part[start_idx:start_idx + len(stop_seq)] == torch.tensor(stop_seq, device=x.device)):
343
+ current_position = inputs_embeds.shape[1] + start_idx
344
+ if not found_stop_seq or current_position < stop_position:
345
+ stop_position = current_position
346
+ found_stop_seq = True
347
+ break
348
+ if found_stop_seq:
349
+ break
350
+ i += 1
351
+
352
+ if threshold is not None:
353
+ print(f'Number of steps: {i}')
354
+
355
+ # Return results
356
+ if found_stop_seq:
357
+ if suffix_len > 0:
358
+ return torch.cat([x[:, inputs_embeds.shape[1]:stop_position], x[:, -suffix_len:]], dim=1)
359
+ else:
360
+ return x[:, inputs_embeds.shape[1]:stop_position]
361
+ else:
362
+ if suffix_len > 0:
363
+ return torch.cat([x[:, inputs_embeds.shape[1]:inputs_embeds.shape[1] + gen_length], x[:, -suffix_len:]], dim=1)
364
+ else:
365
+ return x[:, inputs_embeds.shape[1]:inputs_embeds.shape[1] + gen_length]
366
+
367
+ @staticmethod
368
+ def _apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
369
+ """Apply rotary position embedding to query and key tensors."""
370
+ cos = cos.unsqueeze(unsqueeze_dim)
371
+ sin = sin.unsqueeze(unsqueeze_dim)
372
+ q_embed = (q * cos) + (FastDLLMGenerationHook._rotate_half(q) * sin)
373
+ k_embed = (k * cos) + (FastDLLMGenerationHook._rotate_half(k) * sin)
374
+ return q_embed, k_embed
375
+
376
+ @staticmethod
377
+ def _rotate_half(x):
378
+ """Rotates half the hidden dims of the input."""
379
+ x1 = x[..., : x.shape[-1] // 2]
380
+ x2 = x[..., x.shape[-1] // 2 :]
381
+ return torch.cat((-x2, x1), dim=-1)
382
+
383
+ @staticmethod
384
+ def _repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
385
+ """Repeat key-value pairs for multi-head attention."""
386
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
387
+ if n_rep == 1:
388
+ return hidden_states
389
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
390
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
391
+
392
+ def _get_transfer_index(self, logits, temperature, remasking, mask_index, x, num_transfer_tokens,
393
+ found_stop_seq, stop_position, block_end, suffix_len, threshold=None):
394
+ """Get transfer indices for token updates during generation."""
395
+ logits_with_noise = self._add_gumbel_noise(logits, temperature=temperature)
396
+ x0 = torch.argmax(logits_with_noise, dim=-1)
397
+
398
+ if remasking == 'low_confidence':
399
+ p = F.softmax(logits.to(torch.float64), dim=-1)
400
+ x0_p = torch.squeeze(torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1)
401
+ elif remasking == 'random':
402
+ x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
403
+ else:
404
+ raise NotImplementedError(remasking)
405
+
406
+ # Handle stop sequences and block boundaries
407
+ if found_stop_seq:
408
+ x0_p[:, stop_position:] = -np.inf
409
+ else:
410
+ x0_p[:, block_end:] = -np.inf
411
+
412
+ # Prevent overwriting suffix
413
+ if suffix_len > 0:
414
+ x0_p[:, -suffix_len:] = -np.inf
415
+
416
+ x0 = torch.where(mask_index, x0, x)
417
+ confidence = torch.where(mask_index, x0_p, -np.inf)
418
+
419
+ transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
420
+
421
+ if threshold is not None:
422
+ num_transfer_tokens = mask_index.sum(dim=1, keepdim=True)
423
+
424
+ for j in range(confidence.shape[0]):
425
+ if threshold is None:
426
+ top_i = num_transfer_tokens[j]
427
+ else:
428
+ ns = list(range(1, num_transfer_tokens[j] + 1))
429
+ es = [threshold / (n + 1) for n in ns]
430
+ threshs = [1 - e for e in es]
431
+ threshs[0] = -1 # at least one token is transferred
432
+
433
+ sorted_confidence = torch.sort(confidence[j][mask_index[j]], dim=-1, descending=True)[0]
434
+ assert len(sorted_confidence) == len(threshs)
435
+
436
+ for top_i in range(len(threshs)):
437
+ if sorted_confidence[top_i] < threshs[top_i]:
438
+ break
439
+
440
+ if top_i == 0 or top_i == len(threshs) - 1:
441
+ top_i += 1
442
+
443
+ _, select_index = torch.topk(confidence[j], k=top_i)
444
+ transfer_index[j, select_index] = True
445
+
446
+ return x0, transfer_index
447
+
448
+ @staticmethod
449
+ def _add_gumbel_noise(logits, temperature):
450
+ """Add Gumbel noise for categorical sampling."""
451
+ if temperature == 0:
452
+ return logits
453
+
454
+ logits = logits.to(torch.float64)
455
+ noise = torch.rand_like(logits, dtype=torch.float64)
456
+ gumbel_noise = (-torch.log(noise)) ** temperature
457
+ return logits.exp() / gumbel_noise
458
+
459
+ @staticmethod
460
+ def _get_num_transfer_tokens(mask_index, steps):
461
+ """Precompute the number of tokens to transition at each step."""
462
+ mask_num = mask_index.sum(dim=1, keepdim=True)
463
+ base = mask_num // steps
464
+ remainder = mask_num % steps
465
+
466
+ num_transfer_tokens = base.expand(-1, steps).clone()
467
+
468
+ if remainder.sum() > 0:
469
+ indices = torch.arange(steps, device=mask_index.device)
470
+ mask = indices.unsqueeze(0) < remainder
471
+ num_transfer_tokens[mask] += 1
472
+
473
+ return num_transfer_tokens.to(torch.int64)
474
+
475
+ def _create_cache_slice(self, fast_dllm_cache, block_start):
476
+ """Create a sliced version of fast_dllm_cache for block processing."""
477
+ new_past_key_values = []
478
+ for i in range(len(fast_dllm_cache)):
479
+ new_past_key_values.append([])
480
+ for j in range(len(fast_dllm_cache[i])):
481
+ new_past_key_values[i].append(fast_dllm_cache[i][j][:, :, :block_start])
482
+ return new_past_key_values
483
+
484
+
485
+ def register_fast_dllm_hook(model):
486
+ """
487
+ Register fast dLLM cache hooks to the model.
488
+
489
+ Args:
490
+ model: The LLaDA model to register hooks to
491
+
492
+ Returns:
493
+ FastDLLMGenerationHook: The hook instance for management
494
+ """
495
+ hook = FastDLLMGenerationHook(model)
496
+ hook.register_hooks()
497
+ return hook
498
+
499
+
500
+ def unregister_fast_dllm_hook(hook):
501
+ """
502
+ Unregister fast dLLM cache hooks from the model.
503
+
504
+ Args:
505
+ hook: The FastDLLMGenerationHook instance to unregister
506
+ """
507
+ hook.unregister_hooks()
train/llava/mm_utils.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from io import BytesIO
3
+ import base64
4
+ import math
5
+ import ast
6
+ import re
7
+ import torch
8
+ from transformers import StoppingCriteria
9
+ from llava.constants import IMAGE_TOKEN_INDEX
10
+ from llava.utils import rank0_print, process_video_with_pyav, process_video_with_decord
11
+
12
+
13
+ def resize_and_center_crop(image, shortest_edge_length):
14
+ # Calculate new dimensions and resize
15
+ aspect_ratio = float(image.width) / float(image.height)
16
+ if aspect_ratio > 1:
17
+ new_width = int(shortest_edge_length * aspect_ratio)
18
+ new_height = shortest_edge_length
19
+ else:
20
+ new_width = shortest_edge_length
21
+ new_height = int(shortest_edge_length / aspect_ratio)
22
+ resized_image = image.resize((new_width, new_height), Image.ANTIALIAS)
23
+
24
+ # Calculate the position and perform the center crop
25
+ left = (new_width - shortest_edge_length) / 2
26
+ top = (new_height - shortest_edge_length) / 2
27
+ right = (new_width + shortest_edge_length) / 2
28
+ bottom = (new_height + shortest_edge_length) / 2
29
+ cropped_image = resized_image.crop((left, top, right, bottom))
30
+
31
+ return cropped_image
32
+
33
+
34
+ def auto_pad_images(image, grid_params):
35
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
36
+ assert len(grid_params) > 0, "Grid parameters should not be empty"
37
+
38
+ # Step 1: Calculate and find the closest aspect ratio
39
+ input_width, input_height = image.size
40
+ input_aspect_ratio = input_width / input_height
41
+ candidate_resolutions = [(w / h, w, h) for w in grid_params for h in grid_params]
42
+ closest_aspect_ratio = min(candidate_resolutions, key=lambda x: abs(input_aspect_ratio - x[0]))
43
+
44
+ candidate_resolutions = [(x[1], x[2]) for x in candidate_resolutions if abs(x[0] - closest_aspect_ratio[0]) < 1e-3]
45
+
46
+ target_resolution = min(candidate_resolutions, key=lambda res: abs(max(input_width, input_height) / max(res) - 1))
47
+
48
+ resize_width, resize_height = target_resolution
49
+ if input_width > input_height:
50
+ resize_height = int(resize_width / input_aspect_ratio)
51
+ else:
52
+ resize_width = int(resize_height * input_aspect_ratio)
53
+ resized_image = image.resize((resize_width, resize_height), Image.ANTIALIAS)
54
+
55
+ # Step 5: Pad the resized image if necessary to match the target resolution
56
+ pad_width = target_resolution[0] - resize_width
57
+ pad_height = target_resolution[1] - resize_height
58
+ padded_image = Image.new("RGB", target_resolution, color=(0, 0, 0))
59
+ padded_image.paste(resized_image, (pad_width // 2, pad_height // 2))
60
+
61
+ return padded_image
62
+
63
+
64
+ def extract_patches(image, patch_size, overlap_ratio):
65
+ assert isinstance(image, Image.Image), "Input should be a Pillow Image"
66
+ assert patch_size > 0, "Patch size should be greater than 0"
67
+ assert 0 <= overlap_ratio < 1, "Overlap ratio should be between 0 and 1"
68
+
69
+ W, H = image.size
70
+ patches = []
71
+
72
+ stride = int(patch_size * (1 - overlap_ratio))
73
+
74
+ num_patches_y = (H - patch_size) // stride + 1
75
+ num_patches_x = (W - patch_size) // stride + 1
76
+
77
+ y_start = (H - (num_patches_y - 1) * stride - patch_size) // 2
78
+ x_start = (W - (num_patches_x - 1) * stride - patch_size) // 2
79
+
80
+ for y in range(y_start, y_start + num_patches_y * stride, stride):
81
+ for x in range(x_start, x_start + num_patches_x * stride, stride):
82
+ patch = image.crop((x, y, x + patch_size, y + patch_size))
83
+ patches.append(patch)
84
+
85
+ return patches
86
+
87
+
88
+ def process_highres_image_crop_split(image, data_args, processor=None):
89
+ crop_resolution = data_args.image_crop_resolution
90
+ split_resolution = data_args.image_split_resolution
91
+ if processor is None:
92
+ processor = data_args.image_processor
93
+ image_crop = resize_and_center_crop(image, crop_resolution)
94
+ image_patches = extract_patches(image_crop, patch_size=split_resolution, overlap_ratio=0)
95
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
96
+ return torch.stack(image_patches, dim=0)
97
+
98
+
99
+ def process_highres_image(image, processor, grid_pinpoints):
100
+ grid_params = [int(x) for x in grid_pinpoints.split(",")]
101
+ width_height = max(image.size)
102
+ fit_grid_params = [x for x in grid_params if x >= width_height]
103
+ if len(fit_grid_params) == 0:
104
+ select_size = max(grid_params)
105
+ else:
106
+ select_size = min(fit_grid_params)
107
+ # FIXME: always select the 448
108
+ select_size = max(grid_params)
109
+ image_padded = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
110
+
111
+ # FIXME: this seems to be a bug that it always resizes instead of padding
112
+ image_original_resize = image.resize((processor.size["shortest_edge"], processor.size["shortest_edge"]))
113
+ image_padded = image_padded.resize((select_size, select_size))
114
+ image_patches = extract_patches(image_padded, patch_size=processor.size["shortest_edge"], overlap_ratio=0)
115
+ image_patches = [image_original_resize] + image_patches
116
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
117
+ return torch.stack(image_patches, dim=0)
118
+
119
+
120
+ def select_best_resolution(original_size, possible_resolutions):
121
+ """
122
+ Selects the best resolution from a list of possible resolutions based on the original size.
123
+
124
+ Args:
125
+ original_size (tuple): The original size of the image in the format (width, height).
126
+ possible_resolutions (list): A list of possible resolutions in the format [(width1, height1), (width2, height2), ...].
127
+
128
+ Returns:
129
+ tuple: The best fit resolution in the format (width, height).
130
+ """
131
+ original_width, original_height = original_size
132
+ best_fit = None
133
+ max_effective_resolution = 0
134
+ min_wasted_resolution = float("inf")
135
+
136
+ for width, height in possible_resolutions:
137
+ # Calculate the downscaled size to keep the aspect ratio
138
+ scale = min(width / original_width, height / original_height)
139
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
140
+
141
+ # Calculate effective and wasted resolutions
142
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
143
+ wasted_resolution = (width * height) - effective_resolution
144
+
145
+ if effective_resolution > max_effective_resolution or (effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution):
146
+ max_effective_resolution = effective_resolution
147
+ min_wasted_resolution = wasted_resolution
148
+ best_fit = (width, height)
149
+
150
+ return best_fit
151
+
152
+
153
+ def resize_and_pad_image(image, target_resolution):
154
+ """
155
+ Resize and pad an image to a target resolution while maintaining aspect ratio.
156
+
157
+ Args:
158
+ image (PIL.Image.Image): The input image.
159
+ target_resolution (tuple): The target resolution (width, height) of the image.
160
+
161
+ Returns:
162
+ PIL.Image.Image: The resized and padded image.
163
+ """
164
+ original_width, original_height = image.size
165
+ target_width, target_height = target_resolution
166
+
167
+ # Determine which dimension (width or height) to fill
168
+ scale_w = target_width / original_width
169
+ scale_h = target_height / original_height
170
+
171
+ if scale_w < scale_h:
172
+ # Width will be filled completely
173
+ new_width = target_width
174
+ new_height = min(math.ceil(original_height * scale_w), target_height)
175
+ else:
176
+ # Height will be filled completely
177
+ new_height = target_height
178
+ new_width = min(math.ceil(original_width * scale_h), target_width)
179
+
180
+ # Resize the image
181
+ resized_image = image.resize((new_width, new_height))
182
+
183
+ # Create a new image with the target size and paste the resized image onto it
184
+ new_image = Image.new("RGB", (target_width, target_height), (0, 0, 0))
185
+ paste_x = (target_width - new_width) // 2
186
+ paste_y = (target_height - new_height) // 2
187
+ new_image.paste(resized_image, (paste_x, paste_y))
188
+
189
+ return new_image
190
+
191
+
192
+ def divide_to_patches(image, patch_size):
193
+ """
194
+ Divides an image into patches of a specified size.
195
+
196
+ Args:
197
+ image (PIL.Image.Image): The input image.
198
+ patch_size (int): The size of each patch.
199
+
200
+ Returns:
201
+ list: A list of PIL.Image.Image objects representing the patches.
202
+ """
203
+ patches = []
204
+ width, height = image.size
205
+ for i in range(0, height, patch_size):
206
+ for j in range(0, width, patch_size):
207
+ box = (j, i, j + patch_size, i + patch_size)
208
+ patch = image.crop(box)
209
+ patches.append(patch)
210
+
211
+ return patches
212
+
213
+
214
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
215
+ """
216
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
217
+
218
+ Args:
219
+ image_size (tuple): The size of the input image in the format (width, height).
220
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
221
+ patch_size (int): The size of each image patch.
222
+
223
+ Returns:
224
+ tuple: The shape of the image patch grid in the format (width, height).
225
+ """
226
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
227
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
228
+ # Use regex to extract the range from the input string
229
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
230
+ range_start = tuple(map(int, matches[0]))
231
+ range_end = tuple(map(int, matches[-1]))
232
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
233
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
234
+ # Multiply all elements by patch_size
235
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
236
+ if type(grid_pinpoints) is list:
237
+ possible_resolutions = grid_pinpoints
238
+ else:
239
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
240
+ width, height = select_best_resolution(image_size, possible_resolutions)
241
+ return width // patch_size, height // patch_size
242
+
243
+
244
+ def process_anyres_image(image, processor, grid_pinpoints):
245
+ """
246
+ Process an image with variable resolutions.
247
+
248
+ Args:
249
+ image (PIL.Image.Image): The input image to be processed.
250
+ processor: The image processor object.
251
+ grid_pinpoints (str): A string representation of a list of possible resolutions.
252
+
253
+ Returns:
254
+ torch.Tensor: A tensor containing the processed image patches.
255
+ """
256
+ # Convert grid_pinpoints from string to list
257
+ if isinstance(grid_pinpoints, str) and "x" in grid_pinpoints:
258
+ try:
259
+ patch_size = processor.size[0]
260
+ except Exception as e:
261
+ patch_size = processor.size["shortest_edge"]
262
+ assert patch_size in [224, 336, 384, 448, 512], "patch_size should be in [224, 336, 384, 448, 512]"
263
+ # Use regex to extract the range from the input string
264
+ matches = re.findall(r"\((\d+)x(\d+)\)", grid_pinpoints)
265
+ range_start = tuple(map(int, matches[0]))
266
+ range_end = tuple(map(int, matches[-1]))
267
+ # Generate a matrix of tuples from (range_start[0], range_start[1]) to (range_end[0], range_end[1])
268
+ grid_pinpoints = [(i, j) for i in range(range_start[0], range_end[0] + 1) for j in range(range_start[1], range_end[1] + 1)]
269
+ # Multiply all elements by patch_size
270
+ grid_pinpoints = [[dim * patch_size for dim in pair] for pair in grid_pinpoints]
271
+
272
+ if type(grid_pinpoints) is list:
273
+ possible_resolutions = grid_pinpoints
274
+ else:
275
+ possible_resolutions = ast.literal_eval(grid_pinpoints)
276
+ best_resolution = select_best_resolution(image.size, possible_resolutions)
277
+ image_padded = resize_and_pad_image(image, best_resolution)
278
+
279
+ patches = divide_to_patches(image_padded, processor.crop_size["height"])
280
+
281
+ # FIXME: this seems to be a bug that it resizes instead of pad.
282
+ # but to keep it consistent with previous, i will keep it as it is
283
+ # TODO: uncomment below to ablate with the padding
284
+ if isinstance(processor.size, dict):
285
+ shortest_edge = processor.size["shortest_edge"]
286
+ else:
287
+ shortest_edge = min(processor.size)
288
+ image_original_resize = image.resize((shortest_edge, shortest_edge))
289
+ # image_padded_square = expand2square(image, tuple(int(x*255) for x in processor.image_mean))
290
+ # image_original_resize = image_padded_square.resize((processor.size['shortest_edge'], processor.size['shortest_edge']))
291
+
292
+ image_patches = [image_original_resize] + patches
293
+ image_patches = [processor.preprocess(image_patch, return_tensors="pt")["pixel_values"][0] for image_patch in image_patches]
294
+ return torch.stack(image_patches, dim=0)
295
+
296
+
297
+ def load_image_from_base64(image):
298
+ return Image.open(BytesIO(base64.b64decode(image)))
299
+
300
+
301
+ def expand2square(pil_img, background_color):
302
+ width, height = pil_img.size
303
+ if width == height:
304
+ return pil_img
305
+ elif width > height:
306
+ result = Image.new(pil_img.mode, (width, width), background_color)
307
+ result.paste(pil_img, (0, (width - height) // 2))
308
+ return result
309
+ else:
310
+ result = Image.new(pil_img.mode, (height, height), background_color)
311
+ result.paste(pil_img, ((height - width) // 2, 0))
312
+ return result
313
+
314
+
315
+ def process_images(images, image_processor, model_cfg):
316
+ image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
317
+ new_images = []
318
+ if image_aspect_ratio == "highres":
319
+ for image in images:
320
+ image = process_highres_image(image, image_processor, model_cfg.image_grid_pinpoints)
321
+ new_images.append(image)
322
+ elif image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
323
+ for image in images:
324
+ image = process_anyres_image(image, image_processor, model_cfg.image_grid_pinpoints)
325
+ new_images.append(image)
326
+ elif image_aspect_ratio == "crop_split":
327
+ for image in images:
328
+ image = process_highres_image_crop_split(image, model_cfg, image_processor)
329
+ new_images.append(image)
330
+ elif image_aspect_ratio == "pad":
331
+ for image in images:
332
+ image = expand2square(image, tuple(int(x * 255) for x in image_processor.image_mean))
333
+ image = image_processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
334
+ new_images.append(image)
335
+ else:
336
+ return image_processor.preprocess(images, return_tensors="pt")["pixel_values"]
337
+ if all(x.shape == new_images[0].shape for x in new_images):
338
+ new_images = torch.stack(new_images, dim=0)
339
+ return new_images
340
+
341
+
342
+ def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
343
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
344
+
345
+ def insert_separator(X, sep):
346
+ return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
347
+
348
+ input_ids = []
349
+ offset = 0
350
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
351
+ offset = 1
352
+ input_ids.append(prompt_chunks[0][0])
353
+
354
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
355
+ input_ids.extend(x[offset:])
356
+
357
+ if return_tensors is not None:
358
+ if return_tensors == "pt":
359
+ return torch.tensor(input_ids, dtype=torch.long)
360
+ raise ValueError(f"Unsupported tensor type: {return_tensors}")
361
+ return input_ids
362
+
363
+
364
+ def get_model_name_from_path(model_path):
365
+ model_path = model_path.strip("/")
366
+ model_paths = model_path.split("/")
367
+ if model_paths[-1].startswith("checkpoint-"):
368
+ return model_paths[-2] + "_" + model_paths[-1]
369
+ else:
370
+ return model_paths[-1]
371
+
372
+
373
+ class KeywordsStoppingCriteria(StoppingCriteria):
374
+ def __init__(self, keywords, tokenizer, input_ids):
375
+ self.keywords = keywords
376
+ self.keyword_ids = []
377
+ for keyword in keywords:
378
+ cur_keyword_ids = tokenizer(keyword).input_ids
379
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
380
+ cur_keyword_ids = cur_keyword_ids[1:]
381
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
382
+ self.tokenizer = tokenizer
383
+ self.start_len = input_ids.shape[1]
384
+
385
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
386
+ assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
387
+ offset = min(output_ids.shape[1] - self.start_len, 3)
388
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
389
+ for keyword_id in self.keyword_ids:
390
+ if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
391
+ return True
392
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
393
+ for keyword in self.keywords:
394
+ if keyword in outputs:
395
+ return True
396
+ return False
train/llava/model/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ AVAILABLE_MODELS = {
4
+ "llava_llada": "LlavaLLaDAModelLM, LlavaLLaDAConfig",
5
+ }
6
+
7
+ for model_name, model_classes in AVAILABLE_MODELS.items():
8
+ try:
9
+ exec(f"from .language_model.{model_name} import {model_classes}")
10
+ except Exception as e:
11
+ print(f"Failed to import {model_name} from llava.language_model.{model_name}. Error: {e}")
train/llava/model/apply_delta.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta
4
+ """
5
+
6
+ import argparse
7
+
8
+ import torch
9
+ from tqdm import tqdm
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM
11
+ from llava import LlavaLlamaForCausalLM
12
+
13
+
14
+ def apply_delta(base_model_path, target_model_path, delta_path):
15
+ print("Loading base model")
16
+ base = AutoModelForCausalLM.from_pretrained(base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+
18
+ print("Loading delta")
19
+ delta = LlavaLlamaForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
20
+ delta_tokenizer = AutoTokenizer.from_pretrained(delta_path)
21
+
22
+ print("Applying delta")
23
+ for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"):
24
+ if name not in base.state_dict():
25
+ assert name in ["model.mm_projector.weight", "model.mm_projector.bias"], f"{name} not in base model"
26
+ continue
27
+ if param.data.shape == base.state_dict()[name].shape:
28
+ param.data += base.state_dict()[name]
29
+ else:
30
+ assert name in ["model.embed_tokens.weight", "lm_head.weight"], f"{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}"
31
+ bparam = base.state_dict()[name]
32
+ param.data[: bparam.shape[0], : bparam.shape[1]] += bparam
33
+
34
+ print("Saving target model")
35
+ delta.save_pretrained(target_model_path)
36
+ delta_tokenizer.save_pretrained(target_model_path)
37
+
38
+
39
+ if __name__ == "__main__":
40
+ parser = argparse.ArgumentParser()
41
+ parser.add_argument("--base-model-path", type=str, required=True)
42
+ parser.add_argument("--target-model-path", type=str, required=True)
43
+ parser.add_argument("--delta-path", type=str, required=True)
44
+
45
+ args = parser.parse_args()
46
+
47
+ apply_delta(args.base_model_path, args.target_model_path, args.delta_path)