GuoruiSong commited on
Commit
07af81f
·
verified ·
1 Parent(s): f01711d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LLaVA-NeXT/.dockerignore +21 -0
  2. LLaVA-NeXT/.editorconfig +18 -0
  3. LLaVA-NeXT/.gitattributes +29 -0
  4. LLaVA-NeXT/.gitignore +73 -0
  5. LLaVA-NeXT/LICENSE +201 -0
  6. LLaVA-NeXT/README.md +247 -0
  7. LLaVA-NeXT/cog.yaml +37 -0
  8. LLaVA-NeXT/docs/onevision_trial.py +111 -0
  9. LLaVA-NeXT/llava-critic-r1/EasyR1/Dockerfile +76 -0
  10. LLaVA-NeXT/llava-critic-r1/EasyR1/Dockerfile.legacy +72 -0
  11. LLaVA-NeXT/llava-critic-r1/EasyR1/LICENSE +201 -0
  12. LLaVA-NeXT/llava-critic-r1/EasyR1/Makefile +18 -0
  13. LLaVA-NeXT/llava-critic-r1/EasyR1/README.md +33 -0
  14. LLaVA-NeXT/llava-critic-r1/EasyR1/assets/baselines.md +53 -0
  15. LLaVA-NeXT/llava-critic-r1/EasyR1/assets/qwen2_5_vl_7b_geo.png +0 -0
  16. LLaVA-NeXT/llava-critic-r1/EasyR1/init +1 -0
  17. LLaVA-NeXT/llava-critic-r1/EasyR1/pyproject.toml +39 -0
  18. LLaVA-NeXT/llava-critic-r1/EasyR1/requirements.txt +19 -0
  19. LLaVA-NeXT/llava-critic-r1/EasyR1/scripts/model_merger.py +187 -0
  20. LLaVA-NeXT/llava-critic-r1/EasyR1/setup.py +61 -0
  21. LLaVA-NeXT/llava-critic-r1/EasyR1/verl.egg-info/SOURCES.txt +133 -0
  22. LLaVA-NeXT/llava-critic-r1/EasyR1/verl.egg-info/dependency_links.txt +1 -0
  23. LLaVA-NeXT/llava-critic-r1/EasyR1/verl.egg-info/requires.txt +23 -0
  24. LLaVA-NeXT/llava-critic-r1/EasyR1/verl.egg-info/top_level.txt +1 -0
  25. LLaVA-NeXT/llava-critic-r1/init +1 -0
  26. LLaVA-NeXT/playground/2d_hist.py +132 -0
  27. LLaVA-NeXT/playground/data_checker.py +364 -0
  28. LLaVA-NeXT/playground/demo/video_demo.py +335 -0
  29. LLaVA-NeXT/playground/equal_splitter.py +38 -0
  30. LLaVA-NeXT/playground/llava_ov_plot.ipynb +0 -0
  31. LLaVA-NeXT/playground/remove_mid_ckpt.py +35 -0
  32. LLaVA-NeXT/playground/sgl_llava_inference_multinode.py +125 -0
  33. LLaVA-NeXT/playground/upload_data.py +217 -0
  34. LLaVA-NeXT/predict.py +146 -0
  35. LLaVA-NeXT/pyproject.toml +101 -0
  36. LLaVA-NeXT/requirements.txt +324 -0
  37. LLaVA-NeXT/scripts/qwen.py +19 -0
  38. LLaVA-NeXT/scripts/summarize_data.py +81 -0
  39. LLaVA-NeXT/scripts/zero2.json +41 -0
  40. LLaVA-NeXT/scripts/zero2_fused_adamw.json +41 -0
  41. LLaVA-NeXT/scripts/zero2_offload.json +31 -0
  42. LLaVA-NeXT/scripts/zero3.json +41 -0
  43. LLaVA-NeXT/scripts/zero3_offload.json +48 -0
  44. LLaVA-NeXT/scripts/zero3pp.json +53 -0
  45. data/SEEDBench_IMG_32.json +162 -0
  46. data/download_data.py +28 -0
  47. data/images/MMK12/129c0f1b-27e7-4db0-b11f-e393d50d1b25.png +0 -0
  48. data/images/MMK12/7d90d0b8-8473-482c-bbd3-bc7707f84b50.png +0 -0
  49. data/images/SEEDBench_IMG/0.jpg +0 -0
  50. data/images/SEEDBench_IMG/1.jpg +0 -0
LLaVA-NeXT/.dockerignore ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The .dockerignore file excludes files from the container build process.
2
+ #
3
+ # https://docs.docker.com/engine/reference/builder/#dockerignore-file
4
+
5
+ # Exclude Git files
6
+ .git
7
+ .github
8
+ .gitignore
9
+
10
+ # Exclude Python cache files
11
+ __pycache__
12
+ .mypy_cache
13
+ .pytest_cache
14
+ .ruff_cache
15
+
16
+ # Exclude Python virtual environment
17
+ /venv
18
+
19
+ # Exclude some weights
20
+ /openai
21
+ /liuhaotian
LLaVA-NeXT/.editorconfig ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root = true
2
+
3
+ # Unix-style newlines with a newline ending every file
4
+ [*]
5
+ end_of_line = lf
6
+ insert_final_newline = true
7
+ trim_trailing_whitespace = true
8
+ charset = utf-8
9
+
10
+ # 4 space indentation
11
+ [*.{py,json}]
12
+ indent_style = space
13
+ indent_size = 4
14
+
15
+ # 2 space indentation
16
+ [*.{md,sh,yaml,yml}]
17
+ indent_style = space
18
+ indent_size = 2
LLaVA-NeXT/.gitattributes ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://git-scm.com/docs/gitattributes
2
+
3
+ # Set the default behavior, in case people don't have core.autocrlf set.
4
+ # https://git-scm.com/docs/gitattributes#_end_of_line_conversion
5
+ * text=auto
6
+
7
+ # common python attributes, taken from https://github.com/alexkaratarakis/gitattributes/blob/710900479a2bedeec7003d381719521ffbb18bf8/Python.gitattributes
8
+ # Source files
9
+ # ============
10
+ *.pxd text diff=python
11
+ *.py text diff=python
12
+ *.py3 text diff=python
13
+ *.pyw text diff=python
14
+ *.pyx text diff=python
15
+ *.pyz text diff=python
16
+ *.pyi text diff=python
17
+
18
+ # Binary files
19
+ # ============
20
+ *.db binary
21
+ *.p binary
22
+ *.pkl binary
23
+ *.pickle binary
24
+ *.pyc binary export-ignore
25
+ *.pyo binary export-ignore
26
+ *.pyd binary
27
+
28
+ # Jupyter notebook
29
+ *.ipynb text eol=lf
LLaVA-NeXT/.gitignore ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__
3
+ *.pyc
4
+ *.egg-info
5
+ dist
6
+
7
+ # Log
8
+ *.log
9
+ *.log.*
10
+ # *.json
11
+ # *.jsonl
12
+
13
+ # Data
14
+ !**/alpaca-data-conversation.json
15
+ # Editor
16
+ .idea
17
+ *.swp
18
+ .vscode
19
+
20
+ # Other
21
+ .DS_Store
22
+ wandb
23
+ output
24
+ llavavid
25
+
26
+ checkpoints
27
+ project_checkpoints
28
+ debug_checkpoints
29
+ playground/data
30
+ playground/cc3m_llava34b_cap
31
+ ckpts*
32
+
33
+ .ipynb_checkpoints
34
+ chunyl_scripts
35
+ *.ipynb
36
+
37
+ # DevContainer
38
+ !.devcontainer/*
39
+
40
+ # Demo
41
+ serve_images/
42
+ notebooks/
43
+ logs
44
+ scripts/dist_*
45
+ logs/
46
+ submissions/
47
+ cn_scripts/
48
+ internal_project_checkpoints/
49
+ work_dirs
50
+ scripts/i18n/*
51
+ playground/.nfs028b000000010add00000001
52
+ HIP
53
+ playground/.nfs028b0000017bff2c00000012
54
+ scripts/qwen
55
+ scripts/vicuna
56
+ scripts/mistral
57
+ scripts/baseline_rep
58
+ scripts/cn_boli01_hl
59
+ scripts/cn_boli01_lf
60
+ scripts/cn_lf
61
+ scripts/cn_lq
62
+ scripts/cn_yg
63
+ scripts/cn_yg_hao
64
+ scripts/eva_encoder
65
+ scripts/i18n
66
+ scripts/i18n_higher_res
67
+ scripts/multi-images
68
+ scratchpad
69
+ build/
70
+ playground/*.json
71
+ mlx_configs/
72
+ data_processing/
73
+ # demo/
LLaVA-NeXT/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
LLaVA-NeXT/README.md ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center" width="100%">
2
+ <img src="https://i.postimg.cc/pL17YtG4/WX20240508-220230-2x.png" width="80%" height="80%">
3
+ </p>
4
+
5
+ # LLaVA-NeXT: Open Large Multimodal Models
6
+ [![Static Badge](https://img.shields.io/badge/llava_video-paper-green)](http://arxiv.org/abs/2410.02713)
7
+ [![Static Badge](https://img.shields.io/badge/llava_onevision-paper-green)](https://arxiv.org/abs/2408.03326)
8
+ [![llava_next-blog](https://img.shields.io/badge/llava_next-blog-green)](https://llava-vl.github.io/blog/)
9
+
10
+ [![llava_onevision-demo](https://img.shields.io/badge/llava_onevision-demo-red)](https://llava-onevision.lmms-lab.com/)
11
+ [![llava_next-video_demo](https://img.shields.io/badge/llava_video-demo-red)](https://huggingface.co/spaces/WildVision/vision-arena)
12
+ [![llava_next-interleave_demo](https://img.shields.io/badge/llava_next-interleave_demo-red)](https://huggingface.co/spaces/lmms-lab/LLaVA-NeXT-Interleave-Demo)
13
+ [![Openbayes Demo](https://img.shields.io/static/v1?label=Demo&message=OpenBayes%E8%B4%9D%E5%BC%8F%E8%AE%A1%E7%AE%97&color=green)](https://openbayes.com/console/public/tutorials/gW0ng9jKXfO)
14
+
15
+ [![llava_video-checkpoints](https://img.shields.io/badge/llava_video-checkpoints-blue)](https://huggingface.co/collections/lmms-lab/llava-next-video-661e86f5e8dabc3ff793c944)
16
+ [![llava_onevision-checkpoints](https://img.shields.io/badge/llava_onevision-checkpoints-blue)](https://huggingface.co/collections/lmms-lab/llava-onevision-66a259c3526e15166d6bba37)
17
+ [![llava_next-interleave_checkpoints](https://img.shields.io/badge/llava_next-interleave_checkpoints-blue)](https://huggingface.co/collections/lmms-lab/llava-next-interleave-66763c55c411b340b35873d1)
18
+ [![llava_next-image_checkpoints](https://img.shields.io/badge/llava_next-image_checkpoints-blue)](https://huggingface.co/lmms-lab)
19
+
20
+ ## Release Notes
21
+ - **[2025/08/29] 🔥 LLaVA-Critic-R1** We release LLaVA-Critic-R1, a family of generative critic VLM trained through GRPO using pairwise critic data. LLaVA-Critic-R1 not only demonstrates strong critic capability, but also achieves state-of-the-art policy performance at the 7B scale. Refer to [LLaVA-Critic-R1](llava-critic-r1/EasyR1/README.md) for more training details.
22
+
23
+ 📄 **Explore more**:
24
+ - [LLaVA-Critic-GRPO Dataset](https://huggingface.co/datasets/lmms-lab/LLaVA-Critic-GRPO-dataset): Download the dataset.
25
+ - [LLaVA-Critic-R1-7B](https://huggingface.co/lmms-lab/LLaVA-Critic-R1-7B): LLaVA-Critic-R1 trained based on Qwen-2.5-VL-7B.
26
+ - [LLaVA-Critic-R1-7B-Plus-Qwen](https://huggingface.co/lmms-lab/LLaVA-Critic-R1-7B-Plus-Qwen): LLaVA-Critic-R1+ trained based on ThinkLite-VL-7B.
27
+ - [LLaVA-Critic-R1-7B-Plus-Mimo](https://huggingface.co/lmms-lab/LLaVA-Critic-R1-7B-Plus-Mimo): LLaVA-Critic-R1+ trained based on MiMo-VL-7B-RL-2508.
28
+ - [LLaVA-Critic-R1-7B-Plus-LLaMA32v](https://huggingface.co/lmms-lab/LLaVA-Critic-R1-7B-LLaMA32v): LLaVA-Critic-R1+ trained based on Llama-3.2-11B-Vision-Instruct.
29
+ - [Paper](https://arxiv.org/abs/2509.00676): Detailed information about LLaVA-Critic-R1.
30
+
31
+
32
+ - **[2024/10/04] 🔥 LLaVA-Video** (formerly LLaVA-NeXT-Video) has undergone a major upgrade! We are excited to release **LLaVA-Video-178K**, a high-quality synthetic dataset for video instruction tuning. This dataset includes:
33
+
34
+ - 178,510 caption entries
35
+ - 960,792 open-ended Q&A pairs
36
+ - 196,198 multiple-choice Q&A items
37
+
38
+ Along with this, we’re also releasing the **LLaVA-Video 7B/72B models**, which deliver competitive performance on the latest video benchmarks, including [Video-MME](https://video-mme.github.io/home_page.html#leaderboard), [LongVideoBench](https://longvideobench.github.io/), and [Dream-1K](https://tarsier-vlm.github.io/).
39
+
40
+ 📄 **Explore more**:
41
+ - [LLaVA-Video-178K Dataset](https://huggingface.co/datasets/lmms-lab/LLaVA-Video-178K): Download the dataset.
42
+ - [LLaVA-Video Models](https://huggingface.co/collections/lmms-lab/llava-video-661e86f5e8dabc3ff793c944): Access model checkpoints.
43
+ - [Paper](http://arxiv.org/abs/2410.02713): Detailed information about LLaVA-Video.
44
+ - [LLaVA-Video Documentation](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/docs/LLaVA_Video_1003.md): Guidance on training, inference and evaluation.
45
+
46
+ - [2024/09/13] 🔥 **🚀 [LLaVA-OneVision-Chat](docs/LLaVA_OneVision_Chat.md)**. The new LLaVA-OV-Chat (7B/72B) significantly improves the chat experience of LLaVA-OV. 📄
47
+
48
+ ![](docs/ov_chat_images/chat_results.png)
49
+
50
+ - [2024/08/06] 🔥 **🚀 [LLaVA-OneVision (OV)](https://llava-vl.github.io/blog/2024-08-05-llava-onevision/)!** The new LLaVA-OV models (0.5B/7B/72B) achieve new state-of-the-art performance across single-image, multi-image, and video benchmarks, sometimes rivaling top commercial models on 47 diverse benchmarks. 📄 Explore More:
51
+ * [[Paper]](https://arxiv.org/abs/2408.03326): In-depth insights, new emegerging scenarios, ie, strong video understadning through task transfer from images.
52
+ * [[LLaVA-OV Doc]](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/docs/LLaVA_OneVision.md): Model inference and evaluation guidance.
53
+ * [[Scripts]](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/scripts/train): Start training models on your single-image/multi-image/video data.
54
+
55
+ - [2024/07/16] 🔥 **LLaVA-NeXT-Video** has been upgraded. The new 32B model achieves the best open-source performance on several video benchmarks, including [Video-MME](https://video-mme.github.io/home_page.html#leaderboard). Please refer to [this page](docs/LLaVA-NeXT-Video_0716.md) for details, refer to [llava_next-video_demo](https://huggingface.co/spaces/WildVision/vision-arena) for demo.
56
+
57
+
58
+ - [2024/06/23] 🔥 **LLaVA-NeXT-Interleave** is released. We utilize image-text interleaved format to unify multi-image, video, and 3D tasks in one LLM and achieve **SoTA** performance on a wide range of benchmarks. Check out [paper](https://arxiv.org/pdf/2407.07895), [blog](https://llava-vl.github.io/blog/2024-06-16-llava-next-interleave/), and [checkpoints](https://huggingface.co/collections/lmms-lab/llava-next-interleave-66763c55c411b340b35873d1) to see new capabilities and improved performance! We have released 0.5b, 7b, and 7b-dpo models.
59
+ * An all-round LLM for multi-image, video, and 3D with strong performance \[[demo](https://huggingface.co/spaces/lmms-lab/LLaVA-NeXT-Interleave-Demo)\]
60
+ * Construct interleave training data [**M4-Instruct**](https://huggingface.co/datasets/lmms-lab/M4-Instruct-Data)
61
+ * Construct multi-image benchmark [**LLaVA-Interleave Bench**](https://huggingface.co/datasets/lmms-lab/LLaVA-NeXT-Interleave-Bench)
62
+
63
+
64
+ - [2024/05/25] 🔥 Wondering "[What Else Influences Visual Instruction Tuning Beyond Data?](https://llava-vl.github.io/blog/2024-05-25-llava-next-ablations/)" Our new [blog](https://llava-vl.github.io/blog/2024-05-25-llava-next-ablations/) summarizes empirical explorations to ablate the various design choices in improving LMMs except instruct data itself. Meanwhile, open-source the recapioned high-quality data using LLaVA-NeXT-34B on [[COCO]](https://huggingface.co/datasets/lmms-lab/LLaVA-ReCap-118K) [[LCS]](https://huggingface.co/datasets/lmms-lab/LLaVA-ReCap-558K) [[CC3M]](https://huggingface.co/datasets/lmms-lab/LLaVA-ReCap-CC3M).
65
+ * Architectures (LMM & Vision Encoder)
66
+ * Visual Representations (Resolution & # Tokens)
67
+ * Training Strategies (High-quality data & Trainable modules)
68
+
69
+ - [2024/05/10] 🔥 **LLaVA-NeXT** (Stronger) models are released, with support of stronger LMM inlcuding LLama-3 (8B) and Qwen-1.5 (72B/110B) Check out [[blog](https://llava-vl.github.io/blog/2024-05-10-llava-next-stronger-llms/)] and [[checkpoints](https://huggingface.co/lmms-lab)] to see improved performance!
70
+ - [2024/05/10] 🔥 **LLaVA-NeXT** (Video) is released. The image-only-trained LLaVA-NeXT model is surprisingly strong on video tasks with zero-shot modality transfer. DPO training with AI feedback on videos can yield significant improvement. [[Blog](https://llava-vl.github.io/blog/2024-04-30-llava-next-video/)], [[checkpoints](https://huggingface.co/collections/lmms-lab/llava-next-video-661e86f5e8dabc3ff793c944)] and [[sglang](https://github.com/sgl-project/sglang)]
71
+ - [2024/01/30] 🔥 **LLaVA-NeXT** is out! With additional scaling to LLaVA-1.5, LLaVA-NeXT-34B outperforms Gemini Pro on some benchmarks. It can now process 4x more pixels and perform more tasks/applications than before. Check out the [blog post](https://llava-vl.github.io/blog/2024-01-30-llava-next/), and explore the [demo](https://llava.hliu.cc/)! Models are available in [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md). Training/eval data and scripts coming soon.
72
+ <details>
73
+ <summary>More</summary>
74
+
75
+ - [2024/03/10] 🔥 Releasing **LMMs-Eval**, a highly efficient evaluation pipeline we used when developing LLaVA-NeXT. It supports the evaluation of LMMs on dozens of public datasets and allows new dataset onboarding, making the dev of new LMMs much faster. [[Blog](https://lmms-lab.github.io/lmms-eval-blog/lmms-eval-0.1/)] [[Codebase](https://github.com/EvolvingLMMs-Lab/lmms-eval)]
76
+
77
+ - [2023/11/10] [LLaVA-Plus](https://llava-vl.github.io/llava-plus/) is released: Learning to Use Tools for Creating Multimodal Agents, with LLaVA-Plus (LLaVA that Plug and Learn to Use Skills). [[Project Page](https://llava-vl.github.io/llava-plus/)] [[Demo](https://llavaplus.ngrok.io/)] [[Code](https://github.com/LLaVA-VL/LLaVA-Plus-Codebase)] [[Paper](https://arxiv.org/abs/2311.05437)]
78
+ - [2023/11/02] [LLaVA-Interactive](https://llava-vl.github.io/llava-interactive/) is released: Experience the future of human-AI multimodal interaction with an all-in-one demo for Image Chat, Segmentation, Generation and Editing. [[Project Page](https://llava-vl.github.io/llava-interactive/)] [[Demo](https://llavainteractive.ngrok.io/)] [[Code](https://github.com/LLaVA-VL/LLaVA-Interactive-Demo)] [[Paper](https://arxiv.org/abs/2311.00571)]
79
+ - [2023/10/26] 🔥 LLaVA-1.5 with LoRA achieves comparable performance as full-model finetuning, with a reduced GPU RAM requirement ([ckpts](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md#llava-v15), [script](https://github.com/haotian-liu/LLaVA#train)). We also provide a [doc](https://github.com/haotian-liu/LLaVA/blob/main/docs/Finetune_Custom_Data.md) on how to finetune LLaVA-1.5 on your own dataset with LoRA.
80
+ - [2023/10/12] Check out the Korean LLaVA (Ko-LLaVA), created by ETRI, who has generously supported our research! [[🤗 Demo](https://huggingface.co/spaces/etri-vilab/Ko-LLaVA)]
81
+ - [2023/10/05] 🔥 LLaVA-1.5 is out! Achieving SoTA on 11 benchmarks, with just simple modifications to the original LLaVA, utilizes all public data, completes training in ~1 day on a single 8-A100 node, and surpasses methods like Qwen-VL-Chat that use billion-scale data. Check out the [technical report](https://arxiv.org/abs/2310.03744), and explore the [demo](https://llava.hliu.cc/)! Models are available in [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md). The training data and scripts of LLaVA-1.5 are released [here](https://github.com/haotian-liu/LLaVA#train), and evaluation scripts are released [here](https://github.com/haotian-liu/LLaVA/blob/main/docs/Evaluation.md)!
82
+ - [2023/09/26] LLaVA is improved with reinforcement learning from human feedback (RLHF) to improve fact grounding and reduce hallucination. Check out the new SFT and RLHF checkpoints at project [[LLavA-RLHF]](https://llava-rlhf.github.io/)
83
+ - [2023/09/22] [LLaVA](https://arxiv.org/abs/2304.08485) is accepted by NeurIPS 2023 as **oral presentation**, and [LLaVA-Med](https://arxiv.org/abs/2306.00890) is accepted by NeurIPS 2023 Datasets and Benchmarks Track as **spotlight presentation**.
84
+ - [2023/11/06] Support **Intel** dGPU and CPU platforms. [More details here.](https://github.com/haotian-liu/LLaVA/tree/intel/docs/intel)
85
+ - [2023/10/12] LLaVA is now supported in [llama.cpp](https://github.com/ggerganov/llama.cpp/pull/3436) with 4-bit / 5-bit quantization support!
86
+ - [2023/10/11] The training data and scripts of LLaVA-1.5 are released [here](https://github.com/haotian-liu/LLaVA#train), and evaluation scripts are released [here](https://github.com/haotian-liu/LLaVA/blob/main/docs/Evaluation.md)!
87
+ - [2023/10/10] [Roboflow Deep Dive](https://blog.roboflow.com/first-impressions-with-llava-1-5/): First Impressions with LLaVA-1.5.
88
+ - [2023/09/20] We summarize our empirical study of training 33B and 65B LLaVA models in a [note](https://arxiv.org/abs/2309.09958). Further, if you are interested in the comprehensive review, evolution and trend of multimodal foundation models, please check out our recent survey paper [``Multimodal Foundation Models: From Specialists to General-Purpose Assistants''.](https://arxiv.org/abs/2309.10020)
89
+ <p align="center">
90
+ <img src="https://github.com/Computer-Vision-in-the-Wild/CVinW_Readings/blob/main/images/mfm_evolution.jpeg?raw=true" width=50%/>
91
+ </p>
92
+
93
+ - [2023/07/19] 🔥 We release a major upgrade, including support for LLaMA-2, LoRA training, 4-/8-bit inference, higher resolution (336x336), and a lot more. We release [LLaVA Bench](https://github.com/haotian-liu/LLaVA/blob/main/docs/LLaVA_Bench.md) for benchmarking open-ended visual chat with results from Bard and Bing-Chat. We also support and verify training with RTX 3090 and RTX A6000. Check out [LLaVA-from-LLaMA-2](https://github.com/haotian-liu/LLaVA/blob/main/docs/LLaVA_from_LLaMA2.md), and our [model zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)!
94
+ - [2023/06/26] [CVPR 2023 Tutorial](https://vlp-tutorial.github.io/) on **Large Multimodal Models: Towards Building and Surpassing Multimodal GPT-4**! Please check out [[Slides](https://datarelease.blob.core.windows.net/tutorial/vision_foundation_models_2023/slides/Chunyuan_cvpr2023_tutorial_lmm.pdf)] [[Notes](https://arxiv.org/abs/2306.14895)] [[YouTube](https://youtu.be/mkI7EPD1vp8)] [[Bilibli](https://www.bilibili.com/video/BV1Ng4y1T7v3/)].
95
+ - [2023/06/11] We released the preview for the most requested feature: DeepSpeed and LoRA support! Please see documentations [here](./docs/LoRA.md).
96
+ - [2023/06/01] We released **LLaVA-Med: Large Language and Vision Assistant for Biomedicine**, a step towards building biomedical domain large language and vision models with GPT-4 level capabilities. Checkout the [paper](https://arxiv.org/abs/2306.00890) and [page](https://github.com/microsoft/LLaVA-Med).
97
+ - [2023/05/06] We are releasing [LLaVA-Lighting-MPT-7B-preview](https://huggingface.co/liuhaotian/LLaVA-Lightning-MPT-7B-preview), based on MPT-7B-Chat! See [here](#LLaVA-MPT-7b) for more details.
98
+ - [2023/05/02] 🔥 We are releasing LLaVA-Lighting! Train a lite, multimodal GPT-4 with just $40 in 3 hours! See [here](#train-llava-lightning) for more details.
99
+ - [2023/04/27] Thanks to the community effort, LLaVA-13B with 4-bit quantization allows you to run on a GPU with as few as 12GB VRAM! Try it out [here](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/llava).
100
+ - [2023/04/17] 🔥 We released **LLaVA: Large Language and Vision Assistant**. We propose visual instruction tuning, towards building large language and vision models with GPT-4 level capabilities. Checkout the [paper](https://arxiv.org/abs/2304.08485) and [demo](https://llava.hliu.cc/).
101
+
102
+ </details>
103
+
104
+ <!-- <a href="https://llava.hliu.cc/"><img src="assets/demo.gif" width="70%"></a> -->
105
+
106
+ **Usage and License Notices**: This project utilizes certain datasets and checkpoints that are subject to their respective original licenses. Users must comply with all terms and conditions of these original licenses, including but not limited to the [OpenAI Terms of Use](https://openai.com/policies/terms-of-use) for the dataset and the specific licenses for base language models for checkpoints trained using the dataset (e.g. [Llama-1/2 community license](https://ai.meta.com/llama/license/) for LLaMA-2 and Vicuna-v1.5, [Tongyi Qianwen RESEARCH LICENSE AGREEMENT](https://huggingface.co/Qwen/Qwen1.5-0.5B-Chat/blob/main/LICENSE) and [Llama-3 Research License](https://llama.meta.com/llama3/license/)). This project does not impose any additional constraints beyond those stipulated in the original licenses. Furthermore, users are reminded to ensure that their use of the dataset and checkpoints is in compliance with all applicable laws and regulations.
107
+
108
+ ## Models & Scripts
109
+
110
+ ### Installation
111
+
112
+ #### 1. **Clone this repository and navigate to the LLaVA folder:**
113
+ ```bash
114
+ git clone https://github.com/LLaVA-VL/LLaVA-NeXT
115
+ cd LLaVA-NeXT
116
+ ```
117
+
118
+ #### 2. **Install the inference package:**
119
+ ```bash
120
+ conda create -n llava python=3.10 -y
121
+ conda activate llava
122
+ pip install --upgrade pip # Enable PEP 660 support.
123
+ pip install -e ".[train]"
124
+ ```
125
+
126
+ ### Project Navigation
127
+ Please checkout the following page for more inference & evaluation details.
128
+
129
+ #### - **LLaVA-OneVision: Easy Task Transfer**
130
+ - [LLaVA-OneVision](https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/docs/LLaVA_OneVision.md): for demo inference. The evaluation code is in [lmms-eval](https://github.com/EvolvingLMMs-Lab/lmms-eval).
131
+
132
+ #### - **LLaVA-NeXT: Stronger LLMs Supercharge Multimodal Capabilities in the Wild**
133
+ - [LLaVA-NeXT-Image](./docs/LLaVA-NeXT.md): for image demo inference and evaluation of stronger LMMs using [lmms-eval](https://github.com/EvolvingLMMs-Lab/lmms-eval).
134
+
135
+
136
+ #### - LLaVA-NeXT: A Strong Zero-shot Video Understanding Model
137
+ - [LLaVA-NeXT-Video](./docs/LLaVA-NeXT-Video.md): for video inference and evaluation scripts. We recommend to use [LMMs-video](https://lmms-lab.github.io/posts/lmms-eval-0.2/) for evaluation.
138
+
139
+ #### - LLaVA-NeXT: Tackling Multi-image, Video, and 3D in Large Multimodal Models
140
+ - [LLaVA-NeXT-Interleave](./docs/LLaVA-NeXT-Interleave.md): for multi-image demo and evaluation scripts.
141
+
142
+ ## SGLang for SpeedUp Inference and Deployment
143
+
144
+ We use [SGLang](https://github.com/sgl-project/sglang) to speed up inference and deployment of LLaVA-NeXT. You could make LLaVA-NeXT as a backend API service with SGLang.
145
+
146
+ **Prepare Environment**:
147
+ Following the instruction in the [sglang](https://github.com/sgl-project/sglang?tab=readme-ov-file#install)
148
+
149
+ ### LLaVA-NeXT/OneVision
150
+
151
+ Checkout the HTTP Post/Get and SRT usage at [sglang/examples/runtime/llava_onevision](https://github.com/sgl-project/sglang/tree/main/examples/runtime/llava_onevision)
152
+
153
+ ### LLaVA-NeXT (Video)
154
+
155
+ **Launch and Run on (K) Nodes**:
156
+ - Go to sglang project
157
+ ```
158
+ cd PATH_TO/sglang
159
+ ```
160
+ - First node:
161
+ ```sh
162
+ bash examples/usage/llava_video/srt_example_llava_v.sh K 0 YOUR_VIDEO_PATH YOUR_MODEL_PATH FRAMES_PER_VIDEO
163
+ (e.g. bash examples/usage/llava_video/srt_example_llava_v.sh K 0 examples/usage/llava_video/videos/Q98Z4OTh8RwmDonc.mp4 lmms-lab/LLaVA-NeXT-Video-7B-DPO 16)
164
+ ```
165
+ - Second node:
166
+ ```sh
167
+ bash examples/usage/llava_video/srt_example_llava_v.sh K 1 YOUR_VIDEO_PATH YOUR_MODEL_PATH FRAMES_PER_VIDEO
168
+ ```
169
+ - The K node:
170
+ ```sh
171
+ bash examples/usage/llava_video/srt_example_llava_v.sh K K-1 YOUR_VIDEO_PATH YOUR_MODEL_PATH FRAMES_PER_VIDEO
172
+ ```
173
+
174
+
175
+ ## Citation
176
+
177
+ If you find it useful for your research and applications, please cite related papers/blogs using this BibTeX:
178
+ ```bibtex
179
+ @article{li2024llava,
180
+ title={LLaVA-NeXT-Interleave: Tackling Multi-image, Video, and 3D in Large Multimodal Models},
181
+ author={Li, Feng and Zhang, Renrui and Zhang, Hao and Zhang, Yuanhan and Li, Bo and Li, Wei and Ma, Zejun and Li, Chunyuan},
182
+ journal={arXiv preprint arXiv:2407.07895},
183
+ year={2024}
184
+ }
185
+
186
+ @misc{li2024llavanext-ablations,
187
+ title={LLaVA-NeXT: What Else Influences Visual Instruction Tuning Beyond Data?},
188
+ url={https://llava-vl.github.io/blog/2024-05-25-llava-next-ablations/},
189
+ author={Li, Bo and Zhang, Hao and Zhang, Kaichen and Guo, Dong and Zhang, Yuanhan and Zhang, Renrui and Li, Feng and Liu, Ziwei and Li, Chunyuan},
190
+ month={May},
191
+ year={2024}
192
+ }
193
+
194
+ @misc{li2024llavanext-strong,
195
+ title={LLaVA-NeXT: Stronger LLMs Supercharge Multimodal Capabilities in the Wild},
196
+ url={https://llava-vl.github.io/blog/2024-05-10-llava-next-stronger-llms/},
197
+ author={Li, Bo and Zhang, Kaichen and Zhang, Hao and Guo, Dong and Zhang, Renrui and Li, Feng and Zhang, Yuanhan and Liu, Ziwei and Li, Chunyuan},
198
+ month={May},
199
+ year={2024}
200
+ }
201
+
202
+ @misc{zhang2024llavanext-video,
203
+ title={LLaVA-NeXT: A Strong Zero-shot Video Understanding Model},
204
+ url={https://llava-vl.github.io/blog/2024-04-30-llava-next-video/},
205
+ author={Zhang, Yuanhan and Li, Bo and Liu, haotian and Lee, Yong jae and Gui, Liangke and Fu, Di and Feng, Jiashi and Liu, Ziwei and Li, Chunyuan},
206
+ month={April},
207
+ year={2024}
208
+ }
209
+
210
+ @misc{liu2024llavanext,
211
+ title={LLaVA-NeXT: Improved reasoning, OCR, and world knowledge},
212
+ url={https://llava-vl.github.io/blog/2024-01-30-llava-next/},
213
+ author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Li, Bo and Zhang, Yuanhan and Shen, Sheng and Lee, Yong Jae},
214
+ month={January},
215
+ year={2024}
216
+ }
217
+
218
+ @misc{liu2023improvedllava,
219
+ title={Improved Baselines with Visual Instruction Tuning},
220
+ author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Lee, Yong Jae},
221
+ publisher={arXiv:2310.03744},
222
+ year={2023},
223
+ }
224
+
225
+ @misc{liu2023llava,
226
+ title={Visual Instruction Tuning},
227
+ author={Liu, Haotian and Li, Chunyuan and Wu, Qingyang and Lee, Yong Jae},
228
+ publisher={NeurIPS},
229
+ year={2023},
230
+ }
231
+ ```
232
+
233
+ ## Acknowledgement
234
+
235
+ - [Vicuna](https://github.com/lm-sys/FastChat): the codebase we built upon, and our base model Vicuna-13B that has the amazing language capabilities!
236
+ - The LLaVA-NeXT project is currently maintained by the team along with our contributors (listed alphabetically by the first names): [Bo Li](https://brianboli.com/), [Dong Guo](https://www.linkedin.com/in/dongguoset/), [Feng Li](https://scholar.google.com/citations?hl=zh-CN&user=ybRe9GcAAAAJ&view_op=list_works&sortby=pubdate), [Hao Zhang](https://scholar.google.com/citations?user=B8hPxMQAAAAJ&hl=en), [Kaichen Zhang](https://www.linkedin.com/in/kaichen-zhang-014b17219/?originalSubdomain=sg), [Renrui Zhang](https://zrrskywalker.github.io/), [Yuanhan Zhang](https://zhangyuanhan-ai.github.io/), led by [Chunyuan Li](https://chunyuan.li/) and with the guidance and help from [Haotian Liu](https://hliu.cc/).
237
+ - The `lmms-eval` framework and its core contributors, including Peiyuan Zhang, Fanyi Pu, Joshua Adrian Cahyono, and Kairui Hu, for their support on the evaluation side.
238
+
239
+ ## Related Projects
240
+
241
+ - [Instruction Tuning with GPT-4](https://github.com/Instruction-Tuning-with-GPT-4/GPT-4-LLM)
242
+ - [LLaVA-Med: Training a Large Language-and-Vision Assistant for Biomedicine in One Day](https://github.com/microsoft/LLaVA-Med)
243
+ - [Otter: In-Context Multi-Modal Instruction Tuning](https://github.com/Luodian/Otter)
244
+
245
+ For future project ideas, please check out:
246
+ - [SEEM: Segment Everything Everywhere All at Once](https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once)
247
+ - [Grounded-Segment-Anything](https://github.com/IDEA-Research/Grounded-Segment-Anything) to detect, segment, and generate anything by marrying [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO) and [Segment-Anything](https://github.com/facebookresearch/segment-anything).
LLaVA-NeXT/cog.yaml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration for Cog ⚙️
2
+ # Reference: https://github.com/replicate/cog/blob/main/docs/yaml.md
3
+
4
+ build:
5
+ gpu: true
6
+
7
+ python_version: "3.11"
8
+
9
+ python_packages:
10
+ - "torch==2.0.1"
11
+ - "accelerate==0.21.0"
12
+ - "bitsandbytes==0.41.0"
13
+ - "deepspeed==0.9.5"
14
+ - "einops-exts==0.0.4"
15
+ - "einops==0.6.1"
16
+ - "gradio==3.35.2"
17
+ - "gradio_client==0.2.9"
18
+ - "httpx==0.24.0"
19
+ - "markdown2==2.4.10"
20
+ - "numpy==1.26.0"
21
+ - "peft==0.4.0"
22
+ - "scikit-learn==1.2.2"
23
+ - "sentencepiece==0.1.99"
24
+ - "shortuuid==1.0.11"
25
+ - "timm==0.6.13"
26
+ - "tokenizers==0.13.3"
27
+ - "torch==2.0.1"
28
+ - "torchvision==0.15.2"
29
+ - "transformers==4.31.0"
30
+ - "wandb==0.15.12"
31
+ - "wavedrom==2.0.3.post3"
32
+ - "Pygments==2.16.1"
33
+ run:
34
+ - curl -o /usr/local/bin/pget -L "https://github.com/replicate/pget/releases/download/v0.0.3/pget" && chmod +x /usr/local/bin/pget
35
+
36
+ # predict.py defines how predictions are run on your model
37
+ predict: "predict.py:Predictor"
LLaVA-NeXT/docs/onevision_trial.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llava.model.builder import load_pretrained_model
2
+ from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token
3
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX
4
+ from llava.conversation import conv_templates, SeparatorStyle
5
+
6
+ from PIL import Image
7
+ import requests
8
+ import copy
9
+ import torch
10
+
11
+ import sys
12
+ import warnings
13
+
14
+ warnings.filterwarnings("ignore")
15
+
16
+ pretrained = "lmms-lab/llava-onevision-qwen2-0.5b-si"
17
+ model_name = "llava_qwen"
18
+ device = "cuda"
19
+ device_map = "auto"
20
+ tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, device_map=device_map) # Add any other thing you want to pass in llava_model_args
21
+
22
+ model.eval()
23
+
24
+ url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true"
25
+ image = Image.open(requests.get(url, stream=True).raw)
26
+ image_tensor = process_images([image], image_processor, model.config)
27
+ image_tensor = [_image.to(dtype=torch.float16, device=device) for _image in image_tensor]
28
+
29
+ conv_template = "qwen_1_5" # Make sure you use correct chat template for different models
30
+ question = DEFAULT_IMAGE_TOKEN + "\nWhat is shown in this image?"
31
+ conv = copy.deepcopy(conv_templates[conv_template])
32
+ conv.append_message(conv.roles[0], question)
33
+ conv.append_message(conv.roles[1], None)
34
+ prompt_question = conv.get_prompt()
35
+
36
+ input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device)
37
+ image_sizes = [image.size]
38
+
39
+
40
+ cont = model.generate(
41
+ input_ids,
42
+ images=image_tensor,
43
+ image_sizes=image_sizes,
44
+ do_sample=False,
45
+ temperature=0,
46
+ max_new_tokens=4096,
47
+ )
48
+ text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)
49
+ print(text_outputs)
50
+
51
+ from threading import Thread
52
+ from transformers import TextIteratorStreamer
53
+ import json
54
+
55
+ url = "https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/images/llava_v1_5_radar.jpg?raw=true"
56
+ image = Image.open(requests.get(url, stream=True).raw)
57
+ image_tensor = process_images([image], image_processor, model.config)
58
+ image_tensor = [_image.to(dtype=torch.float16, device=device) for _image in image_tensor]
59
+
60
+ conv_template = "qwen_1_5"
61
+ question = DEFAULT_IMAGE_TOKEN + "\nWhat is shown in this image?"
62
+ conv = copy.deepcopy(conv_templates[conv_template])
63
+ conv.append_message(conv.roles[0], question)
64
+ conv.append_message(conv.roles[1], None)
65
+ prompt_question = conv.get_prompt()
66
+
67
+ input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device)
68
+ image_sizes = [image.size]
69
+
70
+ max_context_length = getattr(model.config, "max_position_embeddings", 2048)
71
+ num_image_tokens = question.count(DEFAULT_IMAGE_TOKEN) * model.get_vision_tower().num_patches
72
+
73
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=15)
74
+
75
+ max_new_tokens = min(4096, max_context_length - input_ids.shape[-1] - num_image_tokens)
76
+
77
+ if max_new_tokens < 1:
78
+ print(
79
+ json.dumps(
80
+ {
81
+ "text": question + "Exceeds max token length. Please start a new conversation, thanks.",
82
+ "error_code": 0,
83
+ }
84
+ )
85
+ )
86
+ else:
87
+ gen_kwargs = {
88
+ "do_sample": False,
89
+ "temperature": 0,
90
+ "max_new_tokens": max_new_tokens,
91
+ "images": image_tensor,
92
+ "image_sizes": image_sizes,
93
+ }
94
+
95
+ thread = Thread(
96
+ target=model.generate,
97
+ kwargs=dict(
98
+ inputs=input_ids,
99
+ streamer=streamer,
100
+ **gen_kwargs,
101
+ ),
102
+ )
103
+ thread.start()
104
+
105
+ generated_text = ""
106
+ for new_text in streamer:
107
+ generated_text += new_text
108
+ sys.stdout.write(new_text)
109
+ sys.stdout.flush()
110
+
111
+ print("\nFinal output:", generated_text)
LLaVA-NeXT/llava-critic-r1/EasyR1/Dockerfile ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10)
2
+ # https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html
3
+ FROM nvcr.io/nvidia/pytorch:24.08-py3
4
+
5
+ # Define environments
6
+ ENV MAX_JOBS=32
7
+ ENV VLLM_WORKER_MULTIPROC_METHOD=spawn
8
+ ENV DEBIAN_FRONTEND=noninteractive
9
+ ENV NODE_OPTIONS=""
10
+ ENV PIP_ROOT_USER_ACTION=ignore
11
+ ENV HF_HUB_ENABLE_HF_TRANSFER="1"
12
+
13
+ # Define installation arguments
14
+ ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/
15
+ ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
16
+
17
+ # Set apt source
18
+ RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \
19
+ { \
20
+ echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \
21
+ echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \
22
+ echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \
23
+ echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \
24
+ } > /etc/apt/sources.list
25
+
26
+ # Install systemctl
27
+ RUN apt-get update && \
28
+ apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \
29
+ apt-get clean
30
+
31
+ # Install tini
32
+ RUN apt-get update && \
33
+ apt-get install -y tini && \
34
+ apt-get clean
35
+
36
+ # Change pip source
37
+ RUN pip config set global.index-url "${PIP_INDEX}" && \
38
+ pip config set global.extra-index-url "${PIP_INDEX}" && \
39
+ python -m pip install --upgrade pip
40
+
41
+ # Uninstall nv-pytorch fork
42
+ RUN pip uninstall -y torch torchvision torchaudio \
43
+ pytorch-quantization pytorch-triton torch-tensorrt \
44
+ transformer_engine flash_attn apex megatron-core \
45
+ xgboost opencv grpcio
46
+
47
+ # Fix cv2
48
+ RUN rm -rf /usr/local/lib/python3.10/dist-packages/cv2
49
+
50
+ # Install torch-2.6.0+cu124 + vllm-0.8.4
51
+ # torch-2.6.0+cu124: cxx11abi=False
52
+ # torch-2.6.0+cu126: cxx11abi=True
53
+ # see https://github.com/flashinfer-ai/flashinfer/issues/911
54
+ RUN pip install --no-cache-dir "vllm==0.8.4" "torch==2.6.0" "torchvision==0.21.0" "torchaudio==2.6.0" tensordict torchdata \
55
+ "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \
56
+ "numpy<2.0.0" "pyarrow>=15.0.0" pandas \
57
+ ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb liger-kernel mathruler \
58
+ pytest yapf py-spy pyext pre-commit ruff
59
+
60
+ # Install flash-attn-2.7.4.post1 (cxx11abi=False)
61
+ RUN wget -nv https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl && \
62
+ pip install --no-cache-dir flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
63
+
64
+ # Install flashinfer-0.2.2.post1+cu124 (cxx11abi=False)
65
+ # vllm-0.8.3 does not support flashinfer>=0.2.3
66
+ # see https://github.com/vllm-project/vllm/pull/15777
67
+ RUN wget -nv https://github.com/flashinfer-ai/flashinfer/releases/download/v0.2.2.post1/flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl && \
68
+ pip install --no-cache-dir flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl
69
+
70
+ # Fix packages
71
+ RUN pip uninstall -y pynvml nvidia-ml-py && \
72
+ pip install --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1"
73
+
74
+ # Reset pip config
75
+ RUN pip config unset global.index-url && \
76
+ pip config unset global.extra-index-url
LLaVA-NeXT/llava-critic-r1/EasyR1/Dockerfile.legacy ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10)
2
+ # https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html
3
+ FROM nvcr.io/nvidia/pytorch:24.08-py3
4
+
5
+ # Define environments
6
+ ENV MAX_JOBS=32
7
+ ENV VLLM_WORKER_MULTIPROC_METHOD=spawn
8
+ ENV DEBIAN_FRONTEND=noninteractive
9
+ ENV NODE_OPTIONS=""
10
+ ENV PIP_ROOT_USER_ACTION=ignore
11
+ ENV HF_HUB_ENABLE_HF_TRANSFER="1"
12
+
13
+ # Define installation arguments
14
+ ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/
15
+ ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
16
+ ARG VLLM_COMMIT=227578480d71fc94ef46ca77fb69496412158d68
17
+
18
+ # Set apt source
19
+ RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \
20
+ { \
21
+ echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \
22
+ echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \
23
+ echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \
24
+ echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \
25
+ } > /etc/apt/sources.list
26
+
27
+ # Install systemctl
28
+ RUN apt-get update && \
29
+ apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \
30
+ apt-get clean
31
+
32
+ # Install tini
33
+ RUN apt-get update && \
34
+ apt-get install -y tini && \
35
+ apt-get clean
36
+
37
+ # Change pip source
38
+ RUN pip config set global.index-url "${PIP_INDEX}" && \
39
+ pip config set global.extra-index-url "${PIP_INDEX}" && \
40
+ python -m pip install --upgrade pip
41
+
42
+ # Uninstall nv-pytorch fork
43
+ RUN pip uninstall -y torch torchvision torchaudio \
44
+ pytorch-quantization pytorch-triton torch-tensorrt \
45
+ transformer_engine flash_attn apex megatron-core \
46
+ xgboost opencv grpcio
47
+
48
+ # Fix cv2
49
+ RUN rm -rf /usr/local/lib/python3.10/dist-packages/cv2
50
+
51
+ # Install vllm-0.7.4-nightly
52
+ RUN pip install --no-cache-dir vllm --pre --extra-index-url "https://wheels.vllm.ai/${VLLM_COMMIT}" && \
53
+ git clone -b verl_v1 https://github.com/hiyouga/vllm.git && \
54
+ cp -r vllm/vllm/ /usr/local/lib/python3.10/dist-packages/
55
+
56
+ # Install torch-2.5.1
57
+ RUN pip install --no-cache-dir "torch==2.5.1" "torchvision==0.20.1" "torchaudio==2.5.1" tensordict torchdata \
58
+ "transformers>=4.49.0" accelerate datasets peft hf-transfer \
59
+ ray[default] codetiming hydra-core pandas "pyarrow>=15.0.0" pylatexenc qwen-vl-utils wandb liger-kernel mathruler \
60
+ pytest yapf py-spy pyext pre-commit ruff
61
+
62
+ # Install flash_attn-2.7.4.post1
63
+ RUN wget -nv https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.5cxx11abiFALSE-cp310-cp310-linux_x86_64.whl && \
64
+ pip install --no-cache-dir flash_attn-2.7.4.post1+cu12torch2.5cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
65
+
66
+ # Fix packages
67
+ RUN pip uninstall -y pynvml nvidia-ml-py && \
68
+ pip install --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1"
69
+
70
+ # Reset pip config
71
+ RUN pip config unset global.index-url && \
72
+ pip config unset global.extra-index-url
LLaVA-NeXT/llava-critic-r1/EasyR1/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
LLaVA-NeXT/llava-critic-r1/EasyR1/Makefile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: build commit quality style
2
+
3
+ check_dirs := examples scripts verl setup.py
4
+
5
+ build:
6
+ python3 setup.py sdist bdist_wheel
7
+
8
+ commit:
9
+ pre-commit install
10
+ pre-commit run --all-files
11
+
12
+ quality:
13
+ ruff check $(check_dirs)
14
+ ruff format --check $(check_dirs)
15
+
16
+ style:
17
+ ruff check $(check_dirs) --fix
18
+ ruff format $(check_dirs)
LLaVA-NeXT/llava-critic-r1/EasyR1/README.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # EasyR1 for LLaVA-Critic-R1
2
+
3
+ This codebase is a customized extension of [EasyR1](https://github.com/hiyouga/EasyR1), specifically modified to support RL training using LLaMA-3.2-Vision-11B-Instruct as the base model. For RL training using Qwen-2.5-VL and Mimo-VL as base models, please use the original EasyR1 codebase. We will integrate support for all models into a unified codebase in the future.
4
+
5
+ ## Training based on Qwen-2.5-VL
6
+
7
+ ```
8
+ bash ./examples/qwen2_5_vl_7b_llava_critic_grpo.sh
9
+ ```
10
+
11
+ ## Training based on ThinkLite-VL
12
+
13
+ ```
14
+ bash ./examples/thinklite_vl_7b_llava_critic_grpo.sh
15
+ ```
16
+
17
+ ## Training based on Mimo-VL
18
+
19
+ ### SFT checkpoint
20
+ ```
21
+ bash ./examples/mimo_vl_7b_llava_critic_grpo.sh
22
+ ```
23
+
24
+ ### RL checkpoint
25
+ ```
26
+ bash ./examples/mimo_vl_rl_7b_llava_critic_grpo.sh
27
+ ```
28
+
29
+ ## Training based on LLaMA-3.2-Vision
30
+
31
+ ```
32
+ bash ./examples/llama3.2v_critic_grpo.sh
33
+ ```
LLaVA-NeXT/llava-critic-r1/EasyR1/assets/baselines.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Baselines
2
+
3
+ Environment: [hiyouga/verl:ngc-th2.6.0-cu126-vllm0.8.3-flashinfer0.2.2-cxx11abi0](https://hub.docker.com/layers/hiyouga/verl/ngc-th2.6.0-cu126-vllm0.8.3-flashinfer0.2.2-cxx11abi0/images/sha256-335ed6cd1fe73090e458409cfa4394d6abf4cd0503ca44dbafdc28ff72e5ed20)
4
+
5
+ EasyR1 version: [v0.3.0](https://github.com/hiyouga/EasyR1/tree/v0.3.0)
6
+
7
+ Welcome to contribute new data points!
8
+
9
+ ## Algorithm Baselines
10
+
11
+ ### [Qwen2.5-Instruct](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct) on [Math12k](https://huggingface.co/datasets/hiyouga/math12k)
12
+
13
+ | Size | Algorithm | Bits | LR | KL | Test Score |
14
+ | ---- | ----------- | ---- | ---- | ---- | ---------- |
15
+ | 7B | GRPO | AMP | 1e-6 | 1e-2 | 0.73->0.79 |
16
+
17
+ ### [Qwen2.5-VL-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) on [Geometry3k](https://huggingface.co/datasets/hiyouga/geometry3k)
18
+
19
+ | Size | Algorithm | Bits | LR | KL | Test Score |
20
+ | ---- | ----------- | ---- | ---- | ---- | ---------- |
21
+ | 7B | GRPO | AMP | 1e-6 | 1e-2 | 0.39->0.52 |
22
+ | 7B | GRPO | BF16 | 1e-6 | 1e-2 | 0.39->0.52 |
23
+ | 7B | GRPO | AMP | 1e-6 | 1e-3 | 0.39->0.52 |
24
+ | 7B | RLOO | AMP | 1e-6 | 1e-2 | 0.39->0.53 |
25
+ | 3B | GRPO | AMP | 1e-6 | 1e-2 | 0.27->0.44 |
26
+ | 32B | GRPO | BF16 | 1e-6 | 1e-2 | 0.46->0.61 |
27
+
28
+ > [!NOTE]
29
+ > The hyper-parameters not listed are all the same as the default values.
30
+
31
+ ## Performance Baselines
32
+
33
+ ### [Qwen2.5-VL-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) on [Geometry3k](https://huggingface.co/datasets/hiyouga/geometry3k)
34
+
35
+ | Size | GPU Type | Bits | Batch Size | vLLM Util | vLLM TP | Peak Mem | Peak VRAM | Throughput | Sec per step | Actor MFU |
36
+ | ---- | ------------- | ---- | ---------- | --------- | ------- | -------- | --------- | ---------- | ------------ | --------- |
37
+ | 3B | 8 * H100 80GB | AMP | 4 / 16 | 0.6 | 2 | 120GB | 35GB | 1200 | 180s | 6.3% |
38
+ | 7B | 8 * H100 80GB | AMP | 4 / 16 | 0.6 | 2 | 140GB | 60GB | 1200 | 180s | 13.6% |
39
+ | 7B | 8 * H100 80GB | AMP | 10 / 20 | 0.6 | 2 | 150GB | 75GB | 1400 | 170s | 19.2% |
40
+ | 7B | 8 * L20 48GB | AMP | 4 / 16 | 0.6 | 2 | 150GB | 44GB | 410 | 580s | 26.5% |
41
+ | 7B | 8 * H100 80GB | BF16 | 4 / 16 | 0.6 | 2 | 150GB | 50GB | 1280 | 190s | 13.9% |
42
+ | 32B | 8 * H100 80GB | BF16 | 1 / 8 | 0.6 | 8 | 240GB | 68GB | 360 | 860s | 11.2% |
43
+
44
+ - Batch Size: micro_batch_size_per_device_for_update / micro_batch_size_per_device_for_experience
45
+ - vLLM Util: rollout.gpu_memory_utilization
46
+ - vLLM TP: rollout.tensor_parallel_size
47
+ - Peak Mem: Peak CPU memory usage
48
+ - Peak VRAM: Peak GPU memory usage
49
+ - Throughput: Number of tokens per second per GPU by one training step
50
+ - Sec per step: Average time per step in seconds
51
+
52
+ > [!NOTE]
53
+ > The hyper-parameters not listed are all the same as the default values.
LLaVA-NeXT/llava-critic-r1/EasyR1/assets/qwen2_5_vl_7b_geo.png ADDED
LLaVA-NeXT/llava-critic-r1/EasyR1/init ADDED
@@ -0,0 +1 @@
 
 
1
+
LLaVA-NeXT/llava-critic-r1/EasyR1/pyproject.toml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "verl"
7
+ dynamic = [
8
+ "version",
9
+ "dependencies",
10
+ "optional-dependencies",
11
+ "requires-python",
12
+ "authors",
13
+ "description",
14
+ "readme",
15
+ "license"
16
+ ]
17
+
18
+ [tool.ruff]
19
+ target-version = "py39"
20
+ line-length = 119
21
+ indent-width = 4
22
+
23
+ [tool.ruff.lint]
24
+ ignore = ["C901", "E501", "E741", "W605", "C408"]
25
+ select = ["C", "E", "F", "I", "W", "RUF022"]
26
+
27
+ [tool.ruff.lint.per-file-ignores]
28
+ "__init__.py" = ["E402", "F401", "F403", "F811"]
29
+
30
+ [tool.ruff.lint.isort]
31
+ lines-after-imports = 2
32
+ known-first-party = ["verl"]
33
+ known-third-party = ["torch", "transformers", "wandb"]
34
+
35
+ [tool.ruff.format]
36
+ quote-style = "double"
37
+ indent-style = "space"
38
+ skip-magic-trailing-comma = false
39
+ line-ending = "auto"
LLaVA-NeXT/llava-critic-r1/EasyR1/requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate
2
+ codetiming
3
+ datasets
4
+ liger-kernel
5
+ mathruler
6
+ numpy
7
+ omegaconf
8
+ pandas
9
+ peft
10
+ pillow
11
+ pyarrow>=15.0.0
12
+ pylatexenc
13
+ qwen-vl-utils
14
+ ray[default]
15
+ tensordict
16
+ torchdata
17
+ transformers>=4.51.0
18
+ vllm>=0.7.3
19
+ wandb
LLaVA-NeXT/llava-critic-r1/EasyR1/scripts/model_merger.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import argparse
16
+ import os
17
+ import re
18
+ from concurrent.futures import ThreadPoolExecutor
19
+ from typing import Dict, List, Tuple
20
+
21
+ import numpy as np
22
+ import torch
23
+ from torch.distributed._tensor import DTensor, Placement, Shard
24
+ from transformers import (
25
+ AutoConfig,
26
+ AutoModelForCausalLM,
27
+ AutoModelForTokenClassification,
28
+ AutoModelForVision2Seq,
29
+ PretrainedConfig,
30
+ PreTrainedModel,
31
+ )
32
+
33
+
34
+ def merge_by_placement(tensors: List[torch.Tensor], placement: Placement):
35
+ if placement.is_replicate():
36
+ return tensors[0]
37
+ elif placement.is_partial():
38
+ raise NotImplementedError("Partial placement is not supported yet")
39
+ elif placement.is_shard():
40
+ return torch.cat(tensors, dim=placement.dim).contiguous()
41
+ else:
42
+ raise ValueError(f"Unsupported placement: {placement}")
43
+
44
+
45
+ def upload_model_to_huggingface(local_path: str, remote_path: str):
46
+ # Push to hugging face
47
+ from huggingface_hub import HfApi
48
+
49
+ api = HfApi()
50
+ api.create_repo(repo_id=remote_path, private=False, exist_ok=True)
51
+ api.upload_folder(repo_id=remote_path, folder_path=local_path, repo_type="model")
52
+
53
+
54
+ if __name__ == "__main__":
55
+ parser = argparse.ArgumentParser()
56
+ parser.add_argument("--local_dir", required=True, type=str, help="The path for your saved model")
57
+ parser.add_argument("--hf_upload_path", default=False, type=str, help="The path of the huggingface repo to upload")
58
+ args = parser.parse_args()
59
+ local_dir: str = args.local_dir
60
+
61
+ assert not local_dir.endswith("huggingface"), "The local_dir should not end with huggingface."
62
+
63
+ # copy rank zero to find the shape of (dp, fsdp)
64
+ rank = 0
65
+ world_size = 0
66
+ for filename in os.listdir(local_dir):
67
+ match = re.match(r"model_world_size_(\d+)_rank_0\.pt", filename)
68
+ if match:
69
+ world_size = match.group(1)
70
+ break
71
+
72
+ assert world_size, "No model file with the proper format."
73
+
74
+ rank0_weight_path = os.path.join(local_dir, f"model_world_size_{world_size}_rank_{rank}.pt")
75
+ state_dict = torch.load(rank0_weight_path, map_location="cpu", weights_only=False)
76
+ pivot_key = sorted(state_dict.keys())[0]
77
+ weight = state_dict[pivot_key]
78
+ if isinstance(weight, DTensor):
79
+ # get sharding info
80
+ device_mesh = weight.device_mesh
81
+ mesh = device_mesh.mesh
82
+ mesh_dim_names = device_mesh.mesh_dim_names
83
+ else:
84
+ # for non-DTensor
85
+ mesh = np.array([int(world_size)], dtype=np.int64)
86
+ mesh_dim_names = ("fsdp",)
87
+
88
+ print(f"Got device mesh {mesh}, mesh_dim_names {mesh_dim_names}")
89
+
90
+ assert mesh_dim_names in (("fsdp",), ("ddp", "fsdp")), f"Unsupported mesh_dim_names {mesh_dim_names}."
91
+
92
+ if "tp" in mesh_dim_names:
93
+ # fsdp * tp
94
+ total_shards = mesh.shape[-1] * mesh.shape[-2]
95
+ mesh_shape = (mesh.shape[-2], mesh.shape[-1])
96
+ else:
97
+ # fsdp
98
+ total_shards = mesh.shape[-1]
99
+ mesh_shape = (mesh.shape[-1],)
100
+
101
+ print(f"Processing {total_shards} model shards in total.")
102
+ model_state_dict_lst = []
103
+ model_state_dict_lst.append(state_dict)
104
+ model_state_dict_lst.extend([""] * (total_shards - 1))
105
+
106
+ def process_one_shard(rank, model_state_dict_lst):
107
+ model_path = os.path.join(local_dir, f"model_world_size_{world_size}_rank_{rank}.pt")
108
+ state_dict = torch.load(model_path, map_location="cpu", weights_only=False)
109
+ model_state_dict_lst[rank] = state_dict
110
+ return state_dict
111
+
112
+ with ThreadPoolExecutor(max_workers=min(32, os.cpu_count())) as executor:
113
+ for rank in range(1, total_shards):
114
+ executor.submit(process_one_shard, rank, model_state_dict_lst)
115
+
116
+ state_dict: Dict[str, List[torch.Tensor]] = {}
117
+ param_placements: Dict[str, List[Placement]] = {}
118
+ keys = set(model_state_dict_lst[0].keys())
119
+ for key in keys:
120
+ state_dict[key] = []
121
+ for model_state_dict in model_state_dict_lst:
122
+ try:
123
+ tensor = model_state_dict.pop(key)
124
+ except Exception:
125
+ print(f"Cannot find key {key} in rank {rank}.")
126
+
127
+ if isinstance(tensor, DTensor):
128
+ state_dict[key].append(tensor._local_tensor.bfloat16())
129
+ placements = tuple(tensor.placements)
130
+ # replicated placement at ddp dimension can be discarded
131
+ if mesh_dim_names[0] == "ddp":
132
+ placements = placements[1:]
133
+
134
+ if key not in param_placements:
135
+ param_placements[key] = placements
136
+ else:
137
+ assert param_placements[key] == placements
138
+ else:
139
+ state_dict[key].append(tensor.bfloat16())
140
+
141
+ del model_state_dict_lst
142
+
143
+ for key in sorted(state_dict):
144
+ if not isinstance(state_dict[key], list):
145
+ print(f"No need to merge key {key}")
146
+ continue
147
+
148
+ if key in param_placements:
149
+ # merge shards
150
+ placements: Tuple[Shard] = param_placements[key]
151
+ if len(mesh_shape) == 1:
152
+ # 1-D list, FSDP without TP
153
+ assert len(placements) == 1
154
+ shards = state_dict[key]
155
+ state_dict[key] = merge_by_placement(shards, placements[0])
156
+ else:
157
+ # 2-D list, FSDP + TP
158
+ raise NotImplementedError("FSDP + TP is not supported yet.")
159
+ else:
160
+ state_dict[key] = torch.cat(state_dict[key], dim=0)
161
+
162
+ print("Merge completed.")
163
+ hf_path = os.path.join(local_dir, "huggingface")
164
+ config: PretrainedConfig = AutoConfig.from_pretrained(hf_path)
165
+ architectures: List[str] = getattr(config, "architectures", ["Unknown"])
166
+
167
+ if "ForTokenClassification" in architectures[0]:
168
+ AutoClass = AutoModelForTokenClassification
169
+ elif "ForCausalLM" in architectures[0]:
170
+ AutoClass = AutoModelForCausalLM
171
+ elif "ForConditionalGeneration" in architectures[0]:
172
+ AutoClass = AutoModelForVision2Seq
173
+ else:
174
+ raise NotImplementedError(f"Unknown architecture {architectures}.")
175
+
176
+ with torch.device("meta"):
177
+ model: PreTrainedModel = AutoClass.from_config(config, torch_dtype=torch.bfloat16)
178
+
179
+ assert isinstance(model, PreTrainedModel)
180
+ model.to_empty(device="cpu")
181
+
182
+ print(f"Saving model to {hf_path}...")
183
+ model.save_pretrained(hf_path, state_dict=state_dict)
184
+ del state_dict, model
185
+
186
+ if args.hf_upload_path:
187
+ upload_model_to_huggingface(hf_path, args.hf_upload_path)
LLaVA-NeXT/llava-critic-r1/EasyR1/setup.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+
18
+ from setuptools import find_packages, setup
19
+
20
+
21
+ def get_version() -> str:
22
+ with open(os.path.join("verl", "__init__.py"), encoding="utf-8") as f:
23
+ file_content = f.read()
24
+ pattern = r"__version__\W*=\W*\"([^\"]+)\""
25
+ (version,) = re.findall(pattern, file_content)
26
+ return version
27
+
28
+
29
+ def get_requires() -> list[str]:
30
+ with open("requirements.txt", encoding="utf-8") as f:
31
+ file_content = f.read()
32
+ lines = [line.strip() for line in file_content.strip().split("\n") if not line.startswith("#")]
33
+ return lines
34
+
35
+
36
+ extra_require = {
37
+ "dev": ["pre-commit", "ruff"],
38
+ }
39
+
40
+
41
+ def main():
42
+ setup(
43
+ name="verl",
44
+ version=get_version(),
45
+ description="An Efficient, Scalable, Multi-Modality RL Training Framework based on veRL",
46
+ long_description=open("README.md", encoding="utf-8").read(),
47
+ long_description_content_type="text/markdown",
48
+ author="verl",
49
+ author_email="zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk, hiyouga@buaa.edu.cn",
50
+ license="Apache 2.0 License",
51
+ url="https://github.com/volcengine/verl",
52
+ package_dir={"": "."},
53
+ packages=find_packages(where="."),
54
+ python_requires=">=3.9.0",
55
+ install_requires=get_requires(),
56
+ extras_require=extra_require,
57
+ )
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()
LLaVA-NeXT/llava-critic-r1/EasyR1/verl.egg-info/SOURCES.txt ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ ./verl/__init__.py
6
+ ./verl/protocol.py
7
+ ./verl/models/__init__.py
8
+ ./verl/models/monkey_patch.py
9
+ ./verl/models/transformers/__init__.py
10
+ ./verl/models/transformers/flash_attention_utils.py
11
+ ./verl/models/transformers/qwen2_vl.py
12
+ ./verl/single_controller/__init__.py
13
+ ./verl/single_controller/base/__init__.py
14
+ ./verl/single_controller/base/decorator.py
15
+ ./verl/single_controller/base/worker.py
16
+ ./verl/single_controller/base/worker_group.py
17
+ ./verl/single_controller/base/register_center/__init__.py
18
+ ./verl/single_controller/base/register_center/ray.py
19
+ ./verl/single_controller/ray/__init__.py
20
+ ./verl/single_controller/ray/base.py
21
+ ./verl/trainer/__init__.py
22
+ ./verl/trainer/config.py
23
+ ./verl/trainer/core_algos.py
24
+ ./verl/trainer/data_loader.py
25
+ ./verl/trainer/main.py
26
+ ./verl/trainer/metrics.py
27
+ ./verl/trainer/ray_trainer.py
28
+ ./verl/utils/__init__.py
29
+ ./verl/utils/dataset.py
30
+ ./verl/utils/flops_counter.py
31
+ ./verl/utils/fsdp_utils.py
32
+ ./verl/utils/model_utils.py
33
+ ./verl/utils/py_functional.py
34
+ ./verl/utils/seqlen_balancing.py
35
+ ./verl/utils/tokenizer.py
36
+ ./verl/utils/torch_dtypes.py
37
+ ./verl/utils/torch_functional.py
38
+ ./verl/utils/ulysses.py
39
+ ./verl/utils/checkpoint/__init__.py
40
+ ./verl/utils/checkpoint/checkpoint_manager.py
41
+ ./verl/utils/checkpoint/fsdp_checkpoint_manager.py
42
+ ./verl/utils/logger/__init__.py
43
+ ./verl/utils/logger/gen_logger.py
44
+ ./verl/utils/logger/logger.py
45
+ ./verl/workers/__init__.py
46
+ ./verl/workers/config.py
47
+ ./verl/workers/fsdp_workers.py
48
+ ./verl/workers/actor/__init__.py
49
+ ./verl/workers/actor/base.py
50
+ ./verl/workers/actor/config.py
51
+ ./verl/workers/actor/dp_actor.py
52
+ ./verl/workers/critic/__init__.py
53
+ ./verl/workers/critic/base.py
54
+ ./verl/workers/critic/config.py
55
+ ./verl/workers/critic/dp_critic.py
56
+ ./verl/workers/reward/__init__.py
57
+ ./verl/workers/reward/config.py
58
+ ./verl/workers/reward/function.py
59
+ ./verl/workers/rollout/__init__.py
60
+ ./verl/workers/rollout/base.py
61
+ ./verl/workers/rollout/config.py
62
+ ./verl/workers/rollout/vllm_rollout_spmd.py
63
+ ./verl/workers/sharding_manager/__init__.py
64
+ ./verl/workers/sharding_manager/base.py
65
+ ./verl/workers/sharding_manager/fsdp_ulysses.py
66
+ ./verl/workers/sharding_manager/fsdp_vllm.py
67
+ verl/__init__.py
68
+ verl/protocol.py
69
+ verl.egg-info/PKG-INFO
70
+ verl.egg-info/SOURCES.txt
71
+ verl.egg-info/dependency_links.txt
72
+ verl.egg-info/requires.txt
73
+ verl.egg-info/top_level.txt
74
+ verl/models/__init__.py
75
+ verl/models/monkey_patch.py
76
+ verl/models/transformers/__init__.py
77
+ verl/models/transformers/flash_attention_utils.py
78
+ verl/models/transformers/qwen2_vl.py
79
+ verl/single_controller/__init__.py
80
+ verl/single_controller/base/__init__.py
81
+ verl/single_controller/base/decorator.py
82
+ verl/single_controller/base/worker.py
83
+ verl/single_controller/base/worker_group.py
84
+ verl/single_controller/base/register_center/__init__.py
85
+ verl/single_controller/base/register_center/ray.py
86
+ verl/single_controller/ray/__init__.py
87
+ verl/single_controller/ray/base.py
88
+ verl/trainer/__init__.py
89
+ verl/trainer/config.py
90
+ verl/trainer/core_algos.py
91
+ verl/trainer/data_loader.py
92
+ verl/trainer/main.py
93
+ verl/trainer/metrics.py
94
+ verl/trainer/ray_trainer.py
95
+ verl/utils/__init__.py
96
+ verl/utils/dataset.py
97
+ verl/utils/flops_counter.py
98
+ verl/utils/fsdp_utils.py
99
+ verl/utils/model_utils.py
100
+ verl/utils/py_functional.py
101
+ verl/utils/seqlen_balancing.py
102
+ verl/utils/tokenizer.py
103
+ verl/utils/torch_dtypes.py
104
+ verl/utils/torch_functional.py
105
+ verl/utils/ulysses.py
106
+ verl/utils/checkpoint/__init__.py
107
+ verl/utils/checkpoint/checkpoint_manager.py
108
+ verl/utils/checkpoint/fsdp_checkpoint_manager.py
109
+ verl/utils/logger/__init__.py
110
+ verl/utils/logger/gen_logger.py
111
+ verl/utils/logger/logger.py
112
+ verl/workers/__init__.py
113
+ verl/workers/config.py
114
+ verl/workers/fsdp_workers.py
115
+ verl/workers/actor/__init__.py
116
+ verl/workers/actor/base.py
117
+ verl/workers/actor/config.py
118
+ verl/workers/actor/dp_actor.py
119
+ verl/workers/critic/__init__.py
120
+ verl/workers/critic/base.py
121
+ verl/workers/critic/config.py
122
+ verl/workers/critic/dp_critic.py
123
+ verl/workers/reward/__init__.py
124
+ verl/workers/reward/config.py
125
+ verl/workers/reward/function.py
126
+ verl/workers/rollout/__init__.py
127
+ verl/workers/rollout/base.py
128
+ verl/workers/rollout/config.py
129
+ verl/workers/rollout/vllm_rollout_spmd.py
130
+ verl/workers/sharding_manager/__init__.py
131
+ verl/workers/sharding_manager/base.py
132
+ verl/workers/sharding_manager/fsdp_ulysses.py
133
+ verl/workers/sharding_manager/fsdp_vllm.py
LLaVA-NeXT/llava-critic-r1/EasyR1/verl.egg-info/dependency_links.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
LLaVA-NeXT/llava-critic-r1/EasyR1/verl.egg-info/requires.txt ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate
2
+ codetiming
3
+ datasets
4
+ liger-kernel
5
+ mathruler
6
+ numpy
7
+ omegaconf
8
+ pandas
9
+ peft
10
+ pillow
11
+ pyarrow>=15.0.0
12
+ pylatexenc
13
+ qwen-vl-utils
14
+ ray[default]
15
+ tensordict
16
+ torchdata
17
+ transformers>=4.51.0
18
+ vllm>=0.7.3
19
+ wandb
20
+
21
+ [dev]
22
+ pre-commit
23
+ ruff
LLaVA-NeXT/llava-critic-r1/EasyR1/verl.egg-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ verl
LLaVA-NeXT/llava-critic-r1/init ADDED
@@ -0,0 +1 @@
 
 
1
+
LLaVA-NeXT/playground/2d_hist.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from PIL import Image
4
+ from tqdm import tqdm
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ from multiprocessing import Pool
8
+ import functools
9
+ import argparse
10
+
11
+
12
+ def load_data(json_path):
13
+ with open(json_path, "r") as f:
14
+ return json.load(f)
15
+
16
+
17
+ def filter_data(data):
18
+ filtered_data = [item for item in data if "image" in item]
19
+ return filtered_data
20
+
21
+
22
+ def calculate_image_dimension(image_path, images_folder):
23
+ full_path = os.path.join(images_folder, image_path)
24
+ try:
25
+ with Image.open(full_path) as img:
26
+ width, height = img.size
27
+ return width, height
28
+ except Exception as e:
29
+ print(f"Error opening {full_path}: {e}")
30
+ return None, None
31
+
32
+
33
+ def calculate_image_dimensions_multiprocess(filtered_data, images_folder, num_processes=256):
34
+ image_paths = []
35
+ for item in filtered_data:
36
+ if isinstance(item["image"], list):
37
+ image_paths.extend(item["image"])
38
+ else:
39
+ image_paths.append(item["image"])
40
+
41
+ with Pool(num_processes) as p:
42
+ dimensions = list(
43
+ tqdm(
44
+ p.imap(functools.partial(calculate_image_dimension, images_folder=images_folder), image_paths),
45
+ total=len(image_paths),
46
+ desc="Calculating image dimensions",
47
+ )
48
+ )
49
+ widths, heights = zip(*[dim for dim in dimensions if dim[0] is not None])
50
+ return list(widths), list(heights)
51
+
52
+
53
+ def tokenize(text):
54
+ return text.split()
55
+
56
+
57
+ def calculate_tokenized_lengths(data):
58
+ lengths = []
59
+ for item in tqdm(data, desc="Tokenizing conversations"):
60
+ for conversation in item["conversations"]:
61
+ tokenized_value = tokenize(conversation["value"])
62
+ lengths.append(len(tokenized_value))
63
+ return lengths
64
+
65
+
66
+ def main():
67
+ parser = argparse.ArgumentParser(description="Process data for LLaVA_Next project.")
68
+ parser.add_argument(
69
+ "--json_path",
70
+ type=str,
71
+ help="Path to the JSON file containing data.",
72
+ default="/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/llava_ofa_DEMON-FULL.json",
73
+ )
74
+ parser.add_argument(
75
+ "--images_folder",
76
+ type=str,
77
+ default="/mnt/bn/vl-research/data/llava_data",
78
+ help="Path to the folder containing images.",
79
+ )
80
+ args = parser.parse_args()
81
+
82
+ llava_instruct_name = os.path.basename(args.json_path).replace(".json", "")
83
+ images_folder = args.images_folder
84
+
85
+ data = load_data(args.json_path)
86
+ filtered_data = filter_data(data)
87
+
88
+ print(f"Total data items: {len(data)}, Filtered data items: {len(filtered_data)}")
89
+ widths, heights = calculate_image_dimensions_multiprocess(filtered_data, images_folder)
90
+ max_width, max_height = max(widths), max(heights)
91
+ print(f"Max width: {max_width}, Max height: {max_height}")
92
+
93
+ tokenized_lengths = calculate_tokenized_lengths(filtered_data)
94
+
95
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 12))
96
+
97
+ # Plot 2D histogram
98
+ widths_bins = [min(widths), max(widths) + 1] if min(widths) == max(widths) else np.arange(min(widths), max(widths) + 100, 100)
99
+ heights_bins = [min(heights), max(heights) + 1] if min(heights) == max(heights) else np.arange(min(heights), max(heights) + 100, 100)
100
+
101
+ h, xedges, yedges, image = ax1.hist2d(widths, heights, bins=[widths_bins, heights_bins], cmap=plt.cm.jet, density=True)
102
+ fig.colorbar(image, ax=ax1)
103
+ ax1.set_xlabel("Width")
104
+ ax1.set_ylabel("Height")
105
+ ax1.set_title(
106
+ f"dist_{llava_instruct_name}_2d_w_h\nMax width: {max(widths)}, Max height: {max(heights)}",
107
+ fontsize=10,
108
+ )
109
+
110
+ # Plot histogram
111
+ hist, bin_edges = np.histogram(tokenized_lengths, bins=np.arange(0, max(tokenized_lengths) + 10, 10))
112
+ bins = np.arange(0, max(tokenized_lengths) + 10, 10)
113
+ ax2.bar(bin_edges[:-1], hist, width=7, edgecolor="black", log=True)
114
+
115
+ # Display every nth label on the x-axis
116
+ n = 8 # Adjust this value to control the number of labels displayed
117
+ ticks = bins[::n]
118
+ tick_labels = [int(tick) for tick in ticks]
119
+ ax2.set_xticks(ticks)
120
+ ax2.set_xticklabels(tick_labels, rotation=90, fontsize=8)
121
+
122
+ ax2.set_xlim(min(bin_edges), max(bin_edges))
123
+ ax2.set_xlabel("Tokenized Length")
124
+ ax2.set_ylabel("Count (log scale)")
125
+ ax2.set_title(f"dist_{llava_instruct_name}_tokenized_length", fontsize=8)
126
+
127
+ plt.tight_layout()
128
+ plt.savefig(f"./dist_{llava_instruct_name}_combined.png")
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
LLaVA-NeXT/playground/data_checker.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from tqdm import tqdm
4
+ from multiprocessing import Pool, cpu_count
5
+ import yaml
6
+
7
+
8
+ class DataProcessor:
9
+ def __init__(self, file_path, image_root, video_root):
10
+ self.file_path = file_path
11
+ self.image_root = image_root
12
+ self.data = None
13
+ self.video_root = video_root
14
+ self.load_data()
15
+
16
+ def load_data(self):
17
+ if self.file_path.endswith(".json"):
18
+ with open(self.file_path, "r") as f:
19
+ self.data = json.load(f)
20
+ elif self.file_path.endswith(".yaml"):
21
+ with open(self.file_path, "r") as f:
22
+ self.data = yaml.safe_load(f)
23
+ elif self.file_path.endswith(".jsonl"):
24
+ with open(self.file_path, "r") as f:
25
+ self.data = [json.loads(line) for line in f.readlines()]
26
+ else:
27
+ raise ValueError("Unsupported file format")
28
+
29
+ def load_json_data(self, json_path):
30
+ if json_path.endswith(".jsonl"):
31
+ cur_data_dict = []
32
+ with open(json_path, "r") as json_file:
33
+ for line in json_file:
34
+ cur_data_dict.append(json.loads(line.strip()))
35
+ return cur_data_dict
36
+ elif json_path.endswith(".json"):
37
+ with open(json_path, "r") as f:
38
+ return json.load(f)
39
+ else:
40
+ raise ValueError("Unsupported file format")
41
+
42
+ def check_image_existence(self, data):
43
+ if "image" in data:
44
+ if type(data["image"]) == list:
45
+ images = data["image"]
46
+ else:
47
+ images = [data["image"]]
48
+
49
+ for image in images:
50
+ full_image_path = os.path.join(self.image_root, image)
51
+ if not os.path.exists(full_image_path):
52
+ print(f"WARNING!!! {full_image_path} not exists !!!")
53
+
54
+ if "video" in data:
55
+ full_video_path = os.path.join(self.video_root, data["video"])
56
+ if not os.path.exists(full_video_path):
57
+ print(f"WARNING!!! {full_video_path} not exists !!!")
58
+
59
+ # if data["conversations"][0]["value"].count("<image>") > 1:
60
+ # print(f"WARNING!!! {data['conversations'][0]['value']} has more than one <image> !!!")
61
+
62
+ def check_item_structure(self, item):
63
+ if not all(key in item for key in ["conversations"]):
64
+ print(f"WARNING!!! Item {item.get('id', 'unknown')} is missing required fields!")
65
+ return False
66
+
67
+ conversations = item["conversations"]
68
+ if not isinstance(conversations, list) or len(conversations) < 2 or len(conversations) % 2 != 0:
69
+ print(f"WARNING!!! Item {item['id']} has invalid conversations structure!")
70
+ return False
71
+
72
+ for i, conv in enumerate(conversations):
73
+ if not all(key in conv for key in ["from", "value"]):
74
+ print(f"WARNING!!! Item {item['id']} has invalid conversation format!")
75
+ return False
76
+
77
+ expected_from = "human" if i % 2 == 0 else "gpt"
78
+ if conv["from"] != expected_from:
79
+ print(f"WARNING!!! Item {item['id']} has incorrect conversation order!")
80
+ return False
81
+
82
+ return True
83
+
84
+ def check_image_and_structure(self, item):
85
+ if not self.check_item_structure(item):
86
+ return
87
+
88
+ # self.check_image_existence(item)
89
+
90
+ def process_images(self):
91
+ if isinstance(self.data, list):
92
+ args = [d for d in self.data]
93
+ with Pool(processes=cpu_count()) as pool:
94
+ list(tqdm(pool.imap(self.check_image_and_structure, args), total=len(self.data)))
95
+ elif isinstance(self.data, dict):
96
+ for d in self.data["datasets"]:
97
+ dd_json_path = d["json_path"]
98
+ data = self.load_json_data(dd_json_path)
99
+ args = [d for d in data]
100
+ with Pool(processes=cpu_count()) as pool:
101
+ list(tqdm(pool.imap(self.check_image_and_structure, args), total=len(data), desc=f"Processing {dd_json_path}"))
102
+
103
+ def count_items(self):
104
+ if isinstance(self.data, list): # Assuming JSON data loaded directly
105
+ return len(self.data)
106
+ elif isinstance(self.data, dict): # Assuming YAML data loaded
107
+ total_items_count = 0
108
+ for d in self.data["datasets"]:
109
+ dd_json_path = d["json_path"]
110
+ data = self.load_json_data(dd_json_path)
111
+ current_items_count = len(data)
112
+
113
+ sampling_strategy = d["sampling_strategy"]
114
+ try:
115
+ if sampling_strategy != "all":
116
+ percentage = float(sampling_strategy.split(":")[-1].replace("%", "")) / 100.0
117
+ else:
118
+ percentage = 1.0
119
+ except Exception as e:
120
+ print(f"Error: {e}")
121
+ percentage = 1.0
122
+
123
+ sampling_count = int(current_items_count * percentage)
124
+ total_items_count += sampling_count
125
+ print(f"{dd_json_path}: {sampling_count}")
126
+ return total_items_count
127
+
128
+ def stat_data(self):
129
+ if isinstance(self.data, dict):
130
+ cur_lens_list = []
131
+ single_image_count = 0
132
+ multiple_image_count = 0
133
+ video_count = 0
134
+ total_count = 0
135
+ text_count = 0
136
+ max_tokens_item = None
137
+ max_tokens = 0
138
+
139
+ for d in self.data["datasets"]:
140
+ dd_json_path = d["json_path"]
141
+ data = self.load_json_data(dd_json_path)
142
+ sampling_strategy = d["sampling_strategy"]
143
+
144
+ try:
145
+ if sampling_strategy != "all":
146
+ percentage = float(sampling_strategy.split(":")[-1].replace("%", "")) / 100.0
147
+ else:
148
+ percentage = 1.0
149
+ except Exception as e:
150
+ print(f"Error parsing sampling strategy: {e}")
151
+ percentage = 1.0
152
+
153
+ sampled_count = int(len(data) * percentage)
154
+ print(f"{dd_json_path}: {sampled_count} (sampled from {len(data)})")
155
+
156
+ for item in data[:sampled_count]:
157
+ conversations = item["conversations"]
158
+ cur_len = sum([len(conv["value"].split()) for conv in conversations])
159
+ cur_lens_list.append(cur_len)
160
+
161
+ if cur_len > max_tokens:
162
+ max_tokens = cur_len
163
+ max_tokens_item = item
164
+
165
+ total_count += 1
166
+ if "image" in item:
167
+ if isinstance(item["image"], list):
168
+ if len(item["image"]) > 1:
169
+ multiple_image_count += 1
170
+ else:
171
+ single_image_count += 1
172
+ else:
173
+ single_image_count += 1
174
+ elif "video" in item:
175
+ video_count += 1
176
+ else:
177
+ text_count += 1
178
+
179
+ print(f"Max length: {max(cur_lens_list)}, Min length: {min(cur_lens_list)}, Average length: {sum(cur_lens_list) / len(cur_lens_list)}")
180
+ print(f"Total items: {total_count}")
181
+ print(f"Text items: {text_count} ({text_count/total_count*100:.2f}%)")
182
+ print(f"Single image items: {single_image_count} ({single_image_count/total_count*100:.2f}%)")
183
+ print(f"Multiple image items: {multiple_image_count} ({multiple_image_count/total_count*100:.2f}%)")
184
+ print(f"Video items: {video_count} ({video_count/total_count*100:.2f}%)")
185
+
186
+ print("\nItem with the largest number of tokens:")
187
+ print(f"Token count: {max_tokens}")
188
+ print("Item content:")
189
+ print(json.dumps(max_tokens_item, indent=2))
190
+
191
+ def filter_data(self):
192
+ if isinstance(self.data, dict):
193
+ for d in self.data["datasets"]:
194
+ dd_json_path = d["json_path"]
195
+ print(f"Processing {dd_json_path}")
196
+ data = self.load_json_data(dd_json_path)
197
+
198
+ filtered_data = []
199
+ mismatch_data = []
200
+ mismatch_flag = False
201
+ for item in data:
202
+ try:
203
+ if "image" in item:
204
+ num_image = len(item["image"]) if isinstance(item["image"], list) else 1
205
+ else:
206
+ num_image = 0
207
+
208
+ if "video" in item:
209
+ num_video = len(item["video"]) if isinstance(item["video"], list) else 1
210
+ else:
211
+ num_video = 0
212
+
213
+ num_visuals = num_image + num_video
214
+ conv_text = ""
215
+ for conv in item["conversations"]:
216
+ conv_text += conv["value"]
217
+
218
+ num_img_token_appearance = conv_text.count("<image>")
219
+ if len(conv_text) == 0:
220
+ print(f"Conversation text is empty for {item}")
221
+
222
+ if num_img_token_appearance == num_visuals or num_img_token_appearance < num_visuals and len(conv_text) > 0:
223
+ filtered_data.append(item)
224
+ elif num_img_token_appearance > num_visuals:
225
+ item["num_img_token_appearance"] = num_img_token_appearance
226
+ item["num_visuals"] = num_visuals
227
+ mismatch_data.append(item)
228
+
229
+ if not mismatch_flag:
230
+ print(f"Data mismatch for {item}")
231
+
232
+ mismatch_flag = True
233
+ except Exception as e:
234
+ print(f"Error: {e}")
235
+ print()
236
+
237
+ if mismatch_flag:
238
+ print(f"Data mismatch for {dd_json_path}")
239
+
240
+ if len(filtered_data) < len(data):
241
+ saving_dd_json_path = dd_json_path.replace(".jsonl", f"fltd_{len(filtered_data)}.json").replace(".json", f"fltd_{len(filtered_data)}.json")
242
+ with open(saving_dd_json_path, "w") as f:
243
+ json.dump(filtered_data, f, indent=2)
244
+ print(f"Filtered data count: {len(filtered_data)}")
245
+ else:
246
+ pass
247
+
248
+ def stat_and_filter_data(self, threshold):
249
+ if isinstance(self.data, dict):
250
+ cur_lens_list = []
251
+ single_image_count = 0
252
+ multiple_image_count = 0
253
+ video_count = 0
254
+ total_count = 0
255
+ text_count = 0
256
+
257
+ for d in self.data["datasets"]:
258
+ dd_json_path = d["json_path"]
259
+ data = self.load_json_data(dd_json_path)
260
+ sampling_strategy = d["sampling_strategy"]
261
+ filtered_data = []
262
+
263
+ try:
264
+ if sampling_strategy != "all":
265
+ percentage = float(sampling_strategy.split(":")[-1].replace("%", "")) / 100.0
266
+ else:
267
+ percentage = 1.0
268
+ except Exception as e:
269
+ print(f"Error parsing sampling strategy: {e}")
270
+ percentage = 1.0
271
+
272
+ sampled_count = int(len(data) * percentage)
273
+ print(f"{dd_json_path}: {sampled_count} (sampled from {len(data)})")
274
+
275
+ save_flag = False
276
+ for item in data:
277
+ total_count += 1
278
+ conversations = item["conversations"]
279
+ filtered_conversations = []
280
+ current_token_count = 0
281
+
282
+ for i in range(0, len(conversations), 2):
283
+ if i + 1 < len(conversations):
284
+ human_conv = conversations[i]
285
+ gpt_conv = conversations[i + 1]
286
+ pair_tokens = len(human_conv["value"].split()) + len(gpt_conv["value"].split())
287
+
288
+ if current_token_count + pair_tokens <= threshold:
289
+ filtered_conversations.extend([human_conv, gpt_conv])
290
+ current_token_count += pair_tokens
291
+ else:
292
+ save_flag = True
293
+ break
294
+
295
+ if filtered_conversations:
296
+ item["conversations"] = filtered_conversations
297
+ cur_len = sum([len(conv["value"].split()) for conv in filtered_conversations])
298
+ cur_lens_list.append(cur_len)
299
+ filtered_data.append(item)
300
+
301
+ if "image" in item:
302
+ if isinstance(item["image"], list):
303
+ if len(item["image"]) > 1:
304
+ multiple_image_count += 1
305
+ else:
306
+ single_image_count += 1
307
+ else:
308
+ single_image_count += 1
309
+ elif "video" in item:
310
+ video_count += 1
311
+ else:
312
+ text_count += 1
313
+
314
+ # Save filtered data for each dataset
315
+ if filtered_data and save_flag:
316
+ if dd_json_path.endswith(".jsonl"):
317
+ output_file = dd_json_path.replace(".jsonl", f"_filtered_{threshold}tokens_{len(filtered_data)}.jsonl")
318
+ with open(output_file, "w") as f:
319
+ for item in filtered_data:
320
+ f.write(json.dumps(item) + "\n")
321
+ else:
322
+ output_file = dd_json_path.replace(".json", f"_filtered_{threshold}tokens_{len(filtered_data)}.json")
323
+ with open(output_file, "w") as f:
324
+ json.dump(filtered_data, f, indent=2)
325
+ print(f"Filtered data for {dd_json_path} saved to: {output_file}")
326
+
327
+ print(f"Max length: {max(cur_lens_list)}, Min length: {min(cur_lens_list)}, Average length: {sum(cur_lens_list) / len(cur_lens_list)}")
328
+ print(f"Total items: {total_count}")
329
+ print(f"Text items: {text_count} ({text_count/total_count*100:.2f}%)")
330
+ print(f"Single image items: {single_image_count} ({single_image_count/total_count*100:.2f}%)")
331
+ print(f"Multiple image items: {multiple_image_count} ({multiple_image_count/total_count*100:.2f}%)")
332
+ print(f"Video items: {video_count} ({video_count/total_count*100:.2f}%)")
333
+
334
+
335
+ def main(file_path, image_root, operation, video_root, threshold=None):
336
+ processor = DataProcessor(file_path, image_root, video_root)
337
+ if operation == "check":
338
+ processor.process_images()
339
+ elif operation == "count":
340
+ total_items = processor.count_items()
341
+ print(f"Total items: {total_items}")
342
+ elif operation == "filter":
343
+ processor.filter_data()
344
+ elif operation == "stat":
345
+ processor.stat_data()
346
+ elif operation == "stat_and_filter":
347
+ if threshold is None:
348
+ raise ValueError("Threshold must be provided for stat_and_filter operation")
349
+ processor.stat_and_filter_data(threshold)
350
+ else:
351
+ raise ValueError("Unsupported operation")
352
+
353
+
354
+ if __name__ == "__main__":
355
+ import argparse
356
+
357
+ parser = argparse.ArgumentParser()
358
+ parser.add_argument("--file_path", type=str, default="/mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/scripts/i18n/scale_llms/next_continual.yaml")
359
+ parser.add_argument("--image_root", type=str, default="/mnt/bn/vl-research/data/llava_data")
360
+ parser.add_argument("--video_root", type=str, default="/mnt/bn/vl-research/data/llava_video")
361
+ parser.add_argument("--operation", type=str, default="filter")
362
+ parser.add_argument("--threshold", type=int, default=None, help="Threshold for stat_and_filter operation")
363
+ args = parser.parse_args()
364
+ main(args.file_path, args.image_root, args.operation, args.video_root, args.threshold)
LLaVA-NeXT/playground/demo/video_demo.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+
4
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
5
+ from llava.conversation import conv_templates, SeparatorStyle
6
+ from llava.model.builder import load_pretrained_model
7
+ from llava.utils import disable_torch_init
8
+ from llava.mm_utils import process_anyres_image,tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
9
+
10
+ import json
11
+ import os
12
+ import math
13
+ from tqdm import tqdm
14
+ from decord import VideoReader, cpu
15
+
16
+ from transformers import AutoConfig
17
+
18
+ import cv2
19
+ import base64
20
+ import openai
21
+
22
+ from PIL import Image
23
+
24
+
25
+
26
+ import numpy as np
27
+
28
+ def split_list(lst, n):
29
+ """Split a list into n (roughly) equal-sized chunks"""
30
+ chunk_size = math.ceil(len(lst) / n) # integer division
31
+ return [lst[i : i + chunk_size] for i in range(0, len(lst), chunk_size)]
32
+
33
+
34
+ def get_chunk(lst, n, k):
35
+ chunks = split_list(lst, n)
36
+ return chunks[k]
37
+
38
+
39
+ def parse_args():
40
+ """
41
+ Parse command-line arguments.
42
+ """
43
+ parser = argparse.ArgumentParser()
44
+
45
+ # Define the command-line arguments
46
+ parser.add_argument("--video_path", help="Path to the video files.", required=True)
47
+ parser.add_argument("--output_dir", help="Directory to save the model results JSON.", required=True)
48
+ parser.add_argument("--output_name", help="Name of the file for storing results JSON.", required=True)
49
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
50
+ parser.add_argument("--model-base", type=str, default=None)
51
+ parser.add_argument("--conv-mode", type=str, default=None)
52
+ parser.add_argument("--chunk-idx", type=int, default=0)
53
+ parser.add_argument("--mm_resampler_type", type=str, default="spatial_pool")
54
+ parser.add_argument("--mm_spatial_pool_stride", type=int, default=4)
55
+ parser.add_argument("--mm_spatial_pool_out_channels", type=int, default=1024)
56
+ parser.add_argument("--mm_spatial_pool_mode", type=str, default="average")
57
+ parser.add_argument("--image_aspect_ratio", type=str, default="anyres")
58
+ parser.add_argument("--image_grid_pinpoints", type=str, default="[(224, 448), (224, 672), (224, 896), (448, 448), (448, 224), (672, 224), (896, 224)]")
59
+ parser.add_argument("--mm_patch_merge_type", type=str, default="spatial_unpad")
60
+ parser.add_argument("--overwrite", type=lambda x: (str(x).lower() == 'true'), default=True)
61
+ parser.add_argument("--for_get_frames_num", type=int, default=4)
62
+ parser.add_argument("--load_8bit", type=lambda x: (str(x).lower() == 'true'), default=False)
63
+ parser.add_argument("--prompt", type=str, default=None)
64
+ parser.add_argument("--api_key", type=str, help="OpenAI API key")
65
+ parser.add_argument("--mm_newline_position", type=str, default="no_token")
66
+ parser.add_argument("--force_sample", type=lambda x: (str(x).lower() == 'true'), default=False)
67
+ parser.add_argument("--add_time_instruction", type=str, default=False)
68
+ return parser.parse_args()
69
+
70
+ def load_video(video_path,args):
71
+ if args.for_get_frames_num == 0:
72
+ return np.zeros((1, 336, 336, 3))
73
+ vr = VideoReader(video_path, ctx=cpu(0),num_threads=1)
74
+ total_frame_num = len(vr)
75
+ video_time = total_frame_num / vr.get_avg_fps()
76
+ fps = round(vr.get_avg_fps())
77
+ frame_idx = [i for i in range(0, len(vr), fps)]
78
+ frame_time = [i/fps for i in frame_idx]
79
+ if len(frame_idx) > args.for_get_frames_num or args.force_sample:
80
+ sample_fps = args.for_get_frames_num
81
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, sample_fps, dtype=int)
82
+ frame_idx = uniform_sampled_frames.tolist()
83
+ frame_time = [i/vr.get_avg_fps() for i in frame_idx]
84
+ frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
85
+ spare_frames = vr.get_batch(frame_idx).asnumpy()
86
+ # import pdb;pdb.set_trace()
87
+
88
+ return spare_frames,frame_time,video_time
89
+
90
+
91
+
92
+
93
+ def load_video_base64(path):
94
+ video = cv2.VideoCapture(path)
95
+
96
+ base64Frames = []
97
+ while video.isOpened():
98
+ success, frame = video.read()
99
+ if not success:
100
+ break
101
+ _, buffer = cv2.imencode(".jpg", frame)
102
+ base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
103
+
104
+ video.release()
105
+ # print(len(base64Frames), "frames read.")
106
+ return base64Frames
107
+
108
+
109
+ def run_inference(args):
110
+ """
111
+ Run inference on ActivityNet QA DataSet using the Video-ChatGPT model.
112
+
113
+ Args:
114
+ args: Command-line arguments.
115
+ """
116
+ # Initialize the model
117
+ if "gpt4v" != args.model_path:
118
+ model_name = get_model_name_from_path(args.model_path)
119
+ # Set model configuration parameters if they exist
120
+ if args.overwrite == True:
121
+ overwrite_config = {}
122
+ overwrite_config["mm_spatial_pool_mode"] = args.mm_spatial_pool_mode
123
+ overwrite_config["mm_spatial_pool_stride"] = args.mm_spatial_pool_stride
124
+ overwrite_config["mm_newline_position"] = args.mm_newline_position
125
+
126
+ cfg_pretrained = AutoConfig.from_pretrained(args.model_path)
127
+
128
+ # import pdb;pdb.set_trace()
129
+ if "qwen" not in args.model_path.lower():
130
+ if "224" in cfg_pretrained.mm_vision_tower:
131
+ # suppose the length of text tokens is around 1000, from bo's report
132
+ least_token_number = args.for_get_frames_num*(16//args.mm_spatial_pool_stride)**2 + 1000
133
+ else:
134
+ least_token_number = args.for_get_frames_num*(24//args.mm_spatial_pool_stride)**2 + 1000
135
+
136
+ scaling_factor = math.ceil(least_token_number/4096)
137
+ if scaling_factor >= 2:
138
+ if "vicuna" in cfg_pretrained._name_or_path.lower():
139
+ print(float(scaling_factor))
140
+ overwrite_config["rope_scaling"] = {"factor": float(scaling_factor), "type": "linear"}
141
+ overwrite_config["max_sequence_length"] = 4096 * scaling_factor
142
+ overwrite_config["tokenizer_model_max_length"] = 4096 * scaling_factor
143
+
144
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, load_8bit=args.load_8bit, overwrite_config=overwrite_config)
145
+ else:
146
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name)
147
+ else:
148
+ pass
149
+
150
+ # import pdb;pdb.set_trace()
151
+ if getattr(model.config, "force_sample", None) is not None:
152
+ args.force_sample = model.config.force_sample
153
+ else:
154
+ args.force_sample = False
155
+
156
+ # import pdb;pdb.set_trace()
157
+
158
+ if getattr(model.config, "add_time_instruction", None) is not None:
159
+ args.add_time_instruction = model.config.add_time_instruction
160
+ else:
161
+ args.add_time_instruction = False
162
+
163
+ # Create the output directory if it doesn't exist
164
+ if not os.path.exists(args.output_dir):
165
+ os.makedirs(args.output_dir)
166
+
167
+ output_name = args.output_name
168
+ answers_file = os.path.join(args.output_dir, f"{output_name}.json")
169
+ ans_file = open(answers_file, "w")
170
+
171
+ video_path = args.video_path
172
+
173
+ all_video_pathes = []
174
+
175
+ # Check if the video_path is a directory or a file
176
+ if os.path.isdir(video_path):
177
+ # If it's a directory, loop over all files in the directory
178
+ for filename in os.listdir(video_path):
179
+ # Load the video file
180
+ cur_video_path = os.path.join(video_path, f"{filename}")
181
+ all_video_pathes.append(os.path.join(video_path, cur_video_path))
182
+ else:
183
+ # If it's a file, just process the video
184
+ all_video_pathes.append(video_path)
185
+
186
+ # import pdb;pdb.set_trace()
187
+ for video_path in all_video_pathes:
188
+
189
+ sample_set = {}
190
+ question = args.prompt
191
+ sample_set["Q"] = question
192
+ sample_set["video_name"] = video_path
193
+
194
+
195
+ # Check if the video exists
196
+ if os.path.exists(video_path):
197
+ if "gpt4v" != args.model_path:
198
+ video,frame_time,video_time = load_video(video_path, args)
199
+ video = image_processor.preprocess(video, return_tensors="pt")["pixel_values"].half().cuda()
200
+ video = [video]
201
+ else:
202
+ spare_frames,frame_time,video_time = load_video_base64(video_path)
203
+ interval = int(len(video) / args.for_get_frames_num)
204
+
205
+ # try:
206
+ # Run inference on the video and add the output to the list
207
+ if "gpt4v" != args.model_path:
208
+ qs = question
209
+ if args.add_time_instruction:
210
+ time_instruciton = f"The video lasts for {video_time:.2f} seconds, and {len(video[0])} frames are uniformly sampled from it. These frames are located at {frame_time}.Please answer the following questions related to this video."
211
+ qs = f'{time_instruciton}\n{qs}'
212
+ if model.config.mm_use_im_start_end:
213
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + "\n" + qs
214
+ else:
215
+ qs = DEFAULT_IMAGE_TOKEN + "\n" + qs
216
+
217
+ conv = conv_templates[args.conv_mode].copy()
218
+ conv.append_message(conv.roles[0], qs)
219
+ conv.append_message(conv.roles[1], None)
220
+ prompt = conv.get_prompt()
221
+
222
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
223
+ if tokenizer.pad_token_id is None:
224
+ if "qwen" in tokenizer.name_or_path.lower():
225
+ print("Setting pad token to bos token for qwen model.")
226
+ tokenizer.pad_token_id = 151643
227
+
228
+ attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
229
+
230
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
231
+ keywords = [stop_str]
232
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
233
+
234
+ cur_prompt = question
235
+ else:
236
+ prompt = question
237
+
238
+ system_error = ""
239
+
240
+ if "gpt4v" != args.model_path:
241
+
242
+
243
+ with torch.inference_mode():
244
+ # model.update_prompt([[cur_prompt]])
245
+ # import pdb;pdb.set_trace()
246
+ # output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=True, temperature=0.2, max_new_tokens=1024, use_cache=True, stopping_criteria=[stopping_criteria])
247
+ if "mistral" not in cfg_pretrained._name_or_path.lower():
248
+ output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=False, temperature=0.0, max_new_tokens=1024, top_p=0.1,num_beams=1,use_cache=True, stopping_criteria=[stopping_criteria])
249
+ # output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=True, temperature=0.2, max_new_tokens=1024, use_cache=True, stopping_criteria=[stopping_criteria])
250
+ else:
251
+ output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=False, temperature=0.0, max_new_tokens=1024, top_p=0.1, num_beams=1, use_cache=True)
252
+ # output_ids = model.generate(inputs=input_ids, images=video, attention_mask=attention_masks, modalities="video", do_sample=True, temperature=0.2, max_new_tokens=1024, use_cache=True)
253
+ else:
254
+ openai.api_key = args.api_key # Your API key here
255
+
256
+ max_num_retries = 0
257
+ retry = 5
258
+ PROMPT_MESSAGES = [
259
+ {
260
+ "role": "user",
261
+ "content": [
262
+ f"These are frames from a video that I want to upload. Answer me one question of this video: {prompt}",
263
+ *map(lambda x: {"image": x, "resize": 336}, video[0::interval]),
264
+ ],
265
+ },
266
+ ]
267
+ params = {
268
+ "model": "gpt-4-vision-preview", #gpt-4-1106-vision-preview
269
+ "messages": PROMPT_MESSAGES,
270
+ "max_tokens": 1024,
271
+ }
272
+ sucess_flag=False
273
+ while max_num_retries < retry:
274
+ try:
275
+ result = openai.ChatCompletion.create(**params)
276
+ outputs = result.choices[0].message.content
277
+ sucess_flag = True
278
+ break
279
+ except Exception as inst :
280
+ if 'error' in dir(inst):
281
+ # import pdb;pdb.set_trace()
282
+ if inst.error.code == 'rate_limit_exceeded':
283
+ if "TPM" in inst.error.message:
284
+ time.sleep(30)
285
+ continue
286
+ else:
287
+ import pdb;pdb.set_trace()
288
+ elif inst.error.code == 'insufficient_quota':
289
+ print(f'insufficient_quota key')
290
+ exit()
291
+ elif inst.error.code == 'content_policy_violation':
292
+ print(f'content_policy_violation')
293
+ system_error = "content_policy_violation"
294
+
295
+ break
296
+ print('Find error message in response: ',str(inst.error.message), 'error code: ', str(inst.error.code))
297
+
298
+ continue
299
+ if not sucess_flag:
300
+ print(f'Calling OpenAI failed after retrying for {max_num_retries} times. Check the logs for details.')
301
+ exit()
302
+
303
+ if "gpt4v" != args.model_path:
304
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
305
+ else:
306
+ print(len(video[0::interval]))
307
+
308
+ print(f"Question: {prompt}\n")
309
+ print(f"Response: {outputs}\n")
310
+
311
+ if "gpt4v" == args.model_path:
312
+ if system_error == 'content_policy_violation':
313
+ continue
314
+ elif system_error == "":
315
+ continue
316
+ else:
317
+ import pdb;pdb.set_trace()
318
+
319
+ # import pdb;pdb.set_trace()
320
+ if "mistral" not in cfg_pretrained._name_or_path.lower():
321
+ if outputs.endswith(stop_str):
322
+ outputs = outputs[: -len(stop_str)]
323
+
324
+ outputs = outputs.strip()
325
+
326
+ sample_set["pred"] = outputs
327
+ ans_file.write(json.dumps(sample_set, ensure_ascii=False) + "\n")
328
+ ans_file.flush()
329
+
330
+ ans_file.close()
331
+
332
+
333
+ if __name__ == "__main__":
334
+ args = parse_args()
335
+ run_inference(args)
LLaVA-NeXT/playground/equal_splitter.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from math import ceil
3
+
4
+
5
+ def split_json_file(input_file, n_splits):
6
+ # Read the JSON file
7
+ with open(input_file, "r") as file:
8
+ data = json.load(file)
9
+
10
+ # Calculate the size of each split
11
+ total_items = len(data)
12
+ items_per_split = ceil(total_items / n_splits)
13
+
14
+ # Split the data and save into separate files
15
+ for i in range(n_splits):
16
+ start_index = i * items_per_split
17
+ end_index = min((i + 1) * items_per_split, total_items)
18
+ split_data = data[start_index:end_index]
19
+
20
+ # Write the split data to a new JSON file
21
+ with open(f"{input_file.split('.')[0]}_split_{i}.json", "w") as split_file:
22
+ json.dump(split_data, split_file, indent=4)
23
+
24
+
25
+ def main():
26
+ import argparse
27
+
28
+ parser = argparse.ArgumentParser(description="Split a JSON file into multiple parts.")
29
+ parser.add_argument("--input_file", type=str, help="The JSON file to split")
30
+ parser.add_argument("--n_splits", type=int, help="The number of splits")
31
+
32
+ args = parser.parse_args()
33
+
34
+ split_json_file(args.input_file, args.n_splits)
35
+
36
+
37
+ if __name__ == "__main__":
38
+ main()
LLaVA-NeXT/playground/llava_ov_plot.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
LLaVA-NeXT/playground/remove_mid_ckpt.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import glob
4
+
5
+
6
+ def remove_checkpoints(directory, pattern):
7
+ # Walk through the directory
8
+ for root, dirs, files in os.walk(directory):
9
+ # Use glob to find paths matching the pattern
10
+ for file_path in glob.glob(os.path.join(root, pattern)):
11
+ # Check if it is a directory
12
+ if "llava-1.6-mistral-7b" in file_path:
13
+ continue
14
+ if os.path.isdir(file_path):
15
+ # Remove the directory
16
+ print(f"Removing {file_path}")
17
+ input("Press Enter to continue...")
18
+ shutil.rmtree(file_path)
19
+ print(f"Removed directory: {file_path}")
20
+ else:
21
+ print(f"Removing {file_path}")
22
+ input("Press Enter to continue...")
23
+ # Remove the file
24
+ os.remove(file_path)
25
+ print(f"Removed file: {file_path}")
26
+
27
+
28
+ # Directory containing the checkpoints
29
+ directory = "/mnt/bn/vl-research/checkpoints/feng/"
30
+
31
+ # Pattern to match in the file names
32
+ pattern = "global_step*"
33
+
34
+ # Call the function
35
+ remove_checkpoints(directory, pattern)
LLaVA-NeXT/playground/sgl_llava_inference_multinode.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import time
4
+ import os
5
+ import tqdm
6
+ import sglang as sgl
7
+ from sglang.test.test_utils import select_sglang_backend
8
+ from sglang.utils import dump_state_text
9
+
10
+
11
+ @sgl.function
12
+ def image_description(s, image_file):
13
+ prompt = "Please generate detailed descriptions of the given image."
14
+ s += sgl.user(sgl.image(image_file) + prompt)
15
+ s += sgl.assistant(sgl.gen("answer", max_tokens=1024, temperature=0.0))
16
+
17
+
18
+ def load_progress(progress_file):
19
+ print(f"Load progress from {progress_file}")
20
+ if os.path.exists(progress_file):
21
+ with open(progress_file, "r") as f:
22
+ return json.load(f)
23
+ return {"last_index": -1, "last_chunk": -1, "results": [], "annotations": []}
24
+
25
+
26
+ def save_progress(progress_file, progress_data):
27
+ with open(progress_file, "w") as f:
28
+ json.dump(progress_data, f, indent=2)
29
+
30
+
31
+ def find_images_in_subfolders(folder_path):
32
+ image_extensions = (".png", ".jpg", ".jpeg", ".gif", ".bmp")
33
+ image_files = []
34
+ for root, dirs, files in os.walk(folder_path):
35
+ for file in files:
36
+ if file.endswith(image_extensions):
37
+ image_files.append(os.path.join(root, file))
38
+ return image_files
39
+
40
+
41
+ def main(args):
42
+ dist_rank = args.dist
43
+ dist_size = args.total_dist
44
+
45
+ base_dir = os.path.dirname(args.result_file)
46
+ os.makedirs(base_dir, exist_ok=True) # Ensure the base directory exists
47
+ progress_file = f"{base_dir}/progress_{dist_rank}_or_{dist_size}.json"
48
+ progress_data = load_progress(progress_file)
49
+
50
+ with open(args.json_path, "r") as fp:
51
+ data = json.load(fp)
52
+
53
+ image_files = [os.path.join(args.images_root, item["image"]) for item in data]
54
+ image_files = image_files[: args.limit] if args.limit > 0 else image_files
55
+
56
+ # Shard the data
57
+ shard_size = len(image_files) // dist_size
58
+ start_index = shard_size * dist_rank
59
+ end_index = start_index + shard_size if dist_rank < dist_size - 1 else len(image_files)
60
+ shard_files = image_files[start_index:end_index]
61
+
62
+ print(f"Querying {len(shard_files)} images from index {start_index} to {end_index - 1}")
63
+
64
+ # Select backend
65
+ backend = select_sglang_backend(args)
66
+ sgl.set_default_backend(backend)
67
+
68
+ tic = time.time()
69
+ batch_size = args.parallel
70
+ for batch_start in tqdm.tqdm(range(0, len(shard_files), batch_size)):
71
+ batch_end = min(batch_start + batch_size, len(shard_files))
72
+ if batch_start <= progress_data.get("last_index", -1):
73
+ print(f"Skipping already processed batch starting at {batch_start}")
74
+ continue
75
+ batch_arguments = [{"image_file": image_file} for image_file in shard_files[batch_start:batch_end]]
76
+ try:
77
+ batch_states = image_description.run_batch(batch_arguments, temperature=0, num_threads=args.parallel, progress_bar=False)
78
+ for i, ret in enumerate(batch_states):
79
+ image_file = batch_arguments[i]["image_file"]
80
+ caption = ret.text().split("ASSISTANT:")[-1].strip()
81
+ progress_data["annotations"].append({"image_file": image_file, "caption": caption})
82
+ progress_data["last_index"] = batch_start + i # Update last_index relative to this rank's shard
83
+
84
+ save_progress(progress_file, progress_data)
85
+ except Exception as e:
86
+ print(f"Error during batch processing: {e}")
87
+ save_progress(progress_file, progress_data)
88
+ break
89
+
90
+ latency = time.time() - tic
91
+ print(f"Latency: {latency:.3f}")
92
+
93
+ value = {
94
+ "task": "image_captioning",
95
+ "backend": args.backend,
96
+ "num_gpus": 1,
97
+ "latency": round(latency, 3),
98
+ "num_requests": len(shard_files),
99
+ "parallel": args.parallel,
100
+ "results": progress_data["annotations"],
101
+ }
102
+
103
+ result_file = args.result_file.replace(".json", f"_shard_{dist_rank}_or_{dist_size}.json")
104
+ print(f"Write output to {result_file}")
105
+ with open(result_file, "w") as fout:
106
+ json.dump(value, fout, indent=2)
107
+
108
+ save_progress(progress_file, progress_data)
109
+
110
+
111
+ if __name__ == "__main__":
112
+ parser = argparse.ArgumentParser()
113
+ parser.add_argument("--images_root", type=str, default="/mnt/bn/vl-research/data/llava_data/cc3m")
114
+ parser.add_argument("--json_path", type=str, default="/mnt/bn/vl-research/data/llava_instruct/cc3m_recap_requery_363707.json")
115
+ parser.add_argument("--max_tokens", type=int, default=1024)
116
+ parser.add_argument("--parallel", type=int, default=32)
117
+ parser.add_argument("--backend", type=str, default="srt")
118
+ parser.add_argument("--host", type=str, default="http://127.0.0.1")
119
+ parser.add_argument("--port", type=int, default=30000)
120
+ parser.add_argument("--result_file", type=str, default="/mnt/bn/vl-research/workspace/boli01/projects/LLaVA_Next/playground/sgl_llava_inference.json")
121
+ parser.add_argument("--limit", type=int, default=-1)
122
+ parser.add_argument("--dist", type=int, default=0, help="The rank of the distributed machine")
123
+ parser.add_argument("--total_dist", type=int, default=6, help="Total number of distributed machines")
124
+ args = parser.parse_args()
125
+ main(args)
LLaVA-NeXT/playground/upload_data.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import Dataset, Features, Value, ClassLabel, Sequence, Image
2
+ import json
3
+ import PIL.Image as pil_image
4
+ from io import BytesIO
5
+ from tqdm import tqdm
6
+
7
+ json_paths = [
8
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mavis_math_metagen_87358.json",
9
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mavis_math_rule_geo_100000.json",
10
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/k12_printing_train_256646.json",
11
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/iiit5k_annotations_2000.json",
12
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/hme100k_train_clean_74502.json",
13
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/ai2d_azuregpt_detailed_understanding_4874.json",
14
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/infographic_vqa_4404.json",
15
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/infographic_azuregpt4v_1992.json",
16
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/lrv_chart_1787.json",
17
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/lrv_normal_gpt4v_filtered_10500.json",
18
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/scienceqa_nona_context_19218.json",
19
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/allava_instruct_vflan4v_20000.json",
20
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/allava_instruct_laion4v_50000.json",
21
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/textocr_gpt4v_train_converted_25114.json",
22
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/ai2d_train_internvl_single_12413.json",
23
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/textcaps_train_21952.json",
24
+ # "/mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_qa_sft.json",
25
+ # "/mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_cap_sft.json",
26
+ # "/mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_ie_sft.json",
27
+ # "/mnt/bn/vl-research/data/llava_instruct/ureader_new/ureader_kg_sft.json",
28
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/vision_flan_filtered_186070.json",
29
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/mathqa_29837.json",
30
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo3k_2101.json",
31
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo170k_qa_converted_67833.json",
32
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/geo170k_align_converted_60252.json",
33
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-coco-50k.json",
34
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-knowledge-2k.json",
35
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-llava-30k.json",
36
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4v-sam-20k.json",
37
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_CLEVR-Math_5290.json",
38
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_FigureQA_17597.json",
39
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_Geometry3K_9734.json",
40
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_GeoQA+_17172.json",
41
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_GEOS_508.json",
42
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_IconQA_22599.json",
43
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_MapQA_5235.json",
44
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_PMC-VQA_35958.json",
45
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_Super-CLEVR_8652.json",
46
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_TabMWP_22462.json",
47
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_UniGeo_11959.json",
48
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/MathV360K_VizWiz_6614.json",
49
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_qwen2_72b_st_300000_sp_token_fltd_299992.json",
50
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_l3_80b_st_300000.json",
51
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/magpie_pro_l3_80b_mt_300000_sp_token_fltd_299998.json",
52
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/image_textualization_dataset_filtered.json",
53
+ # "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/cambrian_filtered_gpt4vo_sp_token_fltd_max10k.json",
54
+ "/mnt/bn/vl-research/data/llava_instruct/real_vision_flan/sharegpt4o_dataset.jsonl",
55
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/ai2d_llava_format_2434.json",
56
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/aokvqa_16539_llava_format.json",
57
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/chart2text_26961.json",
58
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/chartqa_18265_llava_format.json",
59
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/clevr_70000_llava_format.json",
60
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/diagram_image_to_text_300.json",
61
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/dvqa_200000_llava_format.json",
62
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/figureqa_100000_llava_format.json",
63
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/geomverse_9303.json",
64
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/hateful_memes_8500_llava_format.json",
65
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/hitab_2500_llava_format.json",
66
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/iam_5663.json",
67
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/raven_42000.json",
68
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/iconqa_llava_format_27307.json",
69
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/infographic_vqa_2118_llava_format.json",
70
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/intergps_1280_llava_format.json",
71
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/mapqa_37417_llava_format.json",
72
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/multihiertt_7619.json",
73
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/rendered_text_10000.json",
74
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/robut_sqa_8514.json",
75
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/robut_wikisql_74989.json",
76
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/robut_wtq_38246_llava_format.json",
77
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/screen2words_15730.json",
78
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/scienceqa_llava_format_4976.json",
79
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/tabmwp_22722.json",
80
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/tallyqa_98680_llava_format.json",
81
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/st_vqa_17247_llava_format.json",
82
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/tqa_llava_format_27307.json",
83
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/visual7w_llava_format_14366.json",
84
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/visualmrc_3027.json",
85
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/vqarad_313_llava_format.json",
86
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/vsr_2157_llava_format.json",
87
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/vistext_9969.json",
88
+ "/mnt/bn/vl-research/data/llava_instruct/cauldron/websight_10000.json"
89
+ ]
90
+
91
+ short_names = [
92
+ # "mavis_math_metagen",
93
+ # "mavis_math_rule_geo",
94
+ # "k12_printing",
95
+ # "iiit5k",
96
+ # "hme100k",
97
+ # "ai2d(gpt4v)",
98
+ # "infographic_vqa",
99
+ # "infographic(gpt4v)",
100
+ # "lrv_chart",
101
+ # "lrv_normal(filtered)",
102
+ # "scienceqa(nona_context)",
103
+ # "allava_instruct_vflan4v",
104
+ # "allava_instruct_laion4v",
105
+ # "textocr(gpt4v)",
106
+ # "ai2d(internvl)",
107
+ # "textcaps",
108
+ # "ureader_qa", # need to re-upload
109
+ # "ureader_cap", # need to re-upload
110
+ # "ureader_ie", # need to re-upload
111
+ # "ureader_kg", # need to re-upload
112
+ # "vision_flan(filtered)",
113
+ # "mathqa",
114
+ # "geo3k",
115
+ # "geo170k(qa)",
116
+ # "geo170k(align)",
117
+ # "sharegpt4v(coco)",
118
+ # "sharegpt4v(knowledge)",
119
+ # "sharegpt4v(llava)",
120
+ # "sharegpt4v(sam)",
121
+ # "CLEVR-Math(MathV360K)",
122
+ # "FigureQA(MathV360K)",
123
+ # "Geometry3K(MathV360K)",
124
+ # "GeoQA+(MathV360K)",
125
+ # "GEOS(MathV360K)",
126
+ # "IconQA(MathV360K)",
127
+ # "MapQA(MathV360K)",
128
+ # "PMC-VQA(MathV360K)",
129
+ # "Super-CLEVR(MathV360K)",
130
+ # "TabMWP(MathV360K)",
131
+ # "UniGeo(MathV360K)",
132
+ # "VizWiz(MathV360K)",
133
+ # "magpie_pro(qwen2_72b_st)",
134
+ # "magpie_pro(l3_80b_st)",
135
+ # "magpie_pro(l3_80b_mt)",
136
+ # "image_textualization(filtered)",
137
+ # "cambrian(filtered_gpt4vo)", # need to re-upload
138
+ "sharegpt4o",
139
+ "ai2d(cauldron,llava_format)",
140
+ "aokvqa(cauldron,llava_format)",
141
+ "chart2text(cauldron)",
142
+ "chartqa(cauldron,llava_format)",
143
+ "clevr(cauldron,llava_format)",
144
+ "diagram_image_to_text(cauldron)",
145
+ "dvqa(cauldron,llava_format)",
146
+ "figureqa(cauldron,llava_format)",
147
+ "geomverse(cauldron)",
148
+ "hateful_memes(cauldron,llava_format)",
149
+ "hitab(cauldron,llava_format)",
150
+ "iam(cauldron)",
151
+ "raven(cauldron)",
152
+ "iconqa(cauldron,llava_format)",
153
+ "infographic_vqa_llava_format",
154
+ "intergps(cauldron,llava_format)",
155
+ "mapqa(cauldron,llava_format)",
156
+ "multihiertt(cauldron)",
157
+ "rendered_text(cauldron)",
158
+ "robut_sqa(cauldron)",
159
+ "robut_wikisql(cauldron)",
160
+ "robut_wtq(cauldron,llava_format)",
161
+ "screen2words(cauldron)",
162
+ "scienceqa(cauldron,llava_format)",
163
+ "tabmwp(cauldron)",
164
+ "tallyqa(cauldron,llava_format)",
165
+ "st_vqa(cauldron,llava_format)",
166
+ "tqa(cauldron,llava_format)",
167
+ "visual7w(cauldron,llava_format)",
168
+ "visualmrc(cauldron)",
169
+ "vqarad(cauldron,llava_format)",
170
+ "vsr(cauldron,llava_format)",
171
+ "vistext(cauldron)",
172
+ "websight(cauldron)"
173
+ ]
174
+
175
+ def upload_data(json_path, short_name):
176
+ def gen():
177
+ if json_path.endswith(".jsonl"):
178
+ with open(json_path, "r") as f:
179
+ data = [json.loads(line) for line in f]
180
+ else:
181
+ with open(json_path, "r") as f:
182
+ data = json.load(f)
183
+
184
+ preview_index = 5
185
+ idx = 0
186
+ for item in tqdm(data):
187
+ if preview_index > 0:
188
+ preview_index -= 1
189
+ print(item)
190
+ continue
191
+
192
+ try:
193
+ if "image" in item:
194
+ image_path = f"/mnt/bn/vl-research/data/llava_data/{item['image']}"
195
+ try:
196
+ with open(image_path, "rb") as img_file:
197
+ image = pil_image.open(BytesIO(img_file.read()))
198
+ except:
199
+ print(f"Failed to load image {item['image']}")
200
+ continue
201
+ else:
202
+ image = None
203
+
204
+ item_id = item["id"] if "id" in item else f"{idx:06d}"
205
+ yield {"id": item_id, "image": image, "conversations": item["conversations"], "data_source": short_name}
206
+ idx += 1
207
+
208
+ except Exception as e:
209
+ print(e)
210
+ continue
211
+
212
+
213
+ hf_dataset = Dataset.from_generator(generator=gen, num_proc=32)
214
+ hf_dataset.push_to_hub("lmms-lab/LLaVA-OneVision-Data", config_name=short_name, split="train")
215
+
216
+ for json_path, short_name in zip(json_paths, short_names):
217
+ upload_data(json_path, short_name)
LLaVA-NeXT/predict.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
4
+ from llava.conversation import conv_templates, SeparatorStyle
5
+ from llava.model.builder import load_pretrained_model
6
+ from llava.utils import disable_torch_init
7
+ from llava.mm_utils import tokenizer_image_token, KeywordsStoppingCriteria
8
+ from transformers.generation.streamers import TextIteratorStreamer
9
+
10
+ from PIL import Image
11
+
12
+ import requests
13
+ from io import BytesIO
14
+
15
+ from cog import BasePredictor, Input, Path, ConcatenateIterator
16
+ import time
17
+ import subprocess
18
+ from threading import Thread
19
+
20
+ import os
21
+ os.environ["HUGGINGFACE_HUB_CACHE"] = os.getcwd() + "/weights"
22
+
23
+ # url for the weights mirror
24
+ REPLICATE_WEIGHTS_URL = "https://weights.replicate.delivery/default"
25
+ # files to download from the weights mirrors
26
+ weights = [
27
+ {
28
+ "dest": "liuhaotian/llava-v1.5-13b",
29
+ # git commit hash from huggingface
30
+ "src": "llava-v1.5-13b/006818fc465ebda4c003c0998674d9141d8d95f8",
31
+ "files": [
32
+ "config.json",
33
+ "generation_config.json",
34
+ "pytorch_model-00001-of-00003.bin",
35
+ "pytorch_model-00002-of-00003.bin",
36
+ "pytorch_model-00003-of-00003.bin",
37
+ "pytorch_model.bin.index.json",
38
+ "special_tokens_map.json",
39
+ "tokenizer.model",
40
+ "tokenizer_config.json",
41
+ ],
42
+ },
43
+ {
44
+ "dest": "openai/clip-vit-large-patch14-336",
45
+ "src": "clip-vit-large-patch14-336/ce19dc912ca5cd21c8a653c79e251e808ccabcd1",
46
+ "files": ["config.json", "preprocessor_config.json", "pytorch_model.bin"],
47
+ },
48
+ ]
49
+
50
+
51
+ def download_json(url: str, dest: Path):
52
+ res = requests.get(url, allow_redirects=True)
53
+ if res.status_code == 200 and res.content:
54
+ with dest.open("wb") as f:
55
+ f.write(res.content)
56
+ else:
57
+ print(f"Failed to download {url}. Status code: {res.status_code}")
58
+
59
+ def download_weights(baseurl: str, basedest: str, files: list[str]):
60
+ basedest = Path(basedest)
61
+ start = time.time()
62
+ print("downloading to: ", basedest)
63
+ basedest.mkdir(parents=True, exist_ok=True)
64
+ for f in files:
65
+ dest = basedest / f
66
+ url = os.path.join(REPLICATE_WEIGHTS_URL, baseurl, f)
67
+ if not dest.exists():
68
+ print("downloading url: ", url)
69
+ if dest.suffix == ".json":
70
+ download_json(url, dest)
71
+ else:
72
+ subprocess.check_call(["pget", url, str(dest)], close_fds=False)
73
+ print("downloading took: ", time.time() - start)
74
+
75
+ class Predictor(BasePredictor):
76
+ def setup(self) -> None:
77
+ """Load the model into memory to make running multiple predictions efficient"""
78
+ for weight in weights:
79
+ download_weights(weight["src"], weight["dest"], weight["files"])
80
+ disable_torch_init()
81
+ self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model("liuhaotian/llava-v1.5-13b", model_name="llava-v1.5-13b", model_base=None, load_8bit=False, load_4bit=False)
82
+
83
+ def predict(
84
+ self,
85
+ image: Path = Input(description="Input image"),
86
+ prompt: str = Input(description="Prompt to use for text generation"),
87
+ top_p: float = Input(description="When decoding text, samples from the top p percentage of most likely tokens; lower to ignore less likely tokens", ge=0.0, le=1.0, default=1.0),
88
+ temperature: float = Input(description="Adjusts randomness of outputs, greater than 1 is random and 0 is deterministic", default=0.2, ge=0.0),
89
+ max_tokens: int = Input(description="Maximum number of tokens to generate. A word is generally 2-3 tokens", default=1024, ge=0),
90
+ ) -> ConcatenateIterator[str]:
91
+ """Run a single prediction on the model"""
92
+
93
+ conv_mode = "llava_v1"
94
+ conv = conv_templates[conv_mode].copy()
95
+
96
+ image_data = load_image(str(image))
97
+ image_tensor = self.image_processor.preprocess(image_data, return_tensors="pt")["pixel_values"].half().cuda()
98
+
99
+ # loop start
100
+
101
+ # just one turn, always prepend image token
102
+ inp = DEFAULT_IMAGE_TOKEN + "\n" + prompt
103
+ conv.append_message(conv.roles[0], inp)
104
+
105
+ conv.append_message(conv.roles[1], None)
106
+ prompt = conv.get_prompt()
107
+
108
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
109
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
110
+ keywords = [stop_str]
111
+ stopping_criteria = KeywordsStoppingCriteria(keywords, self.tokenizer, input_ids)
112
+ streamer = TextIteratorStreamer(self.tokenizer, skip_prompt=True, timeout=20.0)
113
+
114
+ with torch.inference_mode():
115
+ thread = Thread(
116
+ target=self.model.generate,
117
+ kwargs=dict(inputs=input_ids, images=image_tensor, do_sample=True, temperature=temperature, top_p=top_p, max_new_tokens=max_tokens, streamer=streamer, use_cache=True, stopping_criteria=[stopping_criteria]),
118
+ )
119
+ thread.start()
120
+ # workaround: second-to-last token is always " "
121
+ # but we want to keep it if it's not the second-to-last token
122
+ prepend_space = False
123
+ for new_text in streamer:
124
+ if new_text == " ":
125
+ prepend_space = True
126
+ continue
127
+ if new_text.endswith(stop_str):
128
+ new_text = new_text[: -len(stop_str)].strip()
129
+ prepend_space = False
130
+ elif prepend_space:
131
+ new_text = " " + new_text
132
+ prepend_space = False
133
+ if len(new_text):
134
+ yield new_text
135
+ if prepend_space:
136
+ yield " "
137
+ thread.join()
138
+
139
+
140
+ def load_image(image_file):
141
+ if image_file.startswith("http") or image_file.startswith("https"):
142
+ response = requests.get(image_file)
143
+ image = Image.open(BytesIO(response.content)).convert("RGB")
144
+ else:
145
+ image = Image.open(image_file).convert("RGB")
146
+ return image
LLaVA-NeXT/pyproject.toml ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.black]
2
+ line-length = 240
3
+
4
+ [build-system]
5
+ requires = ["setuptools>=61.0"]
6
+ build-backend = "setuptools.build_meta"
7
+
8
+ [project]
9
+ name = "llava"
10
+ version = "1.7.0.dev0"
11
+ description = "LLaVA OneVision: The Next Generation of LLaVA with Better Image and Video Understanding Capabilities"
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ standalone = [
21
+ "shortuuid",
22
+ "httpx==0.24.0",
23
+ "einops",
24
+ "ftfy",
25
+ ]
26
+
27
+
28
+ train = [
29
+ "llava[standalone]",
30
+ "numpy==1.26.1",
31
+ "open_clip_torch",
32
+ "fastapi",
33
+ "markdown2[all]",
34
+ "numpy",
35
+ "requests",
36
+ "sentencepiece",
37
+ "torch==2.1.2",
38
+ "torchvision==0.16.2",
39
+ "uvicorn",
40
+ "wandb",
41
+ "deepspeed==0.14.4",
42
+ "peft==0.4.0",
43
+ "accelerate>=0.29.1",
44
+ "tokenizers~=0.15.2",
45
+ "transformers@git+https://github.com/huggingface/transformers.git@1c39974a4c4036fd641bc1191cc32799f85715a4",
46
+ "bitsandbytes==0.41.0",
47
+ "scikit-learn==1.2.2",
48
+ "sentencepiece~=0.1.99",
49
+ "einops==0.6.1",
50
+ "einops-exts==0.0.4",
51
+ "gradio_client==0.2.9",
52
+ "urllib3<=2.0.0",
53
+ "datasets==2.16.1",
54
+ "pydantic==1.10.8",
55
+ "timm",
56
+ "hf_transfer",
57
+ "opencv-python",
58
+ "av",
59
+ "decord",
60
+ "tyro",
61
+ "scipy",
62
+ ]
63
+
64
+ [project.urls]
65
+ "Homepage" = "https://llava-vl.github.io"
66
+ "Bug Tracker" = "https://github.com/haotian-liu/LLaVA/issues"
67
+
68
+ [tool.setuptools.packages.find]
69
+ include = ["llava*", "trl*"]
70
+ exclude = [
71
+ "assets*",
72
+ "benchmark*",
73
+ "docs",
74
+ "dist*",
75
+ "playground*",
76
+ "scripts*",
77
+ "tests*",
78
+ "checkpoints*",
79
+ "project_checkpoints*",
80
+ "debug_checkpoints*",
81
+ "mlx_configs*",
82
+ "wandb*",
83
+ "notebooks*",
84
+ ]
85
+
86
+ [tool.wheel]
87
+ exclude = [
88
+ "assets*",
89
+ "benchmark*",
90
+ "docs",
91
+ "dist*",
92
+ "playground*",
93
+ "scripts*",
94
+ "tests*",
95
+ "checkpoints*",
96
+ "project_checkpoints*",
97
+ "debug_checkpoints*",
98
+ "mlx_configs*",
99
+ "wandb*",
100
+ "notebooks*",
101
+ ]
LLaVA-NeXT/requirements.txt ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Babel==2.14.0
2
+ DataProperty==1.0.1
3
+ Deprecated==1.2.14
4
+ GitPython==3.1.43
5
+ Jinja2==3.1.3
6
+ Levenshtein==0.25.1
7
+ MarkupSafe==2.1.5
8
+ PyJWT==2.8.0
9
+ PyYAML==6.0.1
10
+ Pygments==2.17.2
11
+ QtPy==2.4.1
12
+ Send2Trash==1.8.3
13
+ absl-py==2.1.0
14
+ accelerate==0.29.3
15
+ aiofiles==22.1.0
16
+ aiohttp==3.9.5
17
+ aiosignal==1.3.1
18
+ aiosqlite==0.20.0
19
+ altair==5.3.0
20
+ anyio==4.3.0
21
+ appdirs==1.4.4
22
+ argon2-cffi-bindings==21.2.0
23
+ argon2-cffi==23.1.0
24
+ arrow==1.3.0
25
+ asttokens==2.4.1
26
+ async-timeout==4.0.3
27
+ attrs==23.1.0
28
+ beautifulsoup4==4.12.3
29
+ bidict==0.23.1
30
+ bitsandbytes==0.41.0
31
+ black==24.1.0
32
+ bleach==6.1.0
33
+ byted-remote-ikernel==0.4.8
34
+ byted-torch-monitor==0.0.1
35
+ byted-wandb==0.13.72
36
+ bytedance-context==0.7.1
37
+ bytedance-metrics==0.5.1
38
+ bytedance.modelhub==0.0.64
39
+ bytedance.servicediscovery==0.1.2
40
+ bytedbackgrounds==0.0.6
41
+ byteddatabus==1.0.6
42
+ byteddps==0.1.2
43
+ bytedenv==0.6.2
44
+ bytedlogger==0.15.1
45
+ bytedmemfd==0.2
46
+ bytedmetrics==0.10.2
47
+ bytedpymongo==2.0.5
48
+ bytedrh2==1.18.7a2
49
+ bytedservicediscovery==0.17.4
50
+ bytedtcc==1.4.2
51
+ bytedtos==1.1.16
52
+ bytedtrace==0.3.0
53
+ bytedztijwthelper==0.0.22
54
+ bytedztispiffe==0.0.11
55
+ certifi==2024.2.2
56
+ cffi==1.16.0
57
+ cfgv==3.4.0
58
+ chardet==5.2.0
59
+ charset-normalizer==3.3.2
60
+ click==8.1.7
61
+ colorama==0.4.6
62
+ comm==0.2.2
63
+ contourpy==1.2.1
64
+ crcmod==1.7
65
+ cryptography==38.0.4
66
+ cycler==0.12.1
67
+ datasets==2.16.1
68
+ debugpy==1.8.1
69
+ decorator==5.1.1
70
+ decord==0.6.0
71
+ deepspeed==0.12.2
72
+ defusedxml==0.7.1
73
+ dill==0.3.7
74
+ distlib==0.3.8
75
+ distro==1.9.0
76
+ dnspython==2.6.1
77
+ docker-pycreds==0.4.0
78
+ docstring_parser==0.16
79
+ einops-exts==0.0.4
80
+ einops==0.6.1
81
+ entrypoints==0.4
82
+ et-xmlfile==1.1.0
83
+ eval_type_backport==0.2.0
84
+ evaluate==0.4.1
85
+ exceptiongroup==1.2.1
86
+ executing==2.0.1
87
+ fastapi==0.110.2
88
+ fastjsonschema==2.19.1
89
+ ffmpy==0.3.2
90
+ filelock==3.13.4
91
+ flash-attn==2.5.7
92
+ fonttools==4.51.0
93
+ fqdn==1.5.1
94
+ frozenlist==1.4.1
95
+ fsspec==2023.10.0
96
+ ftfy==6.2.0
97
+ gitdb==4.0.11
98
+ gradio==3.35.2
99
+ gradio_client==0.2.9
100
+ grpcio==1.62.2
101
+ h11==0.14.0
102
+ hf_transfer==0.1.6
103
+ hjson==3.1.0
104
+ httpcore==0.17.3
105
+ httpx==0.24.0
106
+ huggingface-hub==0.22.2
107
+ identify==2.5.36
108
+ idna==3.7
109
+ importlib_metadata==7.1.0
110
+ importlib_resources==6.4.0
111
+ iniconfig==2.0.0
112
+ ipaddress==1.0.23
113
+ ipykernel==6.29.4
114
+ ipython-genutils==0.2.0
115
+ ipython==8.18.1
116
+ ipywidgets==8.1.2
117
+ isoduration==20.11.0
118
+ jedi==0.19.1
119
+ joblib==1.4.0
120
+ json5==0.9.25
121
+ jsonlines==4.0.0
122
+ jsonpointer==2.4
123
+ jsonschema-specifications==2023.12.1
124
+ jsonschema==4.21.1
125
+ jupyter-client==7.0.0
126
+ jupyter-console==6.6.3
127
+ jupyter-events==0.10.0
128
+ jupyter-ydoc==0.2.5
129
+ jupyter==1.0.0
130
+ jupyter_core==5.7.2
131
+ jupyter_server==2.14.0
132
+ jupyter_server_fileid==0.9.2
133
+ jupyter_server_terminals==0.5.3
134
+ jupyter_server_ydoc==0.8.0
135
+ jupyterlab==3.6.4
136
+ jupyterlab_pygments==0.3.0
137
+ jupyterlab_server==2.27.1
138
+ jupyterlab_widgets==3.0.10
139
+ kiwisolver==1.4.5
140
+ linkify-it-py==2.0.3
141
+ llava==1.7.0.dev0
142
+ llava==1.7.0.dev0
143
+ lmms_eval==0.1.1
144
+ lxml==5.2.1
145
+ markdown-it-py==2.2.0
146
+ markdown2==2.4.13
147
+ matplotlib-inline==0.1.7
148
+ matplotlib==3.8.4
149
+ mbstrdecoder==1.1.3
150
+ mdit-py-plugins==0.3.3
151
+ mdurl==0.1.2
152
+ mistune==3.0.2
153
+ mpmath==1.3.0
154
+ msgpack==1.0.8
155
+ multidict==6.0.5
156
+ multiprocess==0.70.15
157
+ mypy-extensions==1.0.0
158
+ nbclassic==1.0.0
159
+ nbclient==0.10.0
160
+ nbconvert==7.16.3
161
+ nbformat==5.10.4
162
+ nest-asyncio==1.6.0
163
+ networkx==3.2.1
164
+ ninja==1.11.1.1
165
+ nltk==3.8.1
166
+ nodeenv==1.8.0
167
+ notebook==6.5.6
168
+ notebook_shim==0.2.4
169
+ numexpr==2.10.0
170
+ numpy==1.26.4
171
+ nvidia-cublas-cu12==12.1.3.1
172
+ nvidia-cuda-cupti-cu12==12.1.105
173
+ nvidia-cuda-nvrtc-cu12==12.1.105
174
+ nvidia-cuda-runtime-cu12==12.1.105
175
+ nvidia-cudnn-cu12==8.9.2.26
176
+ nvidia-cufft-cu12==11.0.2.54
177
+ nvidia-curand-cu12==10.3.2.106
178
+ nvidia-cusolver-cu12==11.4.5.107
179
+ nvidia-cusparse-cu12==12.1.0.106
180
+ nvidia-nccl-cu12==2.18.1
181
+ nvidia-nvjitlink-cu12==12.4.127
182
+ nvidia-nvtx-cu12==12.1.105
183
+ open-clip-torch==2.24.0
184
+ openai==1.23.6
185
+ opencv-python-headless==4.9.0.80
186
+ openpyxl==3.1.2
187
+ orjson==3.10.1
188
+ overrides==7.7.0
189
+ packaging==24.0
190
+ pandas==2.2.2
191
+ pandocfilters==1.5.1
192
+ parso==0.8.4
193
+ pathlib2==2.3.7.post1
194
+ pathspec==0.12.1
195
+ pathtools==0.1.2
196
+ pathvalidate==3.2.0
197
+ peft==0.4.0
198
+ pexpect==4.8.0
199
+ pillow==10.3.0
200
+ pip==23.3.1
201
+ pip==24.0
202
+ platformdirs==4.2.1
203
+ pluggy==1.5.0
204
+ ply==3.11
205
+ portalocker==2.8.2
206
+ pre-commit==3.7.0
207
+ prometheus_client==0.20.0
208
+ promise==2.3
209
+ prompt-toolkit==3.0.43
210
+ protobuf==3.20.3
211
+ psutil==5.9.8
212
+ ptyprocess==0.7.0
213
+ pure-eval==0.2.2
214
+ py-cpuinfo==9.0.0
215
+ py-spy==0.3.14
216
+ py==1.11.0
217
+ pyOpenSSL==22.1.0
218
+ pyarrow-hotfix==0.6
219
+ pyarrow==16.0.0
220
+ pybind11==2.12.0
221
+ pycocoevalcap==1.2
222
+ pycocotools==2.0.7
223
+ pycparser==2.22
224
+ pycryptodomex==3.20.0
225
+ pydantic==1.10.8
226
+ pydub==0.25.1
227
+ pynvml==11.5.0
228
+ pyparsing==3.1.2
229
+ pytablewriter==1.2.0
230
+ pytest==6.2.5
231
+ python-consul==1.1.0
232
+ python-dateutil==2.9.0.post0
233
+ python-engineio==4.9.0
234
+ python-etcd==0.4.5
235
+ python-json-logger==2.0.7
236
+ python-multipart==0.0.9
237
+ python-socketio==5.11.2
238
+ pytz==2024.1
239
+ pyzmq==24.0.1
240
+ qtconsole==5.5.1
241
+ rapidfuzz==3.8.1
242
+ referencing==0.35.0
243
+ regex==2024.4.16
244
+ requests==2.31.0
245
+ responses==0.18.0
246
+ rfc3339-validator==0.1.4
247
+ rfc3986-validator==0.1.1
248
+ rich==13.7.1
249
+ rouge-score==0.1.2
250
+ rpds-py==0.18.0
251
+ sacrebleu==2.4.2
252
+ safetensors==0.4.3
253
+ schedule==1.2.1
254
+ scikit-learn==1.2.2
255
+ scipy==1.13.0
256
+ semantic-version==2.10.0
257
+ sentencepiece==0.1.99
258
+ sentry-sdk==2.0.0
259
+ setproctitle==1.3.3
260
+ setuptools==68.2.2
261
+ shortuuid==1.0.13
262
+ shtab==1.7.1
263
+ simple-websocket==1.0.0
264
+ six==1.16.0
265
+ smmap==5.0.1
266
+ sniffio==1.3.1
267
+ soupsieve==2.5
268
+ sqlitedict==2.1.0
269
+ stack-data==0.6.3
270
+ starlette==0.37.2
271
+ svgwrite==1.4.3
272
+ sympy==1.12
273
+ tabledata==1.3.3
274
+ tabulate==0.9.0
275
+ tcolorpy==0.1.4
276
+ tenacity==8.2.3
277
+ terminado==0.18.1
278
+ threadpoolctl==3.4.0
279
+ thriftpy2==0.4.20
280
+ tiktoken==0.6.0
281
+ timm==0.9.16
282
+ tinycss2==1.3.0
283
+ tokenizers==0.15.2
284
+ toml==0.10.2
285
+ tomli==2.0.1
286
+ toolz==0.12.1
287
+ torch==2.1.2
288
+ torchvision==0.16.2
289
+ tornado==6.4
290
+ tox==3.28.0
291
+ tqdm-multiprocess==0.0.11
292
+ tqdm==4.66.2
293
+ traitlets==5.14.3
294
+ transformers-stream-generator==0.0.5
295
+ transformers==4.40.0.dev0
296
+ triton==2.1.0
297
+ typepy==1.3.2
298
+ types-python-dateutil==2.9.0.20240316
299
+ typing_extensions==4.11.0
300
+ tyro==0.8.3
301
+ tzdata==2024.1
302
+ uc-micro-py==1.0.3
303
+ uri-template==1.3.0
304
+ urllib3==2.2.1
305
+ uvicorn==0.29.0
306
+ virtualenv==20.26.0
307
+ wandb==0.16.5
308
+ watchdog==4.0.0
309
+ wavedrom==2.0.3.post3
310
+ wcwidth==0.2.13
311
+ webcolors==1.13
312
+ webencodings==0.5.1
313
+ websocket-client==1.8.0
314
+ websockets==12.0
315
+ wheel==0.41.2
316
+ widgetsnbextension==4.0.10
317
+ wrapt==1.16.0
318
+ wsproto==1.2.0
319
+ xxhash==3.4.1
320
+ y-py==0.6.2
321
+ yarl==1.9.4
322
+ ypy-websocket==0.8.4
323
+ zipp==3.18.1
324
+ zstandard==0.22.0
LLaVA-NeXT/scripts/qwen.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+ import torch
3
+
4
+ device = "cuda" # the device to load the model onto
5
+
6
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B-Chat", torch_dtype=torch.bfloat16, device_map="auto")
7
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-MoE-A2.7B-Chat")
8
+
9
+ prompt = "Give me a short introduction to large language model."
10
+ messages = [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}]
11
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
12
+ model_inputs = tokenizer([text], return_tensors="pt").to(device)
13
+
14
+ generated_ids = model.generate(model_inputs.input_ids, max_new_tokens=512)
15
+ generated_ids = [output_ids[len(input_ids) :] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
16
+
17
+ response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
18
+
19
+ print(response)
LLaVA-NeXT/scripts/summarize_data.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from tqdm import tqdm
4
+
5
+ with open("/mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA/playground/data/llava_v1_5_mix665k.json") as f:
6
+ llava_v1_5_mix665k = json.load(f) # 665298
7
+
8
+ with open("/mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA/playground/data/llava_instruct_150k.json") as f:
9
+ llava_instruct_150k = json.load(f) # 157712
10
+
11
+ # Create sets of "id" fields
12
+ mix665k_ids = set()
13
+ for item in llava_v1_5_mix665k:
14
+ all_conv = ""
15
+ for cur_conversation in item["conversations"]:
16
+ all_conv += cur_conversation["value"]
17
+ mix665k_ids.add(f'{item["id"]}_{all_conv}')
18
+
19
+ instruct_150k_ids = set()
20
+ for item in llava_instruct_150k:
21
+ all_conv = ""
22
+ for cur_conversation in item["conversations"]:
23
+ all_conv += cur_conversation["value"]
24
+ instruct_150k_ids.add(f'{item["id"]}_{all_conv}')
25
+
26
+ share_gpt_ids = set()
27
+ for item in llava_v1_5_mix665k:
28
+ if "image" not in item:
29
+ all_conv = ""
30
+ for cur_conversation in item["conversations"]:
31
+ all_conv += cur_conversation["value"]
32
+ share_gpt_ids.add(f'{item["id"]}_{all_conv}') # 40688
33
+
34
+ # Get "id" fields that are in mix665k but not in instruct_150k and share_gpt
35
+ new_ids = mix665k_ids - instruct_150k_ids - share_gpt_ids # 466898
36
+
37
+ # Get "id" fields that are in mix665k but not in share_gpt
38
+ # new_ids = mix665k_ids - share_gpt_ids #624610
39
+
40
+ # import pdb; pdb.set_trace()
41
+
42
+ # Filter mix665k data based on new_ids
43
+ new_data = []
44
+ for item in llava_v1_5_mix665k:
45
+ all_conv = ""
46
+ for cur_conversation in item["conversations"]:
47
+ all_conv += cur_conversation["value"]
48
+ if f'{item["id"]}_{all_conv}' in new_ids:
49
+ new_data.append(item)
50
+
51
+ import pdb
52
+
53
+ pdb.set_trace()
54
+
55
+ with open("/mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA/playground/data/mixtral_instruct_135K_of_158K_V1.5.json") as f:
56
+ new_mixtral_instruct = json.load(f)
57
+
58
+ # mixtral_instruct_50K_of_80K_V1.json@
59
+
60
+ # print(len(new_data))
61
+ # for _ in new_mixtral_instruct:
62
+ # # import pdb; pdb.set_trace()
63
+ # if "coco" not in _["image"]:
64
+ # _["image"] = f"coco/train2017/{_['image']}"
65
+ # new_data.append(_)
66
+
67
+ # print(len(instruct_150k_ids))
68
+ print(len(new_data))
69
+
70
+ # for _ in tqdm(new_data):
71
+ # if "image" in _:
72
+ # if "000000442654" in _["image"]:
73
+ # all_conv = ""
74
+ # for cur_conversation in _["conversations"]:
75
+ # all_conv += cur_conversation["value"]
76
+ # # if not os.path.exists(f'/mnt/bn/vl-research/workspace/boli01/data/playground/data/{_["image"]}'):
77
+ # import pdb; pdb.set_trace()
78
+
79
+ # Write new_data to a new JSON file
80
+ with open("/mnt/bn/vl-research/workspace/boli01/zzzprojects/LLaVA/playground/data/llava_v1_5_mix665k_minus_llava_instruct_150k_minus_sharegpt_plus_mixtral_instruct_135K_of_158K_V1.5.json", "w") as f:
81
+ json.dump(new_data, f)
LLaVA-NeXT/scripts/zero2.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "optimizer": {
14
+ "type": "AdamW",
15
+ "params": {
16
+ "lr": "auto",
17
+ "betas": "auto",
18
+ "eps": "auto",
19
+ "weight_decay": "auto"
20
+ }
21
+ },
22
+ "zero_optimization": {
23
+ "stage": 2,
24
+ "offload_optimizer": {
25
+ "device": "none",
26
+ "pin_memory": true
27
+ },
28
+ "allgather_partitions": true,
29
+ "allgather_bucket_size": 2e8,
30
+ "overlap_comm": false,
31
+ "reduce_scatter": true,
32
+ "reduce_bucket_size": 2e8,
33
+ "contiguous_gradients": true
34
+ },
35
+ "gradient_accumulation_steps": "auto",
36
+ "gradient_clipping": "auto",
37
+ "steps_per_print": 100,
38
+ "train_batch_size": "auto",
39
+ "train_micro_batch_size_per_gpu": "auto",
40
+ "wall_clock_breakdown": false
41
+ }
LLaVA-NeXT/scripts/zero2_fused_adamw.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "optimizer": {
14
+ "type": "AdamW",
15
+ "params": {
16
+ "lr": "auto",
17
+ "betas": "auto",
18
+ "eps": "auto",
19
+ "weight_decay": "auto"
20
+ }
21
+ },
22
+ "zero_optimization": {
23
+ "stage": 2,
24
+ "offload_optimizer": {
25
+ "device": "none",
26
+ "pin_memory": true
27
+ },
28
+ "allgather_partitions": true,
29
+ "allgather_bucket_size": 2e8,
30
+ "overlap_comm": true,
31
+ "reduce_scatter": true,
32
+ "reduce_bucket_size": 2e8,
33
+ "contiguous_gradients": true
34
+ },
35
+ "gradient_accumulation_steps": "auto",
36
+ "gradient_clipping": "auto",
37
+ "steps_per_print": 100,
38
+ "train_batch_size": "auto",
39
+ "train_micro_batch_size_per_gpu": "auto",
40
+ "wall_clock_breakdown": false
41
+ }
LLaVA-NeXT/scripts/zero2_offload.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "train_micro_batch_size_per_gpu": "auto",
14
+ "train_batch_size": "auto",
15
+ "gradient_accumulation_steps": "auto",
16
+ "zero_optimization": {
17
+ "stage": 2,
18
+ "offload_optimizer": {
19
+ "device": "cpu",
20
+ "pin_memory": true
21
+ },
22
+ "offload_param": {
23
+ "device": "cpu",
24
+ "pin_memory": true
25
+ },
26
+ "overlap_comm": true,
27
+ "contiguous_gradients": true,
28
+ "sub_group_size": 1e9,
29
+ "reduce_bucket_size": "auto"
30
+ }
31
+ }
LLaVA-NeXT/scripts/zero3.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+
14
+ "zero_optimization": {
15
+ "stage": 3,
16
+ "offload_optimizer": {
17
+ "device": "none",
18
+ "pin_memory": true
19
+ },
20
+ "offload_param": {
21
+ "device": "none",
22
+ "pin_memory": true
23
+ },
24
+ "overlap_comm": true,
25
+ "contiguous_gradients": true,
26
+ "sub_group_size": 1e9,
27
+ "reduce_bucket_size": "auto",
28
+ "stage3_prefetch_bucket_size": "auto",
29
+ "stage3_param_persistence_threshold": "auto",
30
+ "stage3_max_live_parameters": 1e9,
31
+ "stage3_max_reuse_distance": 1e9,
32
+ "stage3_gather_16bit_weights_on_model_save": true
33
+ },
34
+
35
+ "gradient_accumulation_steps": "auto",
36
+ "gradient_clipping": "auto",
37
+ "steps_per_print": 100,
38
+ "train_batch_size": "auto",
39
+ "train_micro_batch_size_per_gpu": "auto",
40
+ "wall_clock_breakdown": false
41
+ }
LLaVA-NeXT/scripts/zero3_offload.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "optimizer": {
14
+ "type": "AdamW",
15
+ "params": {
16
+ "lr": "auto",
17
+ "betas": "auto",
18
+ "eps": "auto",
19
+ "weight_decay": "auto"
20
+ }
21
+ },
22
+ "zero_optimization": {
23
+ "stage": 3,
24
+ "offload_optimizer": {
25
+ "device": "cpu",
26
+ "pin_memory": true
27
+ },
28
+ "offload_param": {
29
+ "device": "cpu",
30
+ "pin_memory": true
31
+ },
32
+ "overlap_comm": true,
33
+ "contiguous_gradients": true,
34
+ "sub_group_size": 1e9,
35
+ "reduce_bucket_size": "auto",
36
+ "stage3_prefetch_bucket_size": "auto",
37
+ "stage3_param_persistence_threshold": "auto",
38
+ "stage3_max_live_parameters": 1e9,
39
+ "stage3_max_reuse_distance": 1e9,
40
+ "gather_16bit_weights_on_model_save": true
41
+ },
42
+ "gradient_accumulation_steps": "auto",
43
+ "gradient_clipping": "auto",
44
+ "train_batch_size": "auto",
45
+ "train_micro_batch_size_per_gpu": "auto",
46
+ "steps_per_print": 1e5,
47
+ "wall_clock_breakdown": false
48
+ }
LLaVA-NeXT/scripts/zero3pp.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "optimizer": {
14
+ "type": "AdamW",
15
+ "params": {
16
+ "lr": "auto",
17
+ "betas": "auto",
18
+ "eps": "auto",
19
+ "weight_decay": "auto"
20
+ }
21
+ },
22
+
23
+ "zero_optimization": {
24
+ "stage": 3,
25
+ "offload_optimizer": {
26
+ "device": "none",
27
+ "pin_memory": true
28
+ },
29
+ "offload_param": {
30
+ "device": "none",
31
+ "pin_memory": true
32
+ },
33
+ "overlap_comm": true,
34
+ "contiguous_gradients": true,
35
+ "zero_quantized_weights": true,
36
+ "zero_hpz_partition_size": 16,
37
+ "zero_quantized_gradients": true,
38
+ "sub_group_size": 1e9,
39
+ "reduce_bucket_size": "auto",
40
+ "stage3_prefetch_bucket_size": "auto",
41
+ "stage3_param_persistence_threshold": "auto",
42
+ "stage3_max_live_parameters": 1e9,
43
+ "stage3_max_reuse_distance": 1e9,
44
+ "stage3_gather_16bit_weights_on_model_save": true
45
+ },
46
+
47
+ "gradient_accumulation_steps": "auto",
48
+ "gradient_clipping": "auto",
49
+ "steps_per_print": 100,
50
+ "train_batch_size": "auto",
51
+ "train_micro_batch_size_per_gpu": "auto",
52
+ "wall_clock_breakdown": false
53
+ }
data/SEEDBench_IMG_32.json ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "ground_truth_answer": "A",
4
+ "image": "SEEDBench_IMG/0.jpg",
5
+ "question": "How many towels are in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.One\nB.Two\nC.Three\nD.Four"
6
+ },
7
+ {
8
+ "ground_truth_answer": "C",
9
+ "image": "SEEDBench_IMG/1.jpg",
10
+ "question": "What type of building is in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.A hotel\nB.A house\nC.A cabin\nD.A shed"
11
+ },
12
+ {
13
+ "ground_truth_answer": "C",
14
+ "image": "SEEDBench_IMG/2.jpg",
15
+ "question": "What is the man in the suit doing in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Standing with his arms crossed\nB.Holding a cell phone\nC.Taking a picture\nD.Talking to someone"
16
+ },
17
+ {
18
+ "ground_truth_answer": "A",
19
+ "image": "SEEDBench_IMG/3.jpg",
20
+ "question": "What is the color of the chair seen on the right side of the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.White\nB.Black\nC.Gray\nD.Brown"
21
+ },
22
+ {
23
+ "ground_truth_answer": "D",
24
+ "image": "SEEDBench_IMG/4.jpg",
25
+ "question": "How many people are present in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.One\nB.Two\nC.Three\nD.Four"
26
+ },
27
+ {
28
+ "ground_truth_answer": "B",
29
+ "image": "SEEDBench_IMG/5.jpg",
30
+ "question": "How many men are on the airplane in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.One\nB.Two\nC.Three\nD.Four"
31
+ },
32
+ {
33
+ "ground_truth_answer": "D",
34
+ "image": "SEEDBench_IMG/6.jpg",
35
+ "question": "What type of beard does one of the men in the car have?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Full\nB.Stubble\nC.Goatee\nD.nan"
36
+ },
37
+ {
38
+ "ground_truth_answer": "B",
39
+ "image": "SEEDBench_IMG/7.jpg",
40
+ "question": "Which of the following objects are not detected in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Mouth\nB.Floor\nC.Ear\nD.Toy"
41
+ },
42
+ {
43
+ "ground_truth_answer": "D",
44
+ "image": "SEEDBench_IMG/8.jpg",
45
+ "question": "What is the relation between the soccer player and the football player?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.They are teammates\nB.Cannot be determined\nC.They are not interacting\nD.They are opponents"
46
+ },
47
+ {
48
+ "ground_truth_answer": "B",
49
+ "image": "SEEDBench_IMG/9.jpg",
50
+ "question": "What is the predominant color of the sand on the beach?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.White\nB.Brown\nC.Black\nD.Gray"
51
+ },
52
+ {
53
+ "ground_truth_answer": "D",
54
+ "image": "SEEDBench_IMG/10.jpg",
55
+ "question": "What is in the background of the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.A cloudy sky\nB.A clear blue sky\nC.Trees and mountains\nD.Buildings and houses"
56
+ },
57
+ {
58
+ "ground_truth_answer": "C",
59
+ "image": "SEEDBench_IMG/11.jpg",
60
+ "question": "How many people are in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Three\nB.Two\nC.One\nD.Four"
61
+ },
62
+ {
63
+ "ground_truth_answer": "B",
64
+ "image": "SEEDBench_IMG/12.jpg",
65
+ "question": "What is the main event taking place in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.A group of people playing soccer in a park\nB.A crowd of people watching a live music performance\nC.A group of people attending a political rally\nD.A street performer playing music while people pass by"
66
+ },
67
+ {
68
+ "ground_truth_answer": "A",
69
+ "image": "SEEDBench_IMG/13.jpg",
70
+ "question": "What is the man wearing in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.A suit and tie\nB.A casual t-shirt\nC.A Hawaiian shirt\nD.A sweater and jeans"
71
+ },
72
+ {
73
+ "ground_truth_answer": "D",
74
+ "image": "SEEDBench_IMG/14.jpg",
75
+ "question": "Which object in the image has an attribute of \"leather\"?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Guitar\nB.Microphone\nC.Arm\nD.Shoe"
76
+ },
77
+ {
78
+ "ground_truth_answer": "C",
79
+ "image": "SEEDBench_IMG/15.jpg",
80
+ "question": "Which bird species is not present in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Sparrows\nB.Hummingbirds\nC.None of the above\nD.White doves"
81
+ },
82
+ {
83
+ "ground_truth_answer": "D",
84
+ "image": "SEEDBench_IMG/16.jpg",
85
+ "question": "What is the main focus of the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.A bedroom\nB.A kitchen\nC.A living room\nD.A dining room"
86
+ },
87
+ {
88
+ "ground_truth_answer": "C",
89
+ "image": "SEEDBench_IMG/17.jpg",
90
+ "question": "What is the focus of the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.The gift bag and candy canes in the foreground.\nB.The full moon in the background.\nC.The character on a plane with a bag of presents.\nD.The red heart with white letters."
91
+ },
92
+ {
93
+ "ground_truth_answer": "D",
94
+ "image": "SEEDBench_IMG/18.jpg",
95
+ "question": "What is the color of the man's suit?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Black\nB.White\nC.Gray\nD.Beige"
96
+ },
97
+ {
98
+ "ground_truth_answer": "B",
99
+ "image": "SEEDBench_IMG/19.jpg",
100
+ "question": "What type of furniture is located in the center of the room in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Coffee table\nB.Desk\nC.Dining table\nD.Side table"
101
+ },
102
+ {
103
+ "ground_truth_answer": "C",
104
+ "image": "SEEDBench_IMG/20.jpg",
105
+ "question": "What objects are in the room besides the people and the guitar?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Bicycle\nB.Television\nC.All of the above\nD.Window"
106
+ },
107
+ {
108
+ "ground_truth_answer": "A",
109
+ "image": "SEEDBench_IMG/21.jpg",
110
+ "question": "How does the water appear in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Crystal clear\nB.Muddy and murky\nC.Blue and calm\nD.Rough and wavy"
111
+ },
112
+ {
113
+ "ground_truth_answer": "C",
114
+ "image": "SEEDBench_IMG/22.jpg",
115
+ "question": "What is the spatial relation between the man's hair and his beard?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.The man's hair and beard are the same length\nB.The man's beard is longer than his hair\nC.The man's hair is longer than his beard\nD.The man has no beard"
116
+ },
117
+ {
118
+ "ground_truth_answer": "D",
119
+ "image": "SEEDBench_IMG/23.jpg",
120
+ "question": "How is the woman with blonde hair positioned in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Jumping\nB.Sitting\nC.Lying down\nD.Standing"
121
+ },
122
+ {
123
+ "ground_truth_answer": "C",
124
+ "image": "SEEDBench_IMG/24.jpg",
125
+ "question": "What is the primary natural element in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.A mountain\nB.The sky\nC.A river\nD.A tree"
126
+ },
127
+ {
128
+ "ground_truth_answer": "A",
129
+ "image": "SEEDBench_IMG/25.jpg",
130
+ "question": "What is the main focus of the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.A couple in the center\nB.A bench in the foreground\nC.A tree in the background\nD.The sky in the distance"
131
+ },
132
+ {
133
+ "ground_truth_answer": "A",
134
+ "image": "SEEDBench_IMG/26.jpg",
135
+ "question": "What is the position of the red car in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Centered in the middle of the image\nB.In the foreground, left side of the image\nC.In the background, right side of the image\nD.Cannot be determined"
136
+ },
137
+ {
138
+ "ground_truth_answer": "A",
139
+ "image": "SEEDBench_IMG/27.jpg",
140
+ "question": "What is the prominent feature of the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.The tall skyscrapers in the city skyline\nB.The boats and ships in the dock\nC.The clock tower\nD.The large body of water in front of the city"
141
+ },
142
+ {
143
+ "ground_truth_answer": "D",
144
+ "image": "SEEDBench_IMG/28.jpg",
145
+ "question": "Which of the following objects is not detected in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Rock\nB.Window\nC.Grass\nD.Bench"
146
+ },
147
+ {
148
+ "ground_truth_answer": "C",
149
+ "image": "SEEDBench_IMG/29.jpg",
150
+ "question": "Are there any animals visible in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Yes\nB.Cannot determine from the given information\nC.No\nD.None of the above"
151
+ },
152
+ {
153
+ "ground_truth_answer": "D",
154
+ "image": "SEEDBench_IMG/30.jpg",
155
+ "question": "What type of room is the image taken in?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.Living room\nB.Bathroom\nC.Kitchen\nD.Classroom"
156
+ },
157
+ {
158
+ "ground_truth_answer": "A",
159
+ "image": "SEEDBench_IMG/31.jpg",
160
+ "question": "Which of the following objects is NOT present in the image?Select the correct answer from options A, B, C, or D. Respond with only the letter (A, B, C, or D).\nA.A river\nB.A pine tree\nC.A wooden bench\nD.A dirt road"
161
+ }
162
+ ]
data/download_data.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from huggingface_hub import hf_hub_download
3
+ import shutil
4
+
5
+
6
+ parser = argparse.ArgumentParser(description="Download a dataset from HF hub")
7
+ parser.add_argument(
8
+ "--dataset",
9
+ choices=["PrimeIntellect","MATH_train","demon_openr1math","MATH500","GSM8K","AIME2024","LiveBench","LiveCodeBench","MBPP","HumanEval"],
10
+ required=True,
11
+ help="Which dataset to download"
12
+ )
13
+ args = parser.parse_args()
14
+ dataset = args.dataset
15
+
16
+
17
+ if dataset == "MATH_train" or dataset == "PrimeIntellect" or dataset == "demon_openr1math":
18
+ split = "train"
19
+ else:
20
+ split = "test"
21
+
22
+
23
+ cached_path = hf_hub_download(
24
+ repo_id=f"Gen-Verse/{dataset}",
25
+ repo_type="dataset",
26
+ filename=f"{split}/{dataset}.json"
27
+ )
28
+ shutil.copy(cached_path, f"./{dataset}.json")
data/images/MMK12/129c0f1b-27e7-4db0-b11f-e393d50d1b25.png ADDED
data/images/MMK12/7d90d0b8-8473-482c-bbd3-bc7707f84b50.png ADDED
data/images/SEEDBench_IMG/0.jpg ADDED
data/images/SEEDBench_IMG/1.jpg ADDED