zhicao commited on
Commit
17982ae
·
verified ·
1 Parent(s): 45dd981

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. VLAC/.gitignore +5 -0
  3. VLAC/1.txt +9 -0
  4. VLAC/2.txt +9 -0
  5. VLAC/LICENSE +21 -0
  6. VLAC/README.md +186 -0
  7. VLAC/evo_vlac/__init__.py +21 -0
  8. VLAC/evo_vlac/examples/data_filtering_example.py +63 -0
  9. VLAC/evo_vlac/examples/image_pair.py +45 -0
  10. VLAC/evo_vlac/examples/images/ref/0.png +3 -0
  11. VLAC/evo_vlac/examples/images/ref/1.png +3 -0
  12. VLAC/evo_vlac/examples/images/ref/10.png +3 -0
  13. VLAC/evo_vlac/examples/images/ref/2.png +3 -0
  14. VLAC/evo_vlac/examples/images/ref/3.png +3 -0
  15. VLAC/evo_vlac/examples/images/ref/4.png +3 -0
  16. VLAC/evo_vlac/examples/images/ref/5.png +3 -0
  17. VLAC/evo_vlac/examples/images/ref/6.png +3 -0
  18. VLAC/evo_vlac/examples/images/ref/7.png +3 -0
  19. VLAC/evo_vlac/examples/images/ref/8.png +3 -0
  20. VLAC/evo_vlac/examples/images/ref/9.png +3 -0
  21. VLAC/evo_vlac/examples/images/test/0.png +3 -0
  22. VLAC/evo_vlac/examples/images/test/1.png +3 -0
  23. VLAC/evo_vlac/examples/images/test/2.png +3 -0
  24. VLAC/evo_vlac/examples/images/test/3.png +3 -0
  25. VLAC/evo_vlac/examples/images/test/4.png +3 -0
  26. VLAC/evo_vlac/examples/images/test/5.png +3 -0
  27. VLAC/evo_vlac/examples/images/test/6.png +3 -0
  28. VLAC/evo_vlac/examples/images/test/7.png +3 -0
  29. VLAC/evo_vlac/examples/video_trajectory_critic_example.py +71 -0
  30. VLAC/evo_vlac/examples/videos/pick-bowl-ref.mov +3 -0
  31. VLAC/evo_vlac/examples/videos/pick-bowl-test.mp4 +3 -0
  32. VLAC/evo_vlac/examples/vla_example.py +51 -0
  33. VLAC/evo_vlac/utils/data_processing_vlm.py +692 -0
  34. VLAC/evo_vlac/utils/magic_detect.py +1092 -0
  35. VLAC/evo_vlac/utils/model_utils.py +956 -0
  36. VLAC/evo_vlac/utils/video_tool.py +802 -0
  37. VLAC/extract_hdf5.py +294 -0
  38. VLAC/model/VLAC-8b/.gitattributes +35 -0
  39. VLAC/model/VLAC-8b/README.md +191 -0
  40. VLAC/model/VLAC-8b/added_tokens.json +11 -0
  41. VLAC/model/VLAC-8b/args.json +370 -0
  42. VLAC/model/VLAC-8b/config.json +229 -0
  43. VLAC/model/VLAC-8b/configuration_intern_vit.py +119 -0
  44. VLAC/model/VLAC-8b/configuration_internlm2.py +150 -0
  45. VLAC/model/VLAC-8b/configuration_internvl_chat.py +96 -0
  46. VLAC/model/VLAC-8b/conversation.py +393 -0
  47. VLAC/model/VLAC-8b/generation_config.json +8 -0
  48. VLAC/model/VLAC-8b/latest +1 -0
  49. VLAC/model/VLAC-8b/model-00001-of-00004.safetensors +3 -0
  50. VLAC/model/VLAC-8b/model-00002-of-00004.safetensors +3 -0
.gitattributes CHANGED
@@ -483,3 +483,4 @@ checkpoints/pi05_libero_stage2p5_joint/pi05_track_and_action/15000/params/ocdbt.
483
  checkpoints/pi05_libero_stage2p5_joint/pi05_track_and_action/15000/params/ocdbt.process_0/d/ab851ee680b0b7172638559f7884464d filter=lfs diff=lfs merge=lfs -text
484
  checkpoints/pi05_libero_stage2p5_joint/pi05_track_and_action/15000/params/ocdbt.process_0/d/fd926748ce15ae92bec61681149c99a2 filter=lfs diff=lfs merge=lfs -text
485
  vlac/evo_vlac/examples/videos/pick-bowl-ref.mov filter=lfs diff=lfs merge=lfs -text
 
 
483
  checkpoints/pi05_libero_stage2p5_joint/pi05_track_and_action/15000/params/ocdbt.process_0/d/ab851ee680b0b7172638559f7884464d filter=lfs diff=lfs merge=lfs -text
484
  checkpoints/pi05_libero_stage2p5_joint/pi05_track_and_action/15000/params/ocdbt.process_0/d/fd926748ce15ae92bec61681149c99a2 filter=lfs diff=lfs merge=lfs -text
485
  vlac/evo_vlac/examples/videos/pick-bowl-ref.mov filter=lfs diff=lfs merge=lfs -text
486
+ VLAC/evo_vlac/examples/videos/pick-bowl-ref.mov filter=lfs diff=lfs merge=lfs -text
VLAC/.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ evo_vlac.egg-info/
5
+ build/
VLAC/1.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ index,value,critic,done
2
+ 1,0.0,0.0,0
3
+ 2,0.0,0.0,0
4
+ 3,12.4,12.4,0
5
+ 4,25.0,12.6,0
6
+ 5,27.3,2.3,0
7
+ 6,32.9,5.6,0
8
+ 7,41.2,8.3,0
9
+ 8,50.0,8.8,1
VLAC/2.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ index,value,critic,done
2
+ 1,0.0,0.0,0
3
+ 2,0.0,0.0,0
4
+ 3,10.0,10.0,0
5
+ 4,5.0,-5.0,0
6
+ 5,15.2,10.2,0
7
+ 6,30.0,14.8,0
8
+ 7,25.2,-4.8,0
9
+ 8,35.1,10.1,0
VLAC/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Shanghai AI Lab, VLAC Team.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE
VLAC/README.md ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VLAC: A Vision-Language-Action-Critic Model for Robotic Real-World Reinforcement Learning
2
+ <div align="center">
3
+
4
+ [[paper]](data/VLAC_EAI.pdf)
5
+ [[code]](https://github.com/InternRobotics/VLAC)
6
+ [[model]](https://huggingface.co/InternRobotics/VLAC)
7
+
8
+ </div>
9
+
10
+ ## 🚀 Interactive Demo & Homepage
11
+
12
+ <div align="center">
13
+
14
+ ### [🎮 **Try Interactive & Homepage**](https://vlac.intern-ai.org.cn/)
15
+ > **Online Demo is available now in Homepage, Try as you like!!!**
16
+
17
+ </div>
18
+
19
+ <div align="center">
20
+ <img src="data/title_banner-2.gif" alt="VLAC banner" width="800"></img>
21
+ </div>
22
+
23
+ ## VLAC
24
+
25
+ VLAC is a general-purpose pair-wise critic and manipulation model which designed for real world robot reinforcement learning and data refinement.
26
+
27
+ It provides robust evaluation capabilities for task progress prediction and task completion verification base one images and task description.
28
+
29
+ VLAC trained on 3000h+ human egocentric data, 1200h+ comprehensive public robotic manipulation data, and 15h+ self-collected manipulation data.
30
+
31
+ ## ✨ Key Features
32
+
33
+ • **Pair-wise comparison mechanism** for improved progressing dense critic accuracy, better recognition of state changes, and each step can be the start of the trajectory.
34
+
35
+ • **Multi-modal capabilities** - Supports process tracking, task completion judgment, task description estimation, visual question answering, and even embodied action output, equipped with VLA capabilities.
36
+
37
+ • **Flexible zero-shot and one-shot** - in-context capabilities, maintaining excellent performance across entities, scenarios, and tasks.
38
+
39
+ • **Human-task synesthesia** - Based on the ego4D human dataset, model understands common tasks and build synesthesia for real-world human tasks and embodied tasks.
40
+
41
+ • **Trajectory quality screening** - VLAC can evaluate the collected trajectories and filters out low score trajectories based on the VOC value and mask the action with negative pair-wise score, that is, data with low fluency and quality, improving the effect and efficiency of imitation learning.
42
+
43
+ ## Framework
44
+
45
+ <div align="center">
46
+ <img src="data/framework.png" alt="VLAC Framework" width="800"/>
47
+ </div>
48
+
49
+ *The VLAC model is trained on a combination of comprehensive public robotic manipulation datasets, human demonstration data, self-collected manipulation data, and various image understanding datasets. Video data is processed into pair-wise samples to learn the different task progress between any two frames, supplemented with task descriptions and task completion evaluation to enable task progress understanding and action generation, as illustrated in the bottom-left corner. As shown in the diagram on the right, the model demonstrates strong generalization capabilities to new robots, scenarios, and tasks not covered in the training dataset. It can predict task progress and distinguish failure action or trajectory, providing dense reward feedback for real-world reinforcement learning and offering guidance for data refinement. Additionally, the model can directly perform manipulation tasks, exhibiting zero-shot capabilities to handle different scenarios.*
50
+
51
+ ## Performance
52
+
53
+ Details about the model's performance and evaluation metrics can be found in the [Homepage](https://vlac.intern-ai.org.cn/).
54
+
55
+ ## 🛠️ Installation
56
+
57
+ To install from source:
58
+ ```shell
59
+ git clone https://github.com/InternRobotics/VLAC.git
60
+ cd VLAC
61
+ pip install -e .
62
+ ```
63
+ Running Environment:
64
+
65
+ | | Range | Recommended | Notes |
66
+ | ------------ |--------------| ----------- | ----------------------------------------- |
67
+ | python | >=3.9 | 3.10 | |
68
+ | cuda | | cuda12 | No need to install if using CPU, NPU, MPS |
69
+ | torch | >=2.0 | | |
70
+ | transformers | >=4.51 | 4.51.3 | |
71
+ | peft | >=0.15.2 | | |
72
+ | ms-swift | | 3.3 | |
73
+
74
+
75
+ ## 🚀 Quick Start
76
+
77
+ ```python
78
+ from evo_vlac import GAC_model
79
+ from evo_vlac.utils.video_tool import compress_video
80
+ import os
81
+ #Consistent with the web interface, the value and citic rewards of video input can be evaluated.
82
+
83
+
84
+ #assign local model path
85
+ model_path="set to your local model path"
86
+ #download model form https://huggingface.co/InternRobotics/VLAC
87
+
88
+ #assign video path and task description
89
+ test_video='evo_vlac/examples/videos/pick-bowl-test.mp4'
90
+ ref_video='evo_vlac/examples/videos/pick-bowl-ref.mov'
91
+ task_description='Put up the bowl and place it back in the white storage box.'
92
+
93
+ #init model
94
+ Critic=GAC_model(tag='critic')
95
+ Critic.init_model(model_path=model_path,model_type='internvl2',device_map=f'cuda:0')
96
+ Critic.temperature=0.5
97
+ Critic.top_k=1
98
+ Critic.set_config()
99
+ Critic.set_system_prompt()
100
+
101
+ # transform video
102
+ test_video_compressed = os.path.join(os.path.dirname(test_video),"test.mp4")
103
+ _,output_fps=compress_video(test_video, test_video_compressed,fps=5)
104
+ reference_video_compressed = None
105
+ if ref_video:
106
+ reference_video_compressed = os.path.join(os.path.dirname(ref_video),"ref.mp4")
107
+ compress_video(ref_video, reference_video_compressed,fps=5)
108
+
109
+
110
+ # generate Critic results
111
+ result_path,value_list,critic_list,done_list = Critic.web_trajectory_critic(
112
+ task_description=task_description,
113
+ main_video_path=test_video_compressed,
114
+ reference_video_path=reference_video_compressed,#if None means no reference video, only use task_description to indicate the task
115
+ batch_num=5,#batch number
116
+ ref_num=6,#image number used in reference video
117
+ think=False,# whether to CoT
118
+ skip=5,#pair-wise step
119
+ rich=False,#whether to output decimal value
120
+ reverse_eval=False,#whether to reverse the evaluation(for VROC evaluation)
121
+ output_path="results",
122
+ fps=float(output_fps),
123
+ frame_skip=True,#whether to skip frames(if false, each frame while be evaluated, cost more time)
124
+ done_flag=False,#whether to out put done value
125
+ in_context_done=False,#whether use reference video to generate done value
126
+ done_threshold=0.9,#done threshold
127
+ video_output=True#whether to output video
128
+ )
129
+
130
+
131
+ print("=" * 100)
132
+ print(">>>>>>>>>Critic results<<<<<<<<<<")
133
+ print(" ")
134
+
135
+ print(f"result path: {result_path}")
136
+ print(f"task description: {task_description}")
137
+ print("=" * 50)
138
+
139
+ print("value_list:")
140
+ print(value_list)
141
+ print("=" * 50)
142
+
143
+ print("critic_list:")
144
+ print(critic_list)
145
+ print("=" * 50)
146
+
147
+ print("done_list:")
148
+ print(done_list)
149
+ print("=" * 100)
150
+ ```
151
+ If the GPU memory is insufficient, please reduce the number of "batch_num".
152
+
153
+ More examples of
154
+
155
+ • pair-wise image inputs critic. Please check [this example](evo_vlac/examples/image_pair-wise_critic_example.py)
156
+
157
+ • vla action generation. Please check [this example](evo_vlac/examples/vla_example.py)
158
+
159
+ • data refinement. Please check [this example](evo_vlac/examples/data_filtering_example.py)
160
+
161
+
162
+ For training code, please refer to [InternVL2](https://huggingface.co/OpenGVLab/InternVL2-2B#quick-start).
163
+
164
+ ## 🔗 Citation
165
+
166
+ If you find our work helpful, please cite:
167
+
168
+ ```bibtex
169
+ @article{zhai2025vision,
170
+ title={A Vision-Language-Action-Critic Model for Robotic Real-World Reinforcement Learning},
171
+ author={Zhai, Shaopeng and Zhang, Qi and Zhang, Tianyi and Huang, Fuxian and Zhang, Haoran and Zhou, Ming and Zhang, Shengzhe and Liu, Litao and Lin, Sixu and Pang, Jiangmiao},
172
+ journal={arXiv preprint arXiv:2509.15937},
173
+ year={2025}
174
+ }
175
+ ```
176
+
177
+ ## 📄 License
178
+
179
+ This project is licensed under the MIT License.
180
+
181
+ ## 🙏 Acknowledgments
182
+
183
+ - [SWIFT](https://github.com/modelscope/ms-swift)
184
+ - [InternVL](https://github.com/OpenGVLab/InternVL)
185
+
186
+
VLAC/evo_vlac/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 项目元信息
2
+ __version__ = "1.0.0"
3
+ __author__ = "zhangqi"
4
+ __email__ = "zhangqi1@pjlab.org"
5
+ __description__ = "internEVO Critic and VLA"
6
+
7
+ # 导入主要组件
8
+ from . import utils
9
+
10
+ # 修复导入路径
11
+ from .utils import data_processing_vlm
12
+ from .utils import model_utils
13
+ from .utils.model_utils import GAC_model
14
+ from .utils import video_tool
15
+ # 包级别的便捷函数
16
+ def get_version():
17
+ """获取项目版本"""
18
+ return __version__
19
+
20
+ # 定义包的公开接口
21
+ __all__ = ["utils", "model_utils", "data_processing_vlm", "get_version","GAC_model","video_tool"]
VLAC/evo_vlac/examples/data_filtering_example.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from evo_vlac import GAC_model
2
+ from evo_vlac.utils.video_tool import compress_video
3
+ import os
4
+ #Consistent with the web interface, the value and citic rewards of video input can be evaluated.
5
+
6
+
7
+ #assign local model path
8
+ model_path="set to your local model path"
9
+
10
+ #assign video path and task description
11
+ test_video='./videos/pick-bowl-test.mp4'
12
+ ref_video='./videos/pick-bowl-ref.mov'#optional
13
+ task_description='Put up the bowl and place it back in the white storage box.'
14
+
15
+ #init model
16
+ Critic=GAC_model(tag='critic')
17
+ Critic.init_model(model_path=model_path,model_type='internvl2',device_map=f'cuda:0')
18
+ Critic.temperature=0.5
19
+ Critic.top_k=1
20
+ Critic.set_config()
21
+ Critic.set_system_prompt()
22
+
23
+ # transform video
24
+ test_video_compressed = os.path.join(os.path.dirname(test_video),"test.mp4")
25
+ _,output_fps=compress_video(test_video, test_video_compressed,fps=5)
26
+ reference_video_compressed = None
27
+ if ref_video:
28
+ reference_video_compressed = os.path.join(os.path.dirname(ref_video),"ref.mp4")
29
+ compress_video(ref_video, reference_video_compressed,fps=5)
30
+
31
+
32
+ # generate Critic results
33
+ result_path,value_list,critic_list,done_list = Critic.web_trajectory_critic(
34
+ task_description=task_description,
35
+ main_video_path=test_video_compressed,
36
+ reference_video_path=reference_video_compressed,#if None means no reference video, only use task_description to indicate the task
37
+ batch_num=5,#batch number
38
+ ref_num=6,#image number used in reference video
39
+ think=False,# whether to CoT
40
+ skip=5,#pair-wise step
41
+ rich=False,#whether to output decimal value
42
+ reverse_eval=False,#whether to reverse the evaluation(for VROC evaluation)
43
+ output_path="results",
44
+ fps=float(output_fps),
45
+ frame_skip=True,#whether to skip frames(if false, each frame while be evaluated, cost more time)
46
+ video_output=False
47
+ )
48
+
49
+ value_list=Critic.critic_to_value_simple(critic_list,'mix_f')
50
+ voc=Critic.compute_voc(value_list)
51
+ nr=Critic.compute_negative_rate(critic_list)
52
+ print("=" * 100)
53
+ print(">>>>>>>>>DATA diagnose<<<<<<<<<<")
54
+ print(" ")
55
+ print(f'Negative rate: {nr}')
56
+ print(f"VOC: {voc}")
57
+ print("The larger the VOC value(-1~+1) and lower Negative rate(0~1), the better the data quality; overly values can directly filter out data, and specific thresholds can be selected based on the specific task.")
58
+ print("=" * 50)
59
+
60
+ print("critic_list:")
61
+ print(critic_list)
62
+ print("Actions corresponding to steps with a negative Critic can be filtered out to avoid interference with imitation learning by incorrect movements.")
63
+ print("=" * 50)
VLAC/evo_vlac/examples/image_pair.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from evo_vlac import GAC_model
2
+ from evo_vlac.utils.video_tool import compress_video
3
+ import os
4
+ #Example code for inputting images and evaluating pair-wise
5
+
6
+ #assign local model path
7
+ model_path="/scratch1/home/zhicao/VLAC/model/VLAC-8b"
8
+
9
+ #Input n images, output a critic_list of length n-1 and a value_list of length n. The critic evaluates the results of adjacent images (i, i+1); if i+1 is closer to accomplishing the task than i, the evaluation result is positive; otherwise, it is negative. It can evaluate the action rewards between any pair-wise images. The value_list is calculated based on the critic.
10
+ test_images=['./images/test/0.png','./images/test/1.png','./images/test/2.png','./images/test/3.png','./images/test/4.png','./images/test/5.png','./images/test/6.png','./images/test/7.png']
11
+ #(optional)Input up to 11 images as reference trajectories for tasks, significantly improving adaptation to new tasks and environments.
12
+ ref_images=['./images/ref/0.png','./images/ref/1.png','./images/ref/2.png','./images/ref/3.png','./images/ref/4.png','./images/ref/5.png','./images/ref/6.png','./images/ref/7.png','./images/ref/8.png','./images/ref/9.png','./images/ref/10.png']
13
+ task_description='Close the bottom drawer of the cabinet demo.'
14
+
15
+ #init model
16
+ Critic=GAC_model(tag='critic')
17
+ Critic.init_model(model_path=model_path,model_type='internvl2',device_map=f'cuda:0')
18
+ Critic.temperature=0.5
19
+ Critic.top_k=1
20
+ Critic.set_config()
21
+ Critic.set_system_prompt()
22
+
23
+ # generate Critic results
24
+ critic_list, value_list=Critic.get_trajectory_critic(
25
+ task=task_description,
26
+ image_list=test_images,
27
+ ref_image_list=None,
28
+ batch_num=5,#max batch number when generating critic
29
+ ref_num=len(ref_images),#image number used in ref_images
30
+ rich=False,#whether to output decimal value
31
+ reverse_eval=False,#whether to reverse the evaluation(for VROC evaluation)
32
+ )
33
+
34
+
35
+ print("=" * 100)
36
+ print(">>>>>>>>>Critic results<<<<<<<<<<")
37
+ print(" ")
38
+
39
+ print("value_list:")
40
+ print(value_list)
41
+ print("=" * 50)
42
+
43
+ print("critic_list:")
44
+ print(critic_list)
45
+ print("=" * 50)
VLAC/evo_vlac/examples/images/ref/0.png ADDED

Git LFS Details

  • SHA256: 1fa001aad01632fbdd5accc37489f9f216b524977de21381079c3b9eb46c371a
  • Pointer size: 130 Bytes
  • Size of remote file: 20.5 kB
VLAC/evo_vlac/examples/images/ref/1.png ADDED

Git LFS Details

  • SHA256: 2d32c11f4ca0c0611df09fba262b7abd49584b6819a98eda35b83f155eb306a8
  • Pointer size: 130 Bytes
  • Size of remote file: 25 kB
VLAC/evo_vlac/examples/images/ref/10.png ADDED

Git LFS Details

  • SHA256: fa2aff358c0fe9f2a4d4e93c64c8afd069dcdb9d5f596bf0ab9df3fea450efac
  • Pointer size: 130 Bytes
  • Size of remote file: 24.7 kB
VLAC/evo_vlac/examples/images/ref/2.png ADDED

Git LFS Details

  • SHA256: 39739ff21661b42524fe2cb5c6f7ae45504eb2e970064eadc055467ac919801f
  • Pointer size: 130 Bytes
  • Size of remote file: 28.2 kB
VLAC/evo_vlac/examples/images/ref/3.png ADDED

Git LFS Details

  • SHA256: 71107c26c78d8c91b651b910b4e7ddf8ccfec1b723ca0b555b5e48d18559d521
  • Pointer size: 130 Bytes
  • Size of remote file: 31.6 kB
VLAC/evo_vlac/examples/images/ref/4.png ADDED

Git LFS Details

  • SHA256: 04316d18df4b0e240348268b16ec56070f52f3aa7aa65cc21d4247bc434faad5
  • Pointer size: 130 Bytes
  • Size of remote file: 32.3 kB
VLAC/evo_vlac/examples/images/ref/5.png ADDED

Git LFS Details

  • SHA256: 17da4defaa94a040fc3fb70f70a2ceca96e6c87af11a813524e3b7b528c53c5c
  • Pointer size: 130 Bytes
  • Size of remote file: 33.7 kB
VLAC/evo_vlac/examples/images/ref/6.png ADDED

Git LFS Details

  • SHA256: 32d2a0d6bae1b8c35af56ef9310a14932f180ac7791af39dfbf4fc5c39b12b30
  • Pointer size: 130 Bytes
  • Size of remote file: 32.5 kB
VLAC/evo_vlac/examples/images/ref/7.png ADDED

Git LFS Details

  • SHA256: dee876bb46813346e28cddbaecf419cdf82672f69cdd1827d725651ca3b6c36e
  • Pointer size: 130 Bytes
  • Size of remote file: 28.4 kB
VLAC/evo_vlac/examples/images/ref/8.png ADDED

Git LFS Details

  • SHA256: 6e09a123e3d06f472d98fff396a6e747c6b5dba885e84db03abb38ffc830b058
  • Pointer size: 130 Bytes
  • Size of remote file: 32.8 kB
VLAC/evo_vlac/examples/images/ref/9.png ADDED

Git LFS Details

  • SHA256: 3cf5017331c1c358003094e81e8c8300824f4c3f44e7754d41bf895c6c81f392
  • Pointer size: 130 Bytes
  • Size of remote file: 34 kB
VLAC/evo_vlac/examples/images/test/0.png ADDED

Git LFS Details

  • SHA256: 1fa001aad01632fbdd5accc37489f9f216b524977de21381079c3b9eb46c371a
  • Pointer size: 130 Bytes
  • Size of remote file: 20.5 kB
VLAC/evo_vlac/examples/images/test/1.png ADDED

Git LFS Details

  • SHA256: 75d3dbc16a816db27112ffd76846188b07f0aa4b7aec1c25cbbe4f462e8e0696
  • Pointer size: 130 Bytes
  • Size of remote file: 24.5 kB
VLAC/evo_vlac/examples/images/test/2.png ADDED

Git LFS Details

  • SHA256: 7622ba8985705657061daa498a829c4e03e420582141366ec6b6998356cfb333
  • Pointer size: 130 Bytes
  • Size of remote file: 30.7 kB
VLAC/evo_vlac/examples/images/test/3.png ADDED

Git LFS Details

  • SHA256: 338b6b86f336eb7d8513187c947441f609cf268d322c3a0aa032a24bc456b4c2
  • Pointer size: 130 Bytes
  • Size of remote file: 28.1 kB
VLAC/evo_vlac/examples/images/test/4.png ADDED

Git LFS Details

  • SHA256: 6ae3ee5ef7c99b0de3b92b52414d9fe3f8bf519ba926e8b30e96d8ba2600f924
  • Pointer size: 130 Bytes
  • Size of remote file: 31.7 kB
VLAC/evo_vlac/examples/images/test/5.png ADDED

Git LFS Details

  • SHA256: 7f600ba327d2b52988be3a4a3ced34e1e332c05142bafb7ad9ce313e3687f2a4
  • Pointer size: 130 Bytes
  • Size of remote file: 27.6 kB
VLAC/evo_vlac/examples/images/test/6.png ADDED

Git LFS Details

  • SHA256: 774f389b984536fe33e02d43f4374863e6e2e6da07d4bc788035be7fa698f4b0
  • Pointer size: 130 Bytes
  • Size of remote file: 27.4 kB
VLAC/evo_vlac/examples/images/test/7.png ADDED

Git LFS Details

  • SHA256: fa2aff358c0fe9f2a4d4e93c64c8afd069dcdb9d5f596bf0ab9df3fea450efac
  • Pointer size: 130 Bytes
  • Size of remote file: 24.7 kB
VLAC/evo_vlac/examples/video_trajectory_critic_example.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from evo_vlac import GAC_model
2
+ from evo_vlac.utils.video_tool import compress_video
3
+ import os
4
+ #Consistent with the web interface, the value and citic rewards of video input can be evaluated.
5
+
6
+
7
+ #assign local model path
8
+ model_path="set to your local model path"
9
+
10
+ #assign video path and task description
11
+ test_video='./videos/pick-bowl-test.mp4'
12
+ ref_video='./videos/pick-bowl-ref.mov'
13
+ task_description='Put up the bowl and place it back in the white storage box.'
14
+
15
+ #init model
16
+ Critic=GAC_model(tag='critic')
17
+ Critic.init_model(model_path=model_path,model_type='internvl2',device_map=f'cuda:0')
18
+ Critic.temperature=0.5
19
+ Critic.top_k=1
20
+ Critic.set_config()
21
+ Critic.set_system_prompt()
22
+
23
+ # transform video
24
+ test_video_compressed = os.path.join(os.path.dirname(test_video),"test.mp4")
25
+ _,output_fps=compress_video(test_video, test_video_compressed,fps=5)
26
+ reference_video_compressed = None
27
+ if ref_video:
28
+ reference_video_compressed = os.path.join(os.path.dirname(ref_video),"ref.mp4")
29
+ compress_video(ref_video, reference_video_compressed,fps=5)
30
+
31
+
32
+ # generate Critic results
33
+ result_path,value_list,critic_list,done_list = Critic.web_trajectory_critic(
34
+ task_description=task_description,
35
+ main_video_path=test_video_compressed,
36
+ reference_video_path=reference_video_compressed,#if None means no reference video, only use task_description to indicate the task
37
+ batch_num=5,#batch number
38
+ ref_num=6,#image number used in reference video
39
+ think=False,# whether to CoT
40
+ skip=5,#pair-wise step
41
+ rich=False,#whether to output decimal value
42
+ reverse_eval=False,#whether to reverse the evaluation(for VROC evaluation)
43
+ output_path="results",
44
+ fps=float(output_fps),
45
+ frame_skip=True,#whether to skip frames(if false, each frame while be evaluated, cost more time)
46
+ done_flag=False,#whether to out put done value
47
+ in_context_done=False,#whether use reference video to generate done value
48
+ done_threshold=0.9,#done threshold
49
+ video_output=True#whether to output video
50
+ )
51
+
52
+
53
+ print("=" * 100)
54
+ print(">>>>>>>>>Critic results<<<<<<<<<<")
55
+ print(" ")
56
+
57
+ print(f"result path: {result_path}")
58
+ print(f"task description: {task_description}")
59
+ print("=" * 50)
60
+
61
+ print("value_list:")
62
+ print(value_list)
63
+ print("=" * 50)
64
+
65
+ print("critic_list:")
66
+ print(critic_list)
67
+ print("=" * 50)
68
+
69
+ print("done_list:")
70
+ print(done_list)
71
+ print("=" * 100)
VLAC/evo_vlac/examples/videos/pick-bowl-ref.mov ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9d589e6be00aea3988a0c764caecd5c74e21554b9e92a70a8777fe02a07ddc3
3
+ size 37068557
VLAC/evo_vlac/examples/videos/pick-bowl-test.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b576b4d2a2a7739115d2c5b67e5a6daed6e2ed1b85ef3f9f6533c44b1634339b
3
+ size 8454869
VLAC/evo_vlac/examples/vla_example.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from evo_vlac import GAC_model
2
+ from evo_vlac.utils.video_tool import compress_video
3
+ import os
4
+ #Example code for realizing VLA inference with open tasks and multi-perspective generalization capability, inputs 1-3 images and eef position, outputs delta eef actions, most friendly to songling (pika) robotic arms.
5
+ #This is a preview version, fine-tuning code for different robotic arms will be released together with the paper.
6
+
7
+ #assign local model path
8
+ model_path="/scratch1/home/zhicao/VLAC/models/VLAC"
9
+
10
+ view_images=["./images/test/595-44-565-0.jpg","./images/test/595-44-565-2.jpg"]
11
+ eef_position=[
12
+ -18151,
13
+ 11685,
14
+ 418833,
15
+ -124631,
16
+ 65461,
17
+ -133783,
18
+ 27510
19
+ ]#The unit of xyz is 0.001mm, and the unit of rpy is 0.001 degrees
20
+ task_description='Scoop the rice into the rice cooker.'
21
+
22
+
23
+ history=False#whether to use history chat
24
+ complete_requests_list=None#chat history
25
+
26
+ #init model
27
+ Policy=GAC_model(tag='Policy')
28
+ Policy.init_model(model_path=model_path,model_type='internvl2',device_map=f'cuda:0')
29
+ Policy.temperature=0.5
30
+ Policy.top_k=1
31
+ Policy.set_config()
32
+ Policy.set_system_prompt()
33
+
34
+ query=Policy.get_action_prompt(task=task_description,view_num=len(view_images),position_output=False,simple=False,state=Policy.format_state(eef_position,gripper_format=False),think=False)
35
+ infer_requests=Policy.get_infer_requests(prompt=query,images=view_images)
36
+ if history:
37
+ if complete_requests_list:
38
+ complete_requests_list[0].images.extend(infer_requests[0].images)
39
+ complete_requests_list[0].messages.append(infer_requests[0].messages[1])
40
+ if len(complete_requests_list[0].images)>history_image_num:
41
+ complete_requests_list[0].images=complete_requests_list[0].images[len(infer_requests[0].images):]
42
+ complete_requests_list[0].messages=complete_requests_list[0].messages[:1]+complete_requests_list[0].messages[3:]
43
+ infer_requests=complete_requests_list
44
+ response_list,infer_time=Policy.chat(infer_requests)
45
+ answers_list,complete_requests_list=Policy.results_format(response_list,infer_requests,rich=True)
46
+
47
+
48
+ print("=" * 100)
49
+ print(">>>>>>>>>VLA results<<<<<<<<<<")
50
+ print(" ")
51
+ print(f'action:{answers_list}')
VLAC/evo_vlac/utils/data_processing_vlm.py ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import tqdm
4
+ import random
5
+ import numpy as np
6
+ import cv2
7
+ import pickle
8
+ from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union
9
+ from loguru import logger
10
+
11
+ import matplotlib.pyplot as plt
12
+ from collections import defaultdict
13
+ from scipy.stats import truncnorm
14
+ from PIL import Image, ImageEnhance, ImageFilter
15
+ from pathlib import Path
16
+ import math
17
+ import copy
18
+ import re
19
+ from collections import defaultdict, Counter
20
+ import matplotlib.pyplot as plt
21
+ import pandas as pd
22
+
23
+
24
+ def transform_images(text: str) -> str:
25
+ occurrences = re.findall(r"<image>\n", text)
26
+
27
+ if len(occurrences) <= 1:
28
+ return text
29
+
30
+ count = 0
31
+ def replace_func(match):
32
+ nonlocal count
33
+ count += 1
34
+ return f"Image-{count}: <image>\n"
35
+
36
+ transformed_text = re.sub(r"<image>\n", replace_func, text)
37
+
38
+ return transformed_text
39
+
40
+
41
+
42
+ def is_image_black(image_array):
43
+ # Check if all pixel values are 0 (black image)
44
+ return np.all(image_array == 0)
45
+
46
+ def is_image_almost_black(image_array, threshold=0.80, tolerance=10):
47
+ """
48
+ Check if the RGB image is almost entirely black.
49
+
50
+ Parameters:
51
+ image_array (ndarray): The input RGB image array of shape (height, width, 3).
52
+ threshold (float): The fraction of pixels that must be close to black for the image to be considered almost black.
53
+ tolerance (int): The maximum value a pixel can have in each channel to be considered black (0-255 scale).
54
+
55
+ Returns:
56
+ bool: True if the image is almost black, False otherwise.
57
+ """
58
+ # Check if all channels are below the tolerance for each pixel
59
+ nearly_black_pixels = np.sum(np.all(image_array <= tolerance, axis=-1))
60
+ total_pixels = image_array.shape[0] * image_array.shape[1]
61
+
62
+ fraction_black = nearly_black_pixels / total_pixels
63
+
64
+ return fraction_black >= threshold
65
+
66
+ def is_image_path_almost_black(image_path):
67
+ try:
68
+ img = Image.open(image_path).convert('RGB')
69
+ except:
70
+ return False
71
+ image_array = np.array(img)
72
+ return is_image_almost_black(image_array)
73
+
74
+
75
+ def is_image_path_black(image_path):
76
+ try:
77
+ img = Image.open(image_path).convert('RGB')
78
+ except:
79
+ return False
80
+ image_array = np.array(img)
81
+ return np.all(image_array == 0)
82
+
83
+ def compare_images(image1_path, image2_path):
84
+ # Load the images
85
+ try:
86
+ img1 = Image.open(image1_path).convert('RGB')
87
+ img2 = Image.open(image2_path).convert('RGB')
88
+ except:
89
+ return -1
90
+
91
+ if img1.size != img2.size:
92
+ img2 = img2.resize(img1.size)
93
+
94
+ img1_array = np.array(img1)
95
+ img2_array = np.array(img2)
96
+
97
+ if is_image_almost_black(img1_array) or is_image_almost_black(img2_array):
98
+ return -1
99
+
100
+ difference = np.abs(img1_array - img2_array)
101
+
102
+ num_different_pixels = np.sum(difference > 0)
103
+
104
+ total_pixels = img1_array.size
105
+
106
+ percentage_difference = (num_different_pixels / total_pixels) * 100
107
+
108
+ return percentage_difference
109
+
110
+ def denormalize_with_params(normalized_data, params):
111
+ """
112
+ 使用参数将归一化的数据还原到原始范围
113
+
114
+ Args:
115
+ normalized_data: 归一化后的任意维度数组,但最后一个维度必须是7
116
+ params: 归一化参数字典
117
+
118
+ Returns:
119
+ numpy.ndarray: 还原后的数据,维度与输入一致
120
+ """
121
+ # 转换为numpy数组
122
+ data_array = np.array(normalized_data)
123
+ original_shape = data_array.shape
124
+
125
+ # 检查最后一个维度是否为7
126
+ if len(original_shape) < 2:
127
+ raise ValueError(f"输入数据至少应该是2维的,但得到的是{len(original_shape)}维")
128
+
129
+ if original_shape[-1] != 7:
130
+ raise ValueError(f"输入数据的最后一个维度应该是7,但得到的是{original_shape[-1]}")
131
+
132
+ # 将数据reshape为(..., 7)的形状,然后flatten前面的维度
133
+ working_data = data_array.reshape(-1, 7)
134
+
135
+ # 提取参数
136
+ scale = np.array(params['scale'])
137
+ offset = np.array(params['offset'])
138
+
139
+ # 反向变换: x = normalized * scale + offset
140
+ original_data = working_data * scale + offset
141
+
142
+ # 恢复原始形状
143
+ original_data = original_data.reshape(original_shape)
144
+
145
+ return original_data
146
+
147
+ def agibot_process(action,action_type='action'):
148
+ if action_type=='fast-chunk':
149
+ return action
150
+ def convert_to_int(element):
151
+ if isinstance(element, list):
152
+ return [convert_to_int(sub_element) for sub_element in element]
153
+ else:
154
+ try:
155
+ return int(element)
156
+ except ValueError:
157
+ return element # Return the element unchanged if it can't be converted
158
+
159
+ return convert_to_int(action)
160
+
161
+
162
+ def songling_process_single(action,action_type='action'):
163
+ if type(action) is list:
164
+ for i in range(3,6):
165
+ if abs(action[i])>180000:
166
+ action[i]=((action[i] + 180000) % 360000) - 180000
167
+ if action_type=='fast-chunk':
168
+ new_action=action[:-1]+[int(action[-1]/1000)]
169
+ else:
170
+ new_action=[int(temp/1000.0) for temp in action]
171
+ if action_type=='action' or action_type=='fast-chunk':
172
+ if new_action[-1]<0:
173
+ new_action[-1]=0
174
+ elif new_action[-1]>=1:
175
+ new_action[-1]=1
176
+ else:
177
+ new_action[-1]=0
178
+ if action_type=='state':
179
+ new_action[-1]=round((new_action[-1]//10000)/7.0,1)
180
+ return new_action
181
+ else:
182
+ return None
183
+
184
+ def songling_process(action, action_type='action'):
185
+ if type(action) is list:
186
+ if len(action) == 7 and all(not isinstance(item, list) for item in action):
187
+ return songling_process_single(action, action_type)
188
+ else:
189
+ new_action = []
190
+ for one_action in action:
191
+ processed = songling_process(one_action, action_type)
192
+ if processed is not None:
193
+ new_action.append(processed)
194
+ return new_action if new_action else None
195
+ else:
196
+ return None
197
+
198
+
199
+ def format_songling(action):
200
+ if action is None:
201
+ return 'None'
202
+ elif type(action) is list:
203
+ if type(action[0]) is list:
204
+ if len(action)==2:
205
+ return "\nleft: <action> {{x: {}mm, y: {}mm, z: {}mm, roll: {} degrees, pitch: {} degrees, yaw: {} degrees, open: {}}} </action> \nright: <action> {{x: {}mm, y: {}mm, z: {}mm, roll: {} degrees, pitch: {} degrees, yaw: {} degrees, open: {}}} </action>".format(action[0][0],action[0][1],action[0][2],action[0][3],action[0][4],action[0][5],action[0][6],action[1][0],action[1][1],action[1][2],action[1][3],action[1][4],action[1][5],action[1][6])
206
+ elif len(action)==1:
207
+ return "{{x: {}mm, y: {}mm, z: {}mm, roll: {} degrees, pitch: {} degrees, yaw: {} degrees, open: {}}}".format(action[0][0],action[0][1],action[0][2],action[0][3],action[0][4],action[0][5],action[0][6])
208
+ else:
209
+ return 'None'
210
+ else:
211
+ return "{{x: {}mm, y: {}mm, z: {}mm, roll: {} degrees, pitch: {} degrees, yaw: {} degrees, open: {}}}".format(action[0],action[1],action[2],action[3],action[4],action[5],action[6])
212
+ else:
213
+ return 'End-Effector with units in mm and degrees'
214
+
215
+ def normalize_angle(angle):
216
+ if abs(angle)>180:
217
+ return (angle + 180) % 360 - 180
218
+ else:
219
+ return angle
220
+
221
+
222
+ def format_songling_v2(action,state=False,data_type=None):
223
+ if action is None:
224
+ return 'None'
225
+ elif type(action) is list:
226
+ if type(action[0]) is list:
227
+ pass
228
+ else:
229
+ action = [action]
230
+ if state:
231
+ pass
232
+ else:
233
+ for i in range(len(action)):
234
+ action[i][3]=normalize_angle(action[i][3])
235
+ action[i][4]=normalize_angle(action[i][4])
236
+ action[i][5]=normalize_angle(action[i][5])
237
+ if len(action)==2:
238
+ if state:
239
+ return "\nleft: <position> {{x: {}mm, y: {}mm, z: {}mm, roll: {} degrees, pitch: {} degrees, yaw: {} degrees, open: {}}} </position> \nright: <position> {{x: {}mm, y: {}mm, z: {}mm, roll: {} degrees, pitch: {} degrees, yaw: {} degrees, open: {}}} </position>".format(action[0][0],action[0][1],action[0][2],action[0][3],action[0][4],action[0][5],action[0][6],action[1][0],action[1][1],action[1][2],action[1][3],action[1][4],action[1][5],action[1][6])
240
+ else:
241
+ return "\nleft: <action> {{x: {}mm, y: {}mm, z: {}mm, roll: {} degrees, pitch: {} degrees, yaw: {} degrees, open: {}}} </action> \nright: <action> {{x: {}mm, y: {}mm, z: {}mm, roll: {} degrees, pitch: {} degrees, yaw: {} degrees, open: {}}} </action>".format(action[0][0],action[0][1],action[0][2],action[0][3],action[0][4],action[0][5],action[0][6],action[1][0],action[1][1],action[1][2],action[1][3],action[1][4],action[1][5],action[1][6])
242
+ elif len(action)==1:
243
+ return "{{x: {}mm, y: {}mm, z: {}mm, roll: {} degrees, pitch: {} degrees, yaw: {} degrees, open: {}}}".format(action[0][0],action[0][1],action[0][2],action[0][3],action[0][4],action[0][5],action[0][6])
244
+ else:
245
+ return 'None'
246
+ else:
247
+ if data_type:
248
+ return f'{data_type} End-Effector with units in mm and degrees'
249
+ return 'End-Effector with units in mm and degrees'
250
+
251
+ def format_songling_simple(action,state=False,data_type=None):
252
+ if action is None:
253
+ return 'None'
254
+ elif type(action) is list:
255
+ if type(action[0]) is list:
256
+ pass
257
+ else:
258
+ action = [action]
259
+ if state:
260
+ pass
261
+ else:
262
+ for i in range(len(action)):
263
+ action[i][3]=normalize_angle(action[i][3])
264
+ action[i][4]=normalize_angle(action[i][4])
265
+ action[i][5]=normalize_angle(action[i][5])
266
+ if len(action)==2:
267
+ if state:
268
+ return "\nleft: <(position)> ({} {} {} {} {} {} {}) </(position)> \nright: <(position)> ({}, {}, {}, {}, {}, {}, {}) </(position)>".format(action[0][0],action[0][1],action[0][2],action[0][3],action[0][4],action[0][5],action[0][6],action[1][0],action[1][1],action[1][2],action[1][3],action[1][4],action[1][5],action[1][6])
269
+ else:
270
+ return "\nleft: <(action)> ({} {} {} {} {} {} {}) </(action)> \nright: <(action)> ({}, {}, {}, {}, {}, {}, {}) </(action)>".format(action[0][0],action[0][1],action[0][2],action[0][3],action[0][4],action[0][5],action[0][6],action[1][0],action[1][1],action[1][2],action[1][3],action[1][4],action[1][5],action[1][6])
271
+ elif len(action)==1:
272
+ return "({} {} {} {} {} {} {})".format(action[0][0],action[0][1],action[0][2],action[0][3],action[0][4],action[0][5],action[0][6])
273
+ else:
274
+ return 'None'
275
+ else:
276
+ if data_type:
277
+ return f'{data_type} End-Effector hide units in mm and degrees within () format'
278
+ return 'End-Effector hide units in mm and degrees within () format'
279
+
280
+ def trojectory_example_prompt(images,task):
281
+ prompt=f"<trajectory> <task> {task} </task>:"
282
+ t_len=len(images)-1
283
+ for i,one in enumerate(range(len(images))):
284
+ temp_p=int((i/t_len)*100)
285
+ prompt=prompt+f" {temp_p}% <image>\n"
286
+ prompt=prompt+'</trajectory>'
287
+ return prompt
288
+
289
+
290
+ def describe_move(move_vec):
291
+ names = [
292
+ {-1: "backward", 0: None, 1: "forward"},
293
+ {-1: "right", 0: None, 1: "left"},
294
+ {-1: "down", 0: None, 1: "up"},
295
+ {-1: "tilt down", 0: None, 1: "tilt up"},
296
+ {},
297
+ {-1: "rotate clockwise", 0: None, 1: "rotate counterclockwise"},
298
+ # {-1: "close gripper", 0: None, 1: "open gripper"},
299
+ {0: "close gripper", 1: "open gripper"},
300
+ ]
301
+
302
+ xyz_move = [names[i][move_vec[i]] for i in range(0, 3)]
303
+ xyz_move = [m for m in xyz_move if m is not None]
304
+
305
+ if len(xyz_move) != 0:
306
+ description = "move " + " ".join(xyz_move)
307
+ else:
308
+ description = ""
309
+
310
+ if move_vec[3] == 0:
311
+ move_vec[3] = move_vec[4] # identify rolling and pitching
312
+
313
+ if move_vec[3] != 0:
314
+ if len(description) > 0:
315
+ description = description + ", "
316
+
317
+ description = description + names[3][move_vec[3]]
318
+
319
+ if move_vec[5] != 0:
320
+ if len(description) > 0:
321
+ description = description + ", "
322
+
323
+ description = description + names[5][move_vec[5]]
324
+
325
+ if move_vec[6] != -2:
326
+ if len(description) > 0:
327
+ description = description + ", "
328
+
329
+ description = description + names[6][move_vec[6]]
330
+
331
+ if len(description) == 0:
332
+ description = "stop"
333
+
334
+ return description
335
+
336
+ def denoise_action(action):
337
+ xyz = action[:3]
338
+ rpy = action[3:6]
339
+ open_val = action[6]
340
+
341
+ def normalize_angle(angle):
342
+ return (angle + 180) % 360 - 180
343
+
344
+ def process_dims(values, ref_max=None):
345
+ abs_values = [abs(v) for v in values]
346
+ max_val = max(abs_values)
347
+
348
+ if max_val == 0:
349
+ return [0, 0, 0]
350
+
351
+ processed = [0, 0, 0]
352
+ main_idx = abs_values.index(max_val)
353
+ processed[main_idx] = 1 if values[main_idx] > 0 else -1
354
+
355
+ for i in range(3):
356
+ if i == main_idx:
357
+ continue
358
+ threshold = max_val * 0.25
359
+ if abs(values[i]) < threshold:
360
+ processed[i] = 0
361
+ else:
362
+ processed[i] = 1 if values[i] > 0 else (-1 if values[i] < 0 else 0)
363
+ return processed
364
+
365
+ adjusted_rpy = [normalize_angle(v) for v in rpy]
366
+
367
+ xyz_processed = process_dims(xyz)
368
+ max_xyz = max(abs(v) for v in xyz)
369
+
370
+ rpy_abs = [abs(v) for v in adjusted_rpy]
371
+ max_rpy = max(rpy_abs)
372
+
373
+ if max_rpy < max_xyz * 0.25 and max_rpy <= 4:
374
+ rpy_processed = [0, 0, 0]
375
+ else:
376
+ rpy_processed = process_dims(adjusted_rpy)
377
+
378
+ if max_xyz < max_rpy * 0.25 and max_xyz <= 5:
379
+ xyz_processed = [0, 0, 0]
380
+ else:
381
+ pass
382
+ return xyz_processed + rpy_processed + [open_val]
383
+
384
+ def describe_action(action,threshold=0.3,denoise=True):
385
+ if denoise:
386
+ action=denoise_action(action)
387
+ else:
388
+ for i in range(len(action)-1):
389
+ if action[i]<-threshold:
390
+ action[i]=-1
391
+ elif action[i]>threshold:
392
+ action[i]=1
393
+ else:
394
+ action[i]=0
395
+
396
+ return describe_move(action), action
397
+
398
+ def format_songling_think_one(action,threshold=0.3,denoise=True):
399
+ #think_threshold dis when denoise true
400
+ if action is None:
401
+ return 'None'
402
+ elif type(action) is list:
403
+ if type(action[0]) is list:
404
+ if len(action)==2:
405
+ return f"left: <action> {describe_action(action[0],threshold,denoise)[0]} </action> \nright: <action> {describe_action(action[1],threshold,denoise)[0]} </action>"
406
+ elif len(action)==1:
407
+ return f"{describe_action(action[0],threshold,denoise)[0]}"
408
+ else:
409
+ return 'None'
410
+ else:
411
+ return f"{describe_action(action,threshold,denoise)[0]}"
412
+ else:
413
+ return 'None'
414
+
415
+ def format_songling_think(action,threshold=0.3,denoise=True,multi=False):
416
+ if multi:
417
+ pass
418
+ else:
419
+ action = [action]
420
+ if len(action)==1:
421
+ return f"<think> {format_songling_think_one(action[0],threshold,denoise)} </think> "
422
+ action_think_str=''
423
+ for i,one in enumerate(action):
424
+ action_think_str+=f'{i+1}. '+format_songling_think_one(one,threshold,denoise)+'\n'
425
+ return f"<think> {action_think_str} </think> "
426
+
427
+ def bridge_action_preprocess(one,data,key,td=1):
428
+ trajectory_id,step_id,step_num,view_id= key.split('-')
429
+ step_id=int(step_id)
430
+ step_num=int(step_num)
431
+ next_key=f'{trajectory_id}-{step_id+td}-{step_num}-{view_id}'
432
+ next_one=data.get(next_key)
433
+ if td>1:
434
+ temp_one=data.get(f'{trajectory_id}-{step_id+td-1}-{step_num}-{view_id}')
435
+ else:
436
+ temp_one=one
437
+ if next_one is None:
438
+ return None
439
+ if temp_one is None:
440
+ return None
441
+ one_state=one['position_7d']
442
+ next_state=next_one['position_7d']
443
+ action=[next_state[i]-one_state[i] for i in range(6)]
444
+ action+=[round(temp_one['action'][-1])]
445
+ return action
446
+
447
+ def droid_action_preprocess(one,data,key,td=1):
448
+ trajectory_id,step_id,step_num,view_id= key.split('-')
449
+ step_id=int(step_id)
450
+ step_num=int(step_num)
451
+ next_key=f'{trajectory_id}-{step_id+td}-{step_num}-{view_id}'
452
+ next_one=data.get(next_key)
453
+ if next_one is None:
454
+ return None
455
+ one_state=one['position_7d']
456
+ next_state=next_one['position_7d']
457
+ action=[next_state[i]-one_state[i] for i in range(6)]
458
+ open_action=next_state[-1]-one_state[-1]
459
+ if open_action>0:
460
+ open_action=1
461
+ elif open_action<0:
462
+ open_action=0
463
+ else:
464
+ open_action=1 if next_state[-1] >=0.85 else 0
465
+ action+=[open_action]
466
+ return action
467
+
468
+ def bridge_position_preprocess(one=None,data=None,key=None,td=1,action=True):
469
+ if action:
470
+ trajectory_id,step_id,step_num,view_id= key.split('-')
471
+ step_id=int(step_id)
472
+ step_num=int(step_num)
473
+ next_key=f'{trajectory_id}-{step_id+td}-{step_num}-{view_id}'
474
+ next_one=data.get(next_key)
475
+ if next_one is None:
476
+ return None
477
+ position=next_one['position_7d']
478
+ else:
479
+ position=one['position_7d']
480
+ if type(position) is list:
481
+ processed_position = [
482
+ max(min(int(position[i] * 1000), 999), -999) if i < 3
483
+ else int(position[i] * 360 / 3.1416)
484
+ for i in range(6)
485
+ ]
486
+ processed_position+=[int(position[-1])*100]
487
+ return processed_position
488
+ else:
489
+ return None
490
+
491
+ def songling_position_preprocess(one=None,data=None,key=None,td=1,action=True):
492
+ if action:
493
+ trajectory_id,step_id,step_num,view_id= key.split('-')
494
+ step_id=int(step_id)
495
+ step_num=int(step_num)
496
+ next_key=f'{trajectory_id}-{step_id+td}-{step_num}-{view_id}'
497
+ next_one=data.get(next_key)
498
+ if next_one is None:
499
+ return None
500
+ position=next_one['position_7d']
501
+ else:
502
+ position=one['position_7d']
503
+ if type(position) is list:
504
+ if type(position[0]) is list:
505
+ new_position=[]
506
+ for one_position in position:
507
+ processed_position = [int(temp/1000.0) for temp in position]
508
+ new_position.append(processed_position)
509
+ return new_position
510
+ else:
511
+ processed_position = [int(temp/1000.0) for temp in position]
512
+ return processed_position
513
+ else:
514
+ return None
515
+
516
+ def agibot_position_preprocess(one=None,data=None,key=None,td=1,action=True):
517
+ if action:
518
+ trajectory_id,step_id,step_num,view_id= key.split('-')
519
+ step_id=int(step_id)
520
+ step_num=int(step_num)
521
+ next_key=f'{trajectory_id}-{step_id+td}-{step_num}-{view_id}'
522
+ next_one=data.get(next_key)
523
+ if next_one is None:
524
+ return None
525
+ position=next_one['position_7d']
526
+ else:
527
+ position=one['position_7d']
528
+ if type(position) is list:
529
+ if type(position[0]) is list:
530
+ new_position=[]
531
+ for one_position in position:
532
+ processed_position = [int(temp) for temp in one_position]
533
+ processed_position[2] = processed_position[2]-200
534
+ new_position.append(processed_position)
535
+ return new_position
536
+ else:
537
+ processed_position = [int(temp) for temp in position]
538
+ processed_position[2] = processed_position[2]-200
539
+ return processed_position
540
+ else:
541
+ return None
542
+
543
+ def default_position_preprocess(one=None,data=None,key=None,td=1,action=True):
544
+ if action:
545
+ trajectory_id,step_id,step_num,view_id= key.split('-')
546
+ step_id=int(step_id)
547
+ step_num=int(step_num)
548
+ next_key=f'{trajectory_id}-{step_id+td}-{step_num}-{view_id}'
549
+ next_one=data.get(next_key)
550
+ if next_one is None:
551
+ return None
552
+ position=next_one['position_7d']
553
+ else:
554
+ position=one['position_7d']
555
+ return position
556
+
557
+ def default_position_process(position,action_type='action'):
558
+ return position
559
+
560
+ def default_action_preprocess(one,data=None,key=None,td=1):
561
+ return one['action']
562
+
563
+ def default_process(action,action_type='action'):
564
+ if action_type=='fast-chunk':
565
+ return action
566
+ return [int(temp) for temp in action]
567
+
568
+ def droid_process_single(action,action_type='action'):
569
+ if action_type=='fast-chunk':
570
+ return action
571
+ if type(action) is list:
572
+ processed_action = [
573
+ max(min(int(action[i] * 1000), 999), -999) if i < 3
574
+ else int(action[i] * 360 / 3.1416)
575
+ for i in range(6)
576
+ ]
577
+ processed_action+=[action[-1]]
578
+ return processed_action
579
+ else:
580
+ return None
581
+
582
+ def droid_process(action,action_type='action'):
583
+ if type(action) is list:
584
+ if type(action[0]) is list:
585
+ new_action=[]
586
+ for one_action in action:
587
+ new_action.append(droid_process_single(one_action,action_type))
588
+ return new_action
589
+ else:
590
+ return droid_process_single(action,action_type)
591
+ else:
592
+ return None
593
+
594
+
595
+ class DataProcessor():
596
+ def __init__(self):
597
+ self.action_process={
598
+ 'songling':songling_process,
599
+ 'agibot':agibot_process,
600
+ 'bridge':droid_process,
601
+ 'droid':droid_process,
602
+ 'default':default_process
603
+ }
604
+ self.action_format={
605
+ 'songling':format_songling_v2,
606
+ 'agibot':format_songling_v2,
607
+ 'bridge':format_songling_v2,
608
+ 'droid':format_songling_v2,
609
+ 'default':format_songling_v2
610
+ }
611
+ self.action_format_simple={
612
+ 'songling':format_songling_simple,
613
+ 'agibot':format_songling_simple,
614
+ 'bridge':format_songling_simple,
615
+ 'droid':format_songling_simple,
616
+ 'default':format_songling_simple
617
+ }
618
+ self.action_think_format={
619
+ 'songling':format_songling_think,
620
+ 'agibot':format_songling_think,
621
+ 'bridge':format_songling_think,
622
+ 'droid':format_songling_think,
623
+ 'default':format_songling_think
624
+ }
625
+ self.action_preprocess={
626
+ 'songling':default_action_preprocess,
627
+ 'agibot':default_action_preprocess,
628
+ 'bridge':bridge_action_preprocess,
629
+ 'droid':droid_action_preprocess,
630
+ 'default':default_action_preprocess
631
+ }
632
+ self.position_preprocess={
633
+ 'songling':songling_position_preprocess,
634
+ 'agibot':agibot_position_preprocess,
635
+ 'bridge':bridge_position_preprocess,
636
+ 'droid':bridge_position_preprocess,
637
+ 'default':default_position_preprocess
638
+ }
639
+ self.position_process={
640
+ 'songling':default_position_process,
641
+ 'agibot':default_position_process,
642
+ 'bridge':default_position_process,
643
+ 'droid':default_position_process,
644
+ 'default':default_position_process
645
+ }
646
+
647
+ self.image_prompt_templete={
648
+ 1:'<image>\n',
649
+ 2:'Image-1: <image>\nImage-2: <image>\n',
650
+ 3:'Image-1: <image>\nImage-2: <image>\nImage-3: <image>\n'}
651
+ self.system_prompt='You are a visual-language assistant designed to interpret spatial and task-related information from images and text. Provide precise, context-aware responses and actionable guidance to assist in achieving task objectives.'
652
+ self.prompt_templete={
653
+ "v3":"Image-1: <image>\nImage-2: <image>\nCompare two images and evaluate whether the second image is closer to achieving task objectives compared to the first image.\nPlease directly rate score following below rules:\nPositive Score: If the second image is closer to achieving task objectives than the first image, assign a positive score based on the significance of the improvement.\nNegative Score: If the second image deviates further from the task objectives compared to the first image, assign a negative score based on the degree of deterioration.\nZero Score: If both images demonstrate the same level of task completion, assign a score of 0.\nThe task needs to accomplish is: <task> {} </task> <score>",
654
+
655
+ "v3_think":"0% <image>\nThis image is the trajectory beginning of the following two images\nImage-1: <image>\nImage-2: <image>\nCompare two images and evaluate whether the second image is closer to achieving task objectives compared to the first image.\nPlease directly rate score following below rules:\nPositive Score: If the second image is closer to achieving task objectives than the first image, assign a positive score based on the significance of the improvement.\nNegative Score: If the second image deviates further from the task objectives compared to the first image, assign a negative score based on the degree of deterioration.\nZero Score: If both images demonstrate the same level of task completion, assign a score of 0.\nThe task needs to accomplish is: <task> {} </task> <score>",
656
+
657
+ 'think':" Please give reasoning process enclosed within <think> reasoning process here </think>.",
658
+
659
+ "vqa":"{}",
660
+
661
+ "task_vqa":"Image-1: <image>\nImage-2: <image>\nCompare two images and infer what kind of task is achieving. <infer> <task>",
662
+
663
+ "task_done":"The 1 means yes, the 0 means no. Check if the robot has completed its task: <task> {} </task> <done>",
664
+
665
+ "context_task_done":"<goal> <task> {} </task>: <image>\n<goal>\n<image>\n The 1 means yes, the 0 means no. Refer to the goal, check if the robot has completed its task: <task> {} </task> <done>",
666
+
667
+ "image_done":"<goal> <image>\n<goal>\n<image>\n The 1 means yes, the 0 means no. Check if the robot has completed its image goal <done>",
668
+
669
+ "action_inverse":"Image-1: <image>\nImage-2: <image>\nCompare two images and infer what action between them. <infer> <action>",
670
+
671
+ "task_action":"The current position state of the robotic arm's end gripper in the image is as follows: <state> {} </state>. What action should the robot take to get better completion of instruction: <task> {} </task> <action>",
672
+
673
+ "fast_action":"The current position state of the robotic arm's end gripper in the image is as follows: <state> {} </state>. What action chunks should the robot take to get better completion of instruction: <task> {} </task> <chunk>",
674
+
675
+ "task_action_simple":"The current position state of the robotic arm's end gripper in the image is as follows: <state> {} </state>. What action should the robot take to get better completion of instruction: <task> {} </task> <(action)>",
676
+
677
+ "task_position":"The current position state of the robotic arm's end gripper in the image is as follows: <position> {} </position>. What position should the robot take to get better completion of instruction: <task> {} </task> <position>",
678
+
679
+ "task_position_simple":"The current position state of the robotic arm's end gripper in the image is as follows: <(position)> {} </(position)>. What position should the robot take to get better completion of instruction: <task> {} </task> <(position)>",
680
+
681
+ "task_action_score":"The current position state of the robotic arm's end gripper in the image is as follows: <state> {} </state>. The action robot take now: <action> {} </action>. Please rate score of the action for achieving task: <task> {} </task> <score>",
682
+
683
+ 'action':"{{x: {}mm, y: {}mm, z: {}mm, roll: {} degrees, pitch: {} degrees, yaw: {} degrees, open: {}}}"}
684
+ self.answer_templete={
685
+ "v3":"{}",
686
+ "vqa":"{}",
687
+ "task_vqa":"{}",
688
+ "task_done":"{}",
689
+ "action_inverse":"{}",
690
+ "task_action":"{}",
691
+ "task_action_score":"{}"
692
+ }
VLAC/evo_vlac/utils/magic_detect.py ADDED
@@ -0,0 +1,1092 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ from scipy import signal
4
+ from typing import Tuple, List, Optional, Dict
5
+ import warnings
6
+ from scipy import stats
7
+ from enum import Enum
8
+
9
+ def adaptive_peak_valley_detection(
10
+ data: np.ndarray,
11
+ assist_peaks: np.ndarray=None,
12
+ window_size: Optional[int] = None,
13
+ min_distance: Optional[int] = None,
14
+ prominence_threshold: float = 0.1,
15
+ max_iterations: int = 10,
16
+ verbose: bool = False,
17
+ outlier_sensitivity=1.5,
18
+ min_amplitude_ratio=0.1
19
+ ) -> Dict[str, np.ndarray]:
20
+ """
21
+ 自适应峰谷检测函数,使用滚动窗口方法并通过多轮迭代优化
22
+
23
+ Parameters:
24
+ -----------
25
+ data : np.ndarray
26
+ 输入时间序列数据
27
+ window_size : int, optional
28
+ 滚动窗口大小,如果为None则自动计算
29
+ min_distance : int, optional
30
+ 峰谷间最小距离,如果为None则自动计算
31
+ prominence_threshold : float
32
+ 突出度阈值比例
33
+ max_iterations : int
34
+ 最大迭代次数
35
+ verbose : bool
36
+ 是否输出详细信息
37
+
38
+ Returns:
39
+ --------
40
+ dict : 包含peaks, valleys, segments, window_size, iterations等信息
41
+ """
42
+
43
+ if len(data) < 3:
44
+ raise ValueError("Data length must be >= 3")
45
+
46
+ data = np.array(data)
47
+ n = len(data)
48
+
49
+ # 自适应窗口大小计算
50
+ if window_size is None:
51
+ window_size = _calculate_adaptive_window_size(data)
52
+
53
+ # 自适应最小距离计算
54
+ if min_distance is None:
55
+ min_distance = max(1, window_size // 3)
56
+
57
+ if verbose:
58
+ print(f"Data length: {n}")
59
+ print(f"Adaptive window size: {window_size}")
60
+ print(f"Min distance: {min_distance}")
61
+
62
+ # 第一轮:基于滚动窗口的初始检测
63
+ if assist_peaks:
64
+ initial_peaks=assist_peaks
65
+ initial_valleys=[int((assist_peaks[k]+assist_peaks[k-1])/2)for k in range(1,len(assist_peaks))]
66
+ else:
67
+ initial_peaks, initial_valleys = _rolling_window_detection(
68
+ data, window_size, min_distance, prominence_threshold
69
+ )
70
+
71
+
72
+ if verbose:
73
+ print(f"Initial detection - Peaks: {len(initial_peaks)}, Valleys: {len(initial_valleys)}")
74
+
75
+ # 多轮迭代优化
76
+ peaks, valleys, iterations = _iterative_peak_valley_optimization(
77
+ data, initial_peaks, initial_valleys, max_iterations, verbose,outlier_method='iqr',outlier_sensitivity=outlier_sensitivity,min_amplitude_ratio=min_amplitude_ratio
78
+ )
79
+
80
+ # 生成序列分段
81
+ segments = _generate_segments(peaks, valleys, n)
82
+
83
+ # 计算统计信息
84
+ stats = _calculate_statistics(data, peaks, valleys)
85
+
86
+ return {
87
+ 'peaks': peaks,
88
+ 'valleys': valleys,
89
+ 'segments': segments,
90
+ 'window_size': window_size,
91
+ 'min_distance': min_distance,
92
+ 'iterations': iterations,
93
+ 'stats': stats
94
+ }
95
+
96
+
97
+ def _calculate_adaptive_window_size(data: np.ndarray) -> int:
98
+ """Adaptive window size calculation based on first-order difference periodicity"""
99
+ n = len(data)
100
+
101
+ if n < 10:
102
+ return 3
103
+
104
+ # Calculate first-order difference
105
+ diff_data = np.diff(data)
106
+ diff_n = len(diff_data)
107
+
108
+ try:
109
+ # Method 1: Autocorrelation of first-order difference
110
+ diff_centered = diff_data - np.mean(diff_data)
111
+ autocorr = np.correlate(diff_centered, diff_centered, mode='full')
112
+ autocorr = autocorr[autocorr.size // 2:]
113
+
114
+ # Normalize autocorrelation
115
+ if autocorr[0] > 0:
116
+ autocorr = autocorr / autocorr[0]
117
+
118
+ # Find first significant peak (excluding lag 0)
119
+ # Look for peaks with minimum height and distance
120
+ min_lag = max(2, diff_n // 50) # Minimum lag to consider
121
+ max_lag = min(diff_n // 3, 100) # Maximum lag to consider
122
+
123
+ if max_lag > min_lag:
124
+ search_autocorr = autocorr[min_lag:max_lag]
125
+ peaks_auto, properties = signal.find_peaks(
126
+ search_autocorr,
127
+ height=0.1, # Minimum correlation
128
+ distance=max(1, min_lag // 2)
129
+ )
130
+
131
+ if len(peaks_auto) > 0:
132
+ # First significant peak indicates period
133
+ period = peaks_auto[0] + min_lag
134
+ window_size = min(max(period // 2, 5), n // 4)
135
+ else:
136
+ # Fallback: find first local maximum
137
+ for i in range(1, min(50, len(search_autocorr) - 1)):
138
+ if (search_autocorr[i] > search_autocorr[i-1] and
139
+ search_autocorr[i] > search_autocorr[i+1] and
140
+ search_autocorr[i] > 0.05):
141
+ period = i + min_lag
142
+ window_size = min(max(period // 2, 5), n // 4)
143
+ break
144
+ else:
145
+ window_size = min(max(int(np.sqrt(n)), 5), n // 4)
146
+ else:
147
+ window_size = min(max(int(np.sqrt(n)), 5), n // 4)
148
+
149
+ except Exception as e:
150
+ # Fallback method: FFT-based period detection on difference
151
+ try:
152
+ # Remove DC component
153
+ diff_fft = np.fft.fft(diff_data - np.mean(diff_data))
154
+ freqs = np.fft.fftfreq(diff_n)
155
+
156
+ # Find dominant frequency (excluding DC)
157
+ power_spectrum = np.abs(diff_fft[1:diff_n//2])
158
+ if len(power_spectrum) > 0:
159
+ dominant_freq_idx = np.argmax(power_spectrum) + 1
160
+ dominant_freq = freqs[dominant_freq_idx]
161
+
162
+ if dominant_freq > 0:
163
+ period = int(1 / dominant_freq)
164
+ window_size = min(max(period // 2, 5), n // 4)
165
+ else:
166
+ window_size = min(max(int(np.sqrt(n)), 5), n // 4)
167
+ else:
168
+ window_size = min(max(int(np.sqrt(n)), 5), n // 4)
169
+ except:
170
+ window_size = min(max(int(np.sqrt(n)), 5), n // 4)
171
+
172
+ # Method 2: Statistical approach on difference
173
+ try:
174
+ # Find significant changes in first-order difference
175
+ diff_abs = np.abs(diff_data)
176
+ threshold = np.mean(diff_abs) + 0.5 * np.std(diff_abs)
177
+ change_points = np.where(diff_abs > threshold)[0]
178
+
179
+ if len(change_points) > 2:
180
+ # Calculate average distance between change points
181
+ distances = np.diff(change_points)
182
+ if len(distances) > 0:
183
+ avg_distance = np.median(distances) # Use median for robustness
184
+ window_size_v2 = min(max(int(avg_distance), 5), n // 4)
185
+ # Combine with autocorrelation result
186
+ window_size = int((window_size + window_size_v2) / 2)
187
+ except:
188
+ pass
189
+
190
+ # Ensure window size is odd and within reasonable bounds
191
+ window_size = max(3, min(window_size, n // 3))
192
+ if window_size % 2 == 0:
193
+ window_size += 1
194
+
195
+ return window_size
196
+
197
+
198
+ def _rolling_window_detection(
199
+ data: np.ndarray,
200
+ window_size: int,
201
+ min_distance: int,
202
+ prominence_threshold: float
203
+ ) -> Tuple[np.ndarray, np.ndarray]:
204
+ """基于滚动窗口的初始峰谷检测"""
205
+ n = len(data)
206
+ half_window = window_size // 2
207
+ peaks = []
208
+ valleys = []
209
+
210
+ # 计算全局统计用于突出度判断
211
+ global_std = np.std(data)
212
+ threshold = global_std * prominence_threshold
213
+
214
+ for i in range(half_window, n - half_window):
215
+ # 提取窗口数据
216
+ window_start = max(0, i - half_window)
217
+ window_end = min(n, i + half_window + 1)
218
+ window_data = data[window_start:window_end]
219
+ window_indices = np.arange(window_start, window_end)
220
+
221
+ current_value = data[i]
222
+ window_max = np.max(window_data)
223
+ window_min = np.min(window_data)
224
+
225
+ # 检测峰值
226
+ if (current_value == window_max and
227
+ current_value - window_min > threshold and
228
+ (len(peaks) == 0 or i - peaks[-1] >= min_distance)):
229
+ peaks.append(i)
230
+
231
+ # 检测谷值
232
+ elif (current_value == window_min and
233
+ window_max - current_value > threshold and
234
+ (len(valleys) == 0 or i - valleys[-1] >= min_distance)):
235
+ valleys.append(i)
236
+
237
+ return np.array(peaks), np.array(valleys)
238
+
239
+
240
+ def _iterative_peak_valley_optimization(
241
+ data: np.ndarray,
242
+ initial_peaks: np.ndarray,
243
+ initial_valleys: np.ndarray,
244
+ max_iterations: int,
245
+ verbose: bool,
246
+ outlier_method: str = 'iqr',
247
+ outlier_sensitivity: float = 1.5,
248
+ min_amplitude_ratio: float = 0.1
249
+ ) -> Tuple[np.ndarray, np.ndarray, int]:
250
+ """
251
+ 多轮迭代优化峰谷检测结果,并在结束后进行基于差值分布的后处理
252
+
253
+ Parameters:
254
+ -----------
255
+ data : np.ndarray
256
+ 输入时间序列数据
257
+ initial_peaks : np.ndarray
258
+ 初始峰值索引
259
+ initial_valleys : np.ndarray
260
+ 初始谷值索引
261
+ max_iterations : int
262
+ 最大迭代次数
263
+ verbose : bool
264
+ 是否输出详细信息
265
+ outlier_method : str
266
+ 离群点检测方法 ['iqr', 'zscore', 'percentile', 'mad', 'dbscan']
267
+ outlier_sensitivity : float
268
+ 离群点检测灵敏度参数
269
+ min_amplitude_ratio : float
270
+ 最小振幅比例(相对于数据标准差)
271
+
272
+ Returns:
273
+ --------
274
+ Tuple[np.ndarray, np.ndarray, int] : 峰值索引, 谷值索引, 迭代次数
275
+ """
276
+
277
+ peaks = initial_peaks.copy()
278
+ valleys = initial_valleys.copy()
279
+
280
+ # 原有的迭代优化过程
281
+ for iteration in range(max_iterations):
282
+ old_peaks = peaks.copy()
283
+ old_valleys = valleys.copy()
284
+
285
+ # 合并所有关键点并排序
286
+ all_points = []
287
+ for p in peaks:
288
+ all_points.append((p, 'peak', data[p]))
289
+ for v in valleys:
290
+ all_points.append((v, 'valley', data[v]))
291
+
292
+ all_points.sort(key=lambda x: x[0])
293
+
294
+ if len(all_points) < 2:
295
+ break
296
+
297
+ # 优化规则1: 确保峰谷交替
298
+ optimized_points = _enforce_alternating_pattern(all_points, data)
299
+
300
+ # 优化规则2: 确保峰是两谷间最高点,谷是两峰间最低点
301
+ optimized_points = _optimize_local_extrema(optimized_points, data)
302
+
303
+ # 分离峰谷
304
+ new_peaks = []
305
+ new_valleys = []
306
+ for point in optimized_points:
307
+ if point[1] == 'peak':
308
+ new_peaks.append(point[0])
309
+ else:
310
+ new_valleys.append(point[0])
311
+
312
+ peaks = np.array(new_peaks)
313
+ valleys = np.array(new_valleys)
314
+
315
+ if verbose:
316
+ print(f"Iteration {iteration + 1}: Peaks {len(peaks)}, Valleys {len(valleys)}")
317
+
318
+ # Check convergence
319
+ if (np.array_equal(peaks, old_peaks) and
320
+ np.array_equal(valleys, old_valleys)):
321
+ if verbose:
322
+ print(f"Converged after {iteration + 1} iterations")
323
+ break
324
+
325
+ # 新增:基于峰谷差值分布的后处理
326
+ if verbose:
327
+ print("Starting post-processing based on peak-valley amplitude distribution...")
328
+
329
+ peaks, valleys = _postprocess_amplitude_filtering(
330
+ data, peaks, valleys, outlier_method, outlier_sensitivity,
331
+ min_amplitude_ratio, verbose
332
+ )
333
+
334
+ return peaks, valleys, iteration + 1
335
+
336
+
337
+ def _postprocess_amplitude_filtering(
338
+ data: np.ndarray,
339
+ peaks: np.ndarray,
340
+ valleys: np.ndarray,
341
+ outlier_method: str,
342
+ outlier_sensitivity: float,
343
+ min_amplitude_ratio: float,
344
+ verbose: bool
345
+ ) -> Tuple[np.ndarray, np.ndarray]:
346
+ """
347
+ 基于峰谷差值分布进行后处理,过滤掉差值过小的峰谷对
348
+ """
349
+
350
+ if len(peaks) == 0 or len(valleys) == 0:
351
+ return peaks, valleys
352
+
353
+ # 1. 计算相邻峰谷之间的差值
354
+ peak_valley_pairs, amplitudes = _calculate_peak_valley_amplitudes(data, peaks, valleys)
355
+
356
+ if len(amplitudes) == 0:
357
+ return peaks, valleys
358
+
359
+ if verbose:
360
+ print(f"Found {len(amplitudes)} peak-valley pairs")
361
+ print(f"Amplitude statistics: mean={np.mean(amplitudes):.3f}, std={np.std(amplitudes):.3f}")
362
+ print(f"Amplitude range: [{np.min(amplitudes):.3f}, {np.max(amplitudes):.3f}]")
363
+
364
+ # 2. 检测差值过小的离群点
365
+ outlier_indices = _detect_amplitude_outliers(
366
+ amplitudes, outlier_method, outlier_sensitivity, verbose
367
+ )
368
+
369
+ # 3. 应用最小振幅比例过滤
370
+ data_std = np.std(data)
371
+ min_amplitude = min_amplitude_ratio * data_std
372
+ small_amplitude_indices = np.where(amplitudes < min_amplitude)[0]
373
+
374
+ # 合并两种过滤方法的结果
375
+ all_outlier_indices = np.unique(np.concatenate([outlier_indices, small_amplitude_indices]))
376
+
377
+ if verbose and len(all_outlier_indices) > 0:
378
+ print(f"Detected {len(outlier_indices)} statistical outliers")
379
+ print(f"Detected {len(small_amplitude_indices)} small amplitude pairs (< {min_amplitude:.3f})")
380
+ print(f"Total pairs to filter: {len(all_outlier_indices)}")
381
+
382
+ # 4. 根据离群点删除相应的峰谷点
383
+ if len(all_outlier_indices) > 0:
384
+ peaks, valleys = _remove_outlier_peak_valley_pairs(
385
+ data, peaks, valleys, peak_valley_pairs, all_outlier_indices, verbose
386
+ )
387
+
388
+ # 5. 确保最终结果满足峰谷相间且谷是峰间最低值的要求
389
+ peaks, valleys = _final_peak_valley_validation(data, peaks, valleys, verbose)
390
+
391
+ return peaks, valleys
392
+
393
+
394
+ def _calculate_peak_valley_amplitudes(
395
+ data: np.ndarray,
396
+ peaks: np.ndarray,
397
+ valleys: np.ndarray
398
+ ) -> Tuple[List[Tuple], np.ndarray]:
399
+ """
400
+ 计算相邻峰谷之间的差值(振幅)
401
+
402
+ Returns:
403
+ --------
404
+ peak_valley_pairs : List[Tuple]
405
+ 每个元素为 (peak_idx, valley_idx, amplitude, pair_type)
406
+ pair_type: 'peak_to_valley' 或 'valley_to_peak'
407
+ amplitudes : np.ndarray
408
+ 所有振幅值的数组
409
+ """
410
+
411
+ # 合并峰谷点并排序
412
+ all_extrema = []
413
+ for p in peaks:
414
+ all_extrema.append((p, 'peak', data[p]))
415
+ for v in valleys:
416
+ all_extrema.append((v, 'valley', data[v]))
417
+
418
+ all_extrema.sort(key=lambda x: x[0])
419
+
420
+ peak_valley_pairs = []
421
+ amplitudes = []
422
+
423
+ # 计算相邻极值点之间的振幅
424
+ for i in range(len(all_extrema) - 1):
425
+ current = all_extrema[i]
426
+ next_point = all_extrema[i + 1]
427
+
428
+ # 只计算峰谷相邻的情况
429
+ if current[1] != next_point[1]:
430
+ amplitude = abs(current[2] - next_point[2])
431
+ pair_type = f"{current[1]}_to_{next_point[1]}"
432
+
433
+ peak_valley_pairs.append((
434
+ current[0] if current[1] == 'peak' else next_point[0], # peak_idx
435
+ current[0] if current[1] == 'valley' else next_point[0], # valley_idx
436
+ amplitude,
437
+ pair_type
438
+ ))
439
+ amplitudes.append(amplitude)
440
+
441
+ return peak_valley_pairs, np.array(amplitudes)
442
+
443
+
444
+ def _detect_amplitude_outliers(
445
+ amplitudes: np.ndarray,
446
+ method: str,
447
+ sensitivity: float,
448
+ verbose: bool
449
+ ) -> np.ndarray:
450
+ """
451
+ 检测振幅中的离群点(差值过小的点)
452
+
453
+ Parameters:
454
+ -----------
455
+ amplitudes : np.ndarray
456
+ 振幅数组
457
+ method : str
458
+ 检测方法 ['iqr', 'zscore', 'percentile', 'mad', 'dbscan']
459
+ sensitivity : float
460
+ 灵敏度参数
461
+ verbose : bool
462
+ 是否输出详细信息
463
+
464
+ Returns:
465
+ --------
466
+ np.ndarray : 离群点的索引
467
+ """
468
+
469
+ if len(amplitudes) < 3:
470
+ return np.array([])
471
+
472
+ outlier_indices = []
473
+
474
+ if method == 'iqr':
475
+ # IQR方法:检测下四分位数以下的异常小值
476
+ q1 = np.percentile(amplitudes, 25)
477
+ q3 = np.percentile(amplitudes, 75)
478
+ iqr = q3 - q1
479
+ lower_bound = q1 - sensitivity * iqr
480
+
481
+ outlier_indices = np.where(amplitudes < lower_bound)[0]
482
+
483
+ if verbose:
484
+ print(f"IQR method: Q1={q1:.3f}, Q3={q3:.3f}, IQR={iqr:.3f}")
485
+ print(f"Lower bound: {lower_bound:.3f}")
486
+
487
+ elif method == 'zscore':
488
+ # Z-score方法:检测标准化后绝对值过大的点(但这里我们关注小值)
489
+ z_scores = np.abs(stats.zscore(amplitudes))
490
+ mean_amp = np.mean(amplitudes)
491
+
492
+ # 找出既是统计离群点又是小于均值的点
493
+ small_values = amplitudes < mean_amp
494
+ statistical_outliers = z_scores > sensitivity
495
+ outlier_indices = np.where(small_values & statistical_outliers)[0]
496
+
497
+ if verbose:
498
+ print(f"Z-score method: mean={mean_amp:.3f}, threshold={sensitivity}")
499
+
500
+ elif method == 'percentile':
501
+ # 百分位数方法:直接取最小的sensitivity比例的点
502
+ threshold_percentile = sensitivity * 100 if sensitivity <= 1 else sensitivity
503
+ threshold_value = np.percentile(amplitudes, threshold_percentile)
504
+ outlier_indices = np.where(amplitudes <= threshold_value)[0]
505
+
506
+ if verbose:
507
+ print(f"Percentile method: {threshold_percentile:.1f}th percentile = {threshold_value:.3f}")
508
+
509
+ elif method == 'mad':
510
+ # MAD (Median Absolute Deviation) 方法
511
+ median_amp = np.median(amplitudes)
512
+ mad = np.median(np.abs(amplitudes - median_amp))
513
+
514
+ if mad > 0:
515
+ modified_z_scores = 0.6745 * (amplitudes - median_amp) / mad
516
+ # 找出负的modified z-scores中绝对值较大的(即明显小于中位数的)
517
+ outlier_indices = np.where(modified_z_scores < -sensitivity)[0]
518
+ else:
519
+ outlier_indices = np.array([])
520
+
521
+ if verbose:
522
+ print(f"MAD method: median={median_amp:.3f}, MAD={mad:.3f}")
523
+
524
+ elif method == 'dbscan':
525
+ # DBSCAN聚类方法(需要sklearn)
526
+ try:
527
+ from sklearn.cluster import DBSCAN
528
+
529
+ # 将振幅作为一维特征进行聚类
530
+ X = amplitudes.reshape(-1, 1)
531
+
532
+ # 调整eps参数基于sensitivity
533
+ eps = sensitivity * np.std(amplitudes)
534
+ min_samples = max(2, len(amplitudes) // 10)
535
+
536
+ dbscan = DBSCAN(eps=eps, min_samples=min_samples)
537
+ labels = dbscan.fit_predict(X)
538
+
539
+ # 找出被标记为噪声的点(label = -1)和小振幅的聚类
540
+ noise_points = np.where(labels == -1)[0]
541
+
542
+ # 在非噪声点中,找出平均值最小的聚类
543
+ unique_labels = np.unique(labels[labels != -1])
544
+ if len(unique_labels) > 1:
545
+ cluster_means = []
546
+ for label in unique_labels:
547
+ cluster_indices = np.where(labels == label)[0]
548
+ cluster_mean = np.mean(amplitudes[cluster_indices])
549
+ cluster_means.append((label, cluster_mean))
550
+
551
+ # 找出平均振幅最小的聚类
552
+ min_cluster_label = min(cluster_means, key=lambda x: x[1])[0]
553
+ min_cluster_indices = np.where(labels == min_cluster_label)[0]
554
+
555
+ outlier_indices = np.concatenate([noise_points, min_cluster_indices])
556
+ else:
557
+ outlier_indices = noise_points
558
+
559
+ if verbose:
560
+ print(f"DBSCAN method: eps={eps:.3f}, min_samples={min_samples}")
561
+ print(f"Found {len(unique_labels)} clusters and {len(noise_points)} noise points")
562
+
563
+ except ImportError:
564
+ if verbose:
565
+ print("DBSCAN method requires sklearn, falling back to IQR method")
566
+ return _detect_amplitude_outliers(amplitudes, 'iqr', sensitivity, verbose)
567
+
568
+ else:
569
+ raise ValueError(f"Unknown outlier detection method: {method}")
570
+
571
+ if verbose and len(outlier_indices) > 0:
572
+ outlier_amplitudes = amplitudes[outlier_indices]
573
+ print(f"Detected {len(outlier_indices)} outliers with amplitudes: {outlier_amplitudes}")
574
+
575
+ return np.array(outlier_indices)
576
+
577
+
578
+ def _remove_outlier_peak_valley_pairs(
579
+ data: np.ndarray,
580
+ peaks: np.ndarray,
581
+ valleys: np.ndarray,
582
+ peak_valley_pairs: List[Tuple],
583
+ outlier_indices: np.ndarray,
584
+ verbose: bool
585
+ ) -> Tuple[np.ndarray, np.ndarray]:
586
+ """
587
+ 根据离群点索引删除相应的峰谷点
588
+ """
589
+
590
+ points_to_remove = set()
591
+
592
+ for idx in outlier_indices:
593
+ if idx < len(peak_valley_pairs):
594
+ pair = peak_valley_pairs[idx]
595
+ peak_idx, valley_idx = pair[0], pair[1]
596
+
597
+ # 优先删除谷点,如果谷点被多个峰共享,则可能需要合并峰
598
+ points_to_remove.add(('valley', valley_idx))
599
+
600
+ if verbose:
601
+ print(f"Marking for removal - Peak: {peak_idx}, Valley: {valley_idx}, "
602
+ f"Amplitude: {pair[2]:.3f}")
603
+
604
+ # 删除标记的谷点
605
+ valleys_to_keep = []
606
+ for v in valleys:
607
+ if ('valley', v) not in points_to_remove:
608
+ valleys_to_keep.append(v)
609
+
610
+ new_valleys = np.array(valleys_to_keep)
611
+
612
+ # 处理峰点:如果相邻的峰之间的谷被删除了,需要合并峰点(保留更高的)
613
+ new_peaks = _merge_adjacent_peaks(data, peaks, new_valleys, verbose)
614
+
615
+ if verbose:
616
+ print(f"After outlier removal: Peaks {len(peaks)} -> {len(new_peaks)}, "
617
+ f"Valleys {len(valleys)} -> {len(new_valleys)}")
618
+
619
+ return new_peaks, new_valleys
620
+
621
+
622
+ def _merge_adjacent_peaks(
623
+ data: np.ndarray,
624
+ peaks: np.ndarray,
625
+ valleys: np.ndarray,
626
+ verbose: bool
627
+ ) -> np.ndarray:
628
+ """
629
+ 合并相邻的峰点(当它们之间没有谷点时)
630
+ """
631
+
632
+ if len(peaks) <= 1:
633
+ return peaks
634
+
635
+ # 创建所有极值点的排序列表
636
+ all_points = []
637
+ for p in peaks:
638
+ all_points.append((p, 'peak'))
639
+ for v in valleys:
640
+ all_points.append((v, 'valley'))
641
+
642
+ all_points.sort(key=lambda x: x[0])
643
+
644
+ # 找出相邻的峰点并合并
645
+ merged_peaks = []
646
+ i = 0
647
+
648
+ while i < len(all_points):
649
+ if all_points[i][1] == 'peak':
650
+ # 收集连续的峰点
651
+ consecutive_peaks = [all_points[i][0]]
652
+ j = i + 1
653
+
654
+ while j < len(all_points) and all_points[j][1] == 'peak':
655
+ consecutive_peaks.append(all_points[j][0])
656
+ j += 1
657
+
658
+ # 在连续的峰点中保留最高的
659
+ if len(consecutive_peaks) > 1:
660
+ peak_values = [data[p] for p in consecutive_peaks]
661
+ best_peak_idx = consecutive_peaks[np.argmax(peak_values)]
662
+ merged_peaks.append(best_peak_idx)
663
+
664
+ if verbose:
665
+ print(f"Merged {len(consecutive_peaks)} consecutive peaks, "
666
+ f"kept peak at index {best_peak_idx} with value {data[best_peak_idx]:.3f}")
667
+ else:
668
+ merged_peaks.append(consecutive_peaks[0])
669
+
670
+ i = j
671
+ else:
672
+ i += 1
673
+
674
+ return np.array(merged_peaks)
675
+
676
+
677
+ def _final_peak_valley_validation(
678
+ data: np.ndarray,
679
+ peaks: np.ndarray,
680
+ valleys: np.ndarray,
681
+ verbose: bool
682
+ ) -> Tuple[np.ndarray, np.ndarray]:
683
+ """
684
+ 最终验证:确保峰谷相间且谷是峰间的最低值
685
+ """
686
+
687
+ if len(peaks) == 0 or len(valleys) == 0:
688
+ return peaks, valleys
689
+
690
+ # 创建交替的峰谷序列
691
+ all_points = []
692
+ for p in peaks:
693
+ all_points.append((p, 'peak'))
694
+ for v in valleys:
695
+ all_points.append((v, 'valley'))
696
+
697
+ all_points.sort(key=lambda x: x[0])
698
+
699
+ # 确保峰谷交替
700
+ validated_points = []
701
+ if len(all_points) > 0:
702
+ validated_points.append(all_points[0])
703
+
704
+ for i in range(1, len(all_points)):
705
+ current = all_points[i]
706
+ prev = validated_points[-1]
707
+
708
+ if current[1] != prev[1]: # 类型不同,保留
709
+ validated_points.append(current)
710
+ else: # 类型相同,保留更极端的
711
+ if current[1] == 'peak':
712
+ if data[current[0]] > data[prev[0]]:
713
+ validated_points[-1] = current
714
+ else: # valley
715
+ if data[current[0]] < data[prev[0]]:
716
+ validated_points[-1] = current
717
+
718
+ # 分离最终的峰谷
719
+ final_peaks = []
720
+ final_valleys = []
721
+
722
+ for point in validated_points:
723
+ if point[1] == 'peak':
724
+ final_peaks.append(point[0])
725
+ else:
726
+ final_valleys.append(point[0])
727
+
728
+ # 验证谷是峰间的最低值
729
+ final_valleys = _validate_valleys_between_peaks(data, final_peaks, final_valleys, verbose)
730
+
731
+ if verbose:
732
+ print(f"Final validation: Peaks {len(peaks)} -> {len(final_peaks)}, "
733
+ f"Valleys {len(valleys)} -> {len(final_valleys)}")
734
+
735
+ return np.array(final_peaks), np.array(final_valleys)
736
+
737
+
738
+ def _validate_valleys_between_peaks(
739
+ data: np.ndarray,
740
+ peaks: np.ndarray,
741
+ valleys: np.ndarray,
742
+ verbose: bool
743
+ ) -> np.ndarray:
744
+ """
745
+ 验证每个谷点确实是相邻峰点之间的最低点
746
+ """
747
+
748
+ if len(peaks) < 2 or len(valleys) == 0:
749
+ return valleys
750
+
751
+ validated_valleys = []
752
+ peaks_sorted = np.sort(peaks)
753
+
754
+ for i in range(len(peaks_sorted) - 1):
755
+ left_peak = peaks_sorted[i]
756
+ right_peak = peaks_sorted[i + 1]
757
+
758
+ # 找出在这两个峰之间的谷点
759
+ between_valleys = [v for v in valleys if left_peak < v < right_peak]
760
+
761
+ if len(between_valleys) == 0:
762
+ # 如果没有谷点,在这个区间找最低点
763
+ search_start = left_peak + 1
764
+ search_end = right_peak
765
+ if search_start < search_end:
766
+ segment = data[search_start:search_end]
767
+ min_idx = np.argmin(segment) + search_start
768
+ validated_valleys.append(min_idx)
769
+ if verbose:
770
+ print(f"Added missing valley at index {min_idx} between peaks {left_peak} and {right_peak}")
771
+
772
+ elif len(between_valleys) == 1:
773
+ # 验证这个谷点是否真的是最低的
774
+ valley_idx = between_valleys[0]
775
+ search_start = left_peak + 1
776
+ search_end = right_peak
777
+
778
+ if search_start < search_end:
779
+ segment = data[search_start:search_end]
780
+ true_min_idx = np.argmin(segment) + search_start
781
+
782
+ if true_min_idx == valley_idx:
783
+ validated_valleys.append(valley_idx)
784
+ else:
785
+ validated_valleys.append(true_min_idx)
786
+ if verbose:
787
+ print(f"Corrected valley position from {valley_idx} to {true_min_idx}")
788
+ else:
789
+ validated_valleys.append(valley_idx)
790
+
791
+ else:
792
+ # 多个谷点,保留最低的
793
+ valley_values = [data[v] for v in between_valleys]
794
+ best_valley = between_valleys[np.argmin(valley_values)]
795
+ validated_valleys.append(best_valley)
796
+
797
+ if verbose:
798
+ print(f"Multiple valleys between peaks {left_peak} and {right_peak}, "
799
+ f"kept valley at {best_valley}")
800
+
801
+ return np.array(validated_valleys)
802
+
803
+
804
+ # 需要同时导入的辅助函数(保持原有实现)
805
+ def _enforce_alternating_pattern(all_points: List, data: np.ndarray) -> List:
806
+ """确保峰谷交替出现"""
807
+ if len(all_points) < 2:
808
+ return all_points
809
+
810
+ optimized = [all_points[0]]
811
+
812
+ for i in range(1, len(all_points)):
813
+ current = all_points[i]
814
+ prev = optimized[-1]
815
+
816
+ # 如果类型相同,保留值更极端的点
817
+ if current[1] == prev[1]:
818
+ if current[1] == 'peak':
819
+ # 保留更高的峰
820
+ if current[2] > prev[2]:
821
+ optimized[-1] = current
822
+ else:
823
+ # 保留更低的谷
824
+ if current[2] < prev[2]:
825
+ optimized[-1] = current
826
+ else:
827
+ optimized.append(current)
828
+
829
+ return optimized
830
+
831
+
832
+ def _optimize_local_extrema(points: List, data: np.ndarray) -> List:
833
+ """优化局部极值点位置"""
834
+ if len(points) < 3:
835
+ return points
836
+
837
+ optimized = [points[0]]
838
+
839
+ for i in range(1, len(points) - 1):
840
+ current = points[i]
841
+ prev_idx = optimized[-1][0]
842
+ next_idx = points[i + 1][0]
843
+
844
+ # 在相邻点之间寻找真正的极值
845
+ search_start = max(prev_idx + 1, current[0] - 5)
846
+ search_end = min(next_idx, current[0] + 6)
847
+
848
+ if search_start >= search_end:
849
+ optimized.append(current)
850
+ continue
851
+
852
+ search_range = range(search_start, search_end)
853
+ search_data = data[search_start:search_end]
854
+
855
+ if current[1] == 'peak':
856
+ # 寻找最高点
857
+ max_idx = np.argmax(search_data)
858
+ actual_idx = search_start + max_idx
859
+ optimized.append((actual_idx, 'peak', data[actual_idx]))
860
+ else:
861
+ # 寻找最低点
862
+ min_idx = np.argmin(search_data)
863
+ actual_idx = search_start + min_idx
864
+ optimized.append((actual_idx, 'valley', data[actual_idx]))
865
+
866
+ optimized.append(points[-1])
867
+
868
+
869
+
870
+ def _enforce_alternating_pattern(all_points: List, data: np.ndarray) -> List:
871
+ """确保峰谷交替出现"""
872
+ if len(all_points) < 2:
873
+ return all_points
874
+
875
+ optimized = [all_points[0]]
876
+
877
+ for i in range(1, len(all_points)):
878
+ current = all_points[i]
879
+ prev = optimized[-1]
880
+
881
+ # 如果类型相同,保留值更极端的点
882
+ if current[1] == prev[1]:
883
+ if current[1] == 'peak':
884
+ # 保留更高的峰
885
+ if current[2] > prev[2]:
886
+ optimized[-1] = current
887
+ else:
888
+ # 保留更低的谷
889
+ if current[2] < prev[2]:
890
+ optimized[-1] = current
891
+ else:
892
+ optimized.append(current)
893
+
894
+ return optimized
895
+
896
+
897
+ def _optimize_local_extrema(points: List, data: np.ndarray) -> List:
898
+ """优化局部极值点位置"""
899
+ if len(points) < 3:
900
+ return points
901
+
902
+ optimized = [points[0]]
903
+
904
+ for i in range(1, len(points) - 1):
905
+ current = points[i]
906
+ prev_idx = optimized[-1][0]
907
+ next_idx = points[i + 1][0]
908
+
909
+ # 在相邻点之间寻找真正的极值
910
+ search_start = max(prev_idx + 1, current[0] - 5)
911
+ search_end = min(next_idx, current[0] + 6)
912
+
913
+ if search_start >= search_end:
914
+ optimized.append(current)
915
+ continue
916
+
917
+ search_range = range(search_start, search_end)
918
+ search_data = data[search_start:search_end]
919
+
920
+ if current[1] == 'peak':
921
+ # 寻找最高点
922
+ max_idx = np.argmax(search_data)
923
+ actual_idx = search_start + max_idx
924
+ optimized.append((actual_idx, 'peak', data[actual_idx]))
925
+ else:
926
+ # 寻找最低点
927
+ min_idx = np.argmin(search_data)
928
+ actual_idx = search_start + min_idx
929
+ optimized.append((actual_idx, 'valley', data[actual_idx]))
930
+
931
+ optimized.append(points[-1])
932
+
933
+ return optimized
934
+
935
+
936
+ def _generate_segments(peaks: np.ndarray, valleys: np.ndarray, data_length: int) -> List[Tuple[int, int]]:
937
+ """生成序列分段"""
938
+ all_points = []
939
+ for p in peaks:
940
+ all_points.append(p)
941
+ for v in valleys:
942
+ all_points.append(v)
943
+
944
+ all_points = sorted(all_points)
945
+
946
+ segments = []
947
+ start = 0
948
+
949
+ for point in all_points:
950
+ if point > start:
951
+ segments.append((start, point))
952
+ start = point
953
+
954
+ # 添加最后一段
955
+ if start < data_length - 1:
956
+ segments.append((start, data_length - 1))
957
+
958
+ return segments
959
+
960
+
961
+ def _calculate_statistics(data: np.ndarray, peaks: np.ndarray, valleys: np.ndarray) -> Dict:
962
+ """计算统计信息"""
963
+ stats = {
964
+ 'peak_count': len(peaks),
965
+ 'valley_count': len(valleys),
966
+ 'peak_values': data[peaks] if len(peaks) > 0 else np.array([]),
967
+ 'valley_values': data[valleys] if len(valleys) > 0 else np.array([]),
968
+ }
969
+
970
+ if len(peaks) > 0:
971
+ stats['avg_peak_value'] = np.mean(data[peaks])
972
+ stats['max_peak_value'] = np.max(data[peaks])
973
+ stats['min_peak_value'] = np.min(data[peaks])
974
+
975
+ if len(valleys) > 0:
976
+ stats['avg_valley_value'] = np.mean(data[valleys])
977
+ stats['max_valley_value'] = np.max(data[valleys])
978
+ stats['min_valley_value'] = np.min(data[valleys])
979
+
980
+ # 计算平均间距
981
+ if len(peaks) > 1:
982
+ stats['avg_peak_distance'] = np.mean(np.diff(peaks))
983
+ if len(valleys) > 1:
984
+ stats['avg_valley_distance'] = np.mean(np.diff(valleys))
985
+
986
+ return stats
987
+
988
+
989
+ def plot_results(data: np.ndarray, result: Dict, title: str = "Peak Valley Detection", save_path: str = None):
990
+ """Plot detection results"""
991
+ plt.figure(figsize=(15, 8))
992
+
993
+ # Main plot
994
+ plt.subplot(2, 1, 1)
995
+ plt.plot(data, 'b-', linewidth=1.5, label='Original Data', alpha=0.7)
996
+
997
+ peaks = result['peaks']
998
+ valleys = result['valleys']
999
+
1000
+ if len(peaks) > 0:
1001
+ # Ensure peaks are valid indices
1002
+ valid_peaks = peaks[peaks < len(data)]
1003
+ if len(valid_peaks) > 0:
1004
+ plt.plot(valid_peaks, [data[k] for k in valid_peaks], 'ro',
1005
+ markersize=8, label=f'Peaks ({len(valid_peaks)})')
1006
+
1007
+ if len(valleys) > 0:
1008
+ # Ensure valleys are valid indices
1009
+ valid_valleys = valleys[valleys < len(data)]
1010
+ if len(valid_valleys) > 0:
1011
+ plt.plot(valid_valleys, [data[k] for k in valid_valleys], 'go',
1012
+ markersize=8, label=f'Valleys ({len(valid_valleys)})')
1013
+
1014
+ plt.title(f'{title} (Window: {result["window_size"]}, Iterations: {result["iterations"]})')
1015
+ plt.xlabel('Time')
1016
+ plt.ylabel('Value')
1017
+ plt.legend()
1018
+ plt.grid(True, alpha=0.3)
1019
+
1020
+ # Segmentation plot
1021
+ plt.subplot(2, 1, 2)
1022
+ segments = result['segments']
1023
+ colors = plt.cm.Set3(np.linspace(0, 1, max(len(segments), 1)))
1024
+
1025
+ for i, (start, end) in enumerate(segments):
1026
+ # Ensure segment indices are valid
1027
+ start = max(0, min(start, len(data) - 1))
1028
+ end = max(start, min(end, len(data) - 1))
1029
+
1030
+ if start < end:
1031
+ plt.plot(range(start, end + 1), data[start:end + 1],
1032
+ color=colors[i % len(colors)], linewidth=2, label=f'Segment {i+1}')
1033
+ elif start == end:
1034
+ plt.plot([start], [data[start]], 'o',
1035
+ color=colors[i % len(colors)], markersize=6, label=f'Segment {i+1}')
1036
+
1037
+ plt.title('Sequence Segmentation')
1038
+ plt.xlabel('Time')
1039
+ plt.ylabel('Value')
1040
+ if len(segments) <= 10: # Only show legend if not too many segments
1041
+ plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
1042
+ plt.grid(True, alpha=0.3)
1043
+
1044
+ plt.tight_layout()
1045
+
1046
+ if save_path:
1047
+ plt.savefig(save_path, dpi=300, bbox_inches='tight')
1048
+ print(f"Plot saved to: {save_path}")
1049
+ else:
1050
+ plt.show()
1051
+
1052
+
1053
+ def demo():
1054
+ """Demo function"""
1055
+
1056
+ value_list=[0.0, 0.2, -0.02, -0.04, 0.141, -0.059, 0.301, 0.7, 1.137, 1.769, 2.418, 2.906, 3.333, 3.623, 4.567, 4.644, 6.15, 6.638, 7.777, 11.19, 12.895, 13.853, 13.853, 12.854, 11.599, 9.813, 8.298, 7.454, 6.159, 7.491, 6.714, 5.707, 5.707, 7.027, 3.624, 1.831, 2.283, 3.162, 0.799, 1.593, 1.593, 8.6, 12.31, 15.73, 19.388, 21.564, 18.333, 15.311, 11.856, 9.317, 0.811, -12.818, -13.81, -14.243, -14.563, -14.792, -14.562, -14.241, -13.762, -13.102, -13.532, -13.804, -14.032, -14.26, -14.031, -13.803, -13.576, -13.803, -13.621, -13.621, -13.393, -13.824, -14.553, -14.301, -14.004, -14.232, -13.82, -13.502, -8.576, -9.444, -9.444, -9.576, -9.598, -9.861, -9.751, -9.795, -9.114, -9.55, -9.769, -9.55, -10.054, -9.724, -9.987, -9.833, -10.053, -10.273, -10.559, -10.958, -11.179, -10.89, -10.669, -10.447, -10.204, -10.204, -9.984, -9.588, -8.843, -8.56, -7.561, -6.464, -6.464, -6.464, -5.846, -5.571, -5.149, -4.749, -4.267, -4.059, -3.851, -3.955, -3.726, -3.498, -3.291, -3.084, -2.837, -1.52, -1.317, -0.811, -0.226, 0.295, 1.312, 1.707, 2.788, 3.877, 11.278, 10.444, 10.444, 9.119, 9.119, 9.119, 12.045, 15.475, 18.079, 16.653, 13.92, 16.571, 14.335, 11.217, -0.414, -0.414, -0.856, -0.614, -0.412, 0.13, 0.829, 0.829, 0.829, 0.829, 0.829, 0.829, 0.829, 0.829, 0.829, 0.829, 1.682, 1.682, 1.682, 1.996, 2.408, 2.896, 3.129, 3.323, 3.516, 3.709, 3.921, 3.729, 3.921, 4.229, 4.803, 5.565, 6.415, 7.519, 8.352, 8.352, 8.352, 8.755, 8.755, 8.755, 8.755, 9.813, 10.787, 10.413, 10.95, 11.342, 11.324, 11.271, 11.129, 10.987, 10.88, 10.506, 10.148, 10.615, 11.187, 11.844, 12.373, 13.022, 13.613, 13.959, 14.303, 15.108, 20.66, 20.041, 20.041, 20.041, 20.041, 21.321, 23.713, 25.559, 28.015, 26.691, 25.166, 23.894, 25.066, 15.429, 15.598, 15.784, 15.616, 15.548, 15.227, 15.058, 14.888, 14.718, 14.547, 14.718, 14.889, 15.093, 14.923, 14.753, 14.923, 15.093, 15.263, 15.839, 15.671, 15.84, 15.671, 15.469, 15.638, 15.638, 16.195, 16.379, 16.195, 16.195, 16.38, 16.58, 17.031, 17.529, 18.106, 18.319, 18.531, 18.759, 18.971, 19.116, 19.246, 20.215, 20.215, 20.534, 20.979, 21.358, 22.79, 23.577, 22.813, 23.338, 23.645, 23.645, 24.316, 24.316, 25.83, 25.83, 25.83, 25.83, 28.708, 30.889, 32.161, 31.089, 29.642, 24.351, 25.319, 26.231, 22.837, 22.39, 22.033, 21.814, 22.002, 22.189, 22.454, 22.624, 22.795, 23.011, 22.564, 22.502, 22.719, 23.121, 23.213, 23.398, 23.612, 23.887, 24.496, 24.813, 25.565, 26.801, 32.159, 33.76, 33.839, 33.839, 33.839, 34.713, 35.796, 37.402, 36.513, 35.675, 36.009, 36.534, 36.762, 37.003, 37.683, 38.032, 38.032, 38.317, 38.662, 39.448, 36.614, 36.322, 38.907, 38.907, 38.907, 38.907, 38.907, 40.435, 42.496, 43.347, 42.35, 40.816, 31.737, 30.932, 18.983, 18.691, 18.529, 18.675, 18.919, 19.519, 19.68, 19.889, 20.049, 20.417, 20.035, 20.195, 20.419, 20.848, 21.133, 21.465, 22.124, 23.028, 23.643, 24.544, 23.397, 23.673, 24.498, 24.498, 23.622, 23.622, 23.622, 24.92, 26.302, 26.921, 26.029, 26.429, 26.576, 26.884, 27.25, 27.686, 27.325, 27.063, 28.449, 29.179, 30.085, 30.728, 31.31, 31.942, 31.942, 37.033, 38.683, 41.307, 40.391, 39.318, 38.505, 32.454, 22.12, 21.948, 21.792, 22.027, 22.183, 22.494, 22.727, 22.835, 22.989, 23.143, 23.297, 23.481, 23.221, 23.236, 23.236, 23.482, 23.91, 24.215, 24.381, 25.243, 27.202, 30.871, 30.871, 30.871, 30.871, 33.111, 35.465, 35.904, 36.058, 36.314, 36.569, 36.759, 37.062, 37.314, 37.527, 37.765, 38.648, 39.029, 39.565, 40.303, 41.186, 41.516, 42.007, 42.575, 45.63, 45.63, 45.63, 45.63, 46.304, 47.958, 48.864, 47.596, 46.631, 45.425, 35.842, 35.649, 35.495, 35.714, 35.984, 36.151, 36.546, 36.851, 37.104, 37.506, 37.719, 38.217, 38.353, 38.772, 39.886, 40.536, 40.785, 42.68, 45.007, 45.007, 46.041, 47.164, 47.597, 47.859, 48.099, 48.317, 48.544, 48.822, 49.016, 49.129, 49.332, 49.444, 49.626, 50.24, 50.688, 51.507, 51.72, 53.506, 53.218, 53.218, 53.218, 53.218, 55.791, 57.506, 58.305, 57.288, 56.545, 55.78, 49.501, 49.662, 49.562, 49.662, 49.481, 49.582, 49.683, 49.864, 49.995, 50.275, 50.662, 50.899, 50.998, 50.89, 51.528, 51.722, 51.877, 51.982, 52.117, 52.117, 52.222, 52.71, 53.059, 53.059, 53.407, 53.407, 53.407, 53.407, 55.317, 55.407, 55.041, 54.933, 54.735, 54.554, 54.772, 54.916, 55.025, 54.935, 55.034, 55.807, 55.63, 55.453, 55.453, 55.631, 55.8, 56.489, 55.985, 55.069, 55.438, 57.167, 57.167, 57.167, 57.886, 58.493, 59.854, 60.633, 59.924, 58.858, 51.535, 51.642, 51.477, 51.293, 51.117, 50.961, 50.863, 50.863, 50.529, 50.638, 50.391, 50.54, 50.441, 50.342, 50.332, 50.332, 50.332, 50.332, 50.332]
1057
+ data=value_list
1058
+
1059
+ print("=" * 50)
1060
+ print("Adaptive Peak Valley Detection Demo")
1061
+ print("=" * 50)
1062
+
1063
+ # Run detection
1064
+ result = adaptive_peak_valley_detection(
1065
+ data,
1066
+ window_size=None, # Adaptive window size
1067
+ verbose=True,
1068
+ min_distance=10,
1069
+ prominence_threshold=0.01,
1070
+ )
1071
+
1072
+ print(f"\nDetection Results:")
1073
+ print(f"Peak count: {result['stats']['peak_count']}")
1074
+ print(f"Valley count: {result['stats']['valley_count']}")
1075
+ print(f"Segment count: {len(result['segments'])}")
1076
+
1077
+ if result['stats']['peak_count'] > 0:
1078
+ print(f"Average peak value: {result['stats']['avg_peak_value']:.2f}")
1079
+ print(f"Average peak distance: {result['stats'].get('avg_peak_distance', 0):.1f}")
1080
+
1081
+ if result['stats']['valley_count'] > 0:
1082
+ print(f"Average valley value: {result['stats']['avg_valley_value']:.2f}")
1083
+ print(f"Average valley distance: {result['stats'].get('avg_valley_distance', 0):.1f}")
1084
+
1085
+ # Plot results
1086
+ plot_results(data, result, save_path='demo_result.png') # Set save_path if needed
1087
+
1088
+ return result
1089
+
1090
+
1091
+ if __name__ == "__main__":
1092
+ demo()
VLAC/evo_vlac/utils/model_utils.py ADDED
@@ -0,0 +1,956 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from swift.llm import (
3
+ get_model_tokenizer, get_template, ModelType, load_dataset, EncodePreprocessor
4
+ )
5
+ from swift.utils import seed_everything
6
+ from swift.tuners import Swift
7
+ from typing import Any, Dict, List, Mapping, Optional, Tuple, Union,Literal
8
+ from swift.llm import RequestConfig,InferRequest,TemplateInputs
9
+ import torch
10
+ from loguru import logger
11
+ import copy
12
+ from PIL import Image
13
+ import sys
14
+ import os
15
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
16
+ from data_processing_vlm import DataProcessor,trojectory_example_prompt,denormalize_with_params
17
+ from video_tool import images_get_from_video, video_trajectory
18
+ import tqdm
19
+ import math
20
+ from collections import defaultdict
21
+ import heapq
22
+ from scipy.spatial import cKDTree
23
+ from scipy.stats import spearmanr
24
+ import random
25
+ import numpy as np
26
+ import requests
27
+ import base64
28
+ from io import BytesIO
29
+ import re
30
+
31
+ def clip_one(image):
32
+ width, height = image.size
33
+
34
+ if width > height:
35
+ left = (width - height) // 2
36
+ right = left + height
37
+ top = 0
38
+ bottom = height
39
+ else:
40
+ top = (height - width) // 2
41
+ bottom = top + width
42
+ left = 0
43
+ right = width
44
+ square_image = image.crop((left, top, right, bottom))
45
+ image=square_image
46
+ return image
47
+
48
+ def to_device(data: Any, device: Union[str, torch.device, int]) -> Any:
49
+ """Move inputs to a device"""
50
+ if isinstance(data, Mapping):
51
+ return type(data)({k: to_device(v, device) for k, v in data.items()})
52
+ elif isinstance(data, (tuple, list)):
53
+ return type(data)(to_device(v, device) for v in data)
54
+ elif isinstance(data, torch.Tensor):
55
+ return data.to(device=device)
56
+ else:
57
+ return data
58
+
59
+
60
+ class GAC_model():
61
+ def __init__(self,tag='critic'):
62
+ self.tag=tag
63
+ self.temperature=1
64
+ self.max_tokens=10240
65
+ self.do_sample=True
66
+ self.top_logprobs=10
67
+ self.logprobs=True
68
+ self.top_k=None
69
+ self.system_prompt=None
70
+ self.action_data={}
71
+ self.critic_data={}
72
+ self.sft_dataset=None
73
+ self.dataclient=DataProcessor()
74
+ self.dataclient.prompt_templete['v3']="Image-1: <image>\nImage-2: <image>\nCompare two images and evaluate whether the second image is closer to achieving task objectives compared to the first image. + score means the second image is closer, - score means the first image is closer\nResponse the relative progressing of target task follow <score>. The target task is: <task> {} </task> <score>"
75
+ self.dataclient.prompt_templete['v3_think']="0% <image>\nThis image is the trajectory beginning of the following two images\nImage-1: <image>\nImage-2: <image>\nCompare two images and evaluate whether the second image is closer to achieving task objectives compared to the first image. + score means the second image is closer, - score means the first image is closer\nResponse the relative progressing of target task follow <score>. The target task is: <task> {} </task> <score>"
76
+
77
+
78
+ def _songling_process(self,action):
79
+ action=copy.deepcopy(action)
80
+ for i in range(len(action)):
81
+ if i in [0, 1, 2]:
82
+ action[i]=action[i]//1000
83
+ elif i in [3,4,5]:
84
+ action[i]=action[i]//1000
85
+ elif i ==6:
86
+ pass
87
+ else:
88
+ pass
89
+ return action
90
+
91
+ def format_state(self,state,gripper_format=False):
92
+ state=self._songling_process(state)
93
+ if gripper_format:
94
+ state_open=round((state[6]//10000)/7.0,1)
95
+ state[6]=state_open
96
+ else:
97
+ state[6]=state[6]//1000
98
+ return state
99
+
100
+ def get_score_prompt(self,task,trajectory_len=0,think=False):
101
+ "two or len+3 image"
102
+ if trajectory_len>0:
103
+ trajectory_prompt=trojectory_example_prompt(list(range(trajectory_len)),task=task)
104
+ full_prompt=trajectory_prompt+self.dataclient.prompt_templete['v3_think'].format(task)
105
+ else:
106
+ full_prompt=self.dataclient.prompt_templete['v3'].format(task)
107
+ if think:
108
+ full_prompt+=self.dataclient.prompt_templete['think']
109
+ return full_prompt
110
+ def get_done_prompt(self,task):
111
+ "one image"
112
+ return self.dataclient.prompt_templete["task_done"].format(task)
113
+
114
+ def get_in_context_done_prompt(self,task=None):
115
+ "two image"
116
+ if task:
117
+ return self.dataclient.prompt_templete["context_task_done"].format(task,task)
118
+ else:
119
+ return self.dataclient.prompt_templete["image_done"]
120
+
121
+ def get_task_prompt(self):
122
+ "two image"
123
+ return self.dataclient.prompt_templete["task_vqa"]
124
+ def get_action_inverse_prompt(self):
125
+ "two image"
126
+ return self.dataclient.prompt_templete["action_inverse"]
127
+
128
+ def get_action_score_prompt(self,task,state,action):
129
+ "one image"
130
+ format_fuction=self.dataclient.action_format['songling']
131
+ action_score_prompt=self.dataclient.prompt_templete['task_action_score'].format(format_fuction(state),format_fuction(action),task)
132
+ return action_score_prompt
133
+
134
+ def get_action_prompt(self,task,view_num=1,position_output=False,simple=False,state='type',output_num=1,think=False):
135
+ if simple:
136
+ format_fuction=self.dataclient.action_format_simple['songling']
137
+ action_key='task_action_simple'
138
+ if position_output:
139
+ action_key='task_position_simple'
140
+ else:
141
+ format_fuction=self.dataclient.action_format['songling']
142
+ action_key='task_action'
143
+ if position_output:
144
+ action_key='task_position'
145
+ "view_num(max 3) image"
146
+ image_prompt=self.dataclient.image_prompt_templete[view_num]
147
+ full_prompt=image_prompt+self.dataclient.prompt_templete[action_key].format(format_fuction(state,state=position_output),task)
148
+ if output_num>1:
149
+ full_prompt+=f'*{output_num}'
150
+ if think:
151
+ full_prompt+=self.dataclient.prompt_templete['think']
152
+ return full_prompt
153
+
154
+ def get_fast_action_prompt(self,task,view_num=1,position_output=False,simple=False,state='type',output_num=1,think=False):
155
+ full_prompt = self.get_action_prompt(task,view_num,position_output,simple,state,output_num,think)
156
+ full_prompt+='<chunks>'
157
+ return full_prompt
158
+ def set_config(self):
159
+ self.request_config = RequestConfig(
160
+ max_tokens=self.max_tokens,
161
+ temperature=self.temperature,
162
+ top_k=self.top_k,
163
+ logprobs=self.logprobs,
164
+ top_logprobs=self.top_logprobs,
165
+ # repetition_penalty=args.repetition_penalty,
166
+ # stop=args.stop_words,
167
+ # stream=True
168
+ )
169
+ self.model.generation_config.max_new_tokens = self.max_tokens
170
+ self.model.generation_config.do_sample=self.do_sample
171
+ self.model.generation_config.temperature=self.temperature
172
+
173
+ def _get_internvl2_per_token_logps(self, model, inputs):
174
+ from trl.trainer.utils import selective_log_softmax
175
+ logits_to_keep = inputs['logits_to_keep']
176
+ input_ids = inputs['input_ids']
177
+ inputs = {
178
+ k: v
179
+ for k, v in inputs.items() if k not in
180
+ ['logits_to_keep', 'completion_mask', 'ref_per_token_logps', 'advantages', 'old_per_token_logps']
181
+ }
182
+ _, inputs = self.template.pre_forward_hook(self.model, None, inputs)
183
+ logits = model(**inputs).logits
184
+ # exclude the last logit: it corresponds to the next token pred
185
+ logits = logits[:, -(logits_to_keep + 1):-1, :]
186
+ logits = logits / self.temperature
187
+ input_ids = input_ids[:, -logits_to_keep:]
188
+ return selective_log_softmax(logits, input_ids)
189
+ def init_model(self,model_path,model_type='internvl2',device_map:str = 'auto',torch_dtype=torch.bfloat16,adapter: str = None):
190
+ """
191
+ Args:
192
+ device_map: ['auto', 'cuda:0',...]
193
+ """
194
+ template_type = model_type
195
+ print(f'template_type: {template_type}')
196
+ self.model, tokenizer = get_model_tokenizer(model_id_or_path=model_path,
197
+ model_type=model_type,
198
+ torch_dtype=torch_dtype,
199
+ device_map=device_map,
200
+ attn_impl = 'flash_attn')
201
+ self.template = get_template(template_type, tokenizer)
202
+ if adapter:
203
+ self.model = Swift.from_pretrained(self.model, adapter, adapter_name=None)
204
+
205
+ from swift.llm import PtEngine
206
+ from swift.plugin import InferStats
207
+ self.engine = PtEngine.from_model_template(self.model, self.template, max_batch_size=0)
208
+
209
+ self.infer_stats = InferStats()
210
+ seed_everything(42)
211
+ logger.success("model initialized successfully")
212
+
213
+ def chat(self,infer_requests):
214
+ start_t=time.time()
215
+ response_list = self.engine.infer(
216
+ infer_requests, template=self.template, request_config=self.request_config, metrics=[self.infer_stats])
217
+ end_t=time.time()
218
+ infer_time=end_t-start_t
219
+ return response_list,infer_time
220
+
221
+ def results_format(self,response_list,infer_requests,rich=False):
222
+ infer_requests=copy.deepcopy(infer_requests)
223
+ answers=[]
224
+ for i in range(len(response_list)):
225
+ if rich:
226
+ rich_answer=''
227
+ for one in response_list[i].choices[0].logprobs['content'][:-1]:
228
+ if one['token'].isdigit():
229
+ temp_num=0
230
+ temp_weight=0
231
+ top_prob=math.e**one['top_logprobs'][0]['logprob']
232
+ for one_tops in one['top_logprobs']:
233
+ top_num=one_tops['token']
234
+ if top_num.isdigit():
235
+ prob=math.e**one_tops['logprob']
236
+ if prob>top_prob*0.1:
237
+ temp_num+=float(top_num)*prob
238
+ temp_weight+=prob
239
+ rich_answer+="{:.1f}".format(temp_num/temp_weight)
240
+ else:
241
+ rich_answer+=one['token']
242
+ answers.append(rich_answer)
243
+ else:
244
+ answers.append(response_list[i].choices[0].message.content)
245
+ infer_requests[i].messages.append({'role': 'assistant', 'content': response_list[i].choices[0].message.content})
246
+ return answers,infer_requests
247
+
248
+
249
+ def fast_results_format(self,response_list,infer_requests,tokenizer,time_horizon=10,action_dim=7):
250
+ infer_requests=copy.deepcopy(infer_requests)
251
+ answers=[]
252
+ for i in range(len(response_list)):
253
+ temp=[]
254
+ text=[]
255
+ for one in response_list[i].choices[0].logprobs['content'][:-1]:
256
+ ids=tokenizer.encode(one['token'],add_special_tokens=False)
257
+ if 92537-ids[0]<=2048:
258
+ temp.extend(ids)
259
+ # temp.extend(tokenizer.encode(one['token'],add_special_tokens=False))
260
+ temp=[[92537-one for one in temp]]
261
+ fast_chunk=tokenizer.fasttokenizer.decode(temp,time_horizon=time_horizon,action_dim=action_dim)
262
+ infer_requests[i].messages.append({'role': 'assistant', 'content': response_list[i].choices[0].message.content})
263
+ return fast_chunk,infer_requests
264
+
265
+ def denormalize_fastchunk(self,fast_chunk,params):
266
+ return denormalize_with_params(fast_chunk,params)
267
+
268
+ def set_system_prompt(self,system_prompt=None):
269
+ if system_prompt is not None:
270
+ self.system_prompt=system_prompt
271
+ elif system_prompt=='default':
272
+ self.system_prompt=None
273
+ else:
274
+ self.system_prompt='You are a visual-language assistant designed to interpret spatial and task-related information from images and text. Provide precise, context-aware responses and actionable guidance to assist in achieving task objectives.'
275
+
276
+ def _process_image_to_pil(self, image_input: Union[str, Image.Image]) -> Image.Image:
277
+ """
278
+ 将各种格式的图像输入转换为448x448的PIL.Image
279
+
280
+ Args:
281
+ image_input: 图像URL、文件路径、base64编码字符串或PIL.Image对象
282
+
283
+ Returns:
284
+ PIL.Image: 调整为448x448尺寸的PIL图像
285
+ """
286
+ pil_image = None
287
+
288
+ if isinstance(image_input, Image.Image):
289
+ pil_image = image_input
290
+ elif isinstance(image_input, str):
291
+ if image_input.startswith(('http://', 'https://')):
292
+ response = requests.get(image_input)
293
+ pil_image = Image.open(BytesIO(response.content))
294
+ elif image_input.startswith('data:image'):
295
+ header, encoded = image_input.split(',', 1)
296
+ image_data = base64.b64decode(encoded)
297
+ pil_image = Image.open(BytesIO(image_data))
298
+ elif len(image_input) > 100 and not '/' in image_input and not '\\' in image_input:
299
+ try:
300
+ image_data = base64.b64decode(image_input)
301
+ pil_image = Image.open(BytesIO(image_data))
302
+ except:
303
+ pil_image = Image.open(image_input)
304
+ else:
305
+ pil_image = Image.open(image_input)
306
+ else:
307
+ raise ValueError(f"不支持的图像输入类型: {type(image_input)}")
308
+
309
+ if pil_image.mode != 'RGB':
310
+ pil_image = pil_image.convert('RGB')
311
+
312
+ pil_image = pil_image.resize((448, 448), Image.Resampling.LANCZOS)
313
+
314
+ return pil_image
315
+
316
+ def get_infer_requests(self,prompt,images:List[Union[str, Image.Image]] = None):
317
+ """
318
+ Args:
319
+ prompt: 提示文本
320
+ images: 可以是图像URL、文件路径、base64编码字符串或PIL.Image对象
321
+ """
322
+ if type(prompt)==str:
323
+ prompt=[prompt]
324
+ images=[images]
325
+ infer_requests=[]
326
+ for i in range(len(prompt)):
327
+ one_input=[]
328
+ if self.system_prompt:
329
+ one_input.append(
330
+ {
331
+ 'role': 'system',
332
+ 'content': self.system_prompt
333
+ }
334
+ )
335
+ one_input.append(
336
+ {
337
+ 'role': 'user',
338
+ 'content': prompt[i]
339
+ }
340
+ )
341
+ processed_images = None
342
+ if images[i] is not None:
343
+ if isinstance(images[i], list):
344
+ processed_images = [self._process_image_to_pil(img) for img in images[i] if img is not None]
345
+ else:
346
+ processed_images = [self._process_image_to_pil(images[i])]
347
+
348
+ infer_requests.append(TemplateInputs(
349
+ messages=one_input,
350
+ images=processed_images,
351
+ ))
352
+ # infer_requests.append(TemplateInputs(
353
+ # messages=one_input,
354
+ # images=images[i],
355
+ # ))
356
+ return infer_requests
357
+
358
+ def get_logprobs(self,infer_requests,return_mask=False,digit=False):
359
+ old_mode=self.template.mode
360
+ self.template.set_mode('train')
361
+ mini_batch_encoded_inputs = [self.template.encode(infer_request) for infer_request in infer_requests]
362
+ mini_batch_encoded_inputs = to_device(
363
+ self.template.data_collator(mini_batch_encoded_inputs), self.model.device)
364
+ labels = mini_batch_encoded_inputs.pop('labels')
365
+ logits_to_keep = (labels.shape[-1] - (torch.ne(labels, -100).int().argmax(-1))).max().item()
366
+ mini_batch_encoded_inputs['logits_to_keep'] = logits_to_keep
367
+ mini_batch_encoded_inputs['completion_mask'] = labels[:, -logits_to_keep:] != -100
368
+ per_token_logps = self._get_internvl2_per_token_logps(self.model, mini_batch_encoded_inputs)
369
+ self.template.set_mode(old_mode)
370
+ if return_mask:
371
+ if digit:
372
+ tokenizer = self.template.tokenizer
373
+
374
+ digit_completion_mask = torch.zeros_like(labels[:, -logits_to_keep:], dtype=torch.bool)
375
+ for i in range(labels.shape[0]):
376
+ for j in range(labels.shape[1] - logits_to_keep, labels.shape[1]):
377
+ if labels[i, j] != -100:
378
+ token_id = labels[i, j].item()
379
+ token_str = tokenizer.decode([token_id]).strip()
380
+ if re.search(r'[0-9+\-]', token_str):
381
+ digit_completion_mask[i, j - (labels.shape[1] - logits_to_keep)] = True
382
+ return per_token_logps, mini_batch_encoded_inputs['completion_mask'],digit_completion_mask
383
+ else:
384
+ return per_token_logps,mini_batch_encoded_inputs['completion_mask']
385
+ else:
386
+ return per_token_logps
387
+
388
+
389
+ def get_in_context_done(self,task:str,first_image:List[Image.Image],n_pre_image:List[Image.Image],now_image:List[Image.Image],ref_image_list:List[Image.Image],ref_num=9,rich=False):
390
+ """
391
+ In context 的方式获取done
392
+ 提供一段参考ref_image_list
393
+ first_image是你的轨迹的第一张图,这里为list是可以batch推理
394
+ n_pre_image是上一个时刻
395
+ now_image是当前时刻
396
+ """
397
+ if ref_image_list is not None:
398
+ ref_images=[ref_image_list[0]]
399
+ delta=(len(ref_image_list)-1)/(ref_num-1)
400
+ for i in range(1,ref_num):
401
+ ref_images.append(ref_image_list[int(i*delta)])
402
+ else:
403
+ ref_num=0
404
+ one_prompt=self.get_score_prompt(task=task,trajectory_len=ref_num,think=True)
405
+ batch_prompt=[]
406
+ batch_image=[]
407
+ for i in range(len(now_image)):
408
+ batch_prompt.append(one_prompt)
409
+ batch_image.append(ref_images+[first_image[i],n_pre_image[i],now_image[i]])
410
+ infer_requests=self.get_infer_requests(prompt=batch_prompt,images=batch_image)
411
+ response_list,infer_time=self.chat(infer_requests)
412
+ answers_list,complete_requests_list=self.results_format(response_list,infer_requests,rich=rich)
413
+ think_pre_value_list=[]
414
+ think_post_value_list=[]
415
+ think_critic_list=[]
416
+ for one in answers_list:
417
+ one_critic=one.split('</think>')[1]
418
+ one_pre_value=one.split('first image progressing: ')[1].split('%')[0]
419
+ one_post_value=one.split('second image progressing: ')[1].split('%')[0]
420
+ think_critic_list.append("{:.1f}".format((100-float(one_pre_value))*float(one_critic)/100.0))
421
+ think_pre_value_list.append(one_pre_value)
422
+ think_post_value_list.append("{:.3f}".format(float(one_post_value)/100.0))
423
+ batch_done=think_post_value_list
424
+ batch_related_critic=think_critic_list
425
+ return batch_done,batch_related_critic
426
+
427
+
428
+ def web_trajectory_critic(self, task_description, main_video_path, reference_video_path=None,
429
+ batch_num=20, ref_num=9, think=False, skip=1, rich=False, reverse_eval=False,output_path=None,fps=None,frame_skip=False,addition_scale=1,bias=0,positive_clip=0,negative_clip=0,related_critic=False,done_flag=False,in_context_done=False,done_threshold=False,video_output=True):
430
+ list_video=images_get_from_video(main_video_path)
431
+ ref_list=None
432
+ if reference_video_path is None:
433
+ ref_num=0
434
+ else:
435
+ ref_list=images_get_from_video(reference_video_path)
436
+ if done_flag:
437
+ if in_context_done:
438
+ done_ref=ref_list
439
+ else:
440
+ done_ref=None
441
+ done_list=self.get_trajectory_done(task=task_description,image_list=list_video,ref_image_list=done_ref,batch_num=batch_num,rich=True,ref_num=ref_num,threshold=done_threshold)
442
+ if frame_skip:
443
+ done_list=[done_list[i] for i in range(0,len(done_list),skip)]
444
+ else:
445
+ done_list=None
446
+ critic_list, think_value_list=self.get_trajectory_critic(task=task_description,image_list=list_video,ref_image_list=ref_list,batch_num=batch_num,ref_num=ref_num,think=think,skip=skip,rich=rich,reverse_eval=reverse_eval,frame_skip=frame_skip,addition_scale=addition_scale,bias=bias,positive_clip=positive_clip,negative_clip=negative_clip,related_critic=related_critic)
447
+ value_list=think_value_list
448
+ if video_output:
449
+ if ref_num>0:
450
+ ref_image_paths=ref_list
451
+ else:
452
+ ref_image_paths=None
453
+ if fps:
454
+ pass
455
+ else:
456
+ fps=5.0/skip
457
+ video_path = video_trajectory(
458
+ traj_id='temp',
459
+ view='0',
460
+ image_paths=[],
461
+ image_objects=list_video,
462
+ done_list=done_list,
463
+ critic_list=critic_list,
464
+ value_list=value_list,
465
+ task=task_description,
466
+ output_path=output_path,
467
+ fps=fps,
468
+ ref_image_paths=ref_image_paths,
469
+ n_num=ref_num
470
+ )
471
+ else:
472
+ video_path=None
473
+ return video_path,value_list,critic_list,done_list
474
+
475
+ def web_trajectory_done(self, task_description, main_image_path, reference_image_path=None, rich=False):
476
+ done_list=self.get_trajectory_done(task=task_description,image_list=[main_image_path],batch_num=1,rich=rich)
477
+ return f"Task: {task_description}\nCritic Score: {done_list[0]}"
478
+
479
+
480
+ def get_trajectory_task(self, image_list):
481
+ one_prompt=self.get_task_prompt()
482
+ infer_requests=self.get_infer_requests(prompt=one_prompt,images=[image_list[0],image_list[-1]])
483
+ response_list,infer_time=self.chat(infer_requests)
484
+ answers_list,complete_requests_list=self.results_format(response_list,infer_requests)
485
+ return answers_list
486
+
487
+
488
+ def get_trajectory_done(self,task:str,image_list:List[Image.Image],ref_image_list:List[Image.Image]=None,batch_num:int=20,rich=False,ref_num=9,threshold=0,skip=1,goal_image:Image.Image=None):
489
+ """
490
+ 输入一条trajectory的所有图片,输出每张图片的done,0~1的突变值
491
+ 当有ref_image_list时,进行过程判断,输出0~1的渐变值
492
+ 当有gaol_image时,进行最终状态判断,输出0~1的突变值(与当有ref_image_list冲突),task=None时只依靠图片
493
+ """
494
+ batch_prompt=[]
495
+ batch_image=[]
496
+ done_list=[]
497
+ if skip>1:
498
+ image_list=[image_list[i] for i in range(0,len(image_list),skip)]
499
+ if ref_image_list is None and goal_image is None:
500
+ for i in tqdm.tqdm(range(len(image_list)),desc='done processing'):
501
+ one_prompt=self.get_done_prompt(task=task)
502
+ batch_prompt.append(one_prompt)
503
+ batch_image.append([image_list[i]])
504
+ if (i+1) % batch_num==0 or i==len(image_list)-1:
505
+ infer_requests=self.get_infer_requests(prompt=batch_prompt,images=batch_image)
506
+ response_list,infer_time=self.chat(infer_requests)
507
+ answers_list,complete_requests_list=self.results_format(response_list,infer_requests,rich=rich)
508
+ print(f'infer_time:{infer_time}s')
509
+ print(f'answers_list:{answers_list}')
510
+ done_list.extend(answers_list)
511
+ batch_prompt=[]
512
+ batch_image=[]
513
+ elif ref_image_list:
514
+ first_image=[]
515
+ n_pre_image=[]
516
+ now_image=[]
517
+ for i in tqdm.tqdm(range(1,len(image_list)),desc='done processing'):
518
+ first_image.append(image_list[0])
519
+ n_pre_image.append(image_list[i-1])
520
+ now_image.append(image_list[i])
521
+ if (i+1) % batch_num==0 or i==len(image_list)-1:
522
+ batch_done,batch_related_critic=self.get_in_context_done(task=task,first_image=first_image,n_pre_image=n_pre_image,now_image=now_image,ref_image_list=ref_image_list,ref_num=ref_num,rich=rich)
523
+ print(f'answers_list:{batch_done}')
524
+ done_list.extend(batch_done)
525
+ first_image=[]
526
+ n_pre_image=[]
527
+ now_image=[]
528
+ done_list=[0]+done_list
529
+ else:
530
+ for i in tqdm.tqdm(range(len(image_list)),desc='done processing'):
531
+ one_prompt=self.get_in_context_done_prompt(task=task)
532
+ batch_prompt.append(one_prompt)
533
+ batch_image.append([goal_image,image_list[i]])
534
+ if (i+1) % batch_num==0 or i==len(image_list)-1:
535
+ infer_requests=self.get_infer_requests(prompt=batch_prompt,images=batch_image)
536
+ response_list,infer_time=self.chat(infer_requests)
537
+ answers_list,complete_requests_list=self.results_format(response_list,infer_requests,rich=rich)
538
+ print(f'infer_time:{infer_time}s')
539
+ print(f'answers_list:{answers_list}')
540
+ done_list.extend(answers_list)
541
+ batch_prompt=[]
542
+ batch_image=[]
543
+ done_list = [float(one) if float(one) > threshold else 0.0 for one in done_list]
544
+ return done_list
545
+
546
+ def get_trajectory_critic(self,task:str,image_list:List[Image.Image],ref_image_list:List[Image.Image]=None,batch_num:int=20,ref_num=9,think=False,skip=1,rich=False,reverse_eval=False,frame_skip=True,addition_scale=1,bias=0,related_critic=False,positive_clip=0,negative_clip=0,value_simple=True):
547
+ """
548
+ 输入一条trajectory的所有图片,输出每张图片的critic和processing value
549
+ 可以给一条参考轨迹
550
+ """
551
+ batch_prompt=[]
552
+ batch_image=[]
553
+ critic_list=[]
554
+ value_list=[]
555
+ if ref_image_list is not None:
556
+ ref_images=[ref_image_list[0]]
557
+ delta=(len(ref_image_list)-1)/(ref_num-1)
558
+ for i in range(1,ref_num):
559
+ ref_images.append(ref_image_list[int(i*delta)])
560
+ else:
561
+ ref_num=0
562
+ if frame_skip:
563
+ select_idx=range(skip,len(image_list),skip)
564
+ else:
565
+ select_idx=range(skip,len(image_list))
566
+ for i in tqdm.tqdm(select_idx,desc='critic processing'):
567
+ one_prompt=self.get_score_prompt(task=task,trajectory_len=ref_num,think=think)
568
+ batch_prompt.append(one_prompt)
569
+ if ref_image_list is not None:
570
+ if reverse_eval:
571
+ batch_image.append(ref_images+[image_list[0],image_list[i],image_list[i-skip]])
572
+ else:
573
+ batch_image.append(ref_images+[image_list[0],image_list[i-skip],image_list[i]])
574
+ else:
575
+ if reverse_eval:
576
+ batch_image.append([image_list[i],image_list[i-skip]])
577
+ else:
578
+ batch_image.append([image_list[i-skip],image_list[i]])
579
+ if (len(batch_prompt)) % batch_num==0 or len(critic_list)+len(batch_prompt)==len(select_idx):
580
+ infer_requests=self.get_infer_requests(prompt=batch_prompt,images=batch_image)
581
+ response_list,infer_time=self.chat(infer_requests)
582
+ answers_list,complete_requests_list=self.results_format(response_list,infer_requests,rich=rich)
583
+ print(f'infer_time:{infer_time}s')
584
+ print(f'answers_list:{answers_list}')
585
+ critic_list.extend(answers_list)
586
+ batch_prompt=[]
587
+ batch_image=[]
588
+ if think:
589
+ think_pre_value_list=[]
590
+ think_post_value_list=[]
591
+ think_critic_list=[]
592
+ for one in critic_list:
593
+ one_critic=one.split('</think>')[1]
594
+ one_pre_value=one.split('first image progressing: ')[1].split('%')[0]
595
+ one_post_value=one.split('second image progressing: ')[1].split('%')[0]
596
+ think_critic_list.append(one_critic)
597
+ think_pre_value_list.append(one_pre_value)
598
+ think_post_value_list.append(one_post_value)
599
+ if reverse_eval:
600
+ temp=think_pre_value_list
601
+ think_pre_value_list=think_post_value_list
602
+ think_post_value_list=temp
603
+ think_critic_list=[0-float(one) for one in think_critic_list]
604
+ think_pre_value_list=think_pre_value_list+think_post_value_list[-skip:]
605
+ think_post_value_list=think_pre_value_list[:skip]+think_post_value_list
606
+ critic_list=think_critic_list
607
+ if frame_skip:
608
+ pass
609
+ else:
610
+ critic_list=[float(one)/skip for one in critic_list]
611
+ critic_list=[float(one)/addition_scale for one in critic_list]
612
+ value_list=self.critic_to_value_simple(critic_list,simple=value_simple)
613
+ else:
614
+ if reverse_eval:
615
+ critic_list=[0-float(one) for one in critic_list]
616
+ if frame_skip:
617
+ pass
618
+ else:
619
+ critic_list=[float(one)/skip for one in critic_list]
620
+ critic_list=[float(one)/addition_scale for one in critic_list]
621
+ value_list=self.critic_to_value_simple(critic_list,simple=value_simple)
622
+ if related_critic:
623
+ critic_list=[value_list[i]-value_list[i-1] for i in range(1,len(value_list))]
624
+ if bias!=0:
625
+ critic_list=[one+bias for one in critic_list]
626
+ if positive_clip!=0:
627
+ critic_list=[one if (one<0 or one>positive_clip) else 0 for one in critic_list]
628
+ if negative_clip!=0:
629
+ critic_list=[one if (one>0 or one<-negative_clip) else 0 for one in critic_list]
630
+ if related_critic:
631
+ value_list=[0]
632
+ for one in critic_list:
633
+ value_list.append(value_list[-1]+one)
634
+ else:
635
+ value_list=self.critic_to_value_simple(critic_list,simple=value_simple)
636
+ #这里的value也是done,越接近100完成度越高
637
+ return critic_list,value_list
638
+
639
+ def magic_smooth(self,task,file_path,hz=10,value_simple='mix_f',ref_image_list=None,ref_num=9,think=False,max_skip=3):
640
+ import os
641
+ import pickle
642
+ import gzip
643
+ import subprocess
644
+ from video_tool import read_data_and_create_video,images_get_from_video
645
+ if type(ref_image_list) == str:
646
+ if ref_image_list.endswith(".pkl.gz"):
647
+ ref_image_list = read_data_and_create_video(ref_image_list)
648
+ else:
649
+ ref_image_list=images_get_from_video(ref_image_list)
650
+ image_list=read_data_and_create_video(file_path, camera_name=None, create_video=False, output_path=None, fps=hz, start_frame=0, end_frame=None)
651
+ skip=int(hz/2)
652
+ critic_list,value_list=self.get_trajectory_critic(task=task,image_list=image_list,ref_image_list=ref_image_list,batch_num=10,ref_num=ref_num,think=think,skip=skip,rich=True,reverse_eval=False,frame_skip=True,addition_scale=1,bias=0,related_critic=False,positive_clip=0,negative_clip=0,value_simple=value_simple)
653
+
654
+ skip_idx_range=[]
655
+ skip_idxs=[]
656
+ i=0
657
+ while i <len(critic_list):
658
+ if float(critic_list[i])<=0:
659
+ skip_window=2
660
+ while i+skip_window<len(critic_list) and skip_window<=max_skip:
661
+ two_image=[image_list[0],image_list[i*skip],image_list[(i+skip_window)*skip]]
662
+ one_critic_list,_=self.get_trajectory_critic(task=task,image_list=two_image,ref_image_list=ref_image_list,batch_num=10,ref_num=ref_num,think=think,skip=1,rich=True,reverse_eval=False,frame_skip=True,addition_scale=1,bias=0,related_critic=False,positive_clip=0,negative_clip=0,value_simple=value_simple)
663
+ if float(one_critic_list[-1])<0:
664
+ skip_window+=1
665
+ else:
666
+ break
667
+ skip_idx_range.append([i,i+skip_window])
668
+ skip_idxs.extend(range(i*skip+1,(i+skip_window)*skip))
669
+ i+=skip_window
670
+ print("skip_window:",skip_window)
671
+ else:
672
+ i+=1
673
+ with gzip.open(file_path, 'rb') as f:
674
+ original_data = pickle.load(f)
675
+
676
+ base_dir = os.path.dirname(file_path)
677
+ file_name = os.path.splitext(os.path.splitext(os.path.basename(file_path))[0])[0] # 去掉.pkl.gz
678
+ output_dir = os.path.join(base_dir, f"{file_name}_smoothed")
679
+ os.makedirs(output_dir, exist_ok=True)
680
+ new_data=[one for i,one in enumerate(original_data) if i not in skip_idxs]
681
+ new_images=[one for i,one in enumerate(image_list) if i not in skip_idxs]
682
+
683
+ data_file = os.path.join(output_dir, f"{file_name}_smoothed.pkl.gz")
684
+
685
+ with gzip.open(data_file, 'wb') as f:
686
+ pickle.dump(new_data, f)
687
+
688
+ video_file = os.path.join(output_dir, f"{file_name}_smoothed.mp4")
689
+
690
+ temp_dir = os.path.join(output_dir, f"temp")
691
+ os.makedirs(temp_dir, exist_ok=True)
692
+
693
+ try:
694
+ for j, img in enumerate(new_images):
695
+ frame_file = os.path.join(temp_dir, f"frame_{j:06d}.png")
696
+ if hasattr(img, 'save'):
697
+ img.save(frame_file)
698
+ else:
699
+ from PIL import Image
700
+ if isinstance(img, np.ndarray):
701
+ Image.fromarray(img).save(frame_file)
702
+ else:
703
+ Image.fromarray(np.array(img)).save(frame_file)
704
+
705
+ ffmpeg_cmd = [
706
+ 'ffmpeg', '-y',
707
+ '-framerate', str(hz),
708
+ '-i', os.path.join(temp_dir, 'frame_%06d.png'),
709
+ '-c:v', 'libx264',
710
+ '-pix_fmt', 'yuv420p',
711
+ '-crf', '23',
712
+ video_file
713
+ ]
714
+
715
+ subprocess.run(ffmpeg_cmd, check=True, capture_output=True)
716
+ print(f"Created video: {video_file}")
717
+
718
+ except Exception as e:
719
+ print(f"Error creating video for segment {i}: {e}")
720
+
721
+ finally:
722
+ import shutil
723
+ if os.path.exists(temp_dir):
724
+ shutil.rmtree(temp_dir)
725
+ return new_data
726
+
727
+
728
+
729
+
730
+ def magic_split(self,task,file_path,hz=10,value_simple='mix_f',done_assist=False,ref_image_list=None):
731
+ import os
732
+ import pickle
733
+ import gzip
734
+ import subprocess
735
+ from video_tool import read_data_and_create_video,images_get_from_video
736
+ from magic_detect import adaptive_peak_valley_detection,plot_results
737
+ if type(ref_image_list) == str:
738
+ if ref_image_list.endswith(".pkl.gz"):
739
+ ref_image_list = read_data_and_create_video(ref_image_list)
740
+ else:
741
+ ref_image_list=images_get_from_video(ref_image_list)
742
+
743
+ skip=int(hz/2)
744
+ done_len=4
745
+ gap_merge_len=4#一般看数据的平均记录周期
746
+ image_list=read_data_and_create_video(file_path, camera_name=None, create_video=False, output_path=None, fps=hz, start_frame=0, end_frame=None)
747
+ critic_list,value_list=self.get_trajectory_critic(task=task,image_list=image_list,ref_image_list=ref_image_list,batch_num=10,ref_num=9,think=False,skip=skip,rich=True,reverse_eval=False,frame_skip=True,addition_scale=1,bias=0,related_critic=False,positive_clip=0,negative_clip=0,value_simple=value_simple)
748
+
749
+ if done_assist:
750
+ done_list=self.get_trajectory_done(task=task,image_list=image_list,ref_image_list=None,batch_num=10,ref_num=2,rich=True,threshold=0.9,skip=skip)
751
+ assist_peaks={}
752
+ peak_window=[]
753
+ done_list=done_list+[0]
754
+ for k in range(len(done_list)):
755
+ if done_list[k]>=0.95:
756
+ peak_window.append(k)
757
+ else:
758
+ if len(peak_window)>=done_len:
759
+ assist_peaks[peak_window[done_len-1]]=peak_window
760
+ peak_window=[]
761
+ peak_list=list(assist_peaks.keys())
762
+ index=0
763
+ while index<len(peak_list)-1:
764
+ if assist_peaks[peak_list[index+1]][0]-assist_peaks[peak_list[index]][-1]<=gap_merge_len:
765
+ assist_peaks[peak_list[index]].extend(assist_peaks[peak_list[index+1]])
766
+ del assist_peaks[peak_list[index+1]]
767
+ del peak_list[index+1]
768
+ else:
769
+ index+=1
770
+ result = adaptive_peak_valley_detection(
771
+ value_list,
772
+ assist_peaks=peak_list,
773
+ window_size=None, # Adaptive window size
774
+ verbose=True,
775
+ min_distance=10,
776
+ prominence_threshold=0.1,
777
+ outlier_sensitivity=3
778
+ )
779
+ else:
780
+ result = adaptive_peak_valley_detection(
781
+ value_list,
782
+ window_size=None, # Adaptive window size
783
+ verbose=True,
784
+ min_distance=10,
785
+ prominence_threshold=0.01,
786
+ outlier_sensitivity=1.5
787
+ )
788
+
789
+
790
+ with gzip.open(file_path, 'rb') as f:
791
+ original_data = pickle.load(f)
792
+
793
+ base_dir = os.path.dirname(file_path)
794
+ file_name = os.path.splitext(os.path.splitext(os.path.basename(file_path))[0])[0] # 去掉.pkl.gz
795
+ output_dir = os.path.join(base_dir, f"{file_name}_segments")
796
+ os.makedirs(output_dir, exist_ok=True)
797
+ plot_results(value_list, result,save_path=os.path.join(output_dir, "peak_valley.png"))
798
+ peaks = [one*skip for one in result['peaks']]
799
+ valleys = [one*skip for one in result['valleys']]
800
+
801
+ ascending_dir = os.path.join(output_dir, "ascending")
802
+ descending_dir = os.path.join(output_dir, "descending")
803
+ os.makedirs(ascending_dir, exist_ok=True)
804
+ os.makedirs(descending_dir, exist_ok=True)
805
+
806
+ video_dir = os.path.join(output_dir, "videos")
807
+ os.makedirs(video_dir, exist_ok=True)
808
+
809
+ all_points = []
810
+ for p in peaks:
811
+ all_points.append((p, 'peak'))
812
+ for v in valleys:
813
+ all_points.append((v, 'valley'))
814
+ all_points.sort(key=lambda x: x[0])
815
+
816
+ segments = []
817
+
818
+ for i, (point_idx, point_type) in enumerate(all_points):
819
+ if i == 0:
820
+ prev_type='valley'
821
+ start_idx = 0
822
+ else:
823
+ start_idx=all_points[i-1][0]
824
+ prev_type = all_points[i-1][1]
825
+
826
+ end_idx = point_idx
827
+ if prev_type == 'valley' and point_type == 'peak':
828
+ segment_type = 'ascending'
829
+ elif prev_type == 'peak' and point_type == 'valley':
830
+ segment_type = 'descending'
831
+ else:
832
+ continue
833
+
834
+ data_segment = original_data[start_idx:end_idx]
835
+ image_segment = image_list[start_idx:end_idx]
836
+
837
+ segments.append({
838
+ 'type': segment_type,
839
+ 'start': start_idx,
840
+ 'end': end_idx,
841
+ 'data': data_segment,
842
+ 'images': image_segment
843
+ })
844
+
845
+
846
+ if segments and segments[-1]['type'] == 'descending':
847
+ segments.pop()
848
+
849
+ for i, segment in enumerate(segments):
850
+ segment_type = segment['type']
851
+
852
+ task_name = self.get_trajectory_task(segment['images'])[0].split('</task>')[0].strip().replace(' ', '_').replace('.', '_').replace(',', '_')
853
+
854
+ if segment_type == 'ascending':
855
+ data_file = os.path.join(ascending_dir, f"{task_name}_{i:03d}.pkl.gz")
856
+ else:
857
+ data_file = os.path.join(descending_dir, f"{task_name}_{i:03d}.pkl.gz")
858
+
859
+ with gzip.open(data_file, 'wb') as f:
860
+ pickle.dump(segment['data'], f)
861
+
862
+ video_file = os.path.join(video_dir, f"{segment_type}_{task_name}_{i:03d}.mp4")
863
+
864
+ temp_dir = os.path.join(output_dir, f"temp_{i}")
865
+ os.makedirs(temp_dir, exist_ok=True)
866
+
867
+ try:
868
+ for j, img in enumerate(segment['images']):
869
+ frame_file = os.path.join(temp_dir, f"frame_{j:06d}.png")
870
+ if hasattr(img, 'save'):
871
+ img.save(frame_file)
872
+ else:
873
+ from PIL import Image
874
+ if isinstance(img, np.ndarray):
875
+ Image.fromarray(img).save(frame_file)
876
+ else:
877
+ Image.fromarray(np.array(img)).save(frame_file)
878
+
879
+ ffmpeg_cmd = [
880
+ 'ffmpeg', '-y',
881
+ '-framerate', str(hz),
882
+ '-i', os.path.join(temp_dir, 'frame_%06d.png'),
883
+ '-c:v', 'libx264',
884
+ '-pix_fmt', 'yuv420p',
885
+ '-crf', '23',
886
+ video_file
887
+ ]
888
+
889
+ subprocess.run(ffmpeg_cmd, check=True, capture_output=True)
890
+ print(f"Created video: {video_file}")
891
+
892
+ except Exception as e:
893
+ print(f"Error creating video for segment {i}: {e}")
894
+
895
+ finally:
896
+ import shutil
897
+ if os.path.exists(temp_dir):
898
+ shutil.rmtree(temp_dir)
899
+
900
+ print(f"Processing complete. Segments saved to: {output_dir}")
901
+ print(f"Total segments: {len(segments)}")
902
+ print(f"Ascending segments: {sum(1 for s in segments if s['type'] == 'ascending')}")
903
+ print(f"Descending segments: {sum(1 for s in segments if s['type'] == 'descending')}")
904
+
905
+ return segments
906
+
907
+ def critic_to_value_simple(self,critic_list,simple=True):
908
+ """
909
+ 将critic计算为0-100的value,输入需是一条轨迹按顺序的critic
910
+ """
911
+ value_list=[0]
912
+ for i in range(len(critic_list)):
913
+ if float(critic_list[i])>0 or simple is True:
914
+ value_list.append(value_list[-1]+(100-value_list[-1])*float(critic_list[i])/100.0)
915
+ else:
916
+ if simple=='mix_f':
917
+ if value_list[-1]>50:
918
+ value_list.append(max(10,100-max((100-value_list[-1]),1.0)/(100+float(critic_list[i]))*100.0))
919
+ else:
920
+ value_list.append(value_list[-1]+value_list[-1]*float(critic_list[i])/100.0)
921
+ else:
922
+ value_list.append(100-max((100-value_list[-1]),1.0)/(100+float(critic_list[i]))*100.0)
923
+ return value_list
924
+
925
+ def compute_voc(self,values_list):
926
+ """
927
+ 计算Value-Order Correlation (VOC)
928
+
929
+ 参数:
930
+ predicted_values: 模型预测的值序列,形状为(T,),其中T是时间步数
931
+
932
+ 返回:
933
+ voc: Value-Order Correlation值,范围从-1到1
934
+ """
935
+ T = len(values_list)
936
+ time_order = np.arange(T)
937
+
938
+ correlation, _ = spearmanr(values_list, time_order)
939
+ return correlation
940
+
941
+ def compute_negative_rate(self,critic_list):
942
+ """
943
+ 计算逆序动作的比例
944
+ """
945
+ negative_critic=[one for one in critic_list if one<0]
946
+
947
+ return float(len(negative_critic))/len(critic_list)
948
+
949
+
950
+ def import_external_file(file_path: str):
951
+ import importlib
952
+ file_path = os.path.abspath(os.path.expanduser(file_path))
953
+ py_dir, py_file = os.path.split(file_path)
954
+ assert os.path.isdir(py_dir), f'py_dir: {py_dir}'
955
+ sys.path.insert(0, py_dir)
956
+ return importlib.import_module(py_file.split('.', 1)[0])
VLAC/evo_vlac/utils/video_tool.py ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from loguru import logger
2
+ import traceback
3
+ import numpy as np
4
+ import torch
5
+ import json
6
+ import os
7
+ import io
8
+ import shutil
9
+ import matplotlib
10
+ import matplotlib.pyplot as plt
11
+ from PIL import Image, ImageDraw, ImageFont
12
+ import textwrap
13
+ import random
14
+ import copy
15
+ import re
16
+ import tempfile
17
+ import cv2
18
+ import subprocess
19
+
20
+
21
+ def images_get_from_video(video_path):
22
+ """
23
+ 将 MP4 视频转换为 PIL Image 对象列表
24
+
25
+ 参数:
26
+ video_path (str): 视频文件的路径
27
+
28
+ 返回:
29
+ list: 包含视频每一帧的 PIL Image 对象的列表
30
+ """
31
+ import cv2
32
+ # 打开视频文件
33
+ video = cv2.VideoCapture(video_path)
34
+
35
+ # 检查视频是否成功打开
36
+ if not video.isOpened():
37
+ raise ValueError(f"无法打开视频文件: {video_path}")
38
+
39
+ image_list = []
40
+
41
+ # 逐帧读取视频
42
+ while True:
43
+ # 读取一帧
44
+ ret, frame = video.read()
45
+
46
+ # 如果读取失败,说明到达视频末尾
47
+ if not ret:
48
+ break
49
+
50
+ # 将 OpenCV 的 BGR 格式转换为 RGB 格式
51
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
52
+
53
+ # 将 NumPy 数组转换为 PIL Image 对象
54
+ pil_image = Image.fromarray(rgb_frame)
55
+
56
+ # 将图像添加到列表
57
+ image_list.append(pil_image)
58
+
59
+ # 释放视频资源
60
+ video.release()
61
+
62
+ return image_list
63
+
64
+ def video_trajectory(traj_id, view, image_paths, image_objects, done_list, critic_list, value_list, task, output_path, fps=5, ref_image_paths=None, n_num=5, critic_log_scale=False):
65
+ """
66
+ 将轨迹图片与done和value曲线构建为视频,并在上方添加参考图片
67
+
68
+ 参数:
69
+ - traj_id: 轨迹ID
70
+ - view: 视角
71
+ - image_paths: 图片路径列表
72
+ - image_objects: 图片对象列表
73
+ - done_list: done状态列表
74
+ - critic_list: critic评价列表
75
+ - value_list: 价值评估列表
76
+ - task: 任务描述
77
+ - output_path: 输出路径
78
+ - fps: 视频帧率
79
+ - ref_image_paths: 参考图片路径列表(也可以是对象)
80
+ - n_num: 要展示的参考图片数量
81
+ - critic_log_scale: 是否对critic使用对数坐标
82
+ """
83
+ import os
84
+ import matplotlib.pyplot as plt
85
+ import numpy as np
86
+ import cv2
87
+ from PIL import Image, ImageDraw, ImageFont
88
+ import textwrap
89
+ import matplotlib
90
+ import subprocess
91
+ import tempfile
92
+ import shutil
93
+ matplotlib.use('Agg') # 非交互式后端,避免显示图形
94
+
95
+ # 创建输出目录
96
+ os.makedirs(output_path, exist_ok=True)
97
+
98
+ # 视频文件路径
99
+ video_path = os.path.join(output_path, f"{traj_id}_{view}_trajectory.mp4")
100
+
101
+ # 计算skip值 - 关键修改点
102
+ skip = 1
103
+ if value_list and len(image_objects) > len(value_list):
104
+ skip = round(len(image_objects) / len(value_list))
105
+ print(f"计算得到的skip值: {skip}")
106
+
107
+ # 转换done_list为数值(如果不为None)
108
+ done_values = None
109
+ if done_list is not None and len(done_list) > 0:
110
+ try:
111
+ done_values = [float(d) if d is not None else 0 for d in done_list]
112
+ except:
113
+ done_values = None
114
+
115
+ # 转换critic_list为数值(如果不为None)
116
+ critic_values = None
117
+ if critic_list is not None and len(critic_list) > 0:
118
+ try:
119
+ critic_values = [float(d) if d is not None else 0 for d in critic_list]
120
+ except:
121
+ critic_values = None
122
+
123
+ # 转换value_list为数值(如果不为None)
124
+ value_values = None
125
+ if value_list is not None and len(value_list) > 0:
126
+ try:
127
+ value_values = [float(d) if d is not None else 0 for d in value_list]
128
+ except:
129
+ value_values = None
130
+
131
+ # 处理critic_list,使其前方补0与value_list长度一致
132
+ if critic_values and value_values and len(critic_values) < len(value_values):
133
+ padding_length = len(value_values) - len(critic_values)
134
+ critic_values = [0] * padding_length + critic_values
135
+
136
+ if len(image_paths) > len(image_objects):
137
+ image_objects = [Image.open(img) for img in image_paths]
138
+
139
+ resized_images = []
140
+
141
+ for img in image_objects:
142
+ # 获取原始图片的宽度和高度
143
+ img_width, img_height = img.size
144
+
145
+ # 计算缩放比例
146
+ scale_factor = 480 / img_height
147
+
148
+ # 计算新的宽度和高度
149
+ new_width = int(img_width * scale_factor)
150
+ new_height = 480 # 高度固定为 480
151
+
152
+ # 调整图片大小,使用新的 Resampling 方法
153
+ resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
154
+
155
+ # 保存调整后的图片到新列表
156
+ resized_images.append(resized_img)
157
+ image_objects=resized_images
158
+ # 获取图片尺寸
159
+ sample_img = image_objects[0]
160
+ img_width, img_height = sample_img.size
161
+
162
+ # 处理参考图���
163
+ ref_images = []
164
+ if ref_image_paths and n_num > 0:
165
+ # 等间隔采样参考图片
166
+ if len(ref_image_paths) <= n_num:
167
+ indices = range(len(ref_image_paths))
168
+ else:
169
+ indices = np.linspace(0, len(ref_image_paths) - 1, n_num, dtype=int)
170
+
171
+ for idx in indices:
172
+ try:
173
+ if type(ref_image_paths[idx]) is str:
174
+ ref_img = Image.open(ref_image_paths[idx])
175
+ else:
176
+ ref_img = ref_image_paths[idx]
177
+ ref_images.append(ref_img)
178
+ except Exception as e:
179
+ print(f"无法加载参考图片 {ref_image_paths[idx]}: {e}")
180
+
181
+ # 计算参考图片区域的高度和布局
182
+ ref_height = 0
183
+ reference_text_width = 80
184
+
185
+ # 计算需要绘制的曲线数量
186
+ curves_count = 0
187
+ if done_values is not None:
188
+ curves_count += 1
189
+ if value_values is not None:
190
+ curves_count += 1
191
+ if critic_values is not None:
192
+ curves_count += 1
193
+
194
+ # 根据曲线数量调整布局
195
+ if curves_count == 0:
196
+ plot_width = 200 # 如果没有曲线,只留信息区域
197
+ else:
198
+ plot_width = 448 # 有曲线时的宽度
199
+
200
+ # 设置视频尺寸 - 确保所有内容都能显示
201
+ frame_width = img_width + plot_width
202
+ frame_height = img_height + (ref_height + 30 if ref_images else 0) # 30px间距
203
+
204
+ if ref_images:
205
+ # 参考图片高度为主图高度的1/3,提升显示效果
206
+ ref_height = min(img_height // 3, 150) # 增加最大高度
207
+
208
+ # 计算单个参考图片的宽度
209
+ single_ref_width = int(ref_height * (ref_images[0].width / ref_images[0].height))
210
+
211
+ # 确保参考图片序列不会超出整个frame宽度(包括右侧区域)
212
+ total_available_width = frame_width - reference_text_width - 40 # 留40px边距
213
+ max_ref_width = total_available_width // len(ref_images)
214
+
215
+ if single_ref_width > max_ref_width:
216
+ single_ref_width = max_ref_width
217
+ ref_height = int(single_ref_width * (ref_images[0].height / ref_images[0].width))
218
+
219
+ # 创建临时目录保存帧图片
220
+ temp_dir = tempfile.mkdtemp()
221
+
222
+ # 尝试加载字体
223
+ try:
224
+ font = ImageFont.truetype("arial.ttf", 14) # 稍微缩小字体
225
+ small_font = ImageFont.truetype("arial.ttf", 12)
226
+ ref_font = ImageFont.truetype("arial.ttf", 16)
227
+ except IOError:
228
+ font = ImageFont.load_default()
229
+ small_font = ImageFont.load_default()
230
+ ref_font = ImageFont.load_default()
231
+
232
+ try:
233
+ # 对每一帧图片生成视频帧
234
+ for i in range(len(image_objects)):
235
+ # 创建一个空白画布
236
+ frame = Image.new('RGB', (frame_width, frame_height), color='white')
237
+
238
+ # 如果有参考图片,先添加参考图片和Reference标签
239
+ if ref_images:
240
+ # 添加"Reference"文字标签
241
+ draw = ImageDraw.Draw(frame)
242
+ ref_text_y = (ref_height - 20) // 2
243
+ draw.text((10, ref_text_y), "Reference", fill="black", font=ref_font)
244
+
245
+ # 绘制参考图片
246
+ start_x = reference_text_width
247
+ for j, ref_img in enumerate(ref_images):
248
+ # 调整参考图片大小
249
+ resized_ref = ref_img.resize((single_ref_width, ref_height), Image.LANCZOS)
250
+ # 可以跨越到右侧区域
251
+ paste_x = start_x + j * single_ref_width
252
+ frame.paste(resized_ref, (paste_x, 0))
253
+
254
+ # 粘贴当前图片
255
+ main_img_y = ref_height + 20 if ref_images else 0
256
+ frame.paste(image_objects[i], (0, main_img_y))
257
+
258
+ # 创建绘图对象
259
+ draw = ImageDraw.Draw(frame)
260
+
261
+ # 计算信息显示区域
262
+ info_x = img_width + 10
263
+ info_y = main_img_y + 10
264
+
265
+ # 添加任务描述
266
+ task_lines = textwrap.wrap(f"Task: {task}", width=25) # 缩短任务描述宽度
267
+ task_width = 0
268
+ for line_idx, line in enumerate(task_lines[:4]): # 最多显示2行
269
+ draw.text((info_x-5, info_y + line_idx * 18), line, fill="black", font=font)
270
+ # 计算任务文本的实际宽度
271
+ bbox = draw.textbbox((0, 0), line, font=font)
272
+ line_width = bbox[2] - bbox[0]
273
+ task_width = max(task_width, line_width)
274
+
275
+ # 在任务描述右侧横向排列状态信息
276
+ status_x = info_x + task_width + 30 # 任务文本右侧30px处开始
277
+ status_y = info_y
278
+
279
+ # 计算当前帧在value_list中的对应索引 - 关键修改点
280
+ value_idx = i // skip
281
+
282
+ # 横向排列当前帧状态信息
283
+ current_x = status_x
284
+ if done_list and value_idx < len(done_list):
285
+ done_status = done_list[value_idx]
286
+ done_color = "green" if done_status == "Yes" or done_status == True or done_status == 1 else "red"
287
+ done_text = f"Done: {done_status}"
288
+ draw.text((current_x, status_y), done_text, fill=done_color, font=font)
289
+ # 计算文本宽度并移动到下一个位置
290
+ bbox = draw.textbbox((0, 0), done_text, font=font)
291
+ current_x += (bbox[2] - bbox[0]) + 20
292
+
293
+ if value_list and value_idx < len(value_list):
294
+ value = value_list[value_idx]
295
+ value_color = "green" if value > 0 else "red"
296
+ value_text = f"Value: {value:.4f}"
297
+ draw.text((current_x, status_y), value_text, fill=value_color, font=font)
298
+ # 计算文本宽度并移动到下一个位置
299
+ bbox = draw.textbbox((0, 0), value_text, font=font)
300
+ current_x += (bbox[2] - bbox[0]) + 20
301
+
302
+ if critic_list and value_idx < len(critic_list):
303
+ critic = float(critic_list[value_idx])
304
+ critic_color = "green" if critic >= 0 else "red"
305
+ critic_text = f"Critic: {critic:.4f}"
306
+ draw.text((current_x, status_y), critic_text, fill=critic_color, font=font)
307
+
308
+ # # 在第二行显示帧计数和value索引
309
+ # draw.text((status_x, status_y + 20), f"Frame: {i+1}/{len(image_objects)} (Value idx: {value_idx})", fill="black", font=small_font)
310
+
311
+ # 如果有数据,创建曲线图 - 关键修改点
312
+ if curves_count > 0 and value_values:
313
+ # 固定字体大小
314
+ plt.rcParams.update({
315
+ 'font.size': 10,
316
+ 'axes.titlesize': 11,
317
+ 'axes.labelsize': 10,
318
+ 'xtick.labelsize': 8,
319
+ 'ytick.labelsize': 8
320
+ })
321
+ # 计算适当的高度,保持图表的可读性
322
+ plot_height = frame_height - status_y - 70 # 为上方信息留出更多空间
323
+
324
+ # 根据可用空间确定图形尺寸
325
+ available_width = plot_width - 30 # 留出一些边距
326
+ fig_width = available_width / 100 # 转换为英寸
327
+ fig_height = plot_height/100
328
+
329
+ fig = plt.figure(figsize=(fig_width, fig_height), dpi=100)
330
+
331
+ # 调整子图布局
332
+ plt.subplots_adjust(hspace=0.4, left=0.15, right=0.95, bottom=0.12, top=0.9)
333
+
334
+ subplot_idx = 1
335
+
336
+ # 计算当前应该显示到哪个value点
337
+ current_value_idx = min(value_idx, len(value_values) - 1)
338
+
339
+
340
+ # 绘制value曲线
341
+ if value_values is not None:
342
+ ax = fig.add_subplot(curves_count, 1, subplot_idx)
343
+ if current_value_idx >= 0:
344
+ # 绘制value曲线,根据critic状态着色
345
+ for j in range(current_value_idx):
346
+ color = 'orange' if (critic_values and j < len(critic_values) and critic_values[j] < 0) else 'green'
347
+ ax.plot([j, j+1], [value_values[j], value_values[j+1]], color=color, alpha=0.7)
348
+ marker_color = 'orange' if (critic_values and j < len(critic_values) and critic_values[j] < 0) else 'green'
349
+ ax.plot(j, value_values[j], marker='o', color=marker_color, markersize=2)
350
+
351
+ # 当前点
352
+ current_color = 'orange' if (critic_values and current_value_idx < len(critic_values) and critic_values[current_value_idx] < 0) else 'green'
353
+ ax.plot(current_value_idx, value_values[current_value_idx], marker='o', color=current_color, markersize=4)
354
+
355
+ ax.set_ylabel('Value')
356
+ ax.grid(True, alpha=0.3)
357
+ # 只在最后一个子图显示x轴标签
358
+ if subplot_idx == curves_count:
359
+ ax.set_xlabel('Step')
360
+ else:
361
+ ax.set_xticklabels([]) # 隐藏中间子图的x轴标签
362
+ subplot_idx += 1
363
+
364
+ # 绘制critic曲线
365
+ if critic_values is not None:
366
+ ax = fig.add_subplot(curves_count, 1, subplot_idx)
367
+ if current_value_idx >= 0:
368
+ critic_data = np.array(critic_values[:current_value_idx+1])
369
+
370
+ # 绘制线条
371
+ ax.plot(range(current_value_idx+1), critic_data, 'r-', alpha=0.7)
372
+
373
+ # 绘制点
374
+ for j in range(current_value_idx+1):
375
+ color = 'orange' if critic_values[j] < 0 else 'red'
376
+ ax.plot(j, critic_data[j], marker='o', color=color, markersize=2)
377
+
378
+ # 当前点
379
+ current_color = 'orange' if critic_values[current_value_idx] < 0 else 'red'
380
+ ax.plot(current_value_idx, critic_data[current_value_idx], marker='o', color=current_color, markersize=4,
381
+ markeredgecolor='black', markeredgewidth=0.5)
382
+
383
+ # 设置坐标轴
384
+ if critic_log_scale and len(critic_data) > 0:
385
+ ax.set_yscale('symlog')
386
+ ax.set_ylabel('Critic (log)')
387
+ else:
388
+ ax.set_ylabel('Critic')
389
+
390
+ ax.grid(True, alpha=0.3)
391
+ # 只在最后一个子图显示x轴标签
392
+ if subplot_idx == curves_count:
393
+ ax.set_xlabel('Step')
394
+ else:
395
+ ax.set_xticklabels([]) # 隐藏中间子图的x轴标签
396
+ subplot_idx += 1
397
+
398
+ # 绘制done曲线
399
+ if done_values is not None:
400
+ ax = fig.add_subplot(curves_count, 1, subplot_idx)
401
+ if current_value_idx >= 0:
402
+ ax.plot(done_values[:current_value_idx+1], 'b-', marker='o', markersize=2, label='Done')
403
+ ax.plot([current_value_idx], [done_values[current_value_idx]], 'ro', markersize=4)
404
+ ax.set_ylim(-0.1, 1.1)
405
+ ax.set_ylabel('Done')
406
+ ax.grid(True, alpha=0.3)
407
+ # 只在最后一个子图显示x轴标签
408
+ if subplot_idx == curves_count:
409
+ ax.set_xlabel('Step')
410
+ else:
411
+ ax.set_xticklabels([]) # 隐藏中间子图的x轴标签
412
+ subplot_idx += 1
413
+
414
+ # 将matplotlib图转换为PIL图像
415
+ fig.canvas.draw()
416
+ buf = fig.canvas.buffer_rgba()
417
+ w, h = fig.canvas.get_width_height()
418
+ plot_img = Image.frombuffer('RGBA', (w, h), buf, 'raw', 'RGBA', 0, 1).convert('RGB')
419
+ plt.close(fig)
420
+
421
+ # 调整曲线图大小并粘贴到帧上
422
+ plot_img = plot_img.resize((available_width, plot_height), Image.LANCZOS)
423
+ paste_y = status_y + 50 # 在状态信息下方50px处开始绘制曲线
424
+ frame.paste(plot_img, (info_x, paste_y))
425
+
426
+ # 保存帧为PNG文件
427
+ frame_path = os.path.join(temp_dir, f"{i:08d}.png")
428
+ frame.save(frame_path, "PNG")
429
+
430
+ # 使用FFmpeg生成视频(更好的兼容性)
431
+ try:
432
+ # 检查FFmpeg是否可用
433
+ subprocess.run(["ffmpeg", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
434
+
435
+ # 使用FFmpeg生成视频
436
+ ffmpeg_cmd = [
437
+ "ffmpeg",
438
+ "-y", # 覆盖输出文件
439
+ "-framerate", str(fps),
440
+ "-i", os.path.join(temp_dir, "%08d.png"),
441
+ "-c:v", "libx264", # 使用H.264编码
442
+ "-profile:v", "high",
443
+ "-pix_fmt", "yuv420p", # 确保兼容性
444
+ "-crf", "23", # 控制质量(0-51,数值越小质量越高)
445
+ "-movflags", "+faststart", # 优化网络播放
446
+ video_path
447
+ ]
448
+
449
+ print("正在使用FFmpeg生成视频...")
450
+ result = subprocess.run(ffmpeg_cmd, capture_output=True, text=True)
451
+
452
+ if result.returncode == 0:
453
+ print(f"视频已保存到 {video_path}")
454
+ else:
455
+ print(f"FFmpeg错误: {result.stderr}")
456
+ # 如果FFmpeg失败,回退到OpenCV方法
457
+ raise subprocess.CalledProcessError(result.returncode, ffmpeg_cmd)
458
+
459
+ except (subprocess.CalledProcessError, FileNotFoundError) as e:
460
+ print("FFmpeg不可用或失败,回退到OpenCV方法...")
461
+
462
+ # 回退到OpenCV方法
463
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
464
+ video_writer = cv2.VideoWriter(video_path, fourcc, fps, (frame_width, frame_height))
465
+
466
+ for i in range(len(image_objects)):
467
+ frame_path = os.path.join(temp_dir, f"{i:08d}.png")
468
+ frame_img = cv2.imread(frame_path)
469
+ if frame_img is not None:
470
+ video_writer.write(frame_img)
471
+
472
+ video_writer.release()
473
+ print(f"视频已保存到 {video_path}")
474
+
475
+ finally:
476
+ # 清��临时目录
477
+ shutil.rmtree(temp_dir, ignore_errors=True)
478
+
479
+ return video_path
480
+
481
+
482
+ def visualize_le(image_objects, critic_list, value_list, task, id, output_path, resize_shape=(640, 480), fps=5,
483
+ transparency=0.1, line_width=4, edge_width=2):
484
+ #### 只画value_list
485
+ import matplotlib
486
+ matplotlib.use('Agg')
487
+ import subprocess
488
+ temp_dir = tempfile.mkdtemp()
489
+ os.makedirs(output_path, exist_ok=True)
490
+ video_path = os.path.join(output_path, f"{task}_{id}_trajectory_legend.mp4")
491
+ skip = 1
492
+ skip_step = 0
493
+ if value_list and len(image_objects) > len(value_list):
494
+ skip = round(len(image_objects) / len(value_list))
495
+ print(f"计算得到的skip值: {skip}")
496
+ ### 计算跳帧数
497
+ skip_step = len(image_objects) - len(value_list)
498
+ if value_list is not None and len(value_list) > 0:
499
+ try:
500
+ value_values = [float(d) if d is not None else 0 for d in value_list]
501
+ except:
502
+ value_values = None
503
+ critic_values = None
504
+ if critic_list is not None and len(critic_list) > 0:
505
+ try:
506
+ critic_values = [float(d) if d is not None else 0 for d in critic_list]
507
+ except:
508
+ critic_values = None
509
+
510
+ ### 图片resize
511
+ ### 暂不考虑ref_images
512
+ frame_width, frame_height = resize_shape
513
+ resized_images = []
514
+ for img in image_objects:
515
+ resized_images.append(img.resize(resize_shape, Image.Resampling.LANCZOS))
516
+
517
+ ### 尝试加载字体
518
+ try:
519
+ font = ImageFont.truetype("arial.ttf", 14) # 稍微缩小字体
520
+ small_font = ImageFont.truetype("arial.ttf", 12)
521
+ ref_font = ImageFont.truetype("arial.ttf", 16)
522
+ except IOError:
523
+ font = ImageFont.load_default()
524
+ small_font = ImageFont.load_default()
525
+ ref_font = ImageFont.load_default()
526
+
527
+ try:
528
+ # 对每一帧图片生成视频帧
529
+ for i in range(len(image_objects)):
530
+ # 创建一个空白画布并粘贴画面
531
+ frame = Image.new('RGB', (frame_width, frame_height), color='white')
532
+ frame.paste(resized_images[i], (0, 0))
533
+ draw = ImageDraw.Draw(frame)
534
+
535
+ # 计算当前帧在value_list中的对应索引 - 关键修改点
536
+ value_idx = i // skip - skip_step
537
+
538
+ # 如果有数据,创建曲线图 - 关键修改点
539
+ if value_idx >= 0:
540
+ fig = plt.figure(figsize=(frame_width / 100, frame_height / 100), dpi=100)
541
+ fig.patch.set_alpha(transparency)
542
+ ax = fig.add_axes([0, 0, 1, 1])
543
+ fig.patch.set_alpha(0.0)
544
+ ax.patch.set_alpha(0.0)
545
+ ax.axis('off')
546
+ plt.xlim(0, len(value_values)-1)
547
+ plt.ylim(min(value_values) - abs(max(value_values)) * 0.15, max(value_values) + abs(max(value_values)) * 0.15)
548
+ current_value_idx = min(value_idx, len(value_values) - 1)
549
+ if current_value_idx >= 0:
550
+ for j in range(current_value_idx):
551
+ ax.plot([j, j + 1], [value_values[j], value_values[j + 1]], color='white', alpha=0.3, linewidth=line_width+2*edge_width)
552
+ color = '#4B0082' if (
553
+ critic_values and j < len(critic_values) and critic_values[j] < 0) else '#FF4500'
554
+ ax.plot([j, j + 1], [value_values[j], value_values[j + 1]], color=color, alpha=0.5, linewidth=line_width)
555
+ marker_color = '#4B0082' if (
556
+ critic_values and j < len(critic_values) and critic_values[j] < 0) else '#FF4500'
557
+ ax.plot(j, value_values[j], marker='o', color='black', markersize=line_width + 2, alpha=0.5)
558
+ ax.plot(j, value_values[j], marker='o', color=marker_color, markersize=line_width, alpha=0.5)
559
+
560
+
561
+ # 将matplotlib图转换为PIL图像
562
+ fig.canvas.draw()
563
+ buf = fig.canvas.buffer_rgba()
564
+ w, h = fig.canvas.get_width_height()
565
+ plot_img = Image.frombuffer('RGBA', (w, h), buf, 'raw', 'RGBA', 0, 1)# .convert('RGB')
566
+ plt.close(fig)
567
+ # frame.paste(plot_img, (0, 0), mask=plot_img.convert("RGBA"))
568
+ frame = Image.alpha_composite(frame.convert('RGBA'), plot_img).convert('RGB')
569
+
570
+ # 保存帧为PNG文件
571
+ frame_path = os.path.join(temp_dir, f"{i:08d}.png")
572
+ frame.save(frame_path, "PNG")
573
+
574
+ # 使用FFmpeg生成视频(更好的兼容性)
575
+ try:
576
+ # 检查FFmpeg是否可用
577
+ subprocess.run(["ffmpeg", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
578
+
579
+ # 使用FFmpeg生成视频
580
+ ffmpeg_cmd = [
581
+ "ffmpeg",
582
+ "-y", # 覆盖输出文件
583
+ "-framerate", str(fps),
584
+ "-i", os.path.join(temp_dir, "%08d.png"),
585
+ "-c:v", "libx264", # 使用H.264编码
586
+ "-profile:v", "high",
587
+ "-pix_fmt", "yuv420p", # 确保兼容性
588
+ "-crf", "23", # 控制质量(0-51,数值越小质量越高)
589
+ "-movflags", "+faststart", # 优化网络播放
590
+ video_path
591
+ ]
592
+
593
+ print("正在使用FFmpeg生成视频...")
594
+ result = subprocess.run(ffmpeg_cmd, capture_output=True, text=True)
595
+
596
+ if result.returncode == 0:
597
+ print(f"视频已保存到 {video_path}")
598
+ else:
599
+ print(f"FFmpeg错误: {result.stderr}")
600
+ # 如果FFmpeg失败,回退到OpenCV方法
601
+ raise subprocess.CalledProcessError(result.returncode, ffmpeg_cmd)
602
+
603
+ except (subprocess.CalledProcessError, FileNotFoundError) as e:
604
+ print("FFmpeg不可用或失败,回退到OpenCV方法...")
605
+
606
+ # 回退到OpenCV方法
607
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
608
+ video_writer = cv2.VideoWriter(video_path, fourcc, fps, (frame_width, frame_height))
609
+
610
+ for i in range(len(image_objects)):
611
+ frame_path = os.path.join(temp_dir, f"{i:08d}.png")
612
+ frame_img = cv2.imread(frame_path)
613
+ if frame_img is not None:
614
+ video_writer.write(frame_img)
615
+
616
+ video_writer.release()
617
+ print(f"视频已保存到 {video_path}")
618
+
619
+ finally:
620
+ # 清理临时目录
621
+ shutil.rmtree(temp_dir, ignore_errors=True)
622
+
623
+ return video_path
624
+
625
+
626
+ def read_data_and_create_video(filename, camera_name=None, create_video=False, output_path=None, fps=30, start_frame=0, end_frame=None):
627
+ """
628
+ 读取存储的压缩pickle文件,并可选地将其中的图片生成视频
629
+
630
+ 参数:
631
+ filename (str): 数据文件路径
632
+ camera_name (str, optional): 要处理的相机名称,如果为None则处理第一个找到的相机
633
+ create_video (bool, optional): 是否创建视频,默认为False
634
+ output_path (str, optional): 视频输出路径,如果为None且create_video=True,则使用与输入文件相同的名称
635
+ fps (int, optional): 视频帧率,默认为30
636
+ start_frame (int, optional): 起始帧索引,默认为0
637
+ end_frame (int, optional): 结束帧索引,默认为None表示处理到最后一帧
638
+
639
+ 返回:
640
+ list: PIL.Image对象列表
641
+ """
642
+ import gzip
643
+ import pickle
644
+ import base64
645
+ import numpy as np
646
+ import os
647
+ import cv2
648
+ import tempfile
649
+ import subprocess
650
+ from PIL import Image
651
+ import io
652
+ import shutil
653
+
654
+ # 读取压缩的pickle文件
655
+ with gzip.open(filename, 'rb') as f:
656
+ data = pickle.load(f)
657
+
658
+ # 确定处理的帧范围
659
+ if end_frame is None:
660
+ end_frame = len(data)
661
+ else:
662
+ end_frame = min(end_frame, len(data))
663
+
664
+ # 确保起始帧有效
665
+ start_frame = max(0, min(start_frame, len(data) - 1))
666
+
667
+ # 如果未指定相机名称,使用第一个可用的相机
668
+ print(data[0]['rgb'].keys())
669
+ if camera_name is None and len(data) > 0:
670
+ camera_name = list(data[0]['rgb'].keys())[0]
671
+
672
+ # 存储解码后的图像
673
+ images = []
674
+
675
+ # 创建临时目录用于存储视频帧
676
+ temp_dir = None
677
+ if create_video:
678
+ temp_dir = tempfile.mkdtemp()
679
+
680
+ try:
681
+ # 处理每一帧
682
+ for i, frame_data in enumerate(data[start_frame:end_frame]):
683
+ if camera_name not in frame_data['rgb']:
684
+ print(f"警告: 帧 {i+start_frame} 中没有找到相机 {camera_name}")
685
+ continue
686
+
687
+ # 解码图像
688
+ img_base64 = frame_data['rgb'][camera_name]
689
+ img_data = base64.b64decode(img_base64)
690
+ img_array = np.frombuffer(img_data, np.uint8)
691
+ img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
692
+
693
+ # BGR转RGB
694
+ img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
695
+ pil_img = Image.fromarray(img_rgb)
696
+ images.append(pil_img)
697
+
698
+ # 如果需要创建视频,保存帧到临时目录
699
+ if create_video:
700
+ frame_path = os.path.join(temp_dir, f"{i+start_frame:08d}.png")
701
+ pil_img.save(frame_path)
702
+
703
+ # 创建视频
704
+ if create_video and images:
705
+ if output_path is None:
706
+ # 如果未指定输出路径,创建与输入文件同名的文件夹
707
+ base_name = os.path.splitext(os.path.basename(filename))[0]
708
+ output_dir = os.path.join(os.path.dirname(filename), base_name)
709
+
710
+ # 确保输出目录存在
711
+ os.makedirs(output_dir, exist_ok=True)
712
+
713
+ # 在该目录中创建视频文件
714
+ output_path = os.path.join(output_dir, f"{camera_name}_video.mp4")
715
+
716
+ # 检查ffmpeg是否可用
717
+ try:
718
+ subprocess.run(["ffmpeg", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
719
+
720
+ # 使用FFmpeg生成视频
721
+ ffmpeg_cmd = [
722
+ "ffmpeg",
723
+ "-y", # 覆盖输出文件
724
+ "-framerate", str(fps),
725
+ "-i", os.path.join(temp_dir, "%08d.png"),
726
+ "-c:v", "libx264", # 使用H.264编码
727
+ "-profile:v", "high",
728
+ "-pix_fmt", "yuv420p", # 确保兼容性
729
+ "-crf", "23", # 控制质量(0-51,数值越小质量越高)
730
+ "-movflags", "+faststart", # 优化网络播放
731
+ output_path
732
+ ]
733
+
734
+ subprocess.run(ffmpeg_cmd, check=True)
735
+ print(f"视频已保存至: {output_path}")
736
+ except subprocess.CalledProcessError:
737
+ print("错误: 无法运行FFmpeg,请确保它已正确安装")
738
+ except Exception as e:
739
+ print(f"创建视频时出错: {str(e)}")
740
+
741
+ finally:
742
+ # 清理临时目录
743
+ if temp_dir and os.path.exists(temp_dir):
744
+ shutil.rmtree(temp_dir)
745
+
746
+ return images
747
+
748
+ # 视频压缩函数
749
+ def compress_video(input_path, output_path, target_size=(448, 448), fps=5):
750
+ """
751
+ 压缩视频到指定大小和帧率
752
+ 如果原视频fps小于指定值则保持原帧率
753
+ """
754
+ cap = cv2.VideoCapture(input_path)
755
+
756
+ # 获取原始视频的帧率和尺寸
757
+ original_fps = cap.get(cv2.CAP_PROP_FPS)
758
+ original_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
759
+ original_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
760
+
761
+ # 如果原始帧率小于指定帧率,则使用原始帧率
762
+ output_fps = original_fps if original_fps < fps else fps
763
+ if target_size is None:
764
+ target_size = (original_width, original_height)
765
+
766
+ sampling_interval = int(original_fps / output_fps) if output_fps < original_fps else 1
767
+
768
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
769
+ out = cv2.VideoWriter(output_path, fourcc, output_fps, target_size)
770
+ frame_count = 0
771
+ while True:
772
+ ret, frame = cap.read()
773
+ if not ret:
774
+ break
775
+
776
+ # # 处理宽高比
777
+ # if original_width > original_height * 1.5:
778
+ # # 宽大于高的1.5倍,需要中心裁剪
779
+ # target_width = int(original_height * 1.5)
780
+ # # 计算裁剪的起始x坐标(居中裁剪)
781
+ # start_x = int((original_width - target_width) / 2)
782
+ # # 裁剪frame
783
+ # frame = frame[:, start_x:start_x+target_width]
784
+
785
+ # 只有当前帧是采样帧时才处理和写入
786
+ if frame_count % sampling_interval == 0:
787
+ # 缩放到目标尺寸
788
+ resized = cv2.resize(frame, target_size)
789
+ out.write(resized)
790
+ frame_count += 1
791
+
792
+ cap.release()
793
+ out.release()
794
+ return output_path,output_fps
795
+
796
+ # 图片压缩函数
797
+ def compress_image(input_path, output_path, target_size=(448, 448)):
798
+ """压缩图片到指定大小"""
799
+ img = Image.open(input_path)
800
+ img = img.resize(target_size, Image.Resampling.LANCZOS)
801
+ img.save(output_path)
802
+ return output_path
VLAC/extract_hdf5.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ 从单个 rollout 的 HDF5 中导出视频与逐帧图片。
4
+ 默认读取: root/agentview/video、root/eye_in_hand/video,形状 (1, T, 3, H, W) uint8。
5
+ 同时尽量导出 text prompt(常见 dataset / 组属性),写入 text_prompt.txt 与 text_fields.json。
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import re
12
+ from pathlib import Path
13
+
14
+ import h5py
15
+ import numpy as np
16
+
17
+ # 用于 text_prompt.txt:按顺序尝试这些 dataset 路径(第一个非空即采用)
18
+ DEFAULT_PROMPT_DATASET_PRIORITY: tuple[str, ...] = (
19
+ "root/text_prompt",
20
+ "root/language_instruction",
21
+ "root/task_description",
22
+ "root/instruction",
23
+ "root/language",
24
+ "root/lang",
25
+ "language_instruction",
26
+ "task_description",
27
+ "text_prompt",
28
+ "instruction",
29
+ )
30
+
31
+ # 从这些 group 读取 HDF5 attributes(键名含语言/任务相关子串的会写入 json)
32
+ ATTR_GROUP_PATHS: tuple[str, ...] = ("/", "root", "data")
33
+
34
+
35
+ def video_chw_to_hwc(frames_chw: np.ndarray) -> np.ndarray:
36
+ """(T, 3, H, W) uint8 -> (T, H, W, 3)"""
37
+ return np.transpose(frames_chw, (0, 2, 3, 1))
38
+
39
+
40
+ def _scalar_to_text(v: object) -> str | None:
41
+ if v is None:
42
+ return None
43
+ if isinstance(v, bytes):
44
+ s = v.decode("utf-8", errors="replace").strip()
45
+ return s or None
46
+ if isinstance(v, str):
47
+ s = v.strip()
48
+ return s or None
49
+ if isinstance(v, (np.str_, np.bytes_)):
50
+ if isinstance(v, np.bytes_):
51
+ s = v.tobytes().decode("utf-8", errors="replace").strip()
52
+ else:
53
+ s = str(v).strip()
54
+ return s or None
55
+ if isinstance(v, (np.floating, np.integer, np.bool_)):
56
+ return str(v.item())
57
+ s = str(v).strip()
58
+ return s or None
59
+
60
+
61
+ def _decode_dataset_strings(ds: h5py.Dataset) -> list[str]:
62
+ """将字符串类 dataset 转为非空 str 列表。"""
63
+ try:
64
+ raw = ds.asstr()[()]
65
+ except Exception:
66
+ raw = ds[()]
67
+ arr = np.asarray(raw, dtype=object)
68
+ if arr.ndim == 0:
69
+ s = _scalar_to_text(arr.item())
70
+ return [s] if s else []
71
+ out: list[str] = []
72
+ for item in arr.reshape(-1):
73
+ s = _scalar_to_text(item)
74
+ if s:
75
+ out.append(s)
76
+ return out
77
+
78
+
79
+ def _looks_like_text_dataset(ds: h5py.Dataset) -> bool:
80
+ dt = ds.dtype
81
+ if h5py.check_dtype(vlen=str, dtype=dt):
82
+ return True
83
+ kind = getattr(dt, "kind", None)
84
+ if kind in ("S", "U", "O"):
85
+ return True
86
+ return False
87
+
88
+
89
+ def _attrs_to_text_map(f: h5py.File, group_paths: tuple[str, ...]) -> dict[str, str]:
90
+ """收集各 group 上「可能为任务/语言」的属性。"""
91
+ hint = re.compile(
92
+ r"(lang|language|instruction|prompt|task|text|desc|goal|command)",
93
+ re.I,
94
+ )
95
+ out: dict[str, str] = {}
96
+ for gp in group_paths:
97
+ if gp == "/":
98
+ g = f
99
+ prefix = "@"
100
+ elif gp not in f:
101
+ continue
102
+ else:
103
+ g = f[gp]
104
+ prefix = f"{gp}/@"
105
+ for ak, av in g.attrs.items():
106
+ if not hint.search(str(ak)):
107
+ continue
108
+ flat = np.asarray(av).reshape(-1)
109
+ s = _scalar_to_text(flat[0]) if flat.size else None
110
+ if s is None and isinstance(av, bytes):
111
+ s = _scalar_to_text(av)
112
+ if s:
113
+ out[f"{prefix}{ak}"] = s
114
+ return out
115
+
116
+
117
+ def extract_text_fields(
118
+ f: h5py.File,
119
+ extra_dataset_paths: tuple[str, ...] = (),
120
+ ) -> tuple[dict[str, str | list[str]], str | None]:
121
+ """
122
+ 返回 (fields, primary_prompt)。
123
+ fields: dataset 路径 -> 字符串或字符串列表;属性键为 ``group/@attr``。
124
+ """
125
+ fields: dict[str, str | list[str]] = {}
126
+ seen_paths: set[str] = set()
127
+
128
+ for path in (*DEFAULT_PROMPT_DATASET_PRIORITY, *extra_dataset_paths):
129
+ if path in seen_paths or path not in f:
130
+ continue
131
+ seen_paths.add(path)
132
+ obj = f[path]
133
+ if not isinstance(obj, h5py.Dataset):
134
+ continue
135
+ if not _looks_like_text_dataset(obj):
136
+ continue
137
+ lines = _decode_dataset_strings(obj)
138
+ if not lines:
139
+ continue
140
+ fields[path] = lines[0] if len(lines) == 1 else lines
141
+
142
+ fields.update(_attrs_to_text_map(f, ATTR_GROUP_PATHS))
143
+
144
+ primary: str | None = None
145
+ for path in (*DEFAULT_PROMPT_DATASET_PRIORITY, *extra_dataset_paths):
146
+ if path not in f or not isinstance(f[path], h5py.Dataset):
147
+ continue
148
+ if not _looks_like_text_dataset(f[path]):
149
+ continue
150
+ lines = _decode_dataset_strings(f[path])
151
+ if lines:
152
+ primary = lines[0]
153
+ break
154
+ if primary is None:
155
+ attr_items = [(k, v) for k, v in fields.items() if k.startswith("@") or "/@" in k]
156
+
157
+ def _attr_score(item: tuple[str, str | list[str]]) -> int:
158
+ kl = item[0].lower()
159
+ for i, sub in enumerate(
160
+ ("text_prompt", "language_instruction", "instruction", "task_desc", "task", "goal", "lang")
161
+ ):
162
+ if sub in kl:
163
+ return i
164
+ return 99
165
+
166
+ attr_items.sort(key=_attr_score)
167
+ for _k, v in attr_items:
168
+ primary = v if isinstance(v, str) else v[0]
169
+ break
170
+ return fields, primary
171
+
172
+
173
+ def write_text_exports(
174
+ out_dir: Path,
175
+ fields: dict[str, str | list[str]],
176
+ primary_prompt: str | None,
177
+ ) -> None:
178
+ json_path = out_dir / "text_fields.json"
179
+ with json_path.open("w", encoding="utf-8") as fp:
180
+ json.dump(fields, fp, ensure_ascii=False, indent=2)
181
+
182
+ txt_path = out_dir / "text_prompt.txt"
183
+ if primary_prompt is not None:
184
+ txt_path.write_text(primary_prompt + "\n", encoding="utf-8")
185
+ print(f"[ok] text prompt -> {txt_path} ({len(primary_prompt)} chars)")
186
+ else:
187
+ txt_path.write_text("", encoding="utf-8")
188
+ print("[warn] no text prompt found; wrote empty text_prompt.txt (see text_fields.json)")
189
+ print(f"[ok] all text fields -> {json_path}")
190
+
191
+
192
+ def save_rollout(
193
+ hdf5_path: str | Path,
194
+ out_dir: str | Path | None = None,
195
+ fps: float = 20.0,
196
+ keys: tuple[str, ...] = ("root/agentview/video", "root/eye_in_hand/video"),
197
+ extra_prompt_paths: tuple[str, ...] = (),
198
+ ) -> Path:
199
+ hdf5_path = Path(hdf5_path).resolve()
200
+ if out_dir is None:
201
+ out_dir = hdf5_path.parent / f"{hdf5_path.stem}_export"
202
+ out_dir = Path(out_dir).resolve()
203
+ out_dir.mkdir(parents=True, exist_ok=True)
204
+
205
+ with h5py.File(hdf5_path, "r") as f:
206
+ fields, primary = extract_text_fields(f, extra_dataset_paths=extra_prompt_paths)
207
+ write_text_exports(out_dir, fields, primary)
208
+
209
+ for key in keys:
210
+ if key not in f:
211
+ print(f"[skip] missing dataset: {key}")
212
+ continue
213
+ ds = f[key]
214
+ arr = np.asarray(ds)
215
+ # (1, T, 3, H, W) or (T, 3, H, W)
216
+ if arr.ndim == 5 and arr.shape[0] == 1:
217
+ arr = arr[0]
218
+ if arr.ndim != 4 or arr.shape[1] != 3:
219
+ raise ValueError(f"{key}: expected (T,3,H,W), got {arr.shape}")
220
+
221
+ name = key.split("/")[-2] # agentview / eye_in_hand
222
+ frames_hwc = video_chw_to_hwc(arr)
223
+
224
+ sub = out_dir / name
225
+ sub.mkdir(parents=True, exist_ok=True)
226
+
227
+ for i in range(frames_hwc.shape[0]):
228
+ out_png = sub / f"frame_{i:05d}.png"
229
+ try:
230
+ from PIL import Image
231
+
232
+ Image.fromarray(frames_hwc[i]).save(out_png)
233
+ except ImportError:
234
+ import imageio.v2 as imageio
235
+
236
+ imageio.imwrite(out_png, frames_hwc[i])
237
+
238
+ mp4_path = out_dir / f"{name}.mp4"
239
+ try:
240
+ import imageio.v2 as imageio
241
+
242
+ imageio.mimsave(mp4_path, list(frames_hwc), fps=fps)
243
+ except Exception:
244
+ import cv2
245
+
246
+ h, w = frames_hwc.shape[1:3]
247
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
248
+ writer = cv2.VideoWriter(str(mp4_path), fourcc, fps, (w, h))
249
+ for i in range(frames_hwc.shape[0]):
250
+ bgr = cv2.cvtColor(frames_hwc[i], cv2.COLOR_RGB2BGR)
251
+ writer.write(bgr)
252
+ writer.release()
253
+
254
+ print(f"[ok] {key} -> {sub}/ (frames), {mp4_path} ({frames_hwc.shape[0]} frames @ {fps} fps)")
255
+
256
+ return out_dir
257
+
258
+
259
+ def main():
260
+ parser = argparse.ArgumentParser(description="Export rollout video + frames from HDF5.")
261
+ parser.add_argument(
262
+ "hdf5",
263
+ nargs="?",
264
+ default="/scratch1/home/zhicao/data/real/task_1/train/session_demo_1.hdf5",
265
+ help="Path to rollout .hdf5",
266
+ )
267
+ parser.add_argument(
268
+ "-o",
269
+ "--out-dir",
270
+ default=None,
271
+ help="Output directory (default: <stem>_export next to hdf5)",
272
+ )
273
+ parser.add_argument("--fps", type=float, default=20.0, help="Video FPS")
274
+ parser.add_argument(
275
+ "--prompt-path",
276
+ action="append",
277
+ default=[],
278
+ metavar="H5_PATH",
279
+ help="Extra HDF5 dataset path(s) for text (repeatable), e.g. root/my_prompt",
280
+ )
281
+ args = parser.parse_args()
282
+
283
+ extra = tuple(args.prompt_path) if args.prompt_path else ()
284
+ out = save_rollout(
285
+ args.hdf5,
286
+ out_dir=args.out_dir,
287
+ fps=args.fps,
288
+ extra_prompt_paths=extra,
289
+ )
290
+ print(f"Done. Output: {out}")
291
+
292
+
293
+ if __name__ == "__main__":
294
+ main()
VLAC/model/VLAC-8b/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
VLAC/model/VLAC-8b/README.md ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pipeline_tag: robotics
3
+ library_name: transformers
4
+ license: cc-by-nc-sa-4.0
5
+ tags:
6
+ - vision-language-model
7
+ - manipulation
8
+ - robotics
9
+ ---
10
+
11
+
12
+ # VLAC: A Vision-Language-Action-Critic Model for Robotic Real-World Reinforcement Learning
13
+ <div align="center">
14
+
15
+ [[paper]](https://arxiv.org/abs/2509.15937)
16
+ [[code]](https://github.com/InternRobotics/VLAC)
17
+ [[model]](https://huggingface.co/InternRobotics/VLAC-8b)
18
+
19
+ </div>
20
+
21
+ ## 🚀 Interactive Demo & Homepage
22
+
23
+ <div align="center">
24
+
25
+ [Try Interactive & Homepage](https://vlac.intern-ai.org.cn/)
26
+ > **Online Demo is available now in Homepage, Try as you like!!!**
27
+
28
+ </div>
29
+
30
+ <!-- <div align="center">
31
+ <img src="https://github.com/InternRobotics/VLAC/tree/main/data/title_banner-2.gif" alt="VLAC banner" width="800"></img>
32
+ </div> -->
33
+
34
+ ## VLAC-8B
35
+
36
+ VLAC is a general-purpose pair-wise critic and manipulation model which designed for real world robot reinforcement learning and data refinement.
37
+
38
+ It provides robust evaluation capabilities for task progress prediction and task completion verification base one images and task description.
39
+
40
+ VLAC trained on 3000h+ human egocentric data, 1200h+ comprehensive public robotic manipulation data, and 15h+ self-collected manipulation data.
41
+
42
+ VLAC-8B is open new!
43
+
44
+ ## ✨ Key Features
45
+
46
+ • **Pair-wise comparison mechanism** for improved progressing dense critic accuracy, better recognition of state changes, and each step can be the start of the trajectory.
47
+
48
+ • **Multi-modal capabilities** - Supports process tracking, task completion judgment, task description estimation, visual question answering, and even embodied action output, equipped with VLA capabilities.
49
+
50
+ • **Flexible zero-shot and one-shot** - in-context capabilities, maintaining excellent performance across entities, scenarios, and tasks.
51
+
52
+ • **Human-task synesthesia** - Based on the ego4D human dataset, model understands common tasks and build synesthesia for real-world human tasks and embodied tasks.
53
+
54
+ • **Trajectory quality screening** - VLAC can evaluate the collected trajectories and filters out low score trajectories based on the VOC value and mask the action with negative pair-wise score, that is, data with low fluency and quality, improving the effect and efficiency of imitation learning.
55
+
56
+ <!-- ## Framework
57
+
58
+ <div align="center">
59
+ <img src="https://github.com/InternRobotics/VLAC/blob/main/data/framework.png" alt="VLAC Framework" width="800"/>
60
+ </div>
61
+
62
+ *The VLAC model is trained on a combination of comprehensive public robotic manipulation datasets, human demonstration data, self-collected manipulation data, and various image understanding datasets. Video data is processed into pair-wise samples to learn the different task progress between any two frames, supplemented with task descriptions and task completion evaluation to enable task progress understanding and action generation, as illustrated in the bottom-left corner. As shown in the diagram on the right, the model demonstrates strong generalization capabilities to new robots, scenarios, and tasks not covered in the training dataset. It can predict task progress and distinguish failure action or trajectory, providing dense reward feedback for real-world reinforcement learning and offering guidance for data refinement. Additionally, the model can directly perform manipulation tasks, exhibiting zero-shot capabilities to handle different scenarios.* -->
63
+
64
+ ## Framework & Performance
65
+
66
+ Details about the model's performance and evaluation metrics can be found in the [Homepage](https://vlac.intern-ai.org.cn/).
67
+
68
+ ## 🛠️ Installation
69
+
70
+ To install from source:
71
+ ```shell
72
+ git clone https://github.com/InternRobotics/VLAC.git
73
+ cd VLAC
74
+ pip install -e .
75
+ ```
76
+ Running Environment:
77
+
78
+ | | Range | Recommended | Notes |
79
+ | ------------ |--------------| ----------- | ----------------------------------------- |
80
+ | python | >=3.9 | 3.10 | |
81
+ | cuda | | cuda12 | No need to install if using CPU, NPU, MPS |
82
+ | torch | >=2.0 | | |
83
+ | transformers | >=4.51 | 4.51.3 | |
84
+ | peft | >=0.15.2 | | |
85
+ | ms-swift | | 3.3 | |
86
+
87
+
88
+ ## 🚀 Quick Start
89
+
90
+ ```python
91
+ from evo_vlac import GAC_model
92
+ from evo_vlac.utils.video_tool import compress_video
93
+ import os
94
+ #Consistent with the web interface, the value and citic rewards of video input can be evaluated.
95
+
96
+
97
+ #assign local model path
98
+ model_path="set to your local model path"
99
+ #download model form https://huggingface.co/InternRobotics/VLAC-8b
100
+
101
+ #assign video path and task description
102
+ test_video='evo_vlac/examples/videos/pick-bowl-test.mp4'
103
+ ref_video='evo_vlac/examples/videos/pick-bowl-ref.mov'
104
+ task_description='Put up the bowl and place it back in the white storage box.'
105
+
106
+ #init model
107
+ Critic=GAC_model(tag='critic')
108
+ Critic.init_model(model_path=model_path,model_type='internvl2',device_map=f'cuda:0')
109
+ Critic.temperature=0.5
110
+ Critic.top_k=1
111
+ Critic.set_config()
112
+ Critic.set_system_prompt()
113
+
114
+ # transform video
115
+ test_video_compressed = os.path.join(os.path.dirname(test_video),"test.mp4")
116
+ _,output_fps=compress_video(test_video, test_video_compressed,fps=5)
117
+ reference_video_compressed = None
118
+ if ref_video:
119
+ reference_video_compressed = os.path.join(os.path.dirname(ref_video),"ref.mp4")
120
+ compress_video(ref_video, reference_video_compressed,fps=5)
121
+
122
+
123
+ # generate Critic results
124
+ result_path,value_list,critic_list,done_list = Critic.web_trajectory_critic(
125
+ task_description=task_description,
126
+ main_video_path=test_video_compressed,
127
+ reference_video_path=reference_video_compressed,#if None means no reference video, only use task_description to indicate the task
128
+ batch_num=10,#batch number
129
+ ref_num=6,#image number used in reference video
130
+ think=False,# whether to CoT
131
+ skip=5,#pair-wise step
132
+ rich=False,#whether to output decimal value
133
+ reverse_eval=False,#whether to reverse the evaluation(for VROC evaluation)
134
+ output_path="results",
135
+ fps=float(output_fps),
136
+ frame_skip=True,#whether to skip frames(if false, each frame while be evaluated, cost more time)
137
+ done_flag=False,#whether to out put done value
138
+ in_context_done=False,#whether use reference video to generate done value
139
+ done_threshold=0.9,#done threshold
140
+ video_output=True#whether to output video
141
+ )
142
+
143
+
144
+ print("=" * 100)
145
+ print(">>>>>>>>>Critic results<<<<<<<<<<")
146
+ print(" ")
147
+
148
+ print(f"result path: {result_path}")
149
+ print(f"task description: {task_description}")
150
+ print("=" * 50)
151
+
152
+ print("value_list:")
153
+ print(value_list)
154
+ print("=" * 50)
155
+
156
+ print("critic_list:")
157
+ print(critic_list)
158
+ print("=" * 50)
159
+
160
+ print("done_list:")
161
+ print(done_list)
162
+ print("=" * 100)
163
+ ```
164
+ More examples of
165
+
166
+ • pair-wise image inputs critic. Please check [this example](https://github.com/InternRobotics/VLAC/tree/main/evo_vlac/examples/image_pair-wise_critic_example.py)
167
+
168
+ • vla action generation. Please check [this example](https://github.com/InternRobotics/VLAC/tree/main/evo_vlac/examples/vla_example.py)
169
+
170
+ • data refinement. Please check [this example](https://github.com/InternRobotics/VLAC/tree/main/evo_vlac/examples/data_filtering_example.py)
171
+
172
+
173
+ For training code, please refer to [InternVL2](https://huggingface.co/OpenGVLab/InternVL2-2B#quick-start).
174
+
175
+ ## 🔗 Citation
176
+
177
+ If you find our work helpful, please cite:
178
+
179
+ ```bibtex
180
+ @article{zhai2025vision,
181
+ title={A vision-language-action-critic model for robotic real-world reinforcement learning},
182
+ author={Zhai, Shaopeng and Zhang, Qi and Zhang, Tianyi and Huang, Fuxian and Zhang, Haoran and Zhou, Ming and Zhang, Shengzhe and Liu, Litao and Lin, Sixu and Pang, Jiangmiao},
183
+ journal={arXiv preprint arXiv:2509.15937},
184
+ year={2025}
185
+ }
186
+ ```
187
+
188
+ ## 🙏 Acknowledgments
189
+
190
+ - [SWIFT](https://github.com/modelscope/ms-swift)
191
+ - [InternVL](https://github.com/OpenGVLab/InternVL)
VLAC/model/VLAC-8b/added_tokens.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 92552,
3
+ "</img>": 92545,
4
+ "</quad>": 92548,
5
+ "</ref>": 92550,
6
+ "<IMG_CONTEXT>": 92546,
7
+ "<box>": 92551,
8
+ "<img>": 92544,
9
+ "<quad>": 92547,
10
+ "<ref>": 92549
11
+ }
VLAC/model/VLAC-8b/args.json ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "/cpfs04/user/zhangqi/zhangqi/data/model_garden/0619_intern8b_v7-1-part10-14-resize-constant/v0-20250619-124555/checkpoint-3125",
3
+ "model_type": "internvl2",
4
+ "model_revision": null,
5
+ "task_type": "causal_lm",
6
+ "torch_dtype": "bfloat16",
7
+ "attn_impl": null,
8
+ "num_labels": null,
9
+ "problem_type": null,
10
+ "rope_scaling": null,
11
+ "device_map": null,
12
+ "max_memory": {},
13
+ "local_repo_path": null,
14
+ "template": "internvl2",
15
+ "system": "You are a visual-language assistant designed to interpret spatial and task-related information from images and text. Provide precise, context-aware responses and actionable guidance to assist in achieving task objectives.",
16
+ "max_length": 10240,
17
+ "truncation_strategy": "delete",
18
+ "max_pixels": null,
19
+ "tools_prompt": "react_en",
20
+ "norm_bbox": null,
21
+ "response_prefix": null,
22
+ "padding_side": "right",
23
+ "loss_scale": "default",
24
+ "sequence_parallel_size": 1,
25
+ "use_chat_template": true,
26
+ "template_backend": "swift",
27
+ "dataset": [
28
+ "/cpfs04/user/zhangqi/zhangqi/data/DI-dataset/VLACQA_mix_VLM/v7-1/part15-2000000-00i05-00t01-share.json",
29
+ "/cpfs04/user/zhangqi/zhangqi/data/DI-dataset/VLACQA_mix_VLM/v7-1/part16-2000000-00i05-00t01-share.json",
30
+ "/cpfs04/user/zhangqi/zhangqi/data/DI-dataset/VLACQA_mix_VLM/v7-1/part17-2000000-00i05-00t01-share.json",
31
+ "/cpfs04/user/zhangqi/zhangqi/data/DI-dataset/VLACQA_mix_VLM/v7-1/part18-2000000-00i05-00t01-share.json",
32
+ "/cpfs04/user/zhangqi/zhangqi/data/DI-dataset/VLACQA_mix_VLM/v7-1/part19-2000000-00i05-00t01-share.json"
33
+ ],
34
+ "val_dataset": [
35
+ "/cpfs04/user/zhangqi/zhangqi/data/DI-dataset/VLACQA_mix_VLM/v7-1/test0-20000-00i05-00t01-share.json"
36
+ ],
37
+ "split_dataset_ratio": 0.0,
38
+ "data_seed": 42,
39
+ "dataset_num_proc": 1,
40
+ "streaming": false,
41
+ "enable_cache": false,
42
+ "download_mode": "reuse_dataset_if_exists",
43
+ "columns": {},
44
+ "strict": false,
45
+ "remove_unused_columns": true,
46
+ "model_name": [
47
+ "InternVL2-8B"
48
+ ],
49
+ "model_author": [
50
+ "zq"
51
+ ],
52
+ "custom_dataset_info": [],
53
+ "quant_method": null,
54
+ "quant_bits": null,
55
+ "hqq_axis": null,
56
+ "bnb_4bit_compute_dtype": "bfloat16",
57
+ "bnb_4bit_quant_type": "nf4",
58
+ "bnb_4bit_use_double_quant": true,
59
+ "bnb_4bit_quant_storage": null,
60
+ "max_new_tokens": 64,
61
+ "temperature": 0.0,
62
+ "top_k": null,
63
+ "top_p": null,
64
+ "repetition_penalty": null,
65
+ "num_beams": 1,
66
+ "stream": false,
67
+ "stop_words": [],
68
+ "logprobs": false,
69
+ "top_logprobs": null,
70
+ "ckpt_dir": "/cpfs04/user/zhangqi/zhangqi/data/model_garden/0619_intern8b_v7-1-part10-14-resize-constant/v0-20250619-124555/checkpoint-3125",
71
+ "load_dataset_config": null,
72
+ "lora_modules": [],
73
+ "tuner_backend": "peft",
74
+ "train_type": "full",
75
+ "adapters": [],
76
+ "external_plugins": [],
77
+ "seed": 42,
78
+ "model_kwargs": {},
79
+ "load_args": false,
80
+ "load_data_args": false,
81
+ "use_hf": false,
82
+ "hub_token": null,
83
+ "custom_register_path": [],
84
+ "ignore_args_error": false,
85
+ "use_swift_lora": false,
86
+ "output_dir": "/cpfs04/user/zhangqi/zhangqi/data/model_garden/0619_intern8b_v7-1-part15-19-resize-decay/v1-20250624-140732",
87
+ "overwrite_output_dir": false,
88
+ "do_train": false,
89
+ "do_eval": false,
90
+ "do_predict": false,
91
+ "eval_strategy": "steps",
92
+ "prediction_loss_only": false,
93
+ "per_device_train_batch_size": 2,
94
+ "per_device_eval_batch_size": 1,
95
+ "per_gpu_train_batch_size": null,
96
+ "per_gpu_eval_batch_size": null,
97
+ "gradient_accumulation_steps": 8,
98
+ "eval_accumulation_steps": null,
99
+ "eval_delay": 0,
100
+ "torch_empty_cache_steps": null,
101
+ "learning_rate": 2e-05,
102
+ "weight_decay": 0.1,
103
+ "adam_beta1": 0.9,
104
+ "adam_beta2": 0.95,
105
+ "adam_epsilon": 1e-08,
106
+ "max_grad_norm": 1.0,
107
+ "num_train_epochs": 1.0,
108
+ "max_steps": -1,
109
+ "lr_scheduler_type": "cosine",
110
+ "lr_scheduler_kwargs": null,
111
+ "warmup_ratio": 0.0,
112
+ "warmup_steps": 100,
113
+ "log_level": "passive",
114
+ "log_level_replica": "warning",
115
+ "log_on_each_node": true,
116
+ "logging_dir": "/cpfs04/user/zhangqi/zhangqi/data/model_garden/0619_intern8b_v7-1-part15-19-resize-decay/v1-20250624-140732/runs",
117
+ "logging_strategy": "steps",
118
+ "logging_first_step": true,
119
+ "logging_steps": 5,
120
+ "logging_nan_inf_filter": true,
121
+ "save_strategy": "steps",
122
+ "save_steps": 1000.0,
123
+ "save_total_limit": 1,
124
+ "save_safetensors": true,
125
+ "save_on_each_node": false,
126
+ "save_only_model": false,
127
+ "restore_callback_states_from_checkpoint": false,
128
+ "no_cuda": false,
129
+ "use_cpu": false,
130
+ "use_mps_device": false,
131
+ "jit_mode_eval": false,
132
+ "use_ipex": false,
133
+ "bf16": true,
134
+ "fp16": false,
135
+ "fp16_opt_level": "O1",
136
+ "half_precision_backend": "auto",
137
+ "bf16_full_eval": false,
138
+ "fp16_full_eval": false,
139
+ "tf32": null,
140
+ "local_rank": 0,
141
+ "ddp_backend": null,
142
+ "tpu_num_cores": null,
143
+ "tpu_metrics_debug": false,
144
+ "debug": null,
145
+ "dataloader_drop_last": false,
146
+ "eval_steps": 250.0,
147
+ "dataloader_num_workers": 4,
148
+ "dataloader_prefetch_factor": null,
149
+ "past_index": -1,
150
+ "run_name": null,
151
+ "disable_tqdm": null,
152
+ "label_names": null,
153
+ "load_best_model_at_end": false,
154
+ "metric_for_best_model": "loss",
155
+ "greater_is_better": false,
156
+ "ignore_data_skip": false,
157
+ "fsdp": "",
158
+ "fsdp_min_num_params": 0,
159
+ "fsdp_config": null,
160
+ "fsdp_transformer_layer_cls_to_wrap": null,
161
+ "accelerator_config": {
162
+ "dispatch_batches": false
163
+ },
164
+ "deepspeed": {
165
+ "fp16": {
166
+ "enabled": "auto",
167
+ "loss_scale": 0,
168
+ "loss_scale_window": 1000,
169
+ "initial_scale_power": 16,
170
+ "hysteresis": 2,
171
+ "min_loss_scale": 1
172
+ },
173
+ "bf16": {
174
+ "enabled": "auto"
175
+ },
176
+ "zero_optimization": {
177
+ "stage": 3,
178
+ "offload_optimizer": {
179
+ "device": "none",
180
+ "pin_memory": true
181
+ },
182
+ "offload_param": {
183
+ "device": "none",
184
+ "pin_memory": true
185
+ },
186
+ "overlap_comm": false,
187
+ "contiguous_gradients": true,
188
+ "sub_group_size": 1000000000.0,
189
+ "reduce_bucket_size": "auto",
190
+ "zero_quantized_weights": false,
191
+ "zero_quantized_gradients": false,
192
+ "stage3_prefetch_bucket_size": "auto",
193
+ "stage3_param_persistence_threshold": "auto",
194
+ "stage3_max_live_parameters": 1000000000.0,
195
+ "stage3_max_reuse_distance": 1000000000.0,
196
+ "stage3_gather_16bit_weights_on_model_save": true
197
+ },
198
+ "gradient_accumulation_steps": "auto",
199
+ "gradient_clipping": "auto",
200
+ "steps_per_print": 2000,
201
+ "train_batch_size": "auto",
202
+ "train_micro_batch_size_per_gpu": "auto",
203
+ "wall_clock_breakdown": false
204
+ },
205
+ "label_smoothing_factor": 0.0,
206
+ "optim": "adamw_torch",
207
+ "optim_args": null,
208
+ "adafactor": false,
209
+ "group_by_length": false,
210
+ "length_column_name": "length",
211
+ "report_to": [
212
+ "tensorboard"
213
+ ],
214
+ "ddp_find_unused_parameters": null,
215
+ "ddp_bucket_cap_mb": null,
216
+ "ddp_broadcast_buffers": null,
217
+ "dataloader_pin_memory": true,
218
+ "dataloader_persistent_workers": false,
219
+ "skip_memory_metrics": true,
220
+ "use_legacy_prediction_loop": false,
221
+ "push_to_hub": false,
222
+ "resume_from_checkpoint": null,
223
+ "hub_model_id": null,
224
+ "hub_strategy": "every_save",
225
+ "hub_private_repo": false,
226
+ "hub_always_push": false,
227
+ "gradient_checkpointing": true,
228
+ "gradient_checkpointing_kwargs": null,
229
+ "include_inputs_for_metrics": false,
230
+ "include_for_metrics": [],
231
+ "eval_do_concat_batches": true,
232
+ "fp16_backend": "auto",
233
+ "evaluation_strategy": "steps",
234
+ "push_to_hub_model_id": null,
235
+ "push_to_hub_organization": null,
236
+ "push_to_hub_token": null,
237
+ "mp_parameters": "",
238
+ "auto_find_batch_size": false,
239
+ "full_determinism": false,
240
+ "torchdynamo": null,
241
+ "ray_scope": "last",
242
+ "ddp_timeout": 1800,
243
+ "torch_compile": false,
244
+ "torch_compile_backend": null,
245
+ "torch_compile_mode": null,
246
+ "dispatch_batches": null,
247
+ "split_batches": null,
248
+ "include_tokens_per_second": false,
249
+ "include_num_input_tokens_seen": false,
250
+ "neftune_noise_alpha": null,
251
+ "optim_target_modules": null,
252
+ "batch_eval_metrics": false,
253
+ "eval_on_start": false,
254
+ "use_liger_kernel": false,
255
+ "eval_use_gather_object": false,
256
+ "average_tokens_across_devices": false,
257
+ "sortish_sampler": false,
258
+ "predict_with_generate": false,
259
+ "generation_max_length": null,
260
+ "generation_num_beams": null,
261
+ "generation_config": null,
262
+ "check_model": true,
263
+ "acc_strategy": "token",
264
+ "train_sampler_random": true,
265
+ "metric_warmup_step": 0,
266
+ "fsdp_num": 1,
267
+ "acc_steps": 1,
268
+ "eval_use_evalscope": false,
269
+ "eval_datasets": [],
270
+ "eval_limit": null,
271
+ "eval_datasets_args": null,
272
+ "eval_generation_config": null,
273
+ "freeze_parameters": [
274
+ "vision_model",
275
+ "mlp1"
276
+ ],
277
+ "freeze_parameters_ratio": 0.0,
278
+ "trainable_parameters": [],
279
+ "freeze_llm": false,
280
+ "freeze_vit": true,
281
+ "freeze_aligner": true,
282
+ "target_modules": [
283
+ "all-linear"
284
+ ],
285
+ "target_regex": null,
286
+ "modules_to_save": [],
287
+ "lora_rank": 8,
288
+ "lora_alpha": 32,
289
+ "lora_dropout": 0.05,
290
+ "lora_bias": "none",
291
+ "lora_dtype": null,
292
+ "lorap_lr_ratio": null,
293
+ "use_rslora": false,
294
+ "use_dora": false,
295
+ "lora_ga_batch_size": 2,
296
+ "lora_ga_iters": 2,
297
+ "lora_ga_max_length": 1024,
298
+ "lora_ga_direction": "ArB2r",
299
+ "lora_ga_scale": "stable",
300
+ "lora_ga_stable_gamma": 16,
301
+ "init_weights": true,
302
+ "fourier_n_frequency": 2000,
303
+ "fourier_scaling": 300.0,
304
+ "boft_block_size": 4,
305
+ "boft_block_num": 0,
306
+ "boft_n_butterfly_factor": 1,
307
+ "boft_dropout": 0.0,
308
+ "vera_rank": 256,
309
+ "vera_projection_prng_key": 0,
310
+ "vera_dropout": 0.0,
311
+ "vera_d_initial": 0.1,
312
+ "adapter_act": "gelu",
313
+ "adapter_length": 128,
314
+ "use_galore": false,
315
+ "galore_target_modules": null,
316
+ "galore_rank": 128,
317
+ "galore_update_proj_gap": 50,
318
+ "galore_scale": 1.0,
319
+ "galore_proj_type": "std",
320
+ "galore_optim_per_parameter": false,
321
+ "galore_with_embedding": false,
322
+ "galore_quantization": false,
323
+ "galore_proj_quant": false,
324
+ "galore_proj_bits": 4,
325
+ "galore_proj_group_size": 256,
326
+ "galore_cos_threshold": 0.4,
327
+ "galore_gamma_proj": 2,
328
+ "galore_queue_size": 5,
329
+ "adalora_target_r": 8,
330
+ "adalora_init_r": 12,
331
+ "adalora_tinit": 0,
332
+ "adalora_tfinal": 0,
333
+ "adalora_deltaT": 1,
334
+ "adalora_beta1": 0.85,
335
+ "adalora_beta2": 0.85,
336
+ "adalora_orth_reg_weight": 0.5,
337
+ "llamapro_num_new_blocks": 4,
338
+ "llamapro_num_groups": null,
339
+ "lisa_activated_layers": 0,
340
+ "lisa_step_interval": 20,
341
+ "reft_layer_key": null,
342
+ "reft_layers": null,
343
+ "reft_rank": 4,
344
+ "reft_intervention_type": "LoreftIntervention",
345
+ "reft_args": null,
346
+ "use_liger": false,
347
+ "swanlab_token": null,
348
+ "swanlab_project": null,
349
+ "swanlab_workspace": null,
350
+ "swanlab_exp_name": null,
351
+ "swanlab_mode": "cloud",
352
+ "add_version": true,
353
+ "resume_only_model": false,
354
+ "create_checkpoint_symlink": false,
355
+ "packing": false,
356
+ "lazy_tokenize": true,
357
+ "loss_type": null,
358
+ "optimizer": null,
359
+ "metric": null,
360
+ "zero_hpz_partition_size": null,
361
+ "rank": 0,
362
+ "global_world_size": 200,
363
+ "local_world_size": 8,
364
+ "model_suffix": "checkpoint-3125",
365
+ "model_info": "ModelInfo(model_type='internvl2', model_dir='/cpfs04/user/zhangqi/zhangqi/data/model_garden/0619_intern8b_v7-1-part10-14-resize-constant/v0-20250619-124555/checkpoint-3125', torch_dtype=torch.bfloat16, max_model_len=32768, quant_method=None, quant_bits=None, rope_scaling={'factor': 2.0, 'type': 'dynamic'}, config=None, task_type='causal_lm', num_labels=None)",
366
+ "model_meta": "ModelMeta(model_type='internvl2', model_groups=[ModelGroup(models=[Model(ms_model_id='OpenGVLab/InternVL2-1B', hf_model_id='OpenGVLab/InternVL2-1B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-2B', hf_model_id='OpenGVLab/InternVL2-2B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-8B', hf_model_id='OpenGVLab/InternVL2-8B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-26B', hf_model_id='OpenGVLab/InternVL2-26B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-40B', hf_model_id='OpenGVLab/InternVL2-40B', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-Llama3-76B', hf_model_id='OpenGVLab/InternVL2-Llama3-76B', model_path=None, ms_revision=None, hf_revision=None)], ignore_patterns=None, requires=None, tags=[]), ModelGroup(models=[Model(ms_model_id='OpenGVLab/InternVL2-2B-AWQ', hf_model_id='OpenGVLab/InternVL2-2B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-8B-AWQ', hf_model_id='OpenGVLab/InternVL2-8B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-26B-AWQ', hf_model_id='OpenGVLab/InternVL2-26B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-40B-AWQ', hf_model_id='OpenGVLab/InternVL2-40B-AWQ', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-Llama3-76B-AWQ', hf_model_id='OpenGVLab/InternVL2-Llama3-76B-AWQ', model_path=None, ms_revision=None, hf_revision=None)], ignore_patterns=None, requires=None, tags=[]), ModelGroup(models=[Model(ms_model_id='OpenGVLab/InternVL2-8B-MPO', hf_model_id='OpenGVLab/InternVL2-8B-MPO', model_path=None, ms_revision=None, hf_revision=None)], ignore_patterns=None, requires=None, tags=[]), ModelGroup(models=[Model(ms_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-1B-Pretrain', hf_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-1B-Pretrain', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-2B-Pretrain', hf_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-2B-Pretrain', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-4B-Pretrain', hf_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-4B-Pretrain', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-8B-Pretrain', hf_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-8B-Pretrain', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-26B-Pretrain', hf_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-26B-Pretrain', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-40B-Pretrain', hf_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-40B-Pretrain', model_path=None, ms_revision=None, hf_revision=None), Model(ms_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-Llama3-76B-Pretrain', hf_model_id='OpenGVLab/InternVL2-Pretrain-Models:InternVL2-Llama3-76B-Pretrain', model_path=None, ms_revision=None, hf_revision=None)], ignore_patterns=None, requires=None, tags=[])], template='internvl2', get_function=<function get_model_tokenizer_internvl at 0x7f9363136f80>, model_arch='internvl', architectures=['InternVLChatModel'], additional_saved_files=[], torch_dtype=None, is_multimodal=True, is_reward=False, task_type=None, ignore_patterns=[], requires=['transformers>=4.36', 'timm'], tags=['vision', 'video'])",
367
+ "model_dir": "/cpfs04/user/zhangqi/zhangqi/data/model_garden/0619_intern8b_v7-1-part10-14-resize-constant/v0-20250619-124555/checkpoint-3125",
368
+ "hub": "<class 'swift.hub.hub.MSHub'>",
369
+ "training_args": "Seq2SeqTrainingArguments(output_dir='/cpfs04/user/zhangqi/zhangqi/data/model_garden/0619_intern8b_v7-1-part15-19-resize-decay/v1-20250624-140732', overwrite_output_dir=False, do_train=False, do_eval=True, do_predict=False, eval_strategy=<IntervalStrategy.STEPS: 'steps'>, prediction_loss_only=False, per_device_train_batch_size=2, per_device_eval_batch_size=1, per_gpu_train_batch_size=None, per_gpu_eval_batch_size=None, gradient_accumulation_steps=8, eval_accumulation_steps=None, eval_delay=0, torch_empty_cache_steps=None, learning_rate=2e-05, weight_decay=0.1, adam_beta1=0.9, adam_beta2=0.95, adam_epsilon=1e-08, max_grad_norm=1.0, num_train_epochs=1.0, max_steps=-1, lr_scheduler_type=<SchedulerType.COSINE: 'cosine'>, lr_scheduler_kwargs=None, warmup_ratio=0.0, warmup_steps=100, log_level='passive', log_level_replica='warning', log_on_each_node=True, logging_dir='/cpfs04/user/zhangqi/zhangqi/data/model_garden/0619_intern8b_v7-1-part15-19-resize-decay/v1-20250624-140732/runs', logging_strategy=<IntervalStrategy.STEPS: 'steps'>, logging_first_step=True, logging_steps=5, logging_nan_inf_filter=True, save_strategy=<IntervalStrategy.STEPS: 'steps'>, save_steps=1000, save_total_limit=1, save_safetensors=True, save_on_each_node=False, save_only_model=False, restore_callback_states_from_checkpoint=False, no_cuda=False, use_cpu=False, use_mps_device=False, seed=42, data_seed=42, jit_mode_eval=False, use_ipex=False, bf16=True, fp16=False, fp16_opt_level='O1', half_precision_backend='auto', bf16_full_eval=False, fp16_full_eval=False, tf32=None, local_rank=0, ddp_backend=None, tpu_num_cores=None, tpu_metrics_debug=False, debug=[], dataloader_drop_last=False, eval_steps=250, dataloader_num_workers=4, dataloader_prefetch_factor=None, past_index=-1, run_name='/cpfs04/user/zhangqi/zhangqi/data/model_garden/0619_intern8b_v7-1-part15-19-resize-decay/v1-20250624-140732', disable_tqdm=False, remove_unused_columns=False, label_names=None, load_best_model_at_end=False, metric_for_best_model='loss', greater_is_better=False, ignore_data_skip=False, fsdp=[], fsdp_min_num_params=0, fsdp_config={'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}, fsdp_transformer_layer_cls_to_wrap=None, accelerator_config=AcceleratorConfig(split_batches=False, dispatch_batches=False, even_batches=True, use_seedable_sampler=True, non_blocking=False, gradient_accumulation_kwargs=None, use_configured_state=False), deepspeed={'fp16': {'enabled': 'auto', 'loss_scale': 0, 'loss_scale_window': 1000, 'initial_scale_power': 16, 'hysteresis': 2, 'min_loss_scale': 1}, 'bf16': {'enabled': 'auto'}, 'zero_optimization': {'stage': 3, 'offload_optimizer': {'device': 'none', 'pin_memory': True}, 'offload_param': {'device': 'none', 'pin_memory': True}, 'overlap_comm': False, 'contiguous_gradients': True, 'sub_group_size': 1000000000.0, 'reduce_bucket_size': 'auto', 'zero_quantized_weights': False, 'zero_quantized_gradients': False, 'stage3_prefetch_bucket_size': 'auto', 'stage3_param_persistence_threshold': 'auto', 'stage3_max_live_parameters': 1000000000.0, 'stage3_max_reuse_distance': 1000000000.0, 'stage3_gather_16bit_weights_on_model_save': True}, 'gradient_accumulation_steps': 'auto', 'gradient_clipping': 'auto', 'steps_per_print': 2000, 'train_batch_size': 'auto', 'train_micro_batch_size_per_gpu': 'auto', 'wall_clock_breakdown': False}, label_smoothing_factor=0.0, optim=<OptimizerNames.ADAMW_TORCH: 'adamw_torch'>, optim_args=None, adafactor=False, group_by_length=False, length_column_name='length', report_to=['tensorboard'], ddp_find_unused_parameters=None, ddp_bucket_cap_mb=None, ddp_broadcast_buffers=None, dataloader_pin_memory=True, dataloader_persistent_workers=False, skip_memory_metrics=True, use_legacy_prediction_loop=False, push_to_hub=False, resume_from_checkpoint=None, hub_model_id=None, hub_strategy=<HubStrategy.EVERY_SAVE: 'every_save'>, hub_token=None, hub_private_repo=False, hub_always_push=False, gradient_checkpointing=True, gradient_checkpointing_kwargs=None, include_inputs_for_metrics=False, include_for_metrics=[], eval_do_concat_batches=True, fp16_backend='auto', evaluation_strategy='steps', push_to_hub_model_id=None, push_to_hub_organization=None, push_to_hub_token=None, mp_parameters='', auto_find_batch_size=False, full_determinism=False, torchdynamo=None, ray_scope='last', ddp_timeout=1800, torch_compile=False, torch_compile_backend=None, torch_compile_mode=None, dispatch_batches=None, split_batches=None, include_tokens_per_second=None, include_num_input_tokens_seen=None, neftune_noise_alpha=None, optim_target_modules=None, batch_eval_metrics=False, eval_on_start=False, use_liger_kernel=False, eval_use_gather_object=False, average_tokens_across_devices=None, sortish_sampler=False, predict_with_generate=False, generation_max_length=None, generation_num_beams=None, generation_config=None, check_model=True, acc_strategy='token', train_sampler_random=True, metric_warmup_step=0, fsdp_num=1, acc_steps=1, eval_use_evalscope=False, eval_datasets=[], eval_limit=None, eval_datasets_args=None, eval_generation_config=None, train_type='full', optimizer=None, local_repo_path=None, galore_config=None)"
370
+ }
VLAC/model/VLAC-8b/config.json ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "_name_or_path": "/cpfs04/user/zhangqi/zhangqi/data/model_garden/0619_intern8b_v7-1-part10-14-resize-constant/v0-20250619-124555/checkpoint-3125",
4
+ "architectures": [
5
+ "InternVLChatModel"
6
+ ],
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_internvl_chat.InternVLChatConfig",
10
+ "AutoModel": "modeling_internvl_chat.InternVLChatModel",
11
+ "AutoModelForCausalLM": "modeling_internvl_chat.InternVLChatModel"
12
+ },
13
+ "bias": false,
14
+ "bos_token_id": 1,
15
+ "downsample_ratio": 0.5,
16
+ "dynamic_image_size": true,
17
+ "eos_token_id": 2,
18
+ "force_image_size": 448,
19
+ "hidden_act": "silu",
20
+ "hidden_size": 4096,
21
+ "initializer_range": 0.02,
22
+ "intermediate_size": 14336,
23
+ "keys_to_ignore_at_inference": [
24
+ "past_key_values"
25
+ ],
26
+ "llm_config": {
27
+ "_attn_implementation_autoset": true,
28
+ "_name_or_path": "internlm/internlm2_5-7b-chat",
29
+ "add_cross_attention": false,
30
+ "architectures": [
31
+ "InternLM2ForCausalLM"
32
+ ],
33
+ "attn_implementation": "flash_attention_2",
34
+ "auto_map": {
35
+ "AutoConfig": "configuration_internlm2.InternLM2Config",
36
+ "AutoModel": "modeling_internlm2.InternLM2ForCausalLM",
37
+ "AutoModelForCausalLM": "modeling_internlm2.InternLM2ForCausalLM"
38
+ },
39
+ "bad_words_ids": null,
40
+ "begin_suppress_tokens": null,
41
+ "bias": false,
42
+ "bos_token_id": 1,
43
+ "chunk_size_feed_forward": 0,
44
+ "cross_attention_hidden_size": null,
45
+ "decoder_start_token_id": null,
46
+ "diversity_penalty": 0.0,
47
+ "do_sample": false,
48
+ "early_stopping": false,
49
+ "encoder_no_repeat_ngram_size": 0,
50
+ "eos_token_id": 2,
51
+ "exponential_decay_length_penalty": null,
52
+ "finetuning_task": null,
53
+ "forced_bos_token_id": null,
54
+ "forced_eos_token_id": null,
55
+ "hidden_act": "silu",
56
+ "hidden_size": 4096,
57
+ "id2label": {
58
+ "0": "LABEL_0",
59
+ "1": "LABEL_1"
60
+ },
61
+ "initializer_range": 0.02,
62
+ "intermediate_size": 14336,
63
+ "is_decoder": false,
64
+ "is_encoder_decoder": false,
65
+ "label2id": {
66
+ "LABEL_0": 0,
67
+ "LABEL_1": 1
68
+ },
69
+ "length_penalty": 1.0,
70
+ "max_length": 20,
71
+ "max_position_embeddings": 32768,
72
+ "min_length": 0,
73
+ "model_type": "internlm2",
74
+ "no_repeat_ngram_size": 0,
75
+ "num_attention_heads": 32,
76
+ "num_beam_groups": 1,
77
+ "num_beams": 1,
78
+ "num_hidden_layers": 32,
79
+ "num_key_value_heads": 8,
80
+ "num_return_sequences": 1,
81
+ "output_attentions": false,
82
+ "output_hidden_states": false,
83
+ "output_scores": false,
84
+ "pad_token_id": 2,
85
+ "prefix": null,
86
+ "pretraining_tp": 1,
87
+ "problem_type": null,
88
+ "pruned_heads": {},
89
+ "remove_invalid_values": false,
90
+ "repetition_penalty": 1.0,
91
+ "return_dict": true,
92
+ "return_dict_in_generate": false,
93
+ "rms_norm_eps": 1e-05,
94
+ "rope_scaling": {
95
+ "factor": 2.0,
96
+ "type": "dynamic"
97
+ },
98
+ "rope_theta": 1000000,
99
+ "sep_token_id": null,
100
+ "suppress_tokens": null,
101
+ "task_specific_params": null,
102
+ "temperature": 1.0,
103
+ "tf_legacy_loss": false,
104
+ "tie_encoder_decoder": false,
105
+ "tie_word_embeddings": false,
106
+ "tokenizer_class": null,
107
+ "top_k": 50,
108
+ "top_p": 1.0,
109
+ "torch_dtype": "bfloat16",
110
+ "torchscript": false,
111
+ "transformers_version": "4.46.2",
112
+ "typical_p": 1.0,
113
+ "use_bfloat16": true,
114
+ "use_cache": false,
115
+ "vocab_size": 92553
116
+ },
117
+ "max_dynamic_patch": 12,
118
+ "max_position_embeddings": 32768,
119
+ "min_dynamic_patch": 1,
120
+ "model_type": "internvl_chat",
121
+ "num_attention_heads": 32,
122
+ "num_hidden_layers": 32,
123
+ "num_key_value_heads": 8,
124
+ "pad_token_id": 2,
125
+ "pretraining_tp": 1,
126
+ "ps_version": "v2",
127
+ "rms_norm_eps": 1e-05,
128
+ "rope_scaling": {
129
+ "factor": 2.0,
130
+ "type": "dynamic"
131
+ },
132
+ "rope_theta": 1000000,
133
+ "select_layer": -1,
134
+ "template": "internlm2-chat",
135
+ "tie_word_embeddings": false,
136
+ "torch_dtype": "bfloat16",
137
+ "transformers_version": "4.37.2",
138
+ "use_backbone_lora": 0,
139
+ "use_bfloat16": true,
140
+ "use_cache": false,
141
+ "use_llm_lora": 0,
142
+ "use_thumbnail": true,
143
+ "vision_config": {
144
+ "_attn_implementation_autoset": true,
145
+ "_name_or_path": "",
146
+ "add_cross_attention": false,
147
+ "architectures": [
148
+ "InternVisionModel"
149
+ ],
150
+ "attention_dropout": 0.0,
151
+ "bad_words_ids": null,
152
+ "begin_suppress_tokens": null,
153
+ "bos_token_id": null,
154
+ "chunk_size_feed_forward": 0,
155
+ "cross_attention_hidden_size": null,
156
+ "decoder_start_token_id": null,
157
+ "diversity_penalty": 0.0,
158
+ "do_sample": false,
159
+ "drop_path_rate": 0.0,
160
+ "dropout": 0.0,
161
+ "early_stopping": false,
162
+ "encoder_no_repeat_ngram_size": 0,
163
+ "eos_token_id": null,
164
+ "exponential_decay_length_penalty": null,
165
+ "finetuning_task": null,
166
+ "forced_bos_token_id": null,
167
+ "forced_eos_token_id": null,
168
+ "hidden_act": "gelu",
169
+ "hidden_size": 1024,
170
+ "id2label": {
171
+ "0": "LABEL_0",
172
+ "1": "LABEL_1"
173
+ },
174
+ "image_size": 448,
175
+ "initializer_factor": 1.0,
176
+ "initializer_range": 0.02,
177
+ "intermediate_size": 4096,
178
+ "is_decoder": false,
179
+ "is_encoder_decoder": false,
180
+ "label2id": {
181
+ "LABEL_0": 0,
182
+ "LABEL_1": 1
183
+ },
184
+ "layer_norm_eps": 1e-06,
185
+ "length_penalty": 1.0,
186
+ "max_length": 20,
187
+ "min_length": 0,
188
+ "model_type": "intern_vit_6b",
189
+ "no_repeat_ngram_size": 0,
190
+ "norm_type": "layer_norm",
191
+ "num_attention_heads": 16,
192
+ "num_beam_groups": 1,
193
+ "num_beams": 1,
194
+ "num_channels": 3,
195
+ "num_hidden_layers": 24,
196
+ "num_return_sequences": 1,
197
+ "output_attentions": false,
198
+ "output_hidden_states": false,
199
+ "output_scores": false,
200
+ "pad_token_id": 2,
201
+ "patch_size": 14,
202
+ "prefix": null,
203
+ "problem_type": null,
204
+ "pruned_heads": {},
205
+ "qk_normalization": false,
206
+ "qkv_bias": true,
207
+ "remove_invalid_values": false,
208
+ "repetition_penalty": 1.0,
209
+ "return_dict": true,
210
+ "return_dict_in_generate": false,
211
+ "sep_token_id": null,
212
+ "suppress_tokens": null,
213
+ "task_specific_params": null,
214
+ "temperature": 1.0,
215
+ "tf_legacy_loss": false,
216
+ "tie_encoder_decoder": false,
217
+ "tie_word_embeddings": true,
218
+ "tokenizer_class": null,
219
+ "top_k": 50,
220
+ "top_p": 1.0,
221
+ "torch_dtype": "bfloat16",
222
+ "torchscript": false,
223
+ "transformers_version": "4.46.2",
224
+ "typical_p": 1.0,
225
+ "use_bfloat16": true,
226
+ "use_flash_attn": true
227
+ },
228
+ "vocab_size": 92553
229
+ }
VLAC/model/VLAC-8b/configuration_intern_vit.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import os
7
+ from typing import Union
8
+
9
+ from transformers.configuration_utils import PretrainedConfig
10
+ from transformers.utils import logging
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class InternVisionConfig(PretrainedConfig):
16
+ r"""
17
+ This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
18
+ instantiate a vision encoder according to the specified arguments, defining the model architecture.
19
+
20
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
21
+ documentation from [`PretrainedConfig`] for more information.
22
+
23
+ Args:
24
+ num_channels (`int`, *optional*, defaults to 3):
25
+ Number of color channels in the input images (e.g., 3 for RGB).
26
+ patch_size (`int`, *optional*, defaults to 14):
27
+ The size (resolution) of each patch.
28
+ image_size (`int`, *optional*, defaults to 224):
29
+ The size (resolution) of each image.
30
+ qkv_bias (`bool`, *optional*, defaults to `False`):
31
+ Whether to add a bias to the queries and values in the self-attention layers.
32
+ hidden_size (`int`, *optional*, defaults to 3200):
33
+ Dimensionality of the encoder layers and the pooler layer.
34
+ num_attention_heads (`int`, *optional*, defaults to 25):
35
+ Number of attention heads for each attention layer in the Transformer encoder.
36
+ intermediate_size (`int`, *optional*, defaults to 12800):
37
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
38
+ qk_normalization (`bool`, *optional*, defaults to `True`):
39
+ Whether to normalize the queries and keys in the self-attention layers.
40
+ num_hidden_layers (`int`, *optional*, defaults to 48):
41
+ Number of hidden layers in the Transformer encoder.
42
+ use_flash_attn (`bool`, *optional*, defaults to `True`):
43
+ Whether to use flash attention mechanism.
44
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
45
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
46
+ `"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
47
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
48
+ The epsilon used by the layer normalization layers.
49
+ dropout (`float`, *optional*, defaults to 0.0):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
52
+ Dropout rate for stochastic depth.
53
+ attention_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for the attention probabilities.
55
+ initializer_range (`float`, *optional*, defaults to 0.02):
56
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
57
+ initializer_factor (`float`, *optional*, defaults to 0.1):
58
+ A factor for layer scale.
59
+ """
60
+
61
+ model_type = 'intern_vit_6b'
62
+
63
+ def __init__(
64
+ self,
65
+ num_channels=3,
66
+ patch_size=14,
67
+ image_size=224,
68
+ qkv_bias=False,
69
+ hidden_size=3200,
70
+ num_attention_heads=25,
71
+ intermediate_size=12800,
72
+ qk_normalization=True,
73
+ num_hidden_layers=48,
74
+ use_flash_attn=True,
75
+ hidden_act='gelu',
76
+ norm_type='rms_norm',
77
+ layer_norm_eps=1e-6,
78
+ dropout=0.0,
79
+ drop_path_rate=0.0,
80
+ attention_dropout=0.0,
81
+ initializer_range=0.02,
82
+ initializer_factor=0.1,
83
+ **kwargs,
84
+ ):
85
+ super().__init__(**kwargs)
86
+
87
+ self.hidden_size = hidden_size
88
+ self.intermediate_size = intermediate_size
89
+ self.dropout = dropout
90
+ self.drop_path_rate = drop_path_rate
91
+ self.num_hidden_layers = num_hidden_layers
92
+ self.num_attention_heads = num_attention_heads
93
+ self.num_channels = num_channels
94
+ self.patch_size = patch_size
95
+ self.image_size = image_size
96
+ self.initializer_range = initializer_range
97
+ self.initializer_factor = initializer_factor
98
+ self.attention_dropout = attention_dropout
99
+ self.layer_norm_eps = layer_norm_eps
100
+ self.hidden_act = hidden_act
101
+ self.norm_type = norm_type
102
+ self.qkv_bias = qkv_bias
103
+ self.qk_normalization = qk_normalization
104
+ self.use_flash_attn = use_flash_attn
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
108
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
109
+
110
+ if 'vision_config' in config_dict:
111
+ config_dict = config_dict['vision_config']
112
+
113
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
114
+ logger.warning(
115
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
116
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
117
+ )
118
+
119
+ return cls.from_dict(config_dict, **kwargs)
VLAC/model/VLAC-8b/configuration_internlm2.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/configuration_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ InternLM2 model configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ INTERNLM2_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
24
+
25
+
26
+ # Modified from transformers.model.llama.configuration_llama.LlamaConfig
27
+ class InternLM2Config(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`InternLM2Model`]. It is used to instantiate
30
+ an InternLM2 model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the InternLM2-7B.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the InternLM2 model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`InternLM2Model`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 11008):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer encoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
56
+ `num_attention_heads`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
70
+ Whether to tie weight embeddings
71
+ Example:
72
+
73
+ """
74
+ model_type = 'internlm2'
75
+ _auto_class = 'AutoConfig'
76
+
77
+ def __init__( # pylint: disable=W0102
78
+ self,
79
+ vocab_size=103168,
80
+ hidden_size=4096,
81
+ intermediate_size=11008,
82
+ num_hidden_layers=32,
83
+ num_attention_heads=32,
84
+ num_key_value_heads=None,
85
+ hidden_act='silu',
86
+ max_position_embeddings=2048,
87
+ initializer_range=0.02,
88
+ rms_norm_eps=1e-6,
89
+ use_cache=True,
90
+ pad_token_id=0,
91
+ bos_token_id=1,
92
+ eos_token_id=2,
93
+ tie_word_embeddings=False,
94
+ bias=True,
95
+ rope_theta=10000,
96
+ rope_scaling=None,
97
+ attn_implementation='eager',
98
+ **kwargs,
99
+ ):
100
+ self.vocab_size = vocab_size
101
+ self.max_position_embeddings = max_position_embeddings
102
+ self.hidden_size = hidden_size
103
+ self.intermediate_size = intermediate_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.num_attention_heads = num_attention_heads
106
+ self.bias = bias
107
+
108
+ if num_key_value_heads is None:
109
+ num_key_value_heads = num_attention_heads
110
+ self.num_key_value_heads = num_key_value_heads
111
+
112
+ self.hidden_act = hidden_act
113
+ self.initializer_range = initializer_range
114
+ self.rms_norm_eps = rms_norm_eps
115
+ self.use_cache = use_cache
116
+ self.rope_theta = rope_theta
117
+ self.rope_scaling = rope_scaling
118
+ self._rope_scaling_validation()
119
+
120
+ self.attn_implementation = attn_implementation
121
+ if self.attn_implementation is None:
122
+ self.attn_implementation = 'eager'
123
+ super().__init__(
124
+ pad_token_id=pad_token_id,
125
+ bos_token_id=bos_token_id,
126
+ eos_token_id=eos_token_id,
127
+ tie_word_embeddings=tie_word_embeddings,
128
+ **kwargs,
129
+ )
130
+
131
+ def _rope_scaling_validation(self):
132
+ """
133
+ Validate the `rope_scaling` configuration.
134
+ """
135
+ if self.rope_scaling is None:
136
+ return
137
+
138
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
139
+ raise ValueError(
140
+ '`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, '
141
+ f'got {self.rope_scaling}'
142
+ )
143
+ rope_scaling_type = self.rope_scaling.get('type', None)
144
+ rope_scaling_factor = self.rope_scaling.get('factor', None)
145
+ if rope_scaling_type is None or rope_scaling_type not in ['linear', 'dynamic']:
146
+ raise ValueError(
147
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
148
+ )
149
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor < 1.0:
150
+ raise ValueError(f"`rope_scaling`'s factor field must be a float >= 1, got {rope_scaling_factor}")
VLAC/model/VLAC-8b/configuration_internvl_chat.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+
7
+ import copy
8
+
9
+ from transformers import AutoConfig, LlamaConfig
10
+ from transformers.configuration_utils import PretrainedConfig
11
+ from transformers.utils import logging
12
+
13
+ from .configuration_intern_vit import InternVisionConfig
14
+ from .configuration_internlm2 import InternLM2Config
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+
19
+ class InternVLChatConfig(PretrainedConfig):
20
+ model_type = 'internvl_chat'
21
+ is_composition = True
22
+
23
+ def __init__(
24
+ self,
25
+ vision_config=None,
26
+ llm_config=None,
27
+ use_backbone_lora=0,
28
+ use_llm_lora=0,
29
+ select_layer=-1,
30
+ force_image_size=None,
31
+ downsample_ratio=0.5,
32
+ template=None,
33
+ dynamic_image_size=False,
34
+ use_thumbnail=False,
35
+ ps_version='v1',
36
+ min_dynamic_patch=1,
37
+ max_dynamic_patch=6,
38
+ **kwargs):
39
+ super().__init__(**kwargs)
40
+
41
+ if vision_config is None:
42
+ vision_config = {}
43
+ logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
44
+
45
+ if llm_config is None:
46
+ llm_config = {}
47
+ logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
48
+
49
+ self.vision_config = InternVisionConfig(**vision_config)
50
+ # if llm_config['architectures'][0] == 'LlamaForCausalLM':
51
+ # self.llm_config = LlamaConfig(**llm_config)
52
+ # elif llm_config['architectures'][0] == 'InternLM2ForCausalLM':
53
+ self.llm_config = InternLM2Config(**llm_config)
54
+ # else:
55
+ # raise ValueError('Unsupported architecture: {}'.format(llm_config['architectures'][0]))
56
+ self.use_backbone_lora = use_backbone_lora
57
+ self.use_llm_lora = use_llm_lora
58
+ self.select_layer = select_layer
59
+ self.force_image_size = force_image_size
60
+ self.downsample_ratio = downsample_ratio
61
+ self.template = template
62
+ self.dynamic_image_size = dynamic_image_size
63
+ self.use_thumbnail = use_thumbnail
64
+ self.ps_version = ps_version # pixel shuffle version
65
+ self.min_dynamic_patch = min_dynamic_patch
66
+ self.max_dynamic_patch = max_dynamic_patch
67
+
68
+ logger.info(f'vision_select_layer: {self.select_layer}')
69
+ logger.info(f'ps_version: {self.ps_version}')
70
+ logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
71
+ logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
72
+
73
+ def to_dict(self):
74
+ """
75
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
76
+
77
+ Returns:
78
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
79
+ """
80
+ output = copy.deepcopy(self.__dict__)
81
+ output['vision_config'] = self.vision_config.to_dict()
82
+ output['llm_config'] = self.llm_config.to_dict()
83
+ output['model_type'] = self.__class__.model_type
84
+ output['use_backbone_lora'] = self.use_backbone_lora
85
+ output['use_llm_lora'] = self.use_llm_lora
86
+ output['select_layer'] = self.select_layer
87
+ output['force_image_size'] = self.force_image_size
88
+ output['downsample_ratio'] = self.downsample_ratio
89
+ output['template'] = self.template
90
+ output['dynamic_image_size'] = self.dynamic_image_size
91
+ output['use_thumbnail'] = self.use_thumbnail
92
+ output['ps_version'] = self.ps_version
93
+ output['min_dynamic_patch'] = self.min_dynamic_patch
94
+ output['max_dynamic_patch'] = self.max_dynamic_patch
95
+
96
+ return output
VLAC/model/VLAC-8b/conversation.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversation prompt templates.
3
+
4
+ We kindly request that you import fastchat instead of copying this file if you wish to use it.
5
+ If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
6
+ """
7
+
8
+ import dataclasses
9
+ from enum import IntEnum, auto
10
+ from typing import Any, Dict, List, Tuple, Union
11
+
12
+
13
+ class SeparatorStyle(IntEnum):
14
+ """Separator styles."""
15
+
16
+ ADD_COLON_SINGLE = auto()
17
+ ADD_COLON_TWO = auto()
18
+ ADD_COLON_SPACE_SINGLE = auto()
19
+ NO_COLON_SINGLE = auto()
20
+ NO_COLON_TWO = auto()
21
+ ADD_NEW_LINE_SINGLE = auto()
22
+ LLAMA2 = auto()
23
+ CHATGLM = auto()
24
+ CHATML = auto()
25
+ CHATINTERN = auto()
26
+ DOLLY = auto()
27
+ RWKV = auto()
28
+ PHOENIX = auto()
29
+ ROBIN = auto()
30
+ FALCON_CHAT = auto()
31
+ CHATGLM3 = auto()
32
+ INTERNVL_ZH = auto()
33
+ MPT = auto()
34
+
35
+
36
+ @dataclasses.dataclass
37
+ class Conversation:
38
+ """A class that manages prompt templates and keeps all conversation history."""
39
+
40
+ # The name of this template
41
+ name: str
42
+ # The template of the system prompt
43
+ system_template: str = '{system_message}'
44
+ # The system message
45
+ system_message: str = ''
46
+ # The names of two roles
47
+ roles: Tuple[str] = ('USER', 'ASSISTANT')
48
+ # All messages. Each item is (role, message).
49
+ messages: List[List[str]] = ()
50
+ # The number of few shot examples
51
+ offset: int = 0
52
+ # The separator style and configurations
53
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
54
+ sep: str = '\n'
55
+ sep2: str = None
56
+ # Stop criteria (the default one is EOS token)
57
+ stop_str: Union[str, List[str]] = None
58
+ # Stops generation if meeting any token in this list
59
+ stop_token_ids: List[int] = None
60
+
61
+ def get_prompt(self) -> str:
62
+ """Get the prompt for generation."""
63
+ system_prompt = self.system_template.format(system_message=self.system_message)
64
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
65
+ ret = system_prompt + self.sep
66
+ for role, message in self.messages:
67
+ if message:
68
+ ret += role + ': ' + message + self.sep
69
+ else:
70
+ ret += role + ':'
71
+ return ret
72
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
73
+ seps = [self.sep, self.sep2]
74
+ ret = system_prompt + seps[0]
75
+ for i, (role, message) in enumerate(self.messages):
76
+ if message:
77
+ ret += role + ': ' + message + seps[i % 2]
78
+ else:
79
+ ret += role + ':'
80
+ return ret
81
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
82
+ ret = system_prompt + self.sep
83
+ for role, message in self.messages:
84
+ if message:
85
+ ret += role + ': ' + message + self.sep
86
+ else:
87
+ ret += role + ': ' # must be end with a space
88
+ return ret
89
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
90
+ ret = '' if system_prompt == '' else system_prompt + self.sep
91
+ for role, message in self.messages:
92
+ if message:
93
+ ret += role + '\n' + message + self.sep
94
+ else:
95
+ ret += role + '\n'
96
+ return ret
97
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
98
+ ret = system_prompt
99
+ for role, message in self.messages:
100
+ if message:
101
+ ret += role + message + self.sep
102
+ else:
103
+ ret += role
104
+ return ret
105
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
106
+ seps = [self.sep, self.sep2]
107
+ ret = system_prompt
108
+ for i, (role, message) in enumerate(self.messages):
109
+ if message:
110
+ ret += role + message + seps[i % 2]
111
+ else:
112
+ ret += role
113
+ return ret
114
+ elif self.sep_style == SeparatorStyle.RWKV:
115
+ ret = system_prompt
116
+ for i, (role, message) in enumerate(self.messages):
117
+ if message:
118
+ ret += (
119
+ role
120
+ + ': '
121
+ + message.replace('\r\n', '\n').replace('\n\n', '\n')
122
+ )
123
+ ret += '\n\n'
124
+ else:
125
+ ret += role + ':'
126
+ return ret
127
+ elif self.sep_style == SeparatorStyle.LLAMA2:
128
+ seps = [self.sep, self.sep2]
129
+ if self.system_message:
130
+ ret = system_prompt
131
+ else:
132
+ ret = '[INST] '
133
+ for i, (role, message) in enumerate(self.messages):
134
+ tag = self.roles[i % 2]
135
+ if message:
136
+ if i == 0:
137
+ ret += message + ' '
138
+ else:
139
+ ret += tag + ' ' + message + seps[i % 2]
140
+ else:
141
+ ret += tag
142
+ return ret
143
+ elif self.sep_style == SeparatorStyle.CHATGLM:
144
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
145
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
146
+ round_add_n = 1 if self.name == 'chatglm2' else 0
147
+ if system_prompt:
148
+ ret = system_prompt + self.sep
149
+ else:
150
+ ret = ''
151
+
152
+ for i, (role, message) in enumerate(self.messages):
153
+ if i % 2 == 0:
154
+ ret += f'[Round {i//2 + round_add_n}]{self.sep}'
155
+
156
+ if message:
157
+ ret += f'{role}:{message}{self.sep}'
158
+ else:
159
+ ret += f'{role}:'
160
+ return ret
161
+ elif self.sep_style == SeparatorStyle.CHATML:
162
+ ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
163
+ for role, message in self.messages:
164
+ if message:
165
+ ret += role + '\n' + message + self.sep + '\n'
166
+ else:
167
+ ret += role + '\n'
168
+ return ret
169
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
170
+ ret = ''
171
+ if self.system_message:
172
+ ret += system_prompt
173
+ for role, message in self.messages:
174
+ if message:
175
+ ret += role + '\n' + ' ' + message
176
+ else:
177
+ ret += role
178
+ return ret
179
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
180
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
181
+ seps = [self.sep, self.sep2]
182
+ ret = system_prompt
183
+ for i, (role, message) in enumerate(self.messages):
184
+ # if i % 2 == 0:
185
+ # ret += "<s>"
186
+ if message:
187
+ ret += role + ':' + message + seps[i % 2] + '\n'
188
+ else:
189
+ ret += role + ':'
190
+ return ret
191
+ elif self.sep_style == SeparatorStyle.DOLLY:
192
+ seps = [self.sep, self.sep2]
193
+ ret = system_prompt
194
+ for i, (role, message) in enumerate(self.messages):
195
+ if message:
196
+ ret += role + ':\n' + message + seps[i % 2]
197
+ if i % 2 == 1:
198
+ ret += '\n\n'
199
+ else:
200
+ ret += role + ':\n'
201
+ return ret
202
+ elif self.sep_style == SeparatorStyle.PHOENIX:
203
+ ret = system_prompt
204
+ for role, message in self.messages:
205
+ if message:
206
+ ret += role + ': ' + '<s>' + message + '</s>'
207
+ else:
208
+ ret += role + ': ' + '<s>'
209
+ return ret
210
+ elif self.sep_style == SeparatorStyle.ROBIN:
211
+ ret = system_prompt + self.sep
212
+ for role, message in self.messages:
213
+ if message:
214
+ ret += role + ':\n' + message + self.sep
215
+ else:
216
+ ret += role + ':\n'
217
+ return ret
218
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
219
+ ret = ''
220
+ if self.system_message:
221
+ ret += system_prompt + self.sep
222
+ for role, message in self.messages:
223
+ if message:
224
+ ret += role + ': ' + message + self.sep
225
+ else:
226
+ ret += role + ':'
227
+
228
+ return ret
229
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
230
+ seps = [self.sep, self.sep2]
231
+ ret = self.system_message + seps[0]
232
+ for i, (role, message) in enumerate(self.messages):
233
+ if message:
234
+ ret += role + ': ' + message + seps[i % 2]
235
+ else:
236
+ ret += role + ':'
237
+ return ret
238
+ elif self.sep_style == SeparatorStyle.MPT:
239
+ ret = system_prompt + self.sep
240
+ for role, message in self.messages:
241
+ if message:
242
+ if type(message) is tuple:
243
+ message, _, _ = message
244
+ ret += role + message + self.sep
245
+ else:
246
+ ret += role
247
+ return ret
248
+ else:
249
+ raise ValueError(f'Invalid style: {self.sep_style}')
250
+
251
+ def set_system_message(self, system_message: str):
252
+ """Set the system message."""
253
+ self.system_message = system_message
254
+
255
+ def append_message(self, role: str, message: str):
256
+ """Append a new message."""
257
+ self.messages.append([role, message])
258
+
259
+ def update_last_message(self, message: str):
260
+ """Update the last output.
261
+
262
+ The last message is typically set to be None when constructing the prompt,
263
+ so we need to update it in-place after getting the response from a model.
264
+ """
265
+ self.messages[-1][1] = message
266
+
267
+ def to_gradio_chatbot(self):
268
+ """Convert the conversation to gradio chatbot format."""
269
+ ret = []
270
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
271
+ if i % 2 == 0:
272
+ ret.append([msg, None])
273
+ else:
274
+ ret[-1][-1] = msg
275
+ return ret
276
+
277
+ def to_openai_api_messages(self):
278
+ """Convert the conversation to OpenAI chat completion format."""
279
+ ret = [{'role': 'system', 'content': self.system_message}]
280
+
281
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
282
+ if i % 2 == 0:
283
+ ret.append({'role': 'user', 'content': msg})
284
+ else:
285
+ if msg is not None:
286
+ ret.append({'role': 'assistant', 'content': msg})
287
+ return ret
288
+
289
+ def copy(self):
290
+ return Conversation(
291
+ name=self.name,
292
+ system_template=self.system_template,
293
+ system_message=self.system_message,
294
+ roles=self.roles,
295
+ messages=[[x, y] for x, y in self.messages],
296
+ offset=self.offset,
297
+ sep_style=self.sep_style,
298
+ sep=self.sep,
299
+ sep2=self.sep2,
300
+ stop_str=self.stop_str,
301
+ stop_token_ids=self.stop_token_ids,
302
+ )
303
+
304
+ def dict(self):
305
+ return {
306
+ 'template_name': self.name,
307
+ 'system_message': self.system_message,
308
+ 'roles': self.roles,
309
+ 'messages': self.messages,
310
+ 'offset': self.offset,
311
+ }
312
+
313
+
314
+ # A global registry for all conversation templates
315
+ conv_templates: Dict[str, Conversation] = {}
316
+
317
+
318
+ def register_conv_template(template: Conversation, override: bool = False):
319
+ """Register a new conversation template."""
320
+ if not override:
321
+ assert (
322
+ template.name not in conv_templates
323
+ ), f'{template.name} has been registered.'
324
+
325
+ conv_templates[template.name] = template
326
+
327
+
328
+ def get_conv_template(name: str) -> Conversation:
329
+ """Get a conversation template."""
330
+ return conv_templates[name].copy()
331
+
332
+
333
+ # Both Hermes-2 and internlm2-chat are chatml-format conversation templates. The difference
334
+ # is that during training, the preprocessing function for the Hermes-2 template doesn't add
335
+ # <s> at the beginning of the tokenized sequence, while the internlm2-chat template does.
336
+ # Therefore, they are completely equivalent during inference.
337
+ register_conv_template(
338
+ Conversation(
339
+ name='Hermes-2',
340
+ system_template='<|im_start|>system\n{system_message}',
341
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
342
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
343
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
344
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
345
+ sep_style=SeparatorStyle.MPT,
346
+ sep='<|im_end|>',
347
+ stop_token_ids=[
348
+ 2,
349
+ 6,
350
+ 7,
351
+ 8,
352
+ ],
353
+ stop_str='<|endoftext|>',
354
+ )
355
+ )
356
+
357
+
358
+ register_conv_template(
359
+ Conversation(
360
+ name='internlm2-chat',
361
+ system_template='<|im_start|>system\n{system_message}',
362
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
363
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
364
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
365
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
366
+ sep_style=SeparatorStyle.MPT,
367
+ sep='<|im_end|>',
368
+ stop_token_ids=[
369
+ 2,
370
+ 92543,
371
+ 92542
372
+ ]
373
+ )
374
+ )
375
+
376
+
377
+ register_conv_template(
378
+ Conversation(
379
+ name='phi3-chat',
380
+ system_template='<|system|>\n{system_message}',
381
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
382
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
383
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
384
+ roles=('<|user|>\n', '<|assistant|>\n'),
385
+ sep_style=SeparatorStyle.MPT,
386
+ sep='<|end|>',
387
+ stop_token_ids=[
388
+ 2,
389
+ 32000,
390
+ 32007
391
+ ]
392
+ )
393
+ )
VLAC/model/VLAC-8b/generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": [
4
+ 92542,
5
+ 92543
6
+ ],
7
+ "transformers_version": "4.46.2"
8
+ }
VLAC/model/VLAC-8b/latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step3125
VLAC/model/VLAC-8b/model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a134340f18e6f362c591d1a0a0482108363ebe5d1ab8e4b3ab647eac3c6a995
3
+ size 4939944336
VLAC/model/VLAC-8b/model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7d0a8174fc1c5c4358d3abef79e4398738ab632ce358ba62bc442f040967870e
3
+ size 4915914584