Master-Shi commited on
Commit
6955bc0
·
verified ·
1 Parent(s): 6fd7f83

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/eval_scripts/run_all_diff_region.sh +51 -0
  2. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/eval_scripts/run_all_diff_text.sh +51 -0
  3. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/eval_scripts/run_all_mask_region.sh +51 -0
  4. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/eval_scripts/run_all_mask_text.sh +51 -0
  5. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/eval_scripts/run_all_measure_attention.sh +52 -0
  6. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/.ipynb_checkpoints/HealthGPT-checkpoint.py +173 -0
  7. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/.ipynb_checkpoints/HealthGPT_phi-checkpoint.py +169 -0
  8. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/demo/com_infer_phi4.sh +18 -0
  9. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/demo/utils.py +103 -0
  10. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/__init__.py +53 -0
  11. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/mapping.py +152 -0
  12. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/peft_model.py +932 -0
  13. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/tuners/__init__.py +23 -0
  14. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/tuners/p_tuning.py +159 -0
  15. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/tuners/prompt_tuning.py +120 -0
  16. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/serve/__init__.py +0 -0
  17. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/serve/cli.py +126 -0
  18. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/serve/controller.py +298 -0
  19. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/serve/model_worker.py +288 -0
  20. 之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/serve/test_message.py +62 -0
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/eval_scripts/run_all_diff_region.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # run_all_diff_region: grounding_diff_region.py
3
+ # Oversized models (32B/34B/27B-IT) are pushed to the very end, after every
4
+ # normal-size model has finished, so a stuck/OOM large model never blocks them.
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ cd "$(dirname "$0")/.."
7
+
8
+ echo "=== [qianwen] Qwen25VL_7B COCO ==="
9
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_region/diff_region_COCO_Qwen25VL_7B.sh
10
+ echo "=== [qianwen] Qwen25VL_7B VGMED ==="
11
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_region/diff_region_VGMED_Qwen25VL_7B.sh
12
+ echo "=== [qianwen] Qwen25VL_3B COCO ==="
13
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_region/diff_region_COCO_Qwen25VL_3B.sh
14
+ echo "=== [qianwen] Qwen25VL_3B VGMED ==="
15
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_region/diff_region_VGMED_Qwen25VL_3B.sh
16
+ echo "=== [llava-natural] LLaVA_7B COCO ==="
17
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/diff_region/diff_region_COCO_LLaVA_7B.sh
18
+ echo "=== [llava-natural] LLaVA_7B VGMED ==="
19
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/diff_region/diff_region_VGMED_LLaVA_7B.sh
20
+ echo "=== [llava-natural] LLaVA_13B COCO ==="
21
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/diff_region/diff_region_COCO_LLaVA_13B.sh
22
+ echo "=== [llava-natural] LLaVA_13B VGMED ==="
23
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/diff_region/diff_region_VGMED_LLaVA_13B.sh
24
+ echo "=== [llava-med] LLaVA_Med_7B COCO ==="
25
+ conda run --no-capture-output -n llava-med bash eval_scripts/grounding/diff_region/diff_region_COCO_LLaVA_Med_7B.sh
26
+ echo "=== [llava-med] LLaVA_Med_7B VGMED ==="
27
+ conda run --no-capture-output -n llava-med bash eval_scripts/grounding/diff_region/diff_region_VGMED_LLaVA_Med_7B.sh
28
+ echo "=== [huatuogpt] HuatuoGPT_V_7B COCO ==="
29
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/diff_region/diff_region_COCO_HuatuoGPT_V_7B.sh
30
+ echo "=== [huatuogpt] HuatuoGPT_V_7B VGMED ==="
31
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/diff_region/diff_region_VGMED_HuatuoGPT_V_7B.sh
32
+ echo "=== [gemma] MedGemma_4B_IT COCO ==="
33
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/diff_region/diff_region_COCO_MedGemma_4B_IT.sh
34
+ echo "=== [gemma] MedGemma_4B_IT VGMED ==="
35
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/diff_region/diff_region_VGMED_MedGemma_4B_IT.sh
36
+
37
+ # ── Oversized models (run last; failures here don't block anything above) ──
38
+ echo "=== [qianwen] Qwen25VL_32B COCO ==="
39
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_region/diff_region_COCO_Qwen25VL_32B.sh
40
+ echo "=== [qianwen] Qwen25VL_32B VGMED ==="
41
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_region/diff_region_VGMED_Qwen25VL_32B.sh
42
+ echo "=== [huatuogpt] HuatuoGPT_V_34B COCO ==="
43
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/diff_region/diff_region_COCO_HuatuoGPT_V_34B.sh
44
+ echo "=== [huatuogpt] HuatuoGPT_V_34B VGMED ==="
45
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/diff_region/diff_region_VGMED_HuatuoGPT_V_34B.sh
46
+ echo "=== [gemma] MedGemma_27B_IT COCO ==="
47
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/diff_region/diff_region_COCO_MedGemma_27B_IT.sh
48
+ echo "=== [gemma] MedGemma_27B_IT VGMED ==="
49
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/diff_region/diff_region_VGMED_MedGemma_27B_IT.sh
50
+
51
+ echo "All diff_region jobs finished."
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/eval_scripts/run_all_diff_text.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # run_all_diff_text: grounding_diff_text.py
3
+ # Oversized models (32B/34B/27B-IT) are pushed to the very end, after every
4
+ # normal-size model has finished, so a stuck/OOM large model never blocks them.
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ cd "$(dirname "$0")/.."
7
+
8
+ echo "=== [qianwen] Qwen25VL_7B COCO ==="
9
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_text/diff_text_COCO_Qwen25VL_7B.sh
10
+ echo "=== [qianwen] Qwen25VL_7B VGMED ==="
11
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_text/diff_text_VGMED_Qwen25VL_7B.sh
12
+ echo "=== [qianwen] Qwen25VL_3B COCO ==="
13
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_text/diff_text_COCO_Qwen25VL_3B.sh
14
+ echo "=== [qianwen] Qwen25VL_3B VGMED ==="
15
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_text/diff_text_VGMED_Qwen25VL_3B.sh
16
+ echo "=== [llava-natural] LLaVA_7B COCO ==="
17
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/diff_text/diff_text_COCO_LLaVA_7B.sh
18
+ echo "=== [llava-natural] LLaVA_7B VGMED ==="
19
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/diff_text/diff_text_VGMED_LLaVA_7B.sh
20
+ echo "=== [llava-natural] LLaVA_13B COCO ==="
21
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/diff_text/diff_text_COCO_LLaVA_13B.sh
22
+ echo "=== [llava-natural] LLaVA_13B VGMED ==="
23
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/diff_text/diff_text_VGMED_LLaVA_13B.sh
24
+ echo "=== [llava-med] LLaVA_Med_7B COCO ==="
25
+ conda run --no-capture-output -n llava-med bash eval_scripts/grounding/diff_text/diff_text_COCO_LLaVA_Med_7B.sh
26
+ echo "=== [llava-med] LLaVA_Med_7B VGMED ==="
27
+ conda run --no-capture-output -n llava-med bash eval_scripts/grounding/diff_text/diff_text_VGMED_LLaVA_Med_7B.sh
28
+ echo "=== [huatuogpt] HuatuoGPT_V_7B COCO ==="
29
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/diff_text/diff_text_COCO_HuatuoGPT_V_7B.sh
30
+ echo "=== [huatuogpt] HuatuoGPT_V_7B VGMED ==="
31
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/diff_text/diff_text_VGMED_HuatuoGPT_V_7B.sh
32
+ echo "=== [gemma] MedGemma_4B_IT COCO ==="
33
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/diff_text/diff_text_COCO_MedGemma_4B_IT.sh
34
+ echo "=== [gemma] MedGemma_4B_IT VGMED ==="
35
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/diff_text/diff_text_VGMED_MedGemma_4B_IT.sh
36
+
37
+ # ── Oversized models (run last; failures here don't block anything above) ──
38
+ echo "=== [qianwen] Qwen25VL_32B COCO ==="
39
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_text/diff_text_COCO_Qwen25VL_32B.sh
40
+ echo "=== [qianwen] Qwen25VL_32B VGMED ==="
41
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/diff_text/diff_text_VGMED_Qwen25VL_32B.sh
42
+ echo "=== [huatuogpt] HuatuoGPT_V_34B COCO ==="
43
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/diff_text/diff_text_COCO_HuatuoGPT_V_34B.sh
44
+ echo "=== [huatuogpt] HuatuoGPT_V_34B VGMED ==="
45
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/diff_text/diff_text_VGMED_HuatuoGPT_V_34B.sh
46
+ echo "=== [gemma] MedGemma_27B_IT COCO ==="
47
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/diff_text/diff_text_COCO_MedGemma_27B_IT.sh
48
+ echo "=== [gemma] MedGemma_27B_IT VGMED ==="
49
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/diff_text/diff_text_VGMED_MedGemma_27B_IT.sh
50
+
51
+ echo "All diff_text jobs finished."
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/eval_scripts/run_all_mask_region.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # run_all_mask_region: grounding_mask_region.py
3
+ # Oversized models (32B/34B/27B-IT) are pushed to the very end, after every
4
+ # normal-size model has finished, so a stuck/OOM large model never blocks them.
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ cd "$(dirname "$0")/.."
7
+
8
+ echo "=== [qianwen] Qwen25VL_7B COCO ==="
9
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_region/mask_region_COCO_Qwen25VL_7B.sh
10
+ echo "=== [qianwen] Qwen25VL_7B VGMED ==="
11
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_region/mask_region_VGMED_Qwen25VL_7B.sh
12
+ echo "=== [qianwen] Qwen25VL_3B COCO ==="
13
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_region/mask_region_COCO_Qwen25VL_3B.sh
14
+ echo "=== [qianwen] Qwen25VL_3B VGMED ==="
15
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_region/mask_region_VGMED_Qwen25VL_3B.sh
16
+ echo "=== [llava-natural] LLaVA_7B COCO ==="
17
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/mask_region/mask_region_COCO_LLaVA_7B.sh
18
+ echo "=== [llava-natural] LLaVA_7B VGMED ==="
19
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/mask_region/mask_region_VGMED_LLaVA_7B.sh
20
+ echo "=== [llava-natural] LLaVA_13B COCO ==="
21
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/mask_region/mask_region_COCO_LLaVA_13B.sh
22
+ echo "=== [llava-natural] LLaVA_13B VGMED ==="
23
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/mask_region/mask_region_VGMED_LLaVA_13B.sh
24
+ echo "=== [llava-med] LLaVA_Med_7B COCO ==="
25
+ conda run --no-capture-output -n llava-med bash eval_scripts/grounding/mask_region/mask_region_COCO_LLaVA_Med_7B.sh
26
+ echo "=== [llava-med] LLaVA_Med_7B VGMED ==="
27
+ conda run --no-capture-output -n llava-med bash eval_scripts/grounding/mask_region/mask_region_VGMED_LLaVA_Med_7B.sh
28
+ echo "=== [huatuogpt] HuatuoGPT_V_7B COCO ==="
29
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/mask_region/mask_region_COCO_HuatuoGPT_V_7B.sh
30
+ echo "=== [huatuogpt] HuatuoGPT_V_7B VGMED ==="
31
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/mask_region/mask_region_VGMED_HuatuoGPT_V_7B.sh
32
+ echo "=== [gemma] MedGemma_4B_IT COCO ==="
33
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/mask_region/mask_region_COCO_MedGemma_4B_IT.sh
34
+ echo "=== [gemma] MedGemma_4B_IT VGMED ==="
35
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/mask_region/mask_region_VGMED_MedGemma_4B_IT.sh
36
+
37
+ # ── Oversized models (run last; failures here don't block anything above) ──
38
+ echo "=== [qianwen] Qwen25VL_32B COCO ==="
39
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_region/mask_region_COCO_Qwen25VL_32B.sh
40
+ echo "=== [qianwen] Qwen25VL_32B VGMED ==="
41
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_region/mask_region_VGMED_Qwen25VL_32B.sh
42
+ echo "=== [huatuogpt] HuatuoGPT_V_34B COCO ==="
43
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/mask_region/mask_region_COCO_HuatuoGPT_V_34B.sh
44
+ echo "=== [huatuogpt] HuatuoGPT_V_34B VGMED ==="
45
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/mask_region/mask_region_VGMED_HuatuoGPT_V_34B.sh
46
+ echo "=== [gemma] MedGemma_27B_IT COCO ==="
47
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/mask_region/mask_region_COCO_MedGemma_27B_IT.sh
48
+ echo "=== [gemma] MedGemma_27B_IT VGMED ==="
49
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/mask_region/mask_region_VGMED_MedGemma_27B_IT.sh
50
+
51
+ echo "All mask_region jobs finished."
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/eval_scripts/run_all_mask_text.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # run_all_mask_text: grounding_mask_text.py
3
+ # Oversized models (32B/34B/27B-IT) are pushed to the very end, after every
4
+ # normal-size model has finished, so a stuck/OOM large model never blocks them.
5
+ export CUDA_VISIBLE_DEVICES=0
6
+ cd "$(dirname "$0")/.."
7
+
8
+ echo "=== [qianwen] Qwen25VL_7B COCO ==="
9
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_text/mask_text_COCO_Qwen25VL_7B.sh
10
+ echo "=== [qianwen] Qwen25VL_7B VGMED ==="
11
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_text/mask_text_VGMED_Qwen25VL_7B.sh
12
+ echo "=== [qianwen] Qwen25VL_3B COCO ==="
13
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_text/mask_text_COCO_Qwen25VL_3B.sh
14
+ echo "=== [qianwen] Qwen25VL_3B VGMED ==="
15
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_text/mask_text_VGMED_Qwen25VL_3B.sh
16
+ echo "=== [llava-natural] LLaVA_7B COCO ==="
17
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/mask_text/mask_text_COCO_LLaVA_7B.sh
18
+ echo "=== [llava-natural] LLaVA_7B VGMED ==="
19
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/mask_text/mask_text_VGMED_LLaVA_7B.sh
20
+ echo "=== [llava-natural] LLaVA_13B COCO ==="
21
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/mask_text/mask_text_COCO_LLaVA_13B.sh
22
+ echo "=== [llava-natural] LLaVA_13B VGMED ==="
23
+ conda run --no-capture-output -n llava-natural bash eval_scripts/grounding/mask_text/mask_text_VGMED_LLaVA_13B.sh
24
+ echo "=== [llava-med] LLaVA_Med_7B COCO ==="
25
+ conda run --no-capture-output -n llava-med bash eval_scripts/grounding/mask_text/mask_text_COCO_LLaVA_Med_7B.sh
26
+ echo "=== [llava-med] LLaVA_Med_7B VGMED ==="
27
+ conda run --no-capture-output -n llava-med bash eval_scripts/grounding/mask_text/mask_text_VGMED_LLaVA_Med_7B.sh
28
+ echo "=== [huatuogpt] HuatuoGPT_V_7B COCO ==="
29
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/mask_text/mask_text_COCO_HuatuoGPT_V_7B.sh
30
+ echo "=== [huatuogpt] HuatuoGPT_V_7B VGMED ==="
31
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/mask_text/mask_text_VGMED_HuatuoGPT_V_7B.sh
32
+ echo "=== [gemma] MedGemma_4B_IT COCO ==="
33
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/mask_text/mask_text_COCO_MedGemma_4B_IT.sh
34
+ echo "=== [gemma] MedGemma_4B_IT VGMED ==="
35
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/mask_text/mask_text_VGMED_MedGemma_4B_IT.sh
36
+
37
+ # ── Oversized models (run last; failures here don't block anything above) ──
38
+ echo "=== [qianwen] Qwen25VL_32B COCO ==="
39
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_text/mask_text_COCO_Qwen25VL_32B.sh
40
+ echo "=== [qianwen] Qwen25VL_32B VGMED ==="
41
+ conda run --no-capture-output -n qianwen bash eval_scripts/grounding/mask_text/mask_text_VGMED_Qwen25VL_32B.sh
42
+ echo "=== [huatuogpt] HuatuoGPT_V_34B COCO ==="
43
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/mask_text/mask_text_COCO_HuatuoGPT_V_34B.sh
44
+ echo "=== [huatuogpt] HuatuoGPT_V_34B VGMED ==="
45
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/grounding/mask_text/mask_text_VGMED_HuatuoGPT_V_34B.sh
46
+ echo "=== [gemma] MedGemma_27B_IT COCO ==="
47
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/mask_text/mask_text_COCO_MedGemma_27B_IT.sh
48
+ echo "=== [gemma] MedGemma_27B_IT VGMED ==="
49
+ conda run --no-capture-output -n gemma bash eval_scripts/grounding/mask_text/mask_text_VGMED_MedGemma_27B_IT.sh
50
+
51
+ echo "All mask_text jobs finished."
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/eval_scripts/run_all_measure_attention.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # GPU2: measure_attention for all models (sequential, MedGemma last)
3
+ # Env: qianwen -> llava-natural -> llava-med -> huatuogpt -> gemma
4
+ # Oversized models (32B/34B/27B-IT) are pushed to the very end, after every
5
+ # normal-size model has finished, so a stuck/OOM large model never blocks them.
6
+ export CUDA_VISIBLE_DEVICES=0
7
+ cd "$(dirname "$0")/.."
8
+
9
+ echo "=== [qianwen] Qwen25VL_7B COCO ==="
10
+ conda run --no-capture-output -n qianwen bash eval_scripts/measure_attention/measure_attention_COCO_Qwen25VL_7B.sh
11
+ echo "=== [qianwen] Qwen25VL_7B VGMED ==="
12
+ conda run --no-capture-output -n qianwen bash eval_scripts/measure_attention/measure_attention_VGMED_Qwen25VL_7B.sh
13
+ echo "=== [qianwen] Qwen25VL_3B COCO ==="
14
+ conda run --no-capture-output -n qianwen bash eval_scripts/measure_attention/measure_attention_COCO_Qwen25VL_3B.sh
15
+ echo "=== [qianwen] Qwen25VL_3B VGMED ==="
16
+ conda run --no-capture-output -n qianwen bash eval_scripts/measure_attention/measure_attention_VGMED_Qwen25VL_3B.sh
17
+ echo "=== [llava-natural] LLaVA_7B COCO ==="
18
+ conda run --no-capture-output -n llava-natural bash eval_scripts/measure_attention/measure_attention_COCO_LLaVA_7B.sh
19
+ echo "=== [llava-natural] LLaVA_7B VGMED ==="
20
+ conda run --no-capture-output -n llava-natural bash eval_scripts/measure_attention/measure_attention_VGMED_LLaVA_7B.sh
21
+ echo "=== [llava-natural] LLaVA_13B COCO ==="
22
+ conda run --no-capture-output -n llava-natural bash eval_scripts/measure_attention/measure_attention_COCO_LLaVA_13B.sh
23
+ echo "=== [llava-natural] LLaVA_13B VGMED ==="
24
+ conda run --no-capture-output -n llava-natural bash eval_scripts/measure_attention/measure_attention_VGMED_LLaVA_13B.sh
25
+ echo "=== [llava-med] LLaVA_Med_7B COCO ==="
26
+ conda run --no-capture-output -n llava-med bash eval_scripts/measure_attention/measure_attention_COCO_LLaVA_Med_7B.sh
27
+ echo "=== [llava-med] LLaVA_Med_7B VGMED ==="
28
+ conda run --no-capture-output -n llava-med bash eval_scripts/measure_attention/measure_attention_VGMED_LLaVA_Med_7B.sh
29
+ echo "=== [huatuogpt] HuatuoGPT_V_7B COCO ==="
30
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/measure_attention/measure_attention_COCO_HuatuoGPT_V_7B.sh
31
+ echo "=== [huatuogpt] HuatuoGPT_V_7B VGMED ==="
32
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/measure_attention/measure_attention_VGMED_HuatuoGPT_V_7B.sh
33
+ echo "=== [gemma] MedGemma_4B_IT COCO ==="
34
+ conda run --no-capture-output -n gemma bash eval_scripts/measure_attention/measure_attention_COCO_MedGemma_4B_IT.sh
35
+ echo "=== [gemma] MedGemma_4B_IT VGMED ==="
36
+ conda run --no-capture-output -n gemma bash eval_scripts/measure_attention/measure_attention_VGMED_MedGemma_4B_IT.sh
37
+
38
+ # ── Oversized models (run last; failures here don't block anything above) ──
39
+ echo "=== [qianwen] Qwen25VL_32B COCO ==="
40
+ conda run --no-capture-output -n qianwen bash eval_scripts/measure_attention/measure_attention_COCO_Qwen25VL_32B.sh
41
+ echo "=== [qianwen] Qwen25VL_32B VGMED ==="
42
+ conda run --no-capture-output -n qianwen bash eval_scripts/measure_attention/measure_attention_VGMED_Qwen25VL_32B.sh
43
+ echo "=== [huatuogpt] HuatuoGPT_V_34B COCO ==="
44
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/measure_attention/measure_attention_COCO_HuatuoGPT_V_34B.sh
45
+ echo "=== [huatuogpt] HuatuoGPT_V_34B VGMED ==="
46
+ conda run --no-capture-output -n huatuogpt bash eval_scripts/measure_attention/measure_attention_VGMED_HuatuoGPT_V_34B.sh
47
+ echo "=== [gemma] MedGemma_27B_IT COCO ==="
48
+ conda run --no-capture-output -n gemma bash eval_scripts/measure_attention/measure_attention_COCO_MedGemma_27B_IT.sh
49
+ echo "=== [gemma] MedGemma_27B_IT VGMED ==="
50
+ conda run --no-capture-output -n gemma bash eval_scripts/measure_attention/measure_attention_VGMED_MedGemma_27B_IT.sh
51
+
52
+ echo "All measure_attention jobs finished."
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/.ipynb_checkpoints/HealthGPT-checkpoint.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys
2
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
3
+ import torch
4
+ import transformers
5
+ import tokenizers
6
+
7
+ from PIL import Image
8
+ from tqdm import tqdm
9
+ from packaging import version
10
+ IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse('0.14')
11
+
12
+
13
+ from .llava import conversation as conversation_lib
14
+ from .llava.model import *
15
+ from .llava.mm_utils import tokenizer_image_token,process_images
16
+ from .llava.model.language_model.llava_phi3 import LlavaPhiForCausalLM, LlavaPhiConfig
17
+
18
+ from .utils import find_all_linear_names, add_special_tokens_and_resize_model, load_weights, expand2square,com_vision_args
19
+
20
+
21
+ class HealthGPT:
22
+ def __init__(self,model_path,args):
23
+ super().__init__()
24
+ self.llm = LlavaQwen2ForCausalLM.from_pretrained(
25
+ pretrained_model_name_or_path = model_path,
26
+ attn_implementation="flash_attention_2",
27
+ torch_dtype= torch.float16,
28
+ device_map="cuda"
29
+ )
30
+ from .llava.peft import LoraConfig, get_peft_model
31
+ print("load model done")
32
+ lora_config = LoraConfig(
33
+ r= 32,
34
+ lora_alpha=64,
35
+ target_modules=find_all_linear_names(self.llm),
36
+ lora_dropout=0.0,
37
+ bias='none',
38
+ task_type="CAUSAL_LM",
39
+ lora_nums=4,
40
+ )
41
+ self.llm = get_peft_model(self.llm, lora_config)
42
+ print("load lora done")
43
+
44
+ self.tokenizer = transformers.AutoTokenizer.from_pretrained(
45
+ model_path,
46
+ padding_side="right",
47
+ use_fast=False,
48
+ )
49
+ if self.tokenizer.unk_token:
50
+ self.tokenizer.pad_token = tokenizer.unk_token
51
+ else:
52
+ self.tokenizer.legacy = False
53
+ print("load tokenizer done")
54
+
55
+ from .utils import com_vision_args
56
+ com_vision_args.model_name_or_path = model_path
57
+ com_vision_args.vision_tower = '/mnt/workspace/workgroup_dev/longli/models/hub/clip-vit-large-patch14-336'
58
+ com_vision_args.version = "qwen_2"
59
+
60
+ self.llm.get_model().initialize_vision_modules(model_args=com_vision_args)
61
+ self.llm.get_vision_tower().to(dtype=torch.float16)
62
+ self.llm.get_model().mm_projector.to(dtype=torch.float16)
63
+ print("load vision tower done")
64
+
65
+ self.llm = load_weights(self.llm, "/mnt/workspace/workgroup_dev/longli/models/hub/HealthGPT-XL32/com_hlora_weights_QWEN_32B.bin")
66
+ print("load weights done")
67
+ self.llm.eval()
68
+ self.llm.to(dtype=torch.float16).cuda()
69
+
70
+ self.temperature = args.temperature
71
+ self.top_p = args.top_p
72
+ self.repetition_penalty = args.repetition_penalty
73
+ self.max_tokens = args.max_new_tokens
74
+
75
+
76
+ def process_messages(self,messages):
77
+ conv = conversation_lib.conv_templates["qwen_2"].copy()
78
+ conv.messages = []
79
+ if "system" in messages:
80
+ conv.system = messages["system"]
81
+
82
+ imgs = []
83
+ if "image" in messages:
84
+ image = messages["image"]
85
+ if isinstance(image,str):
86
+ image = Image.open(image).convert('RGB')
87
+ elif isinstance(image,Image.Image):
88
+ image = image.convert('RGB')
89
+
90
+
91
+ imgs.append(image)
92
+ prompt = DEFAULT_IMAGE_TOKEN + '\n' + messages["prompt"]
93
+ elif "images" in messages:
94
+ images = messages["images"]
95
+ prompt = ""
96
+ for i,image in enumerate(images):
97
+ prompt += f"<image_{i+1}>: " + DEFAULT_IMAGE_TOKEN + '\n'
98
+ if isinstance(image,str):
99
+ if os.path.exists(image):
100
+ image = Image.open(image)
101
+ elif isinstance(image,Image.Image):
102
+ image = image.convert("RGB")
103
+ imgs.append(image)
104
+ prompt += messages["prompt"]
105
+ else:
106
+ prompt = messages["prompt"]
107
+ conv.append_message(conv.roles[0],prompt)
108
+ conv.append_message(conv.roles[1],None)
109
+ prompt = conv.get_prompt()
110
+ imgs = None if len(imgs) == 0 else imgs
111
+ return prompt,imgs
112
+
113
+
114
+ def generate_output(self,messages):
115
+ prompt,imgs = self.process_messages(messages)
116
+ if imgs:
117
+ # imgs = imgs[0]
118
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze_(0).cuda()
119
+ imgs = [expand2square(img, tuple(int(x*255) for x in self.llm.get_vision_tower().image_processor.image_mean)) for img in imgs]
120
+ imgs = self.llm.get_vision_tower().image_processor.preprocess(imgs, return_tensors='pt')['pixel_values'].to(dtype=torch.float16, device='cuda', non_blocking=True)
121
+ # imgs = process_images(imgs,self.llm.get_vision_tower().image_processor,self.llm.config)
122
+ else:
123
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze_(0).cuda()
124
+ imgs = None
125
+
126
+ with torch.inference_mode():
127
+ do_sample = False if self.temperature == 0 else True
128
+ output_ids = self.llm.base_model.model.generate(input_ids,images=imgs,do_sample=do_sample,num_beams=5,max_new_tokens=self.max_tokens,temperature = self.temperature,top_p = self.top_p,repetition_penalty = self.repetition_penalty,use_cache=True)
129
+
130
+ outputs = self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
131
+ return outputs
132
+
133
+ def generate_outputs(self,messages_list):
134
+ outputs = []
135
+ for messages in tqdm(messages_list):
136
+ output = self.generate_output(messages)
137
+ outputs.append(output)
138
+ return outputs
139
+
140
+ if __name__ == '__main__':
141
+ # def construct_messages(sample):
142
+ # question = sample["question"]
143
+ # image = sample["image"]
144
+ # answer = sample["answer"]
145
+ # if answer in ["yes","no"]:
146
+ # question += "Please output 'yes' or 'no'(no extra output)"
147
+ # if os.environ.get("STRICT_PROMPT","False") == "True":
148
+ # question += "Wrap your final answer between <answer> and </answer>, for example: <answer>yes</answer>"
149
+ # else:
150
+ # question += 'Answer the question concisely(Keep it short and concise).'
151
+ # if os.environ.get("STRICT_PROMPT","False") == "True":
152
+ # question += "Wrap your final answer between <answer> and </answer>, for example: <answer>positive influence</answer>"
153
+ # messages = {"prompt":question,"image":image}
154
+ # sample["messages"] = messages
155
+ # return sample
156
+
157
+ # from datasets import load_dataset
158
+ # from tqdm import tqdm
159
+ # dataset = load_dataset("/mnt/workspace/workgroup_dev/longli/MedLLMBenchmarks/benchmarks/VQA_RAD",split="test")
160
+
161
+ # llm = HealthGPT()
162
+ # for data in tqdm(dataset):
163
+ # data = construct_messages(data)
164
+ # image = data["image"]
165
+ # messages = {"prompt":data["question"],"image":image}
166
+ # result = llm.generate_output(messages)
167
+
168
+ llm = HealthGPT()
169
+ image = "/mnt/workspace/workgroup_dev/longli/MedLLMBenchmarks/benchmarks/OmniMedVQA/Images/ACRIMA/Im553_g_ACRIMA.png"
170
+ image2 = "/mnt/workspace/workgroup_dev/longli/MedLLMBenchmarks/benchmarks/OmniMedVQA/Images/BreakHis/benign/SOB_B_A-14-22549AB-40-005.png"
171
+ messages = [{ 'images': [image,image2],"prompt":"\nQuestion: 你是一个医疗助手,我的问题是这两张图片里的内容是什么?"}]
172
+ result = llm.generate_outputs(messages)
173
+ print("result:",result)
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/.ipynb_checkpoints/HealthGPT_phi-checkpoint.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys
2
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
3
+ import torch
4
+ import transformers
5
+ import tokenizers
6
+
7
+ from PIL import Image
8
+ from tqdm import tqdm
9
+ from packaging import version
10
+ IS_TOKENIZER_GREATER_THAN_0_14 = version.parse(tokenizers.__version__) >= version.parse('0.14')
11
+
12
+
13
+ from .llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
14
+ from .llava.peft import LoraConfig, get_peft_model
15
+ from .llava import conversation as conversation_lib
16
+ from .llava.model import *
17
+ from .llava.mm_utils import tokenizer_image_token,process_images
18
+ from .llava.model.language_model.llava_phi3 import LlavaPhiForCausalLM
19
+ from .utils import find_all_linear_names, add_special_tokens_and_resize_model, load_weights, expand2square,com_vision_args
20
+
21
+
22
+ class HealthGPT:
23
+ def __init__(self,model_path,args):
24
+ super().__init__()
25
+ self.llm = LlavaPhiForCausalLM.from_pretrained(
26
+ pretrained_model_name_or_path = model_path,
27
+ attn_implementation="flash_attention_2",
28
+ torch_dtype= torch.float16,
29
+ device_map="cuda"
30
+ )
31
+ print("load model done")
32
+ lora_config = LoraConfig(
33
+ r= 32,
34
+ lora_alpha=64,
35
+ target_modules=find_all_linear_names(self.llm),
36
+ lora_dropout=0.0,
37
+ bias='none',
38
+ task_type="CAUSAL_LM",
39
+ lora_nums=4,
40
+ )
41
+ self.llm = get_peft_model(self.llm, lora_config)
42
+ print("load lora done")
43
+
44
+ self.tokenizer = transformers.AutoTokenizer.from_pretrained(
45
+ model_path,
46
+ padding_side="right",
47
+ use_fast=False,
48
+ )
49
+ print("load tokenizer done")
50
+
51
+ num_new_tokens = add_special_tokens_and_resize_model(self.tokenizer, self.llm, 8192)
52
+ print(f"Number of new tokens added for unified task: {num_new_tokens}")
53
+
54
+ com_vision_args.model_name_or_path = model_path
55
+ com_vision_args.vision_tower = '/mnt/workspace/workgroup_dev/longli/models/hub/clip-vit-large-patch14-336'
56
+ com_vision_args.version = "phi4_instruct"
57
+
58
+ self.llm.get_model().initialize_vision_modules(model_args=com_vision_args)
59
+ self.llm.get_vision_tower().to(dtype=torch.float16)
60
+ self.llm.get_model().mm_projector.to(dtype=torch.float16)
61
+ print("load vision tower done")
62
+
63
+ self.llm = load_weights(self.llm, "/mnt/workspace/workgroup_dev/longli/models/hub/HealthGPT-L14/com_hlora_weights_phi4.bin")
64
+ print("load weights done")
65
+ self.llm.eval()
66
+ self.llm.to(dtype=torch.float16).cuda()
67
+
68
+ self.temperature = args.temperature
69
+ self.top_p = args.top_p
70
+ self.repetition_penalty = args.repetition_penalty
71
+ self.max_tokens = args.max_new_tokens
72
+
73
+
74
+ def process_messages(self,messages):
75
+ conv = conversation_lib.conv_templates["phi4_instruct"].copy()
76
+ conv.messages = []
77
+ if "system" in messages:
78
+ conv.system = messages["system"]
79
+
80
+ imgs = []
81
+ if "image" in messages:
82
+ image = messages["image"]
83
+ if isinstance(image,str):
84
+ image = Image.open(image).convert('RGB')
85
+ elif isinstance(image,Image.Image):
86
+ image = image.convert('RGB')
87
+ imgs.append(image)
88
+ prompt = DEFAULT_IMAGE_TOKEN + '\n' + messages["prompt"]
89
+ elif "images" in messages:
90
+ images = messages["images"]
91
+ prompt = ""
92
+ for i,image in enumerate(images):
93
+ prompt += f"<image_{i+1}>: " + DEFAULT_IMAGE_TOKEN + '\n'
94
+ if isinstance(image,str):
95
+ if os.path.exists(image):
96
+ image = Image.open(image)
97
+ elif isinstance(image,Image.Image):
98
+ image = image.convert("RGB")
99
+ imgs.append(image)
100
+ prompt += messages["prompt"]
101
+ else:
102
+ prompt = messages["prompt"]
103
+ conv.append_message(conv.roles[0],prompt)
104
+ conv.append_message(conv.roles[1],None)
105
+ prompt = conv.get_prompt()
106
+ imgs = None if len(imgs) == 0 else imgs
107
+ return prompt,imgs
108
+
109
+
110
+ def generate_output(self,messages):
111
+ prompt,imgs = self.process_messages(messages)
112
+ if imgs:
113
+ # imgs = imgs[0]
114
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze_(0).cuda()
115
+ imgs = [expand2square(img, tuple(int(x*255) for x in self.llm.get_vision_tower().image_processor.image_mean)) for img in imgs]
116
+ imgs = self.llm.get_vision_tower().image_processor.preprocess(imgs, return_tensors='pt')['pixel_values'].to(dtype=torch.float16, device='cuda', non_blocking=True)
117
+ # imgs = process_images(imgs,self.llm.get_vision_tower().image_processor,self.llm.config)
118
+ else:
119
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze_(0).cuda()
120
+ imgs = None
121
+
122
+ with torch.inference_mode():
123
+ do_sample = False if self.temperature == 0 else True
124
+ output_ids = self.llm.base_model.model.generate(input_ids,images=imgs,do_sample=do_sample,num_beams=5,max_new_tokens=self.max_tokens,temperature = self.temperature,top_p = self.top_p,repetition_penalty = self.repetition_penalty,use_cache=True)
125
+
126
+ outputs = self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
127
+ return outputs
128
+
129
+ def generate_outputs(self,messages_list):
130
+ outputs = []
131
+ for messages in tqdm(messages_list):
132
+ output = self.generate_output(messages)
133
+ outputs.append(output)
134
+ return outputs
135
+
136
+ if __name__ == '__main__':
137
+ # def construct_messages(sample):
138
+ # question = sample["question"]
139
+ # image = sample["image"]
140
+ # answer = sample["answer"]
141
+ # if answer in ["yes","no"]:
142
+ # question += "Please output 'yes' or 'no'(no extra output)"
143
+ # if os.environ.get("STRICT_PROMPT","False") == "True":
144
+ # question += "Wrap your final answer between <answer> and </answer>, for example: <answer>yes</answer>"
145
+ # else:
146
+ # question += 'Answer the question concisely(Keep it short and concise).'
147
+ # if os.environ.get("STRICT_PROMPT","False") == "True":
148
+ # question += "Wrap your final answer between <answer> and </answer>, for example: <answer>positive influence</answer>"
149
+ # messages = {"prompt":question,"image":image}
150
+ # sample["messages"] = messages
151
+ # return sample
152
+
153
+ # from datasets import load_dataset
154
+ # from tqdm import tqdm
155
+ # dataset = load_dataset("/mnt/workspace/workgroup_dev/longli/MedLLMBenchmarks/benchmarks/VQA_RAD",split="test")
156
+
157
+ # llm = HealthGPT()
158
+ # for data in tqdm(dataset):
159
+ # data = construct_messages(data)
160
+ # image = data["image"]
161
+ # messages = {"prompt":data["question"],"image":image}
162
+ # result = llm.generate_output(messages)
163
+
164
+ llm = HealthGPT()
165
+ image = "/mnt/workspace/workgroup_dev/longli/MedLLMBenchmarks/benchmarks/OmniMedVQA/Images/ACRIMA/Im553_g_ACRIMA.png"
166
+ image2 = "/mnt/workspace/workgroup_dev/longli/MedLLMBenchmarks/benchmarks/OmniMedVQA/Images/BreakHis/benign/SOB_B_A-14-22549AB-40-005.png"
167
+ messages = [{ 'images': [image,image2],"prompt":"\nQuestion: 你是一个医疗助手,我的问题是这两张图片里的内容是什么?"}]
168
+ result = llm.generate_outputs(messages)
169
+ print("result:",result)
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/demo/com_infer_phi4.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ MODEL_NAME_OR_PATH="microsoft/Phi-4"
4
+ VIT_PATH="openai/clip-vit-large-patch14-336/"
5
+ HLORA_PATH="com_hlora_weights_phi4.bin"
6
+
7
+ python3 com_infer_phi4.py \
8
+ --model_name_or_path "$MODEL_NAME_OR_PATH" \
9
+ --dtype "FP16" \
10
+ --hlora_r "32" \
11
+ --hlora_alpha "64" \
12
+ --hlora_nums "4" \
13
+ --vq_idx_nums "8192" \
14
+ --instruct_template "phi4_instruct" \
15
+ --vit_path "$VIT_PATH" \
16
+ --hlora_path "$HLORA_PATH" \
17
+ --question "Your question" \
18
+ --img_path "path/to/image.jpg"
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/demo/utils.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import transformers
3
+ import tokenizers
4
+ import os, sys
5
+ from dataclasses import dataclass, field
6
+ import argparse
7
+ from PIL import Image
8
+
9
+ def expand2square(pil_img, background_color):
10
+ width, height = pil_img.size
11
+ if width == height:
12
+ return pil_img
13
+ elif width > height:
14
+ result = Image.new(pil_img.mode, (width, width), background_color)
15
+ result.paste(pil_img, (0, (width - height) // 2))
16
+ return result
17
+ else:
18
+ result = Image.new(pil_img.mode, (height, height), background_color)
19
+ result.paste(pil_img, ((height - width) // 2, 0))
20
+ return result
21
+
22
+ def find_all_linear_names(model):
23
+ cls = torch.nn.Linear
24
+ lora_module_names = set()
25
+ multimodal_keywords = ['mm_projector', 'vision_tower', 'vision_resampler']
26
+ for name, module in model.named_modules():
27
+ if any(mm_keyword in name for mm_keyword in multimodal_keywords):
28
+ continue
29
+ if isinstance(module, cls):
30
+ names = name.split('.')
31
+ lora_module_names.add(names[0] if len(names) == 1 else names[-1])
32
+
33
+ if 'lm_head' in lora_module_names: # needed for 16-bit
34
+ lora_module_names.remove('lm_head')
35
+ return list(lora_module_names)
36
+
37
+ def add_special_tokens_and_resize_model(tokenizer, model, vq_idx_nums=8192):
38
+ if len(tokenizer.additional_special_tokens) != 0:
39
+ return tokenizer.additional_special_tokens
40
+ index_tokens = [f"<idx_{i}>" for i in range(vq_idx_nums)]
41
+ special_tokens = {
42
+ 'additional_special_tokens': ['<start_index>'] + index_tokens + ['<end_index>'] + ['<pixel_newline>']
43
+ }
44
+ num_new_tokens = tokenizer.add_special_tokens(special_tokens)
45
+ model.resize_token_embeddings(len(tokenizer))
46
+ if num_new_tokens > 0:
47
+ input_embeddings = model.get_input_embeddings().weight.data
48
+ output_embeddings = model.get_output_embeddings().weight.data
49
+
50
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
51
+ dim=0, keepdim=True)
52
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
53
+ dim=0, keepdim=True)
54
+
55
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
56
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
57
+
58
+ return num_new_tokens
59
+
60
+ com_vision_args = argparse.Namespace(
61
+ freeze_backbone=False,
62
+ mm_patch_merge_type='flat',
63
+ mm_projector_type='mlp2x_gelu',
64
+ mm_use_im_patch_token=False,
65
+ mm_use_im_start_end=False,
66
+ mm_vision_select_feature='patch',
67
+ mm_vision_select_layer=-2,
68
+ model_name_or_path=None,
69
+ pretrain_mm_mlp_adapter=None,
70
+ tune_mm_mlp_adapter=False,
71
+ version=None,
72
+ vision_tower=None
73
+ )
74
+
75
+ gen_vision_args = argparse.Namespace(
76
+ freeze_backbone=False,
77
+ mm_patch_merge_type='flat',
78
+ mm_projector_type='mlp2x_gelu',
79
+ mm_use_im_patch_token=False,
80
+ mm_use_im_start_end=False,
81
+ mm_vision_select_feature='patch',
82
+ mm_vision_select_layer=1,
83
+ model_name_or_path=None,
84
+ pretrain_mm_mlp_adapter=None,
85
+ tune_mm_mlp_adapter=False,
86
+ version=None,
87
+ vision_tower=None
88
+ )
89
+
90
+ def load_weights(model, hlora_path, fusion_layer_path=None):
91
+ hlora_weights = torch.load(hlora_path)
92
+ hlora_unexpected_keys = model.load_state_dict(hlora_weights, strict=False)[1]
93
+ if hlora_unexpected_keys:
94
+ print(f"Warning: Unexpected keys in hlora checkpoint: {hlora_unexpected_keys}")
95
+
96
+ if fusion_layer_path:
97
+ fusion_layer_weights = torch.load(fusion_layer_path)
98
+ fusion_layer_unexpected_keys = model.load_state_dict(fusion_layer_weights, strict=False)[1]
99
+ if fusion_layer_unexpected_keys:
100
+ print(f"Warning: Unexpected keys in fusion_layer checkpoint: {fusion_layer_unexpected_keys}")
101
+
102
+ return model
103
+
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+ # There's no way to ignore "F401 '...' imported but unused" warnings in this
3
+ # module, but to preserve other warnings. So, don't check this module at all.
4
+
5
+ # coding=utf-8
6
+ # Copyright 2023-present the HuggingFace Inc. team.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ __version__ = "0.3.0.dev0"
21
+
22
+ from .mapping import MODEL_TYPE_TO_PEFT_MODEL_MAPPING, PEFT_TYPE_TO_CONFIG_MAPPING, get_peft_config, get_peft_model
23
+ from .peft_model import (
24
+ PeftModel,
25
+ PeftModelForCausalLM,
26
+ PeftModelForSeq2SeqLM,
27
+ PeftModelForSequenceClassification,
28
+ PeftModelForTokenClassification,
29
+ )
30
+ from .tuners import (
31
+ LoraConfig,
32
+ LoraModel,
33
+ PrefixEncoder,
34
+ PrefixTuningConfig,
35
+ PromptEmbedding,
36
+ PromptEncoder,
37
+ PromptEncoderConfig,
38
+ PromptEncoderReparameterizationType,
39
+ PromptTuningConfig,
40
+ PromptTuningInit,
41
+ )
42
+ from .utils import (
43
+ TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING,
44
+ PeftConfig,
45
+ PeftType,
46
+ PromptLearningConfig,
47
+ TaskType,
48
+ bloom_model_postprocess_past_key_value,
49
+ get_peft_model_state_dict,
50
+ # prepare_model_for_int8_training,
51
+ set_peft_model_state_dict,
52
+ shift_tokens_right,
53
+ )
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/mapping.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023-present the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from .peft_model import (
17
+ PeftModel,
18
+ PeftModelForCausalLM,
19
+ PeftModelForSeq2SeqLM,
20
+ PeftModelForSequenceClassification,
21
+ PeftModelForTokenClassification,
22
+ )
23
+ from .tuners import LoraConfig, PrefixTuningConfig, PromptEncoderConfig, PromptTuningConfig
24
+ from .utils import PromptLearningConfig
25
+
26
+
27
+ MODEL_TYPE_TO_PEFT_MODEL_MAPPING = {
28
+ "SEQ_CLS": PeftModelForSequenceClassification,
29
+ "SEQ_2_SEQ_LM": PeftModelForSeq2SeqLM,
30
+ "CAUSAL_LM": PeftModelForCausalLM, # here
31
+ "TOKEN_CLS": PeftModelForTokenClassification,
32
+ }
33
+
34
+ PEFT_TYPE_TO_CONFIG_MAPPING = {
35
+ "PROMPT_TUNING": PromptTuningConfig,
36
+ "PREFIX_TUNING": PrefixTuningConfig,
37
+ "P_TUNING": PromptEncoderConfig,
38
+ "LORA": LoraConfig,
39
+ }
40
+
41
+ TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING = {
42
+ "t5": ["q", "v"],
43
+ "mt5": ["q", "v"],
44
+ "bart": ["q_proj", "v_proj"],
45
+ "gpt2": ["c_attn"],
46
+ "bloom": ["query_key_value"],
47
+ "opt": ["q_proj", "v_proj"],
48
+ "gptj": ["q_proj", "v_proj"],
49
+ "gpt_neox": ["query_key_value"],
50
+ "gpt_neo": ["q_proj", "v_proj"],
51
+ "bert": ["query", "value"],
52
+ "roberta": ["query", "value"],
53
+ "xlm-roberta": ["query", "value"],
54
+ "electra": ["query", "value"],
55
+ "deberta-v2": ["query_proj", "value_proj"],
56
+ "deberta": ["in_proj"],
57
+ "layoutlm": ["query", "value"],
58
+ "llama": ["q_proj", "v_proj"],
59
+ "chatglm": ["query_key_value"],
60
+ }
61
+
62
+
63
+ def get_peft_config(config_dict):
64
+ """
65
+ Returns a Peft config object from a dictionary.
66
+
67
+ Args:
68
+ config_dict (`Dict[str, Any]`): Dictionary containing the configuration parameters.
69
+ """
70
+
71
+ return PEFT_TYPE_TO_CONFIG_MAPPING[config_dict["peft_type"]](**config_dict)
72
+
73
+
74
+ def _prepare_prompt_learning_config(peft_config, model_config):
75
+ if peft_config.num_layers is None:
76
+ if "num_hidden_layers" in model_config:
77
+ num_layers = model_config["num_hidden_layers"]
78
+ elif "num_layers" in model_config:
79
+ num_layers = model_config["num_layers"]
80
+ elif "n_layer" in model_config:
81
+ num_layers = model_config["n_layer"]
82
+ else:
83
+ raise ValueError("Please specify `num_layers` in `peft_config`")
84
+ peft_config.num_layers = num_layers
85
+
86
+ if peft_config.token_dim is None:
87
+ if "hidden_size" in model_config:
88
+ token_dim = model_config["hidden_size"]
89
+ elif "n_embd" in model_config:
90
+ token_dim = model_config["n_embd"]
91
+ elif "d_model" in model_config:
92
+ token_dim = model_config["d_model"]
93
+ else:
94
+ raise ValueError("Please specify `token_dim` in `peft_config`")
95
+ peft_config.token_dim = token_dim
96
+
97
+ if peft_config.num_attention_heads is None:
98
+ if "num_attention_heads" in model_config:
99
+ num_attention_heads = model_config["num_attention_heads"]
100
+ elif "n_head" in model_config:
101
+ num_attention_heads = model_config["n_head"]
102
+ elif "num_heads" in model_config:
103
+ num_attention_heads = model_config["num_heads"]
104
+ elif "encoder_attention_heads" in model_config:
105
+ num_attention_heads = model_config["encoder_attention_heads"]
106
+ else:
107
+ raise ValueError("Please specify `num_attention_heads` in `peft_config`")
108
+ peft_config.num_attention_heads = num_attention_heads
109
+
110
+ if getattr(peft_config, "encoder_hidden_size", None) is None:
111
+ setattr(peft_config, "encoder_hidden_size", token_dim)
112
+
113
+ return peft_config
114
+
115
+
116
+ def _prepare_lora_config(peft_config, model_config):
117
+ if peft_config.target_modules is None:
118
+ if model_config["model_type"] not in TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING:
119
+ raise ValueError("Please specify `target_modules` in `peft_config`")
120
+ peft_config.target_modules = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING[model_config["model_type"]]
121
+ if len(peft_config.target_modules) == 1:
122
+ peft_config.fan_in_fan_out = True
123
+ peft_config.enable_lora = [True, False, True]
124
+ if peft_config.inference_mode:
125
+ peft_config.merge_weights = True
126
+ return peft_config
127
+
128
+
129
+ def get_peft_model(model, peft_config):
130
+ """
131
+ Returns a Peft model object from a model and a config.
132
+
133
+ Args:
134
+ model ([`transformers.PreTrainedModel`]): Model to be wrapped.
135
+ peft_config ([`PeftConfig`]): Configuration object containing the parameters of the Peft model.
136
+ """
137
+
138
+ model_config = model.config.to_dict()
139
+ peft_config.base_model_name_or_path = model.__dict__.get("name_or_path", None)
140
+
141
+ # PeftModelForCausalLM <- PeftModel
142
+ if peft_config.task_type not in MODEL_TYPE_TO_PEFT_MODEL_MAPPING.keys():
143
+ peft_config = _prepare_lora_config(peft_config, model_config)
144
+ return PeftModel(model, peft_config)
145
+ if not isinstance(peft_config, PromptLearningConfig): # -------------> here
146
+ peft_config = _prepare_lora_config(peft_config, model_config)
147
+ else:
148
+ peft_config = _prepare_prompt_learning_config(peft_config, model_config)
149
+
150
+
151
+ return MODEL_TYPE_TO_PEFT_MODEL_MAPPING[peft_config.task_type](model, peft_config)
152
+
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/peft_model.py ADDED
@@ -0,0 +1,932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023-present the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import inspect
17
+ import os
18
+ import warnings
19
+ from contextlib import contextmanager
20
+ import sys
21
+
22
+
23
+ import torch
24
+ from accelerate import dispatch_model, infer_auto_device_map
25
+ from accelerate.hooks import AlignDevicesHook, add_hook_to_module, remove_hook_from_submodules
26
+ from accelerate.utils import get_balanced_memory
27
+ from huggingface_hub import hf_hub_download
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+ from transformers import PreTrainedModel
30
+ from transformers.modeling_outputs import SequenceClassifierOutput, TokenClassifierOutput
31
+ from transformers.utils import PushToHubMixin
32
+
33
+ from .tuners import LoraModel, PrefixEncoder, PromptEmbedding, PromptEncoder
34
+ from .utils import (
35
+ TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING,
36
+ WEIGHTS_NAME,
37
+ PeftConfig,
38
+ PeftType,
39
+ PromptLearningConfig,
40
+ TaskType,
41
+ _set_trainable,
42
+ get_peft_model_state_dict,
43
+ set_peft_model_state_dict,
44
+ shift_tokens_right,
45
+ )
46
+
47
+
48
+ class PeftModel(PushToHubMixin, torch.nn.Module):
49
+ """
50
+ Parameter-Efficient Fine-Tuning Model. Base model encompassing various Peft methods.
51
+
52
+ Args:
53
+ model ([`PreTrainedModel`]): The base transformer model used for Peft.
54
+ peft_config ([`PeftConfig`]): The configuration of the Peft model.
55
+
56
+
57
+ **Attributes**:
58
+ - **base_model** ([`PreTrainedModel`]) -- The base transformer model used for Peft.
59
+ - **peft_config** ([`PeftConfig`]) -- The configuration of the Peft model.
60
+ - **modules_to_save** (`list` of `str`) -- The list of sub-module names to save when
61
+ saving the model.
62
+ - **prompt_encoder** ([`PromptEncoder`]) -- The prompt encoder used for Peft if
63
+ `isinstance(self.peft_config, PromptLearningConfig)`.
64
+ - **prompt_tokens** (`torch.Tensor`) -- The virtual prompt tokens used for Peft if
65
+ `isinstance(self.peft_config, PromptLearningConfig)`.
66
+ - **transformer_backbone_name** (`str`) -- The name of the transformer
67
+ backbone in the base model if `isinstance(self.peft_config, PromptLearningConfig)`.
68
+ - **word_embeddings** (`torch.nn.Embedding`) -- The word embeddings of the transformer backbone
69
+ in the base model if `isinstance(self.peft_config, PromptLearningConfig)`.
70
+ """
71
+
72
+ def __init__(self, model, peft_config: PeftConfig): # casualLM, LoraConfig
73
+ super().__init__()
74
+ self.peft_config = peft_config
75
+ self.base_model = model
76
+ self.config = self.base_model.config
77
+ self.modules_to_save = None
78
+ if isinstance(self.peft_config, PromptLearningConfig):
79
+ self._setup_prompt_encoder()
80
+ else: # --------------> here
81
+ self.base_model = LoraModel(peft_config, model)
82
+ if getattr(self.peft_config, "modules_to_save", None) is not None:
83
+ self.modules_to_save = self.peft_config.modules_to_save
84
+ _set_trainable(self)
85
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
86
+
87
+ def save_pretrained(self, save_directory, **kwargs):
88
+ r"""
89
+ Args:
90
+ This function saves the adapter model and the adapter configuration files to a directory, so that it can be
91
+ re-loaded using the `LoraModel.from_pretrained` class method, and also used by the `LoraModel.push_to_hub`
92
+ method.
93
+ save_directory (`str`):
94
+ Directory where the adapter model and configuration files will be saved (will be created if it does not
95
+ exist).
96
+ **kwargs:
97
+ Additional keyword arguments passed along to the `push_to_hub` method.
98
+ """
99
+ if os.path.isfile(save_directory):
100
+ raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")
101
+ os.makedirs(save_directory, exist_ok=True)
102
+
103
+ # save only the trainable weights
104
+ output_state_dict = get_peft_model_state_dict(self, kwargs.get("state_dict", None))
105
+ torch.save(output_state_dict, os.path.join(save_directory, WEIGHTS_NAME))
106
+
107
+ # save the config and change the inference mode to `True`
108
+ if self.peft_config.base_model_name_or_path is None:
109
+ self.peft_config.base_model_name_or_path = (
110
+ self.base_model.__dict__.get("name_or_path", None)
111
+ if isinstance(self.peft_config, PromptLearningConfig)
112
+ else self.base_model.model.__dict__.get("name_or_path", None)
113
+ )
114
+ inference_mode = self.peft_config.inference_mode
115
+ self.peft_config.inference_mode = True
116
+ self.peft_config.save_pretrained(save_directory)
117
+ self.peft_config.inference_mode = inference_mode
118
+
119
+ @classmethod
120
+ def from_pretrained(cls, model, model_id, **kwargs):
121
+ r"""
122
+ Args:
123
+ Instantiate a `LoraModel` from a pretrained Lora configuration and weights.
124
+ model (`transformers.PreTrainedModel`):
125
+ The model to be adapted. The model should be initialized with the `from_pretrained` method. from
126
+ `transformers` library.
127
+ model_id (`str`):
128
+ The name of the Lora configuration to use. Can be either:
129
+ - A string, the `model id` of a Lora configuration hosted inside a model repo on
130
+ huggingface Hub
131
+ - A path to a directory containing a Lora configuration file saved using the
132
+ `save_pretrained` method, e.g., ``./my_lora_config_directory/``.
133
+ """
134
+ from .mapping import MODEL_TYPE_TO_PEFT_MODEL_MAPPING, PEFT_TYPE_TO_CONFIG_MAPPING
135
+
136
+ # load the config
137
+ config = PEFT_TYPE_TO_CONFIG_MAPPING[PeftConfig.from_pretrained(model_id).peft_type].from_pretrained(model_id)
138
+
139
+ if getattr(model, "hf_device_map", None) is not None:
140
+ remove_hook_from_submodules(model)
141
+
142
+ if config.task_type not in MODEL_TYPE_TO_PEFT_MODEL_MAPPING.keys():
143
+ model = cls(model, config)
144
+ else: # -----------------> here
145
+ model = MODEL_TYPE_TO_PEFT_MODEL_MAPPING[config.task_type](model, config)
146
+
147
+ if os.path.exists(os.path.join(model_id, WEIGHTS_NAME)):
148
+ filename = os.path.join(model_id, WEIGHTS_NAME)
149
+ else:
150
+ try:
151
+ filename = hf_hub_download(model_id, WEIGHTS_NAME)
152
+ except:
153
+ raise ValueError(
154
+ f"Can't find weights for {model_id} in {model_id} or in the Hugging Face Hub. "
155
+ f"Please check that the file {WEIGHTS_NAME} is present at {model_id}."
156
+ )
157
+
158
+ adapters_weights = torch.load(
159
+ filename, map_location=torch.device("cuda" if torch.cuda.is_available() else "cpu")
160
+ )
161
+ # load the weights into the model
162
+ model = set_peft_model_state_dict(model, adapters_weights)
163
+
164
+
165
+ if getattr(model, "hf_device_map", None) is not None:
166
+ device_map = kwargs.get("device_map", "auto")
167
+ max_memory = kwargs.get("max_memory", None)
168
+ no_split_module_classes = model._no_split_modules
169
+ if device_map != "sequential":
170
+ max_memory = get_balanced_memory(
171
+ model,
172
+ max_memory=max_memory,
173
+ no_split_module_classes=no_split_module_classes,
174
+ low_zero=(device_map == "balanced_low_0"),
175
+ )
176
+ if isinstance(device_map, str):
177
+ device_map = infer_auto_device_map(
178
+ model, max_memory=max_memory, no_split_module_classes=no_split_module_classes
179
+ )
180
+ model = dispatch_model(model, device_map=device_map)
181
+ hook = AlignDevicesHook(io_same_device=True)
182
+ if model.peft_config.peft_type == PeftType.LORA:
183
+ add_hook_to_module(model.base_model.model, hook)
184
+ else:
185
+ remove_hook_from_submodules(model.prompt_encoder)
186
+ add_hook_to_module(model.base_model, hook)
187
+ return model
188
+
189
+ def _setup_prompt_encoder(self):
190
+ transformer_backbone = None
191
+ for name, module in self.base_model.named_children():
192
+ for param in module.parameters():
193
+ param.requires_grad = False
194
+ if isinstance(module, PreTrainedModel):
195
+ # Make sure to freeze Tranformers model
196
+ if transformer_backbone is None:
197
+ transformer_backbone = module
198
+ self.transformer_backbone_name = name
199
+
200
+ if self.peft_config.num_transformer_submodules is None:
201
+ self.peft_config.num_transformer_submodules = (
202
+ 2 if self.peft_config.task_type == TaskType.SEQ_2_SEQ_LM else 1
203
+ )
204
+
205
+ for named_param, value in list(transformer_backbone.named_parameters()):
206
+ if value.shape[0] == self.base_model.config.vocab_size:
207
+ self.word_embeddings = transformer_backbone.get_submodule(named_param.replace(".weight", ""))
208
+ break
209
+
210
+ if self.peft_config.peft_type == PeftType.PROMPT_TUNING:
211
+ prompt_encoder = PromptEmbedding(self.peft_config, self.word_embeddings)
212
+ elif self.peft_config.peft_type == PeftType.P_TUNING:
213
+ prompt_encoder = PromptEncoder(self.peft_config)
214
+ elif self.peft_config.peft_type == PeftType.PREFIX_TUNING:
215
+ prompt_encoder = PrefixEncoder(self.peft_config)
216
+ else:
217
+ raise ValueError("Not supported")
218
+ self.prompt_encoder = prompt_encoder
219
+ self.prompt_tokens = torch.arange(
220
+ self.peft_config.num_virtual_tokens * self.peft_config.num_transformer_submodules
221
+ ).long()
222
+
223
+ def get_prompt_embedding_to_save(self):
224
+ """
225
+ Returns the prompt embedding to save when saving the model. Only applicable when `peft_config.peft_type !=
226
+ PeftType.LORA`.
227
+ """
228
+ prompt_tokens = self.prompt_tokens.unsqueeze(0).expand(1, -1).to(self.device)
229
+ if self.peft_config.peft_type == PeftType.PREFIX_TUNING:
230
+ prompt_tokens = prompt_tokens[:, : self.peft_config.num_virtual_tokens]
231
+ prompt_embeddings = self.prompt_encoder(prompt_tokens)
232
+ return prompt_embeddings[0].detach().cpu()
233
+
234
+ def get_prompt(self, batch_size):
235
+ """
236
+ Returns the virtual prompts to use for Peft. Only applicable when `peft_config.peft_type != PeftType.LORA`.
237
+ """
238
+ prompt_tokens = self.prompt_tokens.unsqueeze(0).expand(batch_size, -1).to(self.device)
239
+ if self.peft_config.peft_type == PeftType.PREFIX_TUNING:
240
+ prompt_tokens = prompt_tokens[:, : self.peft_config.num_virtual_tokens]
241
+ if self.peft_config.inference_mode:
242
+ past_key_values = self.prompt_encoder.embedding.weight.repeat(batch_size, 1, 1)
243
+ else:
244
+ past_key_values = self.prompt_encoder(prompt_tokens)
245
+ past_key_values = past_key_values.view(
246
+ batch_size,
247
+ self.peft_config.num_virtual_tokens,
248
+ self.peft_config.num_layers * 2,
249
+ self.peft_config.num_attention_heads,
250
+ self.peft_config.token_dim // self.peft_config.num_attention_heads,
251
+ )
252
+ if self.peft_config.num_transformer_submodules == 2:
253
+ past_key_values = torch.cat([past_key_values, past_key_values], dim=2)
254
+ past_key_values = past_key_values.permute([2, 0, 3, 1, 4]).split(
255
+ self.peft_config.num_transformer_submodules * 2
256
+ )
257
+ if TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING.get(self.config.model_type, None) is not None:
258
+ post_process_fn = TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING[self.config.model_type]
259
+ past_key_values = post_process_fn(past_key_values)
260
+ return past_key_values
261
+ else:
262
+ if self.peft_config.inference_mode:
263
+ prompts = self.prompt_encoder.embedding.weight.repeat(batch_size, 1, 1)
264
+ else:
265
+ prompts = self.prompt_encoder(prompt_tokens)
266
+ return prompts
267
+
268
+ def print_trainable_parameters(self):
269
+ """
270
+ Prints the number of trainable parameters in the model.
271
+ """
272
+ trainable_params = 0
273
+ all_param = 0
274
+ for _, param in self.named_parameters():
275
+ num_params = param.numel()
276
+ # if using DS Zero 3 and the weights are initialized empty
277
+ if num_params == 0 and hasattr(param, "ds_numel"):
278
+ num_params = param.ds_numel
279
+
280
+ all_param += num_params
281
+ if param.requires_grad:
282
+ # print(f'trainable, name: {_}, params: {param}')
283
+ trainable_params += num_params
284
+ # else:
285
+ # print(f'freeze, name: {_}, params: {param}')
286
+ print(
287
+ f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}"
288
+ )
289
+
290
+ def __getattr__(self, name: str):
291
+ """Forward missing attributes to the wrapped module."""
292
+ try:
293
+ return super().__getattr__(name) # defer to nn.Module's logic
294
+ except AttributeError:
295
+ return getattr(self.base_model, name)
296
+
297
+ def forward(self, *args, **kwargs): # pylint: disable=E0202
298
+ """
299
+ Forward pass of the model.
300
+ """
301
+ return self.get_base_model()(*args, **kwargs)
302
+
303
+ @contextmanager
304
+ def disable_adapter(self):
305
+ """
306
+ Disables the adapter module.
307
+ """
308
+ if isinstance(self.peft_config, PromptLearningConfig):
309
+ old_forward = self.forward
310
+ self.forward = self.base_model.forward
311
+ else:
312
+ self.base_model.disable_adapter_layers()
313
+ yield
314
+ if isinstance(self.peft_config, PromptLearningConfig):
315
+ self.forward = old_forward
316
+ else:
317
+ self.base_model.enable_adapter_layers()
318
+
319
+ def get_base_model(self):
320
+ """
321
+ Returns the base model.
322
+ """
323
+ return self.base_model if isinstance(self.peft_config, PromptLearningConfig) else self.base_model.model
324
+
325
+
326
+ class PeftModelForSequenceClassification(PeftModel):
327
+ """
328
+ Peft model for sequence classification tasks.
329
+
330
+ Args:
331
+ model ([`PreTrainedModel`]): Base transformer model
332
+ peft_config ([`PeftConfig`]): Peft config.
333
+
334
+ **Attributes**:
335
+ - **config** ([`PretrainedConfig`]) -- The configuration object of the base model.
336
+ - **cls_layer_name** (`str`) -- The name of the classification layer.
337
+
338
+ Example::
339
+
340
+ >>> from transformers import AutoModelForSequenceClassification >>> from peft import
341
+ PeftModelForSequenceClassification, get_peft_config >>> config = {
342
+ 'peft_type': 'PREFIX_TUNING', 'task_type': 'SEQ_CLS', 'inference_mode': False, 'num_virtual_tokens':
343
+ 20, 'token_dim': 768, 'num_transformer_submodules': 1, 'num_attention_heads': 12, 'num_layers': 12,
344
+ 'encoder_hidden_size': 768, 'prefix_projection': False, 'postprocess_past_key_value_function': None
345
+ }
346
+ >>> peft_config = get_peft_config(config) >>> model =
347
+ AutoModelForSequenceClassification.from_pretrained("bert-base-cased") >>> peft_model =
348
+ PeftModelForSequenceClassification(model, peft_config) >>> peft_model.print_trainable_parameters() trainable
349
+ params: 370178 || all params: 108680450 || trainable%: 0.3406113979101117
350
+ """
351
+
352
+ def __init__(self, model, peft_config: PeftConfig):
353
+ super().__init__(model, peft_config)
354
+ self.modules_to_save = ["classifier", "score"]
355
+
356
+ for name, _ in self.base_model.named_children():
357
+ if any(module_name in name for module_name in self.modules_to_save):
358
+ self.cls_layer_name = name
359
+ break
360
+
361
+ # to make sure classifier layer is trainable
362
+ _set_trainable(self)
363
+
364
+ def forward( # pylint: disable=W0221
365
+ self,
366
+ input_ids=None,
367
+ attention_mask=None,
368
+ inputs_embeds=None,
369
+ labels=None,
370
+ output_attentions=None,
371
+ output_hidden_states=None,
372
+ return_dict=None,
373
+ **kwargs,
374
+ ):
375
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
376
+
377
+ if not isinstance(self.peft_config, PromptLearningConfig):
378
+ return self.base_model(
379
+ input_ids=input_ids,
380
+ attention_mask=attention_mask,
381
+ inputs_embeds=inputs_embeds,
382
+ labels=labels,
383
+ output_attentions=output_attentions,
384
+ output_hidden_states=output_hidden_states,
385
+ return_dict=return_dict,
386
+ **kwargs,
387
+ )
388
+
389
+ batch_size = input_ids.shape[0]
390
+ if attention_mask is not None:
391
+ # concat prompt attention mask
392
+ prefix_attention_mask = torch.ones(batch_size, self.peft_config.num_virtual_tokens).to(self.device)
393
+ attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)
394
+ if kwargs.get("position_ids", None) is not None:
395
+ warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.")
396
+ kwargs["position_ids"] = None
397
+ kwargs.update(
398
+ {
399
+ "attention_mask": attention_mask,
400
+ "labels": labels,
401
+ "output_attentions": output_attentions,
402
+ "output_hidden_states": output_hidden_states,
403
+ "return_dict": return_dict,
404
+ }
405
+ )
406
+
407
+ if self.peft_config.peft_type == PeftType.PREFIX_TUNING:
408
+ return self._prefix_tuning_forward(input_ids=input_ids, **kwargs)
409
+ else:
410
+ if kwargs.get("token_type_ids", None) is not None:
411
+ kwargs["token_type_ids"] = torch.cat(
412
+ (
413
+ torch.zeros(batch_size, self.peft_config.num_virtual_tokens).to(self.device),
414
+ kwargs["token_type_ids"],
415
+ ),
416
+ dim=1,
417
+ ).long()
418
+ if inputs_embeds is None:
419
+ inputs_embeds = self.word_embeddings(input_ids)
420
+ prompts = self.get_prompt(batch_size=batch_size)
421
+ prompts = prompts.to(inputs_embeds.dtype)
422
+ inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1)
423
+ return self.base_model(inputs_embeds=inputs_embeds, **kwargs)
424
+
425
+ def _prefix_tuning_forward(
426
+ self,
427
+ input_ids=None,
428
+ attention_mask=None,
429
+ inputs_embeds=None,
430
+ labels=None,
431
+ output_attentions=None,
432
+ output_hidden_states=None,
433
+ return_dict=None,
434
+ **kwargs,
435
+ ):
436
+ batch_size = input_ids.shape[0]
437
+ past_key_values = self.get_prompt(batch_size)
438
+ fwd_params = list(inspect.signature(self.base_model.forward).parameters.keys())
439
+ kwargs.update(
440
+ {
441
+ "input_ids": input_ids,
442
+ "attention_mask": attention_mask,
443
+ "inputs_embeds": inputs_embeds,
444
+ "output_attentions": output_attentions,
445
+ "output_hidden_states": output_hidden_states,
446
+ "return_dict": return_dict,
447
+ "past_key_values": past_key_values,
448
+ }
449
+ )
450
+ if "past_key_values" in fwd_params:
451
+ return self.base_model(labels=labels, **kwargs)
452
+ else:
453
+ transformer_backbone_name = self.base_model.get_submodule(self.transformer_backbone_name)
454
+ fwd_params = list(inspect.signature(transformer_backbone_name.forward).parameters.keys())
455
+ if "past_key_values" not in fwd_params:
456
+ raise ValueError("Model does not support past key values which are required for prefix tuning.")
457
+ outputs = transformer_backbone_name(**kwargs)
458
+ pooled_output = outputs[1] if len(outputs) > 1 else outputs[0]
459
+ if "dropout" in [name for name, _ in list(self.base_model.named_children())]:
460
+ pooled_output = self.base_model.dropout(pooled_output)
461
+ logits = self.base_model.get_submodule(self.cls_layer_name)(pooled_output)
462
+
463
+ loss = None
464
+ if labels is not None:
465
+ if self.config.problem_type is None:
466
+ if self.base_model.num_labels == 1:
467
+ self.config.problem_type = "regression"
468
+ elif self.base_model.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
469
+ self.config.problem_type = "single_label_classification"
470
+ else:
471
+ self.config.problem_type = "multi_label_classification"
472
+
473
+ if self.config.problem_type == "regression":
474
+ loss_fct = MSELoss()
475
+ if self.base_model.num_labels == 1:
476
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
477
+ else:
478
+ loss = loss_fct(logits, labels)
479
+ elif self.config.problem_type == "single_label_classification":
480
+ loss_fct = CrossEntropyLoss()
481
+ loss = loss_fct(logits.view(-1, self.base_model.num_labels), labels.view(-1))
482
+ elif self.config.problem_type == "multi_label_classification":
483
+ loss_fct = BCEWithLogitsLoss()
484
+ loss = loss_fct(logits, labels)
485
+ if not return_dict:
486
+ output = (logits,) + outputs[2:]
487
+ return ((loss,) + output) if loss is not None else output
488
+
489
+ return SequenceClassifierOutput(
490
+ loss=loss,
491
+ logits=logits,
492
+ hidden_states=outputs.hidden_states,
493
+ attentions=outputs.attentions,
494
+ )
495
+
496
+
497
+ class PeftModelForCausalLM(PeftModel):
498
+ """
499
+ Peft model for Causal LM
500
+
501
+ Args:
502
+ model ([`PreTrainedModel`]): Base transformer model
503
+ peft_config ([`PeftConfig`]): Peft config.
504
+
505
+
506
+ Example::
507
+
508
+ >>> from transformers import AutoModelForCausalLM >>> from peft import PeftModelForCausalLM, get_peft_config
509
+ >>> config = {
510
+ 'peft_type': 'PREFIX_TUNING', 'task_type': 'CAUSAL_LM', 'inference_mode': False, 'num_virtual_tokens':
511
+ 20, 'token_dim': 1280, 'num_transformer_submodules': 1, 'num_attention_heads': 20, 'num_layers': 36,
512
+ 'encoder_hidden_size': 1280, 'prefix_projection': False, 'postprocess_past_key_value_function': None
513
+ }
514
+ >>> peft_config = get_peft_config(config) >>> model = AutoModelForCausalLM.from_pretrained("gpt2-large") >>>
515
+ peft_model = PeftModelForCausalLM(model, peft_config) >>> peft_model.print_trainable_parameters() trainable
516
+ """
517
+
518
+ def __init__(self, model, peft_config: PeftConfig): # casualLM, LoraConfig
519
+ super().__init__(model, peft_config)
520
+ self.base_model_prepare_inputs_for_generation = self.base_model.prepare_inputs_for_generation
521
+
522
+ def forward(# pylint: disable=W0221
523
+ self,
524
+ input_ids=None,
525
+ attention_mask=None,
526
+ inputs_embeds=None,
527
+ labels=None,
528
+ output_attentions=None,
529
+ output_hidden_states=None,
530
+ return_dict=None,
531
+ # task_types=None,
532
+ **kwargs,
533
+ ):
534
+ if not isinstance(self.peft_config, PromptLearningConfig): # here
535
+ return self.base_model(
536
+ input_ids=input_ids,
537
+ attention_mask=attention_mask,
538
+ inputs_embeds=inputs_embeds,
539
+ labels=labels,
540
+ output_attentions=output_attentions,
541
+ output_hidden_states=output_hidden_states,
542
+ return_dict=return_dict,
543
+ # task_types=task_types,
544
+ **kwargs,
545
+ )
546
+
547
+ batch_size = input_ids.shape[0]
548
+ if attention_mask is not None:
549
+ # concat prompt attention mask
550
+ prefix_attention_mask = torch.ones(batch_size, self.peft_config.num_virtual_tokens).to(self.device)
551
+ attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)
552
+
553
+ if kwargs.get("position_ids", None) is not None:
554
+ warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.")
555
+ kwargs["position_ids"] = None
556
+ if kwargs.get("token_type_ids", None) is not None:
557
+ warnings.warn("Token type ids are not supported for parameter efficient tuning. Ignoring token type ids")
558
+ kwargs["token_type_ids"] = None
559
+ kwargs.update(
560
+ {
561
+ "attention_mask": attention_mask,
562
+ "labels": labels,
563
+ "output_attentions": output_attentions,
564
+ "output_hidden_states": output_hidden_states,
565
+ "return_dict": return_dict,
566
+ }
567
+ )
568
+
569
+ if self.peft_config.peft_type == PeftType.PREFIX_TUNING:
570
+ past_key_values = self.get_prompt(batch_size)
571
+ return self.base_model(input_ids=input_ids, past_key_values=past_key_values, **kwargs)
572
+ else:
573
+ if inputs_embeds is None:
574
+ inputs_embeds = self.word_embeddings(input_ids)
575
+ # concat prompt labels
576
+ if labels is not None:
577
+ prefix_labels = torch.full((batch_size, self.peft_config.num_virtual_tokens), -100).to(self.device)
578
+ kwargs["labels"] = torch.cat((prefix_labels, labels), dim=1)
579
+ prompts = self.get_prompt(batch_size=batch_size)
580
+ prompts = prompts.to(inputs_embeds.dtype)
581
+ inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1)
582
+ return self.base_model(inputs_embeds=inputs_embeds, **kwargs)
583
+
584
+ def generate(self, **kwargs):
585
+ self.base_model.prepare_inputs_for_generation = self.prepare_inputs_for_generation
586
+ try:
587
+ outputs = self.base_model.generate(**kwargs)
588
+ except:
589
+ self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation
590
+ raise
591
+ else:
592
+ self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation
593
+ return outputs
594
+
595
+ def prepare_inputs_for_generation(self, *args, **kwargs):
596
+ model_kwargs = self.base_model_prepare_inputs_for_generation(*args, **kwargs)
597
+ if isinstance(self.peft_config, PromptLearningConfig):
598
+ if model_kwargs["past_key_values"] is None and self.peft_config.peft_type == PeftType.PREFIX_TUNING:
599
+ past_key_values = self.get_prompt(batch_size=model_kwargs["input_ids"].shape[0])
600
+ model_kwargs["past_key_values"] = past_key_values
601
+ else:
602
+ if model_kwargs["past_key_values"] is None:
603
+ inputs_embeds = self.word_embeddings(model_kwargs["input_ids"])
604
+ prompts = self.get_prompt(batch_size=model_kwargs["input_ids"].shape[0])
605
+ prompts = prompts.to(inputs_embeds.dtype)
606
+ model_kwargs["inputs_embeds"] = torch.cat((prompts, inputs_embeds), dim=1)
607
+ model_kwargs["input_ids"] = None
608
+
609
+ return model_kwargs
610
+
611
+
612
+
613
+ class PeftModelForSeq2SeqLM(PeftModel):
614
+ """
615
+ Peft model for Seq2Seq LM
616
+
617
+ Args:
618
+ model ([`PreTrainedModel`]): Base transformer model
619
+ peft_config ([`PeftConfig`]): Peft config.
620
+
621
+
622
+ Example::
623
+
624
+ >>> from transformers import AutoModelForSeq2SeqLM >>> from peft import PeftModelForSeq2SeqLM, get_peft_config
625
+ >>> config = {
626
+ 'peft_type': 'LORA', 'task_type': 'SEQ_2_SEQ_LM', 'inference_mode': False, 'r': 8, 'target_modules':
627
+ ['q', 'v'], 'lora_alpha': 32, 'lora_dropout': 0.1, 'merge_weights': False, 'fan_in_fan_out': False,
628
+ 'enable_lora': None, 'bias': 'none'
629
+ }
630
+ >>> peft_config = get_peft_config(config) >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") >>>
631
+ peft_model = PeftModelForSeq2SeqLM(model, peft_config) >>> peft_model.print_trainable_parameters() trainable
632
+ params: 884736 || all params: 223843584 || trainable%: 0.3952474242013566
633
+ """
634
+
635
+ def __init__(self, model, peft_config: PeftConfig):
636
+ super().__init__(model, peft_config)
637
+ self.base_model_prepare_inputs_for_generation = self.base_model.prepare_inputs_for_generation
638
+ self.base_model_prepare_encoder_decoder_kwargs_for_generation = (
639
+ self.base_model._prepare_encoder_decoder_kwargs_for_generation
640
+ )
641
+
642
+ def forward(
643
+ self,
644
+ input_ids=None,
645
+ attention_mask=None,
646
+ inputs_embeds=None,
647
+ decoder_input_ids=None,
648
+ decoder_attention_mask=None,
649
+ decoder_inputs_embeds=None,
650
+ labels=None,
651
+ output_attentions=None,
652
+ output_hidden_states=None,
653
+ return_dict=None,
654
+ **kwargs,
655
+ ):
656
+ if not isinstance(self.peft_config, PromptLearningConfig):
657
+ return self.base_model(
658
+ input_ids=input_ids,
659
+ attention_mask=attention_mask,
660
+ inputs_embeds=inputs_embeds,
661
+ decoder_input_ids=decoder_input_ids,
662
+ decoder_attention_mask=decoder_attention_mask,
663
+ decoder_inputs_embeds=decoder_inputs_embeds,
664
+ labels=labels,
665
+ output_attentions=output_attentions,
666
+ output_hidden_states=output_hidden_states,
667
+ return_dict=return_dict,
668
+ **kwargs,
669
+ )
670
+
671
+ batch_size = input_ids.shape[0]
672
+ if decoder_attention_mask is not None:
673
+ # concat prompt attention mask
674
+ prefix_attention_mask = torch.ones(batch_size, self.peft_config.num_virtual_tokens).to(self.device)
675
+ decoder_attention_mask = torch.cat((prefix_attention_mask, decoder_attention_mask), dim=1)
676
+
677
+ if kwargs.get("position_ids", None) is not None:
678
+ warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.")
679
+ kwargs["position_ids"] = None
680
+ if kwargs.get("token_type_ids", None) is not None:
681
+ warnings.warn("Token type ids are not supported for parameter efficient tuning. Ignoring token type ids")
682
+ kwargs["token_type_ids"] = None
683
+ kwargs.update(
684
+ {
685
+ "attention_mask": attention_mask,
686
+ "decoder_attention_mask": decoder_attention_mask,
687
+ "labels": labels,
688
+ "output_attentions": output_attentions,
689
+ "output_hidden_states": output_hidden_states,
690
+ "return_dict": return_dict,
691
+ }
692
+ )
693
+
694
+ if self.peft_config.peft_type == PeftType.PREFIX_TUNING:
695
+ past_key_values = self.get_prompt(batch_size)
696
+ return self.base_model(
697
+ input_ids=input_ids, decoder_input_ids=decoder_input_ids, past_key_values=past_key_values, **kwargs
698
+ )
699
+ else:
700
+ if inputs_embeds is None:
701
+ inputs_embeds = self.word_embeddings(input_ids)
702
+ if decoder_inputs_embeds is None and decoder_input_ids is None:
703
+ decoder_input_ids = shift_tokens_right(
704
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
705
+ )
706
+ decoder_inputs_embeds = self.word_embeddings(decoder_input_ids)
707
+
708
+ if attention_mask is not None:
709
+ # concat prompt attention mask
710
+ prefix_attention_mask = torch.ones(batch_size, self.peft_config.num_virtual_tokens).to(self.device)
711
+ kwargs["attention_mask"] = torch.cat((prefix_attention_mask, attention_mask), dim=1)
712
+ # concat prompt labels
713
+ if labels is not None:
714
+ if self.peft_config.num_transformer_submodules == 1:
715
+ kwargs["labels"] = labels
716
+ elif self.peft_config.num_transformer_submodules == 2:
717
+ prefix_labels = torch.full((batch_size, self.peft_config.num_virtual_tokens), -100).to(self.device)
718
+ kwargs["labels"] = torch.cat((prefix_labels, labels), dim=1)
719
+ prompts = self.get_prompt(batch_size=batch_size)
720
+ prompts = prompts.to(inputs_embeds.dtype)
721
+ inputs_embeds = torch.cat((prompts[:, : self.peft_config.num_virtual_tokens], inputs_embeds), dim=1)
722
+ if self.peft_config.num_transformer_submodules == 1:
723
+ return self.base_model(inputs_embeds=inputs_embeds, **kwargs)
724
+ elif self.peft_config.num_transformer_submodules == 2:
725
+ decoder_inputs_embeds = torch.cat(
726
+ (prompts[:, self.peft_config.num_virtual_tokens :], decoder_inputs_embeds), dim=1
727
+ )
728
+ return self.base_model(
729
+ inputs_embeds=inputs_embeds, decoder_inputs_embeds=decoder_inputs_embeds, **kwargs
730
+ )
731
+
732
+ def generate(self, **kwargs):
733
+ self.base_model.prepare_inputs_for_generation = self.prepare_inputs_for_generation
734
+ self.base_model._prepare_encoder_decoder_kwargs_for_generation = (
735
+ self._prepare_encoder_decoder_kwargs_for_generation
736
+ )
737
+ try:
738
+ if not isinstance(self.peft_config, PromptLearningConfig):
739
+ outputs = self.base_model.generate(**kwargs)
740
+ else:
741
+ if "input_ids" not in kwargs:
742
+ raise ValueError("input_ids must be provided for Peft model generation")
743
+ if kwargs.get("position_ids", None) is not None:
744
+ warnings.warn(
745
+ "Position ids are not supported for parameter efficient tuning. Ignoring position ids."
746
+ )
747
+ kwargs["position_ids"] = None
748
+ if kwargs.get("token_type_ids", None) is not None:
749
+ warnings.warn(
750
+ "Token type ids are not supported for parameter efficient tuning. Ignoring token type ids"
751
+ )
752
+ kwargs["token_type_ids"] = None
753
+
754
+ if self.peft_config.peft_type == PeftType.PREFIX_TUNING:
755
+ outputs = self.base_model.generate(**kwargs)
756
+ else:
757
+ raise NotImplementedError
758
+ except:
759
+ self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation
760
+ self.base_model._prepare_encoder_decoder_kwargs_for_generation = (
761
+ self.base_model_prepare_encoder_decoder_kwargs_for_generation
762
+ )
763
+ raise
764
+ else:
765
+ self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation
766
+ self.base_model._prepare_encoder_decoder_kwargs_for_generation = (
767
+ self.base_model_prepare_encoder_decoder_kwargs_for_generation
768
+ )
769
+ return outputs
770
+
771
+ def prepare_inputs_for_generation(self, *args, **kwargs):
772
+ model_kwargs = self.base_model_prepare_inputs_for_generation(*args, **kwargs)
773
+ if model_kwargs["past_key_values"] is None and self.peft_config.peft_type == PeftType.PREFIX_TUNING:
774
+ batch_size = model_kwargs["decoder_input_ids"].shape[0]
775
+ past_key_values = self.get_prompt(batch_size)
776
+ model_kwargs["past_key_values"] = past_key_values
777
+ return model_kwargs
778
+
779
+
780
+ class PeftModelForTokenClassification(PeftModel):
781
+ """
782
+ Peft model for sequence classification tasks.
783
+
784
+ Args:
785
+ model ([`PreTrainedModel`]): Base transformer model
786
+ peft_config ([`PeftConfig`]): Peft config.
787
+
788
+ **Attributes**:
789
+ - **config** ([`PretrainedConfig`]) -- The configuration object of the base model.
790
+ - **cls_layer_name** (`str`) -- The name of the classification layer.
791
+
792
+ Example::
793
+
794
+ >>> from transformers import AutoModelForSequenceClassification >>> from peft import
795
+ PeftModelForTokenClassification, get_peft_config >>> config = {
796
+ 'peft_type': 'PREFIX_TUNING', 'task_type': 'TOKEN_CLS', 'inference_mode': False, 'num_virtual_tokens':
797
+ 20, 'token_dim': 768, 'num_transformer_submodules': 1, 'num_attention_heads': 12, 'num_layers': 12,
798
+ 'encoder_hidden_size': 768, 'prefix_projection': False, 'postprocess_past_key_value_function': None
799
+ }
800
+ >>> peft_config = get_peft_config(config) >>> model =
801
+ AutoModelForTokenClassification.from_pretrained("bert-base-cased") >>> peft_model =
802
+ PeftModelForTokenClassification(model, peft_config) >>> peft_model.print_trainable_parameters() trainable
803
+ params: 370178 || all params: 108680450 || trainable%: 0.3406113979101117
804
+ """
805
+
806
+ def __init__(self, model, peft_config: PeftConfig):
807
+ super().__init__(model, peft_config)
808
+ self.modules_to_save = ["classifier", "score"]
809
+
810
+ for name, _ in self.base_model.named_children():
811
+ if any(module_name in name for module_name in self.modules_to_save):
812
+ self.cls_layer_name = name
813
+ break
814
+
815
+ # to make sure classifier layer is trainable
816
+ _set_trainable(self)
817
+
818
+ def forward(
819
+ self,
820
+ input_ids=None,
821
+ attention_mask=None,
822
+ inputs_embeds=None,
823
+ labels=None,
824
+ output_attentions=None,
825
+ output_hidden_states=None,
826
+ return_dict=None,
827
+ **kwargs,
828
+ ):
829
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
830
+
831
+ if not isinstance(self.peft_config, PromptLearningConfig):
832
+ return self.base_model(
833
+ input_ids=input_ids,
834
+ attention_mask=attention_mask,
835
+ inputs_embeds=inputs_embeds,
836
+ labels=labels,
837
+ output_attentions=output_attentions,
838
+ output_hidden_states=output_hidden_states,
839
+ return_dict=return_dict,
840
+ **kwargs,
841
+ )
842
+
843
+ batch_size = input_ids.shape[0]
844
+ if attention_mask is not None:
845
+ # concat prompt attention mask
846
+ prefix_attention_mask = torch.ones(batch_size, self.peft_config.num_virtual_tokens).to(self.device)
847
+ attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)
848
+ if kwargs.get("position_ids", None) is not None:
849
+ warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.")
850
+ kwargs["position_ids"] = None
851
+ kwargs.update(
852
+ {
853
+ "attention_mask": attention_mask,
854
+ "labels": labels,
855
+ "output_attentions": output_attentions,
856
+ "output_hidden_states": output_hidden_states,
857
+ "return_dict": return_dict,
858
+ }
859
+ )
860
+
861
+ if self.peft_config.peft_type == PeftType.PREFIX_TUNING:
862
+ return self._prefix_tuning_forward(input_ids=input_ids, **kwargs)
863
+ else:
864
+ if kwargs.get("token_type_ids", None) is not None:
865
+ kwargs["token_type_ids"] = torch.cat(
866
+ (
867
+ torch.zeros(batch_size, self.peft_config.num_virtual_tokens).to(self.device),
868
+ kwargs["token_type_ids"],
869
+ ),
870
+ dim=1,
871
+ ).long()
872
+ if inputs_embeds is None:
873
+ inputs_embeds = self.word_embeddings(input_ids)
874
+ prompts = self.get_prompt(batch_size=batch_size)
875
+ prompts = prompts.to(inputs_embeds.dtype)
876
+ inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1)
877
+ return self.base_model(inputs_embeds=inputs_embeds, **kwargs)
878
+
879
+ def _prefix_tuning_forward(
880
+ self,
881
+ input_ids=None,
882
+ attention_mask=None,
883
+ inputs_embeds=None,
884
+ labels=None,
885
+ output_attentions=None,
886
+ output_hidden_states=None,
887
+ return_dict=None,
888
+ **kwargs,
889
+ ):
890
+ batch_size = input_ids.shape[0]
891
+ past_key_values = self.get_prompt(batch_size)
892
+ fwd_params = list(inspect.signature(self.base_model.forward).parameters.keys())
893
+ kwargs.update(
894
+ {
895
+ "input_ids": input_ids,
896
+ "attention_mask": attention_mask,
897
+ "inputs_embeds": inputs_embeds,
898
+ "output_attentions": output_attentions,
899
+ "output_hidden_states": output_hidden_states,
900
+ "return_dict": return_dict,
901
+ "past_key_values": past_key_values,
902
+ }
903
+ )
904
+ if "past_key_values" in fwd_params:
905
+ return self.base_model(labels=labels, **kwargs)
906
+ else:
907
+ transformer_backbone_name = self.base_model.get_submodule(self.transformer_backbone_name)
908
+ fwd_params = list(inspect.signature(transformer_backbone_name.forward).parameters.keys())
909
+ if "past_key_values" not in fwd_params:
910
+ raise ValueError("Model does not support past key values which are required for prefix tuning.")
911
+ outputs = transformer_backbone_name(**kwargs)
912
+ sequence_output = outputs[0]
913
+ if "dropout" in [name for name, _ in list(self.base_model.named_children())]:
914
+ sequence_output = self.base_model.dropout(sequence_output)
915
+ logits = self.base_model.get_submodule(self.cls_layer_name)(sequence_output)
916
+
917
+ loss = None
918
+ loss = None
919
+ if labels is not None:
920
+ loss_fct = CrossEntropyLoss()
921
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
922
+
923
+ if not return_dict:
924
+ output = (logits,) + outputs[2:]
925
+ return ((loss,) + output) if loss is not None else output
926
+
927
+ return TokenClassifierOutput(
928
+ loss=loss,
929
+ logits=logits,
930
+ hidden_states=outputs.hidden_states,
931
+ attentions=outputs.attentions,
932
+ )
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/tuners/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+ # There's no way to ignore "F401 '...' imported but unused" warnings in this
3
+ # module, but to preserve other warnings. So, don't check this module at all
4
+
5
+ # coding=utf-8
6
+ # Copyright 2023-present the HuggingFace Inc. team.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ from .lora import LoraConfig, LoraModel
21
+ from .p_tuning import PromptEncoder, PromptEncoderConfig, PromptEncoderReparameterizationType
22
+ from .prefix_tuning import PrefixEncoder, PrefixTuningConfig
23
+ from .prompt_tuning import PromptEmbedding, PromptTuningConfig, PromptTuningInit
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/tuners/p_tuning.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023-present the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import enum
17
+ import warnings
18
+ from dataclasses import dataclass, field
19
+ from typing import Union
20
+
21
+ import torch
22
+
23
+ from ..utils import PeftType, PromptLearningConfig
24
+
25
+
26
+ class PromptEncoderReparameterizationType(str, enum.Enum):
27
+ MLP = "MLP"
28
+ LSTM = "LSTM"
29
+
30
+
31
+ @dataclass
32
+ class PromptEncoderConfig(PromptLearningConfig):
33
+ """
34
+ This is the configuration class to store the configuration of a [`~peft.PromptEncoder`].
35
+
36
+ Args:
37
+ encoder_reparameterization_type
38
+ (Union[[`PromptEncoderReparameterizationType`], `str`]): The type of reparameterization to use.
39
+ encoder_hidden_size (`int`): The hidden size of the prompt encoder.
40
+ encoder_num_layers (`int`): The number of layers of the prompt encoder.
41
+ encoder_dropout (`float`): The dropout probability of the prompt encoder.
42
+ """
43
+
44
+ encoder_reparameterization_type: Union[str, PromptEncoderReparameterizationType] = field(
45
+ default=PromptEncoderReparameterizationType.MLP,
46
+ metadata={"help": "How to reparameterize the prompt encoder"},
47
+ )
48
+ encoder_hidden_size: int = field(
49
+ default=None,
50
+ metadata={"help": "The hidden size of the prompt encoder"},
51
+ )
52
+ encoder_num_layers: int = field(
53
+ default=2,
54
+ metadata={"help": "The number of layers of the prompt encoder"},
55
+ )
56
+ encoder_dropout: float = field(
57
+ default=0.0,
58
+ metadata={"help": "The dropout of the prompt encoder"},
59
+ )
60
+
61
+ def __post_init__(self):
62
+ self.peft_type = PeftType.P_TUNING
63
+
64
+
65
+ # Based on https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/nlp/modules/common/prompt_encoder.py
66
+ # with some refactor
67
+ class PromptEncoder(torch.nn.Module):
68
+ """
69
+ The prompt encoder network that is used to generate the virtual token embeddings for p-tuning.
70
+
71
+ Args:
72
+ config ([`PromptEncoderConfig`]): The configuration of the prompt encoder.
73
+
74
+ Example::
75
+
76
+ >>> from peft import PromptEncoder, PromptEncoderConfig >>> config = PromptEncoderConfig(
77
+ peft_type="P_TUNING", task_type="SEQ_2_SEQ_LM", num_virtual_tokens=20, token_dim=768,
78
+ num_transformer_submodules=1, num_attention_heads=12, num_layers=12,
79
+ encoder_reparameterization_type="MLP", encoder_hidden_size=768
80
+ )
81
+ >>> prompt_encoder = PromptEncoder(config)
82
+
83
+ **Attributes**:
84
+ - **embedding** ([`~torch.nn.Embedding`]) -- The embedding layer of the prompt encoder.
85
+ - **mlp_head** ([`~torch.nn.Sequential`]) -- The MLP head of the prompt encoder if `inference_mode=False`.
86
+ - **lstm_head** ([`~torch.nn.LSTM`]) -- The LSTM head of the prompt encoder if `inference_mode=False` and
87
+ `encoder_reparameterization_type="LSTM"`.
88
+ - **token_dim** (`int`) -- The hidden embedding dimension of the base transformer model.
89
+ - **input_size** (`int`) -- The input size of the prompt encoder.
90
+ - **output_size** (`int`) -- The output size of the prompt encoder.
91
+ - **hidden_size** (`int`) -- The hidden size of the prompt encoder.
92
+ - **total_virtual_tokens** (`int`): The total number of virtual tokens of the
93
+ prompt encoder.
94
+ - **encoder_type** (Union[[`PromptEncoderReparameterizationType`], `str`]):
95
+ The encoder type of the prompt encoder.
96
+
97
+
98
+ Input shape: (batch_size, total_virtual_tokens)
99
+
100
+ Output shape: (batch_size, total_virtual_tokens, token_dim)
101
+ """
102
+
103
+ def __init__(self, config):
104
+ super().__init__()
105
+ self.token_dim = config.token_dim
106
+ self.input_size = self.token_dim
107
+ self.output_size = self.token_dim
108
+ self.hidden_size = config.encoder_hidden_size
109
+ self.total_virtual_tokens = config.num_virtual_tokens * config.num_transformer_submodules
110
+ self.encoder_type = config.encoder_reparameterization_type
111
+
112
+ # embedding
113
+ self.embedding = torch.nn.Embedding(self.total_virtual_tokens, self.token_dim)
114
+ if not config.inference_mode:
115
+ if self.encoder_type == PromptEncoderReparameterizationType.LSTM:
116
+ lstm_dropout = config.encoder_dropout
117
+ num_layers = config.encoder_num_layers
118
+ # LSTM
119
+ self.lstm_head = torch.nn.LSTM(
120
+ input_size=self.input_size,
121
+ hidden_size=self.hidden_size,
122
+ num_layers=num_layers,
123
+ dropout=lstm_dropout,
124
+ bidirectional=True,
125
+ batch_first=True,
126
+ )
127
+
128
+ self.mlp_head = torch.nn.Sequential(
129
+ torch.nn.Linear(self.hidden_size * 2, self.hidden_size * 2),
130
+ torch.nn.ReLU(),
131
+ torch.nn.Linear(self.hidden_size * 2, self.output_size),
132
+ )
133
+
134
+ elif self.encoder_type == PromptEncoderReparameterizationType.MLP:
135
+ warnings.warn(
136
+ f"for {self.encoder_type}, the `encoder_num_layers` is ignored. Exactly 2 MLP layers are used."
137
+ )
138
+ layers = [
139
+ torch.nn.Linear(self.input_size, self.hidden_size),
140
+ torch.nn.ReLU(),
141
+ torch.nn.Linear(self.hidden_size, self.hidden_size),
142
+ torch.nn.ReLU(),
143
+ torch.nn.Linear(self.hidden_size, self.output_size),
144
+ ]
145
+ self.mlp_head = torch.nn.Sequential(*layers)
146
+
147
+ else:
148
+ raise ValueError("Prompt encoder type not recognized. Please use one of MLP (recommended) or LSTM.")
149
+
150
+ def forward(self, indices):
151
+ input_embeds = self.embedding(indices)
152
+ if self.encoder_type == PromptEncoderReparameterizationType.LSTM:
153
+ output_embeds = self.mlp_head(self.lstm_head(input_embeds)[0])
154
+ elif self.encoder_type == PromptEncoderReparameterizationType.MLP:
155
+ output_embeds = self.mlp_head(input_embeds)
156
+ else:
157
+ raise ValueError("Prompt encoder type not recognized. Please use one of MLP (recommended) or LSTM.")
158
+
159
+ return output_embeds
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/peft/tuners/prompt_tuning.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023-present the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import enum
17
+ import math
18
+ from dataclasses import dataclass, field
19
+ from typing import Optional, Union
20
+
21
+ import torch
22
+
23
+ from ..utils import PeftType, PromptLearningConfig
24
+
25
+
26
+ class PromptTuningInit(str, enum.Enum):
27
+ TEXT = "TEXT"
28
+ RANDOM = "RANDOM"
29
+
30
+
31
+ @dataclass
32
+ class PromptTuningConfig(PromptLearningConfig):
33
+ """
34
+ This is the configuration class to store the configuration of a [`~peft.PromptEmbedding`].
35
+
36
+ Args:
37
+ prompt_tuning_init (Union[[`PromptTuningInit`], `str`]): The initialization of the prompt embedding.
38
+ prompt_tuning_init_text ( Optional[`str`]): The text to initialize the prompt embedding.
39
+ Only used if `prompt_tuning_init` is `TEXT`
40
+ tokenizer_name_or_path ( Optional[`str`]): The name or path of the tokenizer.
41
+ Only used if `prompt_tuning_init` is `TEXT`
42
+ """
43
+
44
+ prompt_tuning_init: Union[PromptTuningInit, str] = field(
45
+ default=PromptTuningInit.RANDOM,
46
+ metadata={"help": "How to initialize the prompt tuning parameters"},
47
+ )
48
+ prompt_tuning_init_text: Optional[str] = field(
49
+ default=None,
50
+ metadata={
51
+ "help": "The text to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`"
52
+ },
53
+ )
54
+ tokenizer_name_or_path: Optional[str] = field(
55
+ default=None,
56
+ metadata={
57
+ "help": "The tokenizer to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`"
58
+ },
59
+ )
60
+
61
+ def __post_init__(self):
62
+ self.peft_type = PeftType.PROMPT_TUNING
63
+
64
+
65
+ class PromptEmbedding(torch.nn.Module):
66
+ """
67
+ The model to encode virtual tokens into prompt embeddings.
68
+
69
+ Args:
70
+ config ([`PromptTuningConfig`]): The configuration of the prompt embedding.
71
+ word_embeddings (`torch.nn.Module`): The word embeddings of the base transformer model.
72
+
73
+ **Attributes**:
74
+ **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prompt embedding.
75
+
76
+ Example::
77
+
78
+ >>> from peft import PromptEmbedding, PromptTuningConfig >>> config = PromptTuningConfig(
79
+ peft_type="PROMPT_TUNING", task_type="SEQ_2_SEQ_LM", num_virtual_tokens=20, token_dim=768,
80
+ num_transformer_submodules=1, num_attention_heads=12, num_layers=12, prompt_tuning_init="TEXT",
81
+ prompt_tuning_init_text="Predict if sentiment of this review is positive, negative or neutral",
82
+ tokenizer_name_or_path="t5-base",
83
+ )
84
+ >>> # t5_model.shared is the word embeddings of the base model >>> prompt_embedding = PromptEmbedding(config,
85
+ t5_model.shared)
86
+
87
+
88
+ Input Shape: (batch_size, total_virtual_tokens)
89
+
90
+ Output Shape: (batch_size, total_virtual_tokens, token_dim)
91
+ """
92
+
93
+ def __init__(self, config, word_embeddings):
94
+ super().__init__()
95
+
96
+ total_virtual_tokens = config.num_virtual_tokens * config.num_transformer_submodules
97
+ self.embedding = torch.nn.Embedding(total_virtual_tokens, config.token_dim)
98
+ if config.prompt_tuning_init == PromptTuningInit.TEXT:
99
+ from transformers import AutoTokenizer
100
+
101
+ tokenizer = AutoTokenizer.from_pretrained(config.tokenizer_name_or_path)
102
+ init_text = config.prompt_tuning_init_text
103
+ init_token_ids = tokenizer(init_text)["input_ids"]
104
+ # Trim or iterate until num_text_tokens matches total_virtual_tokens
105
+ num_text_tokens = len(init_token_ids)
106
+ if num_text_tokens > total_virtual_tokens:
107
+ init_token_ids = init_token_ids[:total_virtual_tokens]
108
+ elif num_text_tokens < total_virtual_tokens:
109
+ num_reps = math.ceil(total_virtual_tokens / num_text_tokens)
110
+ init_token_ids = init_token_ids * num_reps
111
+ init_token_ids = init_token_ids[:total_virtual_tokens]
112
+
113
+ word_embedding_weights = word_embeddings(torch.LongTensor(init_token_ids)).detach().clone()
114
+ word_embedding_weights = word_embedding_weights.to(torch.float32)
115
+ self.embedding.weight = torch.nn.Parameter(word_embedding_weights)
116
+
117
+ def forward(self, indices):
118
+ # Just get embeddings
119
+ prompt_embeddings = self.embedding(indices)
120
+ return prompt_embeddings
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/serve/__init__.py ADDED
File without changes
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/serve/cli.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+
4
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
5
+ from llava.conversation import conv_templates, SeparatorStyle
6
+ from llava.model.builder import load_pretrained_model
7
+ from llava.utils import disable_torch_init
8
+ from llava.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path
9
+
10
+ from PIL import Image
11
+
12
+ import requests
13
+ from PIL import Image
14
+ from io import BytesIO
15
+ from transformers import TextStreamer
16
+
17
+
18
+ def load_image(image_file):
19
+ if image_file.startswith('http://') or image_file.startswith('https://'):
20
+ response = requests.get(image_file)
21
+ image = Image.open(BytesIO(response.content)).convert('RGB')
22
+ else:
23
+ image = Image.open(image_file).convert('RGB')
24
+ return image
25
+
26
+
27
+ def main(args):
28
+ # Model
29
+ disable_torch_init()
30
+
31
+ model_name = get_model_name_from_path(args.model_path)
32
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device)
33
+
34
+ if "llama-2" in model_name.lower():
35
+ conv_mode = "llava_llama_2"
36
+ elif "mistral" in model_name.lower():
37
+ conv_mode = "mistral_instruct"
38
+ elif "v1.6-34b" in model_name.lower():
39
+ conv_mode = "chatml_direct"
40
+ elif "v1" in model_name.lower():
41
+ conv_mode = "llava_v1"
42
+ elif "mpt" in model_name.lower():
43
+ conv_mode = "mpt"
44
+ else:
45
+ conv_mode = "llava_v0"
46
+
47
+ if args.conv_mode is not None and conv_mode != args.conv_mode:
48
+ print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode))
49
+ else:
50
+ args.conv_mode = conv_mode
51
+
52
+ conv = conv_templates[args.conv_mode].copy()
53
+ if "mpt" in model_name.lower():
54
+ roles = ('user', 'assistant')
55
+ else:
56
+ roles = conv.roles
57
+
58
+ image = load_image(args.image_file)
59
+ image_size = image.size
60
+ # Similar operation in model_worker.py
61
+ image_tensor = process_images([image], image_processor, model.config)
62
+ if type(image_tensor) is list:
63
+ image_tensor = [image.to(model.device, dtype=torch.float16) for image in image_tensor]
64
+ else:
65
+ image_tensor = image_tensor.to(model.device, dtype=torch.float16)
66
+
67
+ while True:
68
+ try:
69
+ inp = input(f"{roles[0]}: ")
70
+ except EOFError:
71
+ inp = ""
72
+ if not inp:
73
+ print("exit...")
74
+ break
75
+
76
+ print(f"{roles[1]}: ", end="")
77
+
78
+ if image is not None:
79
+ # first message
80
+ if model.config.mm_use_im_start_end:
81
+ inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp
82
+ else:
83
+ inp = DEFAULT_IMAGE_TOKEN + '\n' + inp
84
+ image = None
85
+
86
+ conv.append_message(conv.roles[0], inp)
87
+ conv.append_message(conv.roles[1], None)
88
+ prompt = conv.get_prompt()
89
+
90
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device)
91
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
92
+ keywords = [stop_str]
93
+ streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
94
+
95
+ with torch.inference_mode():
96
+ output_ids = model.generate(
97
+ input_ids,
98
+ images=image_tensor,
99
+ image_sizes=[image_size],
100
+ do_sample=True if args.temperature > 0 else False,
101
+ temperature=args.temperature,
102
+ max_new_tokens=args.max_new_tokens,
103
+ streamer=streamer,
104
+ use_cache=True)
105
+
106
+ outputs = tokenizer.decode(output_ids[0]).strip()
107
+ conv.messages[-1][-1] = outputs
108
+
109
+ if args.debug:
110
+ print("\n", {"prompt": prompt, "outputs": outputs}, "\n")
111
+
112
+
113
+ if __name__ == "__main__":
114
+ parser = argparse.ArgumentParser()
115
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
116
+ parser.add_argument("--model-base", type=str, default=None)
117
+ parser.add_argument("--image-file", type=str, required=True)
118
+ parser.add_argument("--device", type=str, default="cuda")
119
+ parser.add_argument("--conv-mode", type=str, default=None)
120
+ parser.add_argument("--temperature", type=float, default=0.2)
121
+ parser.add_argument("--max-new-tokens", type=int, default=512)
122
+ parser.add_argument("--load-8bit", action="store_true")
123
+ parser.add_argument("--load-4bit", action="store_true")
124
+ parser.add_argument("--debug", action="store_true")
125
+ args = parser.parse_args()
126
+ main(args)
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/serve/controller.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A controller manages distributed workers.
3
+ It sends worker addresses to clients.
4
+ """
5
+ import argparse
6
+ import asyncio
7
+ import dataclasses
8
+ from enum import Enum, auto
9
+ import json
10
+ import logging
11
+ import time
12
+ from typing import List, Union
13
+ import threading
14
+
15
+ from fastapi import FastAPI, Request
16
+ from fastapi.responses import StreamingResponse
17
+ import numpy as np
18
+ import requests
19
+ import uvicorn
20
+
21
+ from llava.constants import CONTROLLER_HEART_BEAT_EXPIRATION
22
+ from llava.utils import build_logger, server_error_msg
23
+
24
+
25
+ logger = build_logger("controller", "controller.log")
26
+
27
+
28
+ class DispatchMethod(Enum):
29
+ LOTTERY = auto()
30
+ SHORTEST_QUEUE = auto()
31
+
32
+ @classmethod
33
+ def from_str(cls, name):
34
+ if name == "lottery":
35
+ return cls.LOTTERY
36
+ elif name == "shortest_queue":
37
+ return cls.SHORTEST_QUEUE
38
+ else:
39
+ raise ValueError(f"Invalid dispatch method")
40
+
41
+
42
+ @dataclasses.dataclass
43
+ class WorkerInfo:
44
+ model_names: List[str]
45
+ speed: int
46
+ queue_length: int
47
+ check_heart_beat: bool
48
+ last_heart_beat: str
49
+
50
+
51
+ def heart_beat_controller(controller):
52
+ while True:
53
+ time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION)
54
+ controller.remove_stable_workers_by_expiration()
55
+
56
+
57
+ class Controller:
58
+ def __init__(self, dispatch_method: str):
59
+ # Dict[str -> WorkerInfo]
60
+ self.worker_info = {}
61
+ self.dispatch_method = DispatchMethod.from_str(dispatch_method)
62
+
63
+ self.heart_beat_thread = threading.Thread(
64
+ target=heart_beat_controller, args=(self,), daemon=True)
65
+ self.heart_beat_thread.start()
66
+
67
+ logger.info("Init controller")
68
+
69
+ def register_worker(self, worker_name: str, check_heart_beat: bool,
70
+ worker_status: dict):
71
+ if worker_name not in self.worker_info:
72
+ logger.info(f"Register a new worker: {worker_name}")
73
+ else:
74
+ logger.info(f"Register an existing worker: {worker_name}")
75
+
76
+ if not worker_status:
77
+ worker_status = self.get_worker_status(worker_name)
78
+ if not worker_status:
79
+ return False
80
+
81
+ self.worker_info[worker_name] = WorkerInfo(
82
+ worker_status["model_names"], worker_status["speed"], worker_status["queue_length"],
83
+ check_heart_beat, time.time())
84
+
85
+ logger.info(f"Register done: {worker_name}, {worker_status}")
86
+ return True
87
+
88
+ def get_worker_status(self, worker_name: str):
89
+ try:
90
+ r = requests.post(worker_name + "/worker_get_status", timeout=5)
91
+ except requests.exceptions.RequestException as e:
92
+ logger.error(f"Get status fails: {worker_name}, {e}")
93
+ return None
94
+
95
+ if r.status_code != 200:
96
+ logger.error(f"Get status fails: {worker_name}, {r}")
97
+ return None
98
+
99
+ return r.json()
100
+
101
+ def remove_worker(self, worker_name: str):
102
+ del self.worker_info[worker_name]
103
+
104
+ def refresh_all_workers(self):
105
+ old_info = dict(self.worker_info)
106
+ self.worker_info = {}
107
+
108
+ for w_name, w_info in old_info.items():
109
+ if not self.register_worker(w_name, w_info.check_heart_beat, None):
110
+ logger.info(f"Remove stale worker: {w_name}")
111
+
112
+ def list_models(self):
113
+ model_names = set()
114
+
115
+ for w_name, w_info in self.worker_info.items():
116
+ model_names.update(w_info.model_names)
117
+
118
+ return list(model_names)
119
+
120
+ def get_worker_address(self, model_name: str):
121
+ if self.dispatch_method == DispatchMethod.LOTTERY:
122
+ worker_names = []
123
+ worker_speeds = []
124
+ for w_name, w_info in self.worker_info.items():
125
+ if model_name in w_info.model_names:
126
+ worker_names.append(w_name)
127
+ worker_speeds.append(w_info.speed)
128
+ worker_speeds = np.array(worker_speeds, dtype=np.float32)
129
+ norm = np.sum(worker_speeds)
130
+ if norm < 1e-4:
131
+ return ""
132
+ worker_speeds = worker_speeds / norm
133
+ if True: # Directly return address
134
+ pt = np.random.choice(np.arange(len(worker_names)),
135
+ p=worker_speeds)
136
+ worker_name = worker_names[pt]
137
+ return worker_name
138
+
139
+ # Check status before returning
140
+ while True:
141
+ pt = np.random.choice(np.arange(len(worker_names)),
142
+ p=worker_speeds)
143
+ worker_name = worker_names[pt]
144
+
145
+ if self.get_worker_status(worker_name):
146
+ break
147
+ else:
148
+ self.remove_worker(worker_name)
149
+ worker_speeds[pt] = 0
150
+ norm = np.sum(worker_speeds)
151
+ if norm < 1e-4:
152
+ return ""
153
+ worker_speeds = worker_speeds / norm
154
+ continue
155
+ return worker_name
156
+ elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE:
157
+ worker_names = []
158
+ worker_qlen = []
159
+ for w_name, w_info in self.worker_info.items():
160
+ if model_name in w_info.model_names:
161
+ worker_names.append(w_name)
162
+ worker_qlen.append(w_info.queue_length / w_info.speed)
163
+ if len(worker_names) == 0:
164
+ return ""
165
+ min_index = np.argmin(worker_qlen)
166
+ w_name = worker_names[min_index]
167
+ self.worker_info[w_name].queue_length += 1
168
+ logger.info(f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}")
169
+ return w_name
170
+ else:
171
+ raise ValueError(f"Invalid dispatch method: {self.dispatch_method}")
172
+
173
+ def receive_heart_beat(self, worker_name: str, queue_length: int):
174
+ if worker_name not in self.worker_info:
175
+ logger.info(f"Receive unknown heart beat. {worker_name}")
176
+ return False
177
+
178
+ self.worker_info[worker_name].queue_length = queue_length
179
+ self.worker_info[worker_name].last_heart_beat = time.time()
180
+ logger.info(f"Receive heart beat. {worker_name}")
181
+ return True
182
+
183
+ def remove_stable_workers_by_expiration(self):
184
+ expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION
185
+ to_delete = []
186
+ for worker_name, w_info in self.worker_info.items():
187
+ if w_info.check_heart_beat and w_info.last_heart_beat < expire:
188
+ to_delete.append(worker_name)
189
+
190
+ for worker_name in to_delete:
191
+ self.remove_worker(worker_name)
192
+
193
+ def worker_api_generate_stream(self, params):
194
+ worker_addr = self.get_worker_address(params["model"])
195
+ if not worker_addr:
196
+ logger.info(f"no worker: {params['model']}")
197
+ ret = {
198
+ "text": server_error_msg,
199
+ "error_code": 2,
200
+ }
201
+ yield json.dumps(ret).encode() + b"\0"
202
+
203
+ try:
204
+ response = requests.post(worker_addr + "/worker_generate_stream",
205
+ json=params, stream=True, timeout=5)
206
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
207
+ if chunk:
208
+ yield chunk + b"\0"
209
+ except requests.exceptions.RequestException as e:
210
+ logger.info(f"worker timeout: {worker_addr}")
211
+ ret = {
212
+ "text": server_error_msg,
213
+ "error_code": 3,
214
+ }
215
+ yield json.dumps(ret).encode() + b"\0"
216
+
217
+
218
+ # Let the controller act as a worker to achieve hierarchical
219
+ # management. This can be used to connect isolated sub networks.
220
+ def worker_api_get_status(self):
221
+ model_names = set()
222
+ speed = 0
223
+ queue_length = 0
224
+
225
+ for w_name in self.worker_info:
226
+ worker_status = self.get_worker_status(w_name)
227
+ if worker_status is not None:
228
+ model_names.update(worker_status["model_names"])
229
+ speed += worker_status["speed"]
230
+ queue_length += worker_status["queue_length"]
231
+
232
+ return {
233
+ "model_names": list(model_names),
234
+ "speed": speed,
235
+ "queue_length": queue_length,
236
+ }
237
+
238
+
239
+ app = FastAPI()
240
+
241
+
242
+ @app.post("/register_worker")
243
+ async def register_worker(request: Request):
244
+ data = await request.json()
245
+ controller.register_worker(
246
+ data["worker_name"], data["check_heart_beat"],
247
+ data.get("worker_status", None))
248
+
249
+
250
+ @app.post("/refresh_all_workers")
251
+ async def refresh_all_workers():
252
+ models = controller.refresh_all_workers()
253
+
254
+
255
+ @app.post("/list_models")
256
+ async def list_models():
257
+ models = controller.list_models()
258
+ return {"models": models}
259
+
260
+
261
+ @app.post("/get_worker_address")
262
+ async def get_worker_address(request: Request):
263
+ data = await request.json()
264
+ addr = controller.get_worker_address(data["model"])
265
+ return {"address": addr}
266
+
267
+
268
+ @app.post("/receive_heart_beat")
269
+ async def receive_heart_beat(request: Request):
270
+ data = await request.json()
271
+ exist = controller.receive_heart_beat(
272
+ data["worker_name"], data["queue_length"])
273
+ return {"exist": exist}
274
+
275
+
276
+ @app.post("/worker_generate_stream")
277
+ async def worker_api_generate_stream(request: Request):
278
+ params = await request.json()
279
+ generator = controller.worker_api_generate_stream(params)
280
+ return StreamingResponse(generator)
281
+
282
+
283
+ @app.post("/worker_get_status")
284
+ async def worker_api_get_status(request: Request):
285
+ return controller.worker_api_get_status()
286
+
287
+
288
+ if __name__ == "__main__":
289
+ parser = argparse.ArgumentParser()
290
+ parser.add_argument("--host", type=str, default="localhost")
291
+ parser.add_argument("--port", type=int, default=21001)
292
+ parser.add_argument("--dispatch-method", type=str, choices=[
293
+ "lottery", "shortest_queue"], default="shortest_queue")
294
+ args = parser.parse_args()
295
+ logger.info(f"args: {args}")
296
+
297
+ controller = Controller(args.dispatch_method)
298
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/serve/model_worker.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A model worker executes the model.
3
+ """
4
+ import argparse
5
+ import asyncio
6
+ import json
7
+ import time
8
+ import threading
9
+ import uuid
10
+
11
+ from fastapi import FastAPI, Request, BackgroundTasks
12
+ from fastapi.responses import StreamingResponse
13
+ import requests
14
+ import torch
15
+ import uvicorn
16
+ from functools import partial
17
+
18
+ from llava.constants import WORKER_HEART_BEAT_INTERVAL
19
+ from llava.utils import (build_logger, server_error_msg,
20
+ pretty_print_semaphore)
21
+ from llava.model.builder import load_pretrained_model
22
+ from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token
23
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
24
+ from transformers import TextIteratorStreamer
25
+ from threading import Thread
26
+
27
+
28
+ GB = 1 << 30
29
+
30
+ worker_id = str(uuid.uuid4())[:6]
31
+ logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
32
+ global_counter = 0
33
+
34
+ model_semaphore = None
35
+
36
+
37
+ def heart_beat_worker(controller):
38
+
39
+ while True:
40
+ time.sleep(WORKER_HEART_BEAT_INTERVAL)
41
+ controller.send_heart_beat()
42
+
43
+
44
+ class ModelWorker:
45
+ def __init__(self, controller_addr, worker_addr,
46
+ worker_id, no_register,
47
+ model_path, model_base, model_name,
48
+ load_8bit, load_4bit, device, use_flash_attn=False):
49
+ self.controller_addr = controller_addr
50
+ self.worker_addr = worker_addr
51
+ self.worker_id = worker_id
52
+ if model_path.endswith("/"):
53
+ model_path = model_path[:-1]
54
+ if model_name is None:
55
+ model_paths = model_path.split("/")
56
+ if model_paths[-1].startswith('checkpoint-'):
57
+ self.model_name = model_paths[-2] + "_" + model_paths[-1]
58
+ else:
59
+ self.model_name = model_paths[-1]
60
+ else:
61
+ self.model_name = model_name
62
+
63
+ self.device = device
64
+ logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...")
65
+ self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(
66
+ model_path, model_base, self.model_name, load_8bit, load_4bit, device=self.device, use_flash_attn=use_flash_attn)
67
+ self.is_multimodal = 'llava' in self.model_name.lower()
68
+
69
+ if not no_register:
70
+ self.register_to_controller()
71
+ self.heart_beat_thread = threading.Thread(
72
+ target=heart_beat_worker, args=(self,), daemon=True)
73
+ self.heart_beat_thread.start()
74
+
75
+ def register_to_controller(self):
76
+ logger.info("Register to controller")
77
+
78
+ url = self.controller_addr + "/register_worker"
79
+ data = {
80
+ "worker_name": self.worker_addr,
81
+ "check_heart_beat": True,
82
+ "worker_status": self.get_status()
83
+ }
84
+ r = requests.post(url, json=data)
85
+ assert r.status_code == 200
86
+
87
+ def send_heart_beat(self):
88
+ logger.info(f"Send heart beat. Models: {[self.model_name]}. "
89
+ f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
90
+ f"global_counter: {global_counter}")
91
+
92
+ url = self.controller_addr + "/receive_heart_beat"
93
+
94
+ while True:
95
+ try:
96
+ ret = requests.post(url, json={
97
+ "worker_name": self.worker_addr,
98
+ "queue_length": self.get_queue_length()}, timeout=5)
99
+ exist = ret.json()["exist"]
100
+ break
101
+ except requests.exceptions.RequestException as e:
102
+ logger.error(f"heart beat error: {e}")
103
+ time.sleep(5)
104
+
105
+ if not exist:
106
+ self.register_to_controller()
107
+
108
+ def get_queue_length(self):
109
+ if model_semaphore is None:
110
+ return 0
111
+ else:
112
+ return args.limit_model_concurrency - model_semaphore._value + (len(
113
+ model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
114
+
115
+ def get_status(self):
116
+ return {
117
+ "model_names": [self.model_name],
118
+ "speed": 1,
119
+ "queue_length": self.get_queue_length(),
120
+ }
121
+
122
+ @torch.inference_mode()
123
+ def generate_stream(self, params):
124
+ tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor
125
+
126
+ prompt = params["prompt"]
127
+ ori_prompt = prompt
128
+ images = params.get("images", None)
129
+ num_image_tokens = 0
130
+ if images is not None and len(images) > 0 and self.is_multimodal:
131
+ if len(images) > 0:
132
+ if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
133
+ raise ValueError("Number of images does not match number of <image> tokens in prompt")
134
+
135
+ images = [load_image_from_base64(image) for image in images]
136
+ image_sizes = [image.size for image in images]
137
+ images = process_images(images, image_processor, model.config)
138
+
139
+ if type(images) is list:
140
+ images = [image.to(self.model.device, dtype=torch.float16) for image in images]
141
+ else:
142
+ images = images.to(self.model.device, dtype=torch.float16)
143
+
144
+ replace_token = DEFAULT_IMAGE_TOKEN
145
+ if getattr(self.model.config, 'mm_use_im_start_end', False):
146
+ replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
147
+ prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
148
+
149
+ num_image_tokens = prompt.count(replace_token) * model.get_vision_tower().num_patches
150
+ else:
151
+ images = None
152
+ image_sizes = None
153
+ image_args = {"images": images, "image_sizes": image_sizes}
154
+ else:
155
+ images = None
156
+ image_args = {}
157
+
158
+ temperature = float(params.get("temperature", 1.0))
159
+ top_p = float(params.get("top_p", 1.0))
160
+ max_context_length = getattr(model.config, 'max_position_embeddings', 2048)
161
+ max_new_tokens = min(int(params.get("max_new_tokens", 256)), 1024)
162
+ stop_str = params.get("stop", None)
163
+ do_sample = True if temperature > 0.001 else False
164
+
165
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device)
166
+ keywords = [stop_str]
167
+ # stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
168
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)
169
+
170
+ max_new_tokens = min(max_new_tokens, max_context_length - input_ids.shape[-1] - num_image_tokens)
171
+
172
+ if max_new_tokens < 1:
173
+ yield json.dumps({"text": ori_prompt + "Exceeds max token length. Please start a new conversation, thanks.", "error_code": 0}).encode() + b"\0"
174
+ return
175
+
176
+ thread = Thread(target=model.generate, kwargs=dict(
177
+ inputs=input_ids,
178
+ do_sample=do_sample,
179
+ temperature=temperature,
180
+ top_p=top_p,
181
+ max_new_tokens=max_new_tokens,
182
+ streamer=streamer,
183
+ use_cache=True,
184
+ **image_args
185
+ ))
186
+ thread.start()
187
+
188
+ generated_text = ori_prompt
189
+ for new_text in streamer:
190
+ generated_text += new_text
191
+ if generated_text.endswith(stop_str):
192
+ generated_text = generated_text[:-len(stop_str)]
193
+ yield json.dumps({"text": generated_text, "error_code": 0}).encode() + b"\0"
194
+
195
+ def generate_stream_gate(self, params):
196
+ try:
197
+ for x in self.generate_stream(params):
198
+ yield x
199
+ except ValueError as e:
200
+ print("Caught ValueError:", e)
201
+ ret = {
202
+ "text": server_error_msg,
203
+ "error_code": 1,
204
+ }
205
+ yield json.dumps(ret).encode() + b"\0"
206
+ except torch.cuda.CudaError as e:
207
+ print("Caught torch.cuda.CudaError:", e)
208
+ ret = {
209
+ "text": server_error_msg,
210
+ "error_code": 1,
211
+ }
212
+ yield json.dumps(ret).encode() + b"\0"
213
+ except Exception as e:
214
+ print("Caught Unknown Error", e)
215
+ ret = {
216
+ "text": server_error_msg,
217
+ "error_code": 1,
218
+ }
219
+ yield json.dumps(ret).encode() + b"\0"
220
+
221
+
222
+ app = FastAPI()
223
+
224
+
225
+ def release_model_semaphore(fn=None):
226
+ model_semaphore.release()
227
+ if fn is not None:
228
+ fn()
229
+
230
+
231
+ @app.post("/worker_generate_stream")
232
+ async def generate_stream(request: Request):
233
+ global model_semaphore, global_counter
234
+ global_counter += 1
235
+ params = await request.json()
236
+
237
+ if model_semaphore is None:
238
+ model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
239
+ await model_semaphore.acquire()
240
+ worker.send_heart_beat()
241
+ generator = worker.generate_stream_gate(params)
242
+ background_tasks = BackgroundTasks()
243
+ background_tasks.add_task(partial(release_model_semaphore, fn=worker.send_heart_beat))
244
+ return StreamingResponse(generator, background=background_tasks)
245
+
246
+
247
+ @app.post("/worker_get_status")
248
+ async def get_status(request: Request):
249
+ return worker.get_status()
250
+
251
+
252
+ if __name__ == "__main__":
253
+ parser = argparse.ArgumentParser()
254
+ parser.add_argument("--host", type=str, default="localhost")
255
+ parser.add_argument("--port", type=int, default=21002)
256
+ parser.add_argument("--worker-address", type=str,
257
+ default="http://localhost:21002")
258
+ parser.add_argument("--controller-address", type=str,
259
+ default="http://localhost:21001")
260
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
261
+ parser.add_argument("--model-base", type=str, default=None)
262
+ parser.add_argument("--model-name", type=str)
263
+ parser.add_argument("--device", type=str, default="cuda")
264
+ parser.add_argument("--multi-modal", action="store_true", help="Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
265
+ parser.add_argument("--limit-model-concurrency", type=int, default=5)
266
+ parser.add_argument("--stream-interval", type=int, default=1)
267
+ parser.add_argument("--no-register", action="store_true")
268
+ parser.add_argument("--load-8bit", action="store_true")
269
+ parser.add_argument("--load-4bit", action="store_true")
270
+ parser.add_argument("--use-flash-attn", action="store_true")
271
+ args = parser.parse_args()
272
+ logger.info(f"args: {args}")
273
+
274
+ if args.multi_modal:
275
+ logger.warning("Multimodal mode is automatically detected with model name, please make sure `llava` is included in the model path.")
276
+
277
+ worker = ModelWorker(args.controller_address,
278
+ args.worker_address,
279
+ worker_id,
280
+ args.no_register,
281
+ args.model_path,
282
+ args.model_base,
283
+ args.model_name,
284
+ args.load_8bit,
285
+ args.load_4bit,
286
+ args.device,
287
+ use_flash_attn=args.use_flash_attn)
288
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
之前的代码版本/第二版代码-简单干预文本侧,图像侧,both的代码/MedEvalKit/models/HealthGPT/llava/serve/test_message.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+
4
+ import requests
5
+
6
+ from llava.conversation import default_conversation
7
+
8
+
9
+ def main():
10
+ if args.worker_address:
11
+ worker_addr = args.worker_address
12
+ else:
13
+ controller_addr = args.controller_address
14
+ ret = requests.post(controller_addr + "/refresh_all_workers")
15
+ ret = requests.post(controller_addr + "/list_models")
16
+ models = ret.json()["models"]
17
+ models.sort()
18
+ print(f"Models: {models}")
19
+
20
+ ret = requests.post(controller_addr + "/get_worker_address",
21
+ json={"model": args.model_name})
22
+ worker_addr = ret.json()["address"]
23
+ print(f"worker_addr: {worker_addr}")
24
+
25
+ if worker_addr == "":
26
+ return
27
+
28
+ conv = default_conversation.copy()
29
+ conv.append_message(conv.roles[0], args.message)
30
+ prompt = conv.get_prompt()
31
+
32
+ headers = {"User-Agent": "LLaVA Client"}
33
+ pload = {
34
+ "model": args.model_name,
35
+ "prompt": prompt,
36
+ "max_new_tokens": args.max_new_tokens,
37
+ "temperature": 0.7,
38
+ "stop": conv.sep,
39
+ }
40
+ response = requests.post(worker_addr + "/worker_generate_stream", headers=headers,
41
+ json=pload, stream=True)
42
+
43
+ print(prompt.replace(conv.sep, "\n"), end="")
44
+ for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b"\0"):
45
+ if chunk:
46
+ data = json.loads(chunk.decode("utf-8"))
47
+ output = data["text"].split(conv.sep)[-1]
48
+ print(output, end="\r")
49
+ print("")
50
+
51
+
52
+ if __name__ == "__main__":
53
+ parser = argparse.ArgumentParser()
54
+ parser.add_argument("--controller-address", type=str, default="http://localhost:21001")
55
+ parser.add_argument("--worker-address", type=str)
56
+ parser.add_argument("--model-name", type=str, default="facebook/opt-350m")
57
+ parser.add_argument("--max-new-tokens", type=int, default=32)
58
+ parser.add_argument("--message", type=str, default=
59
+ "Tell me a story with more than 1000 words.")
60
+ args = parser.parse_args()
61
+
62
+ main()