multitensor commited on
Commit
bbfa6f6
·
verified ·
1 Parent(s): a79bbd7

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +5 -0
  2. LICENSE +201 -0
  3. README.md +458 -3
  4. blip2_pretrained_flant5xxl.pth +3 -0
  5. cog.yaml +36 -0
  6. docs/Customize_Component.md +20 -0
  7. docs/Data.md +29 -0
  8. docs/Evaluation.md +167 -0
  9. docs/Finetune_Custom_Data.md +37 -0
  10. docs/Intel.md +7 -0
  11. docs/LLaVA_Bench.md +31 -0
  12. docs/LLaVA_from_LLaMA2.md +29 -0
  13. docs/LoRA.md +46 -0
  14. docs/MODEL_ZOO.md +150 -0
  15. docs/ScienceQA.md +53 -0
  16. docs/Windows.md +27 -0
  17. docs/macOS.md +29 -0
  18. flash_attn-2.3.6+cu122torch2.1cxx11abiFALSE-cp39-cp39-linux_x86_64.whl +3 -0
  19. handler.py +276 -0
  20. handler_cpu.py +209 -0
  21. images/demo_cli.gif +3 -0
  22. inference_deployment/__init__.py +0 -0
  23. inference_deployment/convert2inf2.py +181 -0
  24. inference_deployment/predict.py +153 -0
  25. inference_deployment/predict_v09.py +151 -0
  26. inference_deployment/qformer_tian.py +1151 -0
  27. llava/__init__.py +9 -0
  28. llava/__pycache__/__init__.cpython-310.pyc +0 -0
  29. llava/__pycache__/__init__.cpython-39.pyc +0 -0
  30. llava/__pycache__/constants.cpython-310.pyc +0 -0
  31. llava/__pycache__/constants.cpython-39.pyc +0 -0
  32. llava/__pycache__/conversation.cpython-310.pyc +0 -0
  33. llava/__pycache__/conversation.cpython-39.pyc +0 -0
  34. llava/__pycache__/mm_utils.cpython-310.pyc +0 -0
  35. llava/__pycache__/mm_utils.cpython-39.pyc +0 -0
  36. llava/__pycache__/utils.cpython-310.pyc +0 -0
  37. llava/__pycache__/utils.cpython-39.pyc +0 -0
  38. llava/configs/action_dataset_ablation/finetune_webvid.yaml +11 -0
  39. llava/configs/action_dataset_ablation/finetune_webvid_act.yaml +11 -0
  40. llava/configs/action_dataset_ablation/finetune_webvid_hdvila.yaml +11 -0
  41. llava/configs/action_dataset_ablation/finetune_webvid_vidal.yaml +11 -0
  42. llava/configs/adso_increasing_ablation/finetune_data_pure_gpt4v.yaml +55 -0
  43. llava/configs/adso_increasing_ablation/finetune_gpt4v_adso135k.yaml +57 -0
  44. llava/configs/adso_increasing_ablation/finetune_gpt4v_adso185k.yaml +57 -0
  45. llava/configs/adso_increasing_ablation/finetune_gpt4v_adso185k_baseline.yaml +55 -0
  46. llava/configs/adso_increasing_ablation/finetune_gpt4v_adso185k_no_qa.yaml +57 -0
  47. llava/configs/adso_increasing_ablation/finetune_gpt4v_adso65k.yaml +57 -0
  48. llava/configs/finetune_debug.yaml +8 -0
  49. llava/configs/finetune_gpt4v_adso65k.yaml +56 -0
  50. llava/configs/gpt4v_increasing_ablation/finetune_gpt4v_public500k.yaml +57 -0
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ flash_attn-2.3.6+cu122torch2.1cxx11abiFALSE-cp39-cp39-linux_x86_64.whl filter=lfs diff=lfs merge=lfs -text
37
+ images/demo_cli.gif filter=lfs diff=lfs merge=lfs -text
38
+ masp_094_v2/video_chair/masp_pred_nvv_sample.json filter=lfs diff=lfs merge=lfs -text
39
+ masp_094_v2/video_chair/uniform_pred_result.json filter=lfs diff=lfs merge=lfs -text
40
+ masp_094_v2/video_chair/uniform_pred_result_detail_res.json filter=lfs diff=lfs merge=lfs -text
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.
README.md CHANGED
@@ -1,3 +1,458 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🌋 LLaVA: Large Language and Vision Assistant
2
+
3
+ *Visual instruction tuning towards large language and vision models with GPT-4 level capabilities.*
4
+
5
+ [📢 [LLaVA-NeXT Blog](https://llava-vl.github.io/blog/2024-01-30-llava-next/)] [[Project Page](https://llava-vl.github.io/)] [[Demo](https://llava.hliu.cc/)] [[Data](https://github.com/haotian-liu/LLaVA/blob/main/docs/Data.md)] [[Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)]
6
+
7
+ 🤝Community Contributions: [[llama.cpp](https://github.com/ggerganov/llama.cpp/pull/3436)] [[Colab](https://github.com/camenduru/LLaVA-colab)] [[🤗Space](https://huggingface.co/spaces/badayvedat/LLaVA)] [[Replicate](https://replicate.com/yorickvp/llava-13b)] [[AutoGen](https://github.com/microsoft/autogen/blob/main/notebook/agentchat_lmm_llava.ipynb)] [[BakLLaVA](https://github.com/SkunkworksAI/BakLLaVA)]
8
+
9
+ **Improved Baselines with Visual Instruction Tuning** [[Paper](https://arxiv.org/abs/2310.03744)] [[HF](https://huggingface.co/papers/2310.03744)] <br>
10
+ [Haotian Liu](https://hliu.cc), [Chunyuan Li](https://chunyuan.li/), [Yuheng Li](https://yuheng-li.github.io/), [Yong Jae Lee](https://pages.cs.wisc.edu/~yongjaelee/)
11
+
12
+ **Visual Instruction Tuning** (NeurIPS 2023, **Oral**) [[Paper](https://arxiv.org/abs/2304.08485)] [[HF](https://huggingface.co/papers/2304.08485)] <br>
13
+ [Haotian Liu*](https://hliu.cc), [Chunyuan Li*](https://chunyuan.li/), [Qingyang Wu](https://scholar.google.ca/citations?user=HDiw-TsAAAAJ&hl=en/), [Yong Jae Lee](https://pages.cs.wisc.edu/~yongjaelee/) (*Equal Contribution)
14
+
15
+ <!--p align="center">
16
+ <a href="https://llava.hliu.cc/"><img src="images/llava_logo.png" width="50%"></a> <br>
17
+ Generated by <a href="https://gligen.github.io/">GLIGEN</a> via "a cute lava llama with glasses" and box prompt
18
+ </p-->
19
+
20
+
21
+ ## Release
22
+ - [1/30] 🔥 LLaVA-NeXT (LLaVA-1.6) 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.
23
+ - [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)]
24
+ - [11/2] [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)]
25
+ - [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.
26
+ - [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)]
27
+ - [10/5] 🔥 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)!
28
+ - [9/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/)
29
+ - [9/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**.
30
+
31
+ <details>
32
+ <summary>More</summary>
33
+
34
+ - [11/6] Support **Intel** dGPU and CPU platforms. [More details here.](https://github.com/haotian-liu/LLaVA/tree/intel/docs/intel)
35
+ - [10/12] LLaVA is now supported in [llama.cpp](https://github.com/ggerganov/llama.cpp/pull/3436) with 4-bit / 5-bit quantization support!
36
+ - [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)!
37
+ - [10/10] [Roboflow Deep Dive](https://blog.roboflow.com/first-impressions-with-llava-1-5/): First Impressions with LLaVA-1.5.
38
+ - [9/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)
39
+ <p align="center">
40
+ <img src="https://github.com/Computer-Vision-in-the-Wild/CVinW_Readings/blob/main/images/mfm_evolution.jpeg?raw=true" width=50%/>
41
+ </p>
42
+
43
+ - [7/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)!
44
+ - [6/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/)].
45
+ - [6/11] We released the preview for the most requested feature: DeepSpeed and LoRA support! Please see documentations [here](./docs/LoRA.md).
46
+ - [6/1] 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).
47
+ - [5/6] 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.
48
+ - [5/2] 🔥 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.
49
+ - [4/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).
50
+ - [4/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/).
51
+
52
+ </details>
53
+
54
+ <!-- <a href="https://llava.hliu.cc/"><img src="assets/demo.gif" width="70%"></a> -->
55
+
56
+ [![Code License](https://img.shields.io/badge/Code%20License-Apache_2.0-green.svg)](https://github.com/tatsu-lab/stanford_alpaca/blob/main/LICENSE)
57
+ **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 community license](https://ai.meta.com/llama/license/) for LLaMA-2 and Vicuna-v1.5). 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.
58
+
59
+
60
+ ## Contents
61
+ - [Install](#install)
62
+ - [LLaVA Weights](#llava-weights)
63
+ - [Demo](#Demo)
64
+ - [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md)
65
+ - [Dataset](https://github.com/haotian-liu/LLaVA/blob/main/docs/Data.md)
66
+ - [Train](#train)
67
+ - [Evaluation](#evaluation)
68
+
69
+ ## Install
70
+
71
+ If you are not using Linux, do *NOT* proceed, see instructions for [macOS](https://github.com/haotian-liu/LLaVA/blob/main/docs/macOS.md) and [Windows](https://github.com/haotian-liu/LLaVA/blob/main/docs/Windows.md).
72
+
73
+ 1. Clone this repository and navigate to LLaVA folder
74
+ ```bash
75
+ git clone https://github.com/haotian-liu/LLaVA.git
76
+ cd LLaVA
77
+ ```
78
+
79
+ 2. Install Package
80
+ ```Shell
81
+ conda create -n llava python=3.10 -y
82
+ conda activate llava
83
+ pip install --upgrade pip # enable PEP 660 support
84
+ pip install -e .
85
+ ```
86
+
87
+ 3. Install additional packages for training cases
88
+ ```
89
+ pip install -e ".[train]"
90
+ pip install flash-attn --no-build-isolation
91
+ ```
92
+
93
+ ### Upgrade to latest code base
94
+
95
+ ```Shell
96
+ git pull
97
+ pip install -e .
98
+
99
+ # if you see some import errors when you upgrade, please try running the command below (without #)
100
+ # pip install flash-attn --no-build-isolation --no-cache-dir
101
+ ```
102
+
103
+ ### Quick Start With HuggingFace
104
+
105
+ <details>
106
+ <summary>Example Code</summary>
107
+
108
+ ```Python
109
+ from llava.model.builder import load_pretrained_model
110
+ from llava.mm_utils import get_model_name_from_path
111
+ from llava.eval.run_llava import eval_model
112
+
113
+ model_path = "liuhaotian/llava-v1.5-7b"
114
+
115
+ tokenizer, model, image_processor, context_len = load_pretrained_model(
116
+ model_path=model_path,
117
+ model_base=None,
118
+ model_name=get_model_name_from_path(model_path)
119
+ )
120
+ ```
121
+
122
+ Check out the details wth the `load_pretrained_model` function in `llava/model/builder.py`.
123
+
124
+ You can also use the `eval_model` function in `llava/eval/run_llava.py` to get the output easily. By doing so, you can use this code on Colab directly after downloading this repository.
125
+
126
+ ``` python
127
+ model_path = "liuhaotian/llava-v1.5-7b"
128
+ prompt = "What are the things I should be cautious about when I visit here?"
129
+ image_file = "https://llava-vl.github.io/static/images/view.jpg"
130
+
131
+ args = type('Args', (), {
132
+ "model_path": model_path,
133
+ "model_base": None,
134
+ "model_name": get_model_name_from_path(model_path),
135
+ "query": prompt,
136
+ "conv_mode": None,
137
+ "image_file": image_file,
138
+ "sep": ",",
139
+ "temperature": 0,
140
+ "top_p": None,
141
+ "num_beams": 1,
142
+ "max_new_tokens": 512
143
+ })()
144
+
145
+ eval_model(args)
146
+ ```
147
+ </details>
148
+
149
+ ## LLaVA Weights
150
+ Please check out our [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md) for all public LLaVA checkpoints, and the instructions of how to use the weights.
151
+
152
+ ## Demo
153
+
154
+ ### Gradio Web UI
155
+
156
+ To launch a Gradio demo locally, please run the following commands one by one. If you plan to launch multiple model workers to compare between different checkpoints, you only need to launch the controller and the web server *ONCE*.
157
+
158
+ ```mermaid
159
+ flowchart BT
160
+ %% Declare Nodes
161
+ gws("Gradio (UI Server)")
162
+ c("Controller (API Server):<br/>PORT: 10000")
163
+ mw7b("Model Worker:<br/>llava-v1.5-7b<br/>PORT: 40000")
164
+ mw13b("Model Worker:<br/>llava-v1.5-13b<br/>PORT: 40001")
165
+ sglw13b("SGLang Backend:<br/>llava-v1.6-34b<br/>http://localhost:30000")
166
+ lsglw13b("SGLang Worker:<br/>llava-v1.6-34b<br/>PORT: 40002")
167
+
168
+ %% Declare Styles
169
+ classDef data fill:#3af,stroke:#48a,stroke-width:2px,color:#444
170
+ classDef success fill:#8f8,stroke:#0a0,stroke-width:2px,color:#444
171
+ classDef failure fill:#f88,stroke:#f00,stroke-width:2px,color:#444
172
+
173
+ %% Assign Styles
174
+ class id,od data;
175
+ class cimg,cs_s,scsim_s success;
176
+ class ncimg,cs_f,scsim_f failure;
177
+
178
+ subgraph Demo Connections
179
+ direction BT
180
+ c<-->gws
181
+
182
+ mw7b<-->c
183
+ mw13b<-->c
184
+ lsglw13b<-->c
185
+ sglw13b<-->lsglw13b
186
+ end
187
+ ```
188
+
189
+ #### Launch a controller
190
+ ```Shell
191
+ python -m llava.serve.controller --host 0.0.0.0 --port 10000
192
+ ```
193
+
194
+ #### Launch a gradio web server.
195
+ ```Shell
196
+ python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
197
+ ```
198
+ You just launched the Gradio web interface. Now, you can open the web interface with the URL printed on the screen. You may notice that there is no model in the model list. Do not worry, as we have not launched any model worker yet. It will be automatically updated when you launch a model worker.
199
+
200
+ #### Launch a SGLang worker
201
+
202
+ This is the recommended way to serve LLaVA model with high throughput, and you need to install SGLang first. Note that currently `4-bit` quantization is not supported yet on SGLang-LLaVA, and if you have limited GPU VRAM, please check out model worker with [quantization](https://github.com/haotian-liu/LLaVA?tab=readme-ov-file#launch-a-model-worker-4-bit-8-bit-inference-quantized).
203
+
204
+ ```Shell
205
+ pip install "sglang[all]"
206
+ ```
207
+
208
+ You'll first launch a SGLang backend worker which will execute the models on GPUs. Remember the `--port` you've set and you'll use that later.
209
+
210
+ ```Shell
211
+ # Single GPU
212
+ CUDA_VISIBLE_DEVICES=0 python3 -m sglang.launch_server --model-path liuhaotian/llava-v1.5-7b --tokenizer-path llava-hf/llava-1.5-7b-hf --port 30000
213
+
214
+ # Multiple GPUs with tensor parallel
215
+ CUDA_VISIBLE_DEVICES=0,1 python3 -m sglang.launch_server --model-path liuhaotian/llava-v1.5-13b --tokenizer-path llava-hf/llava-1.5-13b-hf --port 30000 --tp 2
216
+ ```
217
+
218
+ Tokenizers (temporary): `llava-hf/llava-1.5-7b-hf`, `llava-hf/llava-1.5-13b-hf`, `liuhaotian/llava-v1.6-34b-tokenizer`.
219
+
220
+ You'll then launch a LLaVA-SGLang worker that will communicate between LLaVA controller and SGLang backend to route the requests. Set `--sgl-endpoint` to `http://127.0.0.1:port` where `port` is the one you just set (default: 30000).
221
+
222
+ ```Shell
223
+ python -m llava.serve.sglang_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --sgl-endpoint http://127.0.0.1:30000
224
+ ```
225
+
226
+ #### Launch a model worker
227
+
228
+ This is the actual *worker* that performs the inference on the GPU. Each worker is responsible for a single model specified in `--model-path`.
229
+
230
+ ```Shell
231
+ python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-v1.5-13b
232
+ ```
233
+ Wait until the process finishes loading the model and you see "Uvicorn running on ...". Now, refresh your Gradio web UI, and you will see the model you just launched in the model list.
234
+
235
+ You can launch as many workers as you want, and compare between different model checkpoints in the same Gradio interface. Please keep the `--controller` the same, and modify the `--port` and `--worker` to a different port number for each worker.
236
+ ```Shell
237
+ python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port <different from 40000, say 40001> --worker http://localhost:<change accordingly, i.e. 40001> --model-path <ckpt2>
238
+ ```
239
+
240
+ If you are using an Apple device with an M1 or M2 chip, you can specify the mps device by using the `--device` flag: `--device mps`.
241
+
242
+ #### Launch a model worker (Multiple GPUs, when GPU VRAM <= 24GB)
243
+
244
+ If the VRAM of your GPU is less than 24GB (e.g., RTX 3090, RTX 4090, etc.), you may try running it with multiple GPUs. Our latest code base will automatically try to use multiple GPUs if you have more than one GPU. You can specify which GPUs to use with `CUDA_VISIBLE_DEVICES`. Below is an example of running with the first two GPUs.
245
+
246
+ ```Shell
247
+ CUDA_VISIBLE_DEVICES=0,1 python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-v1.5-13b
248
+ ```
249
+
250
+ #### Launch a model worker (4-bit, 8-bit inference, quantized)
251
+
252
+ You can launch the model worker with quantized bits (4-bit, 8-bit), which allows you to run the inference with reduced GPU memory footprint, potentially allowing you to run on a GPU with as few as 12GB VRAM. Note that inference with quantized bits may not be as accurate as the full-precision model. Simply append `--load-4bit` or `--load-8bit` to the **model worker** command that you are executing. Below is an example of running with 4-bit quantization.
253
+
254
+ ```Shell
255
+ python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-v1.5-13b --load-4bit
256
+ ```
257
+
258
+ #### Launch a model worker (LoRA weights, unmerged)
259
+
260
+ You can launch the model worker with LoRA weights, without merging them with the base checkpoint, to save disk space. There will be additional loading time, while the inference speed is the same as the merged checkpoints. Unmerged LoRA checkpoints do not have `lora-merge` in the model name, and are usually much smaller (less than 1GB) than the merged checkpoints (13G for 7B, and 25G for 13B).
261
+
262
+ To load unmerged LoRA weights, you simply need to pass an additional argument `--model-base`, which is the base LLM that is used to train the LoRA weights. You can check the base LLM of each LoRA weights in the [model zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md).
263
+
264
+ ```Shell
265
+ python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-v1-0719-336px-lora-vicuna-13b-v1.3 --model-base lmsys/vicuna-13b-v1.3
266
+ ```
267
+
268
+ ### CLI Inference
269
+
270
+ Chat about images using LLaVA without the need of Gradio interface. It also supports multiple GPUs, 4-bit and 8-bit quantized inference. With 4-bit quantization, for our LLaVA-1.5-7B, it uses less than 8GB VRAM on a single GPU.
271
+
272
+ ```Shell
273
+ python -m llava.serve.cli \
274
+ --model-path liuhaotian/llava-v1.5-7b \
275
+ --image-file "https://llava-vl.github.io/static/images/view.jpg" \
276
+ --load-4bit
277
+ ```
278
+
279
+ <img src="images/demo_cli.gif" width="70%">
280
+
281
+ ## Train
282
+
283
+ *Below is the latest training configuration for LLaVA v1.5. For legacy models, please refer to README of [this](https://github.com/haotian-liu/LLaVA/tree/v1.0.1) version for now. We'll add them in a separate doc later.*
284
+
285
+ LLaVA training consists of two stages: (1) feature alignment stage: use our 558K subset of the LAION-CC-SBU dataset to connect a *frozen pretrained* vision encoder to a *frozen LLM*; (2) visual instruction tuning stage: use 150K GPT-generated multimodal instruction-following data, plus around 515K VQA data from academic-oriented tasks, to teach the model to follow multimodal instructions.
286
+
287
+ LLaVA is trained on 8 A100 GPUs with 80GB memory. To train on fewer GPUs, you can reduce the `per_device_train_batch_size` and increase the `gradient_accumulation_steps` accordingly. Always keep the global batch size the same: `per_device_train_batch_size` x `gradient_accumulation_steps` x `num_gpus`.
288
+
289
+ ### Hyperparameters
290
+ We use a similar set of hyperparameters as Vicuna in finetuning. Both hyperparameters used in pretraining and finetuning are provided below.
291
+
292
+ 1. Pretraining
293
+
294
+ | Hyperparameter | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
295
+ | --- | ---: | ---: | ---: | ---: | ---: |
296
+ | LLaVA-v1.5-13B | 256 | 1e-3 | 1 | 2048 | 0 |
297
+
298
+ 2. Finetuning
299
+
300
+ | Hyperparameter | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
301
+ | --- | ---: | ---: | ---: | ---: | ---: |
302
+ | LLaVA-v1.5-13B | 128 | 2e-5 | 1 | 2048 | 0 |
303
+
304
+ ### Download Vicuna checkpoints (automatically)
305
+
306
+ Our base model Vicuna v1.5, which is an instruction-tuned chatbot, will be downloaded automatically when you run our provided training scripts. No action is needed.
307
+
308
+ ### Pretrain (feature alignment)
309
+
310
+ Please download the 558K subset of the LAION-CC-SBU dataset with BLIP captions we use in the paper [here](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain).
311
+
312
+ Pretrain takes around 5.5 hours for LLaVA-v1.5-13B on 8x A100 (80G), due to the increased resolution to 336px. It takes around 3.5 hours for LLaVA-v1.5-7B.
313
+
314
+ Training script with DeepSpeed ZeRO-2: [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/pretrain.sh).
315
+
316
+ - `--mm_projector_type mlp2x_gelu`: the two-layer MLP vision-language connector.
317
+ - `--vision_tower openai/clip-vit-large-patch14-336`: CLIP ViT-L/14 336px.
318
+
319
+ <details>
320
+ <summary>Pretrain takes around 20 hours for LLaVA-7B on 8x V100 (32G)</summary>
321
+
322
+ We provide training script with DeepSpeed [here](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain_xformers.sh).
323
+ Tips:
324
+ - If you are using V100 which is not supported by FlashAttention, you can use the [memory-efficient attention](https://arxiv.org/abs/2112.05682) implemented in [xFormers](https://github.com/facebookresearch/xformers). Install xformers and replace `llava/train/train_mem.py` above with [llava/train/train_xformers.py](llava/train/train_xformers.py).
325
+ </details>
326
+
327
+ ### Visual Instruction Tuning
328
+
329
+ 1. Prepare data
330
+
331
+ Please download the annotation of the final mixture our instruction tuning data [llava_v1_5_mix665k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_v1_5_mix665k.json), and download the images from constituting datasets:
332
+
333
+ - COCO: [train2017](http://images.cocodataset.org/zips/train2017.zip)
334
+ - GQA: [images](https://downloads.cs.stanford.edu/nlp/data/gqa/images.zip)
335
+ - OCR-VQA: [download script](https://drive.google.com/drive/folders/1_GYPY5UkUy7HIcR0zq3ZCFgeZN7BAfm_?usp=sharing), **we save all files as `.jpg`**
336
+ - TextVQA: [train_val_images](https://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip)
337
+ - VisualGenome: [part1](https://cs.stanford.edu/people/rak248/VG_100K_2/images.zip), [part2](https://cs.stanford.edu/people/rak248/VG_100K_2/images2.zip)
338
+
339
+ After downloading all of them, organize the data as follows in `./playground/data`,
340
+
341
+ ```
342
+ ├── coco
343
+ │ └── train2017
344
+ ├── gqa
345
+ │ └── images
346
+ ├── ocr_vqa
347
+ │ └── images
348
+ ├── textvqa
349
+ │ └── train_images
350
+ └── vg
351
+ ├── VG_100K
352
+ └── VG_100K_2
353
+ ```
354
+
355
+ 2. Start training!
356
+
357
+ You may download our pretrained projectors in [Model Zoo](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md). It is not recommended to use legacy projectors, as they may be trained with a different version of the codebase, and if any option is off, the model will not function/train as we expected.
358
+
359
+ Visual instruction tuning takes around 20 hours for LLaVA-v1.5-13B on 8x A100 (80G), due to the increased resolution to 336px. It takes around 10 hours for LLaVA-v1.5-7B on 8x A100 (40G).
360
+
361
+ Training script with DeepSpeed ZeRO-3: [`finetune.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune.sh).
362
+
363
+ If you are do not have enough GPU memory:
364
+
365
+ - Use LoRA: [`finetune_lora.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune_lora.sh). We are able to fit 13B training in 8-A100-40G/8-A6000, and 7B training in 8-RTX3090. Make sure `per_device_train_batch_size*gradient_accumulation_steps` is the same as the provided script for best reproducibility.
366
+ - Replace `zero3.json` with `zero3_offload.json` which offloads some parameters to CPU RAM. This slows down the training speed.
367
+
368
+ If you are interested in finetuning LLaVA model to your own task/data, please check out [`Finetune_Custom_Data.md`](https://github.com/haotian-liu/LLaVA/blob/main/docs/Finetune_Custom_Data.md)。
369
+
370
+ New options to note:
371
+
372
+ - `--mm_projector_type mlp2x_gelu`: the two-layer MLP vision-language connector.
373
+ - `--vision_tower openai/clip-vit-large-patch14-336`: CLIP ViT-L/14 336px.
374
+ - `--image_aspect_ratio pad`: this pads the non-square images to square, instead of cropping them; it slightly reduces hallucination.
375
+ - `--group_by_modality_length True`: this should only be used when your instruction tuning dataset contains both language (e.g. ShareGPT) and multimodal (e.g. LLaVA-Instruct). It makes the training sampler only sample a single modality (either image or language) during training, which we observe to speed up training by ~25%, and does not affect the final outcome.
376
+
377
+ ## Evaluation
378
+
379
+ In LLaVA-1.5, we evaluate models on a diverse set of 12 benchmarks. To ensure the reproducibility, we evaluate the models with greedy decoding. We do not evaluate using beam search to make the inference process consistent with the chat demo of real-time outputs.
380
+
381
+ See [Evaluation.md](https://github.com/haotian-liu/LLaVA/blob/main/docs/Evaluation.md).
382
+
383
+ ### GPT-assisted Evaluation
384
+
385
+ Our GPT-assisted evaluation pipeline for multimodal modeling is provided for a comprehensive understanding of the capabilities of vision-language models. Please see our paper for more details.
386
+
387
+ 1. Generate LLaVA responses
388
+
389
+ ```Shell
390
+ python model_vqa.py \
391
+ --model-path ./checkpoints/LLaVA-13B-v0 \
392
+ --question-file \
393
+ playground/data/coco2014_val_qa_eval/qa90_questions.jsonl \
394
+ --image-folder \
395
+ /path/to/coco2014_val \
396
+ --answers-file \
397
+ /path/to/answer-file-our.jsonl
398
+ ```
399
+
400
+ 2. Evaluate the generated responses. In our case, [`answer-file-ref.jsonl`](./playground/data/coco2014_val_qa_eval/qa90_gpt4_answer.jsonl) is the response generated by text-only GPT-4 (0314), with the context captions/boxes provided.
401
+
402
+ ```Shell
403
+ OPENAI_API_KEY="sk-***********************************" python llava/eval/eval_gpt_review_visual.py \
404
+ --question playground/data/coco2014_val_qa_eval/qa90_questions.jsonl \
405
+ --context llava/eval/table/caps_boxes_coco2014_val_80.jsonl \
406
+ --answer-list \
407
+ /path/to/answer-file-ref.jsonl \
408
+ /path/to/answer-file-our.jsonl \
409
+ --rule llava/eval/table/rule.json \
410
+ --output /path/to/review.json
411
+ ```
412
+
413
+ 3. Summarize the evaluation results
414
+
415
+ ```Shell
416
+ python summarize_gpt_review.py
417
+ ```
418
+
419
+ ## Citation
420
+
421
+ If you find LLaVA useful for your research and applications, please cite using this BibTeX:
422
+ ```bibtex
423
+ @misc{liu2024llavanext,
424
+ title={LLaVA-NeXT: Improved reasoning, OCR, and world knowledge},
425
+ url={https://llava-vl.github.io/blog/2024-01-30-llava-next/},
426
+ author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Li, Bo and Zhang, Yuanhan and Shen, Sheng and Lee, Yong Jae},
427
+ month={January},
428
+ year={2024}
429
+ }
430
+
431
+ @misc{liu2023improvedllava,
432
+ title={Improved Baselines with Visual Instruction Tuning},
433
+ author={Liu, Haotian and Li, Chunyuan and Li, Yuheng and Lee, Yong Jae},
434
+ publisher={arXiv:2310.03744},
435
+ year={2023},
436
+ }
437
+
438
+ @misc{liu2023llava,
439
+ title={Visual Instruction Tuning},
440
+ author={Liu, Haotian and Li, Chunyuan and Wu, Qingyang and Lee, Yong Jae},
441
+ publisher={NeurIPS},
442
+ year={2023},
443
+ }
444
+ ```
445
+
446
+ ## Acknowledgement
447
+
448
+ - [Vicuna](https://github.com/lm-sys/FastChat): the codebase we built upon, and our base model Vicuna-13B that has the amazing language capabilities!
449
+
450
+ ## Related Projects
451
+
452
+ - [Instruction Tuning with GPT-4](https://github.com/Instruction-Tuning-with-GPT-4/GPT-4-LLM)
453
+ - [LLaVA-Med: Training a Large Language-and-Vision Assistant for Biomedicine in One Day](https://github.com/microsoft/LLaVA-Med)
454
+ - [Otter: In-Context Multi-Modal Instruction Tuning](https://github.com/Luodian/Otter)
455
+
456
+ For future project ideas, please check out:
457
+ - [SEEM: Segment Everything Everywhere All at Once](https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once)
458
+ - [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).
blip2_pretrained_flant5xxl.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b3839ea6c617f315ead9bf4036bbb0f0cf6bf62695ecfc14968ea626af03a29
3
+ size 433481467
cog.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.10"
8
+
9
+ python_packages:
10
+ - "torch==2.1.2"
11
+ - "accelerate==0.27.2"
12
+ - "bitsandbytes==0.41.0"
13
+ - "deepspeed==0.12.2"
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.9.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.15.2"
27
+ - "torchvision==0.16.2"
28
+ - "transformers==4.38.1"
29
+ - "wandb==0.15.12"
30
+ - "wavedrom==2.0.3.post3"
31
+ - "Pygments==2.16.1"
32
+ run:
33
+ - curl -o /usr/local/bin/pget -L "https://github.com/replicate/pget/releases/download/v0.0.3/pget" && chmod +x /usr/local/bin/pget
34
+
35
+ # predict.py defines how predictions are run on your model
36
+ predict: "predict.py:Predictor"
docs/Customize_Component.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Customize Components in LLaVA
2
+
3
+ This is an initial guide on how to replace the LLMs, visual encoders, etc. with your choice of components.
4
+
5
+ ## LLM
6
+
7
+ It is quite simple to swap out LLaMA to any other LLMs. You can refer to our implementation of [`llava_llama.py`](https://raw.githubusercontent.com/haotian-liu/LLaVA/main/llava/model/language_model/llava_llama.py) for an example of how to replace the LLM.
8
+
9
+ Although it may seem that it still needs ~100 lines of code, most of them are copied from the original `llama.py` from HF. The only part that is different is to insert some lines for processing the multimodal inputs.
10
+
11
+ In `forward` function, you can see that we call `self.prepare_inputs_labels_for_multimodal` to process the multimodal inputs. This function is defined in `LlavaMetaForCausalLM` and you just need to insert it into the `forward` function of your LLM.
12
+
13
+ In `prepare_inputs_for_generation` function, you can see that we add `images` to the `model_inputs`. This is because we need to pass the images to the LLM during generation.
14
+
15
+ These are basically all the changes you need to make to replace the LLM.
16
+
17
+ ## Visual Encoder
18
+
19
+ You can check out [`clip_encoder.py`](https://github.com/haotian-liu/LLaVA/blob/main/llava/model/multimodal_encoder/clip_encoder.py) on how we implement the CLIP visual encoder.
20
+
docs/Data.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Data
2
+
3
+ | Data file name | Size |
4
+ | --- | ---: |
5
+ | [llava_instruct_150k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_150k.json) | 229 MB |
6
+ | [llava_instruct_80k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_80k.json) | 229 MB |
7
+ | [conversation_58k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/conversation_58k.json) | 126 MB |
8
+ | [detail_23k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/detail_23k.json) | 20.5 MB |
9
+ | [complex_reasoning_77k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/complex_reasoning_77k.json) | 79.6 MB |
10
+
11
+ ### Pretraining Dataset
12
+ The pretraining dataset used in this release is a subset of CC-3M dataset, filtered with a more balanced concept coverage distribution. Please see [here](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K) for a detailed description of the dataset structure and how to download the images.
13
+
14
+ If you already have CC-3M dataset on your disk, the image names follow this format: `GCC_train_000000000.jpg`. You may edit the `image` field correspondingly if necessary.
15
+
16
+ | Data | Chat File | Meta Data | Size |
17
+ | --- | --- | --- | ---: |
18
+ | CC-3M Concept-balanced 595K | [chat.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/chat.json) | [metadata.json](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/metadata.json) | 211 MB
19
+ | LAION/CC/SBU BLIP-Caption Concept-balanced 558K | [blip_laion_cc_sbu_558k.json](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain/blob/main/blip_laion_cc_sbu_558k.json) | [metadata.json](#) | 181 MB
20
+
21
+ **Important notice**: Upon the request from the community, as ~15% images of the original CC-3M dataset are no longer accessible, we upload [`images.zip`](https://huggingface.co/datasets/liuhaotian/LLaVA-CC3M-Pretrain-595K/blob/main/images.zip) for better reproducing our work in research community. It must not be used for any other purposes. The use of these images must comply with the CC-3M license. This may be taken down at any time when requested by the original CC-3M dataset owner or owners of the referenced images.
22
+
23
+ ### GPT-4 Prompts
24
+
25
+ We provide our prompts and few-shot samples for GPT-4 queries, to better facilitate research in this domain. Please check out the [`prompts`](https://github.com/haotian-liu/LLaVA/tree/main/playground/data/prompts) folder for three kinds of questions: conversation, detail description, and complex reasoning.
26
+
27
+ They are organized in a format of `system_message.txt` for system message, pairs of `abc_caps.txt` for few-shot sample user input, and `abc_conv.txt` for few-shot sample reference output.
28
+
29
+ Note that you may find them in different format. For example, `conversation` is in `jsonl`, and detail description is answer-only. The selected format in our preliminary experiments works slightly better than a limited set of alternatives that we tried: `jsonl`, more natural format, answer-only. If interested, you may try other variants or conduct more careful study in this. Contributions are welcomed!
docs/Evaluation.md ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluation
2
+
3
+ In LLaVA-1.5, we evaluate models on a diverse set of 12 benchmarks. To ensure the reproducibility, we evaluate the models with greedy decoding. We do not evaluate using beam search to make the inference process consistent with the chat demo of real-time outputs.
4
+
5
+ Currently, we mostly utilize the official toolkit or server for the evaluation.
6
+
7
+ ## Evaluate on Custom Datasets
8
+
9
+ You can evaluate LLaVA on your custom datasets by converting your dataset to LLaVA's jsonl format, and evaluate using [`model_vqa.py`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/model_vqa.py).
10
+
11
+ Below we provide a general guideline for evaluating datasets with some common formats.
12
+
13
+ 1. Short-answer (e.g. VQAv2, MME).
14
+
15
+ ```
16
+ <question>
17
+ Answer the question using a single word or phrase.
18
+ ```
19
+
20
+ 2. Option-only for multiple-choice (e.g. MMBench, SEED-Bench).
21
+
22
+ ```
23
+ <question>
24
+ A. <option_1>
25
+ B. <option_2>
26
+ C. <option_3>
27
+ D. <option_4>
28
+ Answer with the option's letter from the given choices directly.
29
+ ```
30
+
31
+ 3. Natural QA (e.g. LLaVA-Bench, MM-Vet).
32
+
33
+ No postprocessing is needed.
34
+
35
+ ## Scripts
36
+
37
+ Before preparing task-specific data, **you MUST first download [eval.zip](https://drive.google.com/file/d/1atZSBBrAX54yYpxtVVW33zFvcnaHeFPy/view?usp=sharing)**. It contains custom annotations, scripts, and the prediction files with LLaVA v1.5. Extract to `./playground/data/eval`. This also provides a general structure for all datasets.
38
+
39
+ ### VQAv2
40
+
41
+ 1. Download [`test2015`](http://images.cocodataset.org/zips/test2015.zip) and put it under `./playground/data/eval/vqav2`.
42
+ 2. Multi-GPU inference.
43
+ ```Shell
44
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/vqav2.sh
45
+ ```
46
+ 3. Submit the results to the [evaluation server](https://eval.ai/web/challenges/challenge-page/830/my-submission): `./playground/data/eval/vqav2/answers_upload`.
47
+
48
+ ### GQA
49
+
50
+ 1. Download the [data](https://cs.stanford.edu/people/dorarad/gqa/download.html) and [evaluation scripts](https://cs.stanford.edu/people/dorarad/gqa/evaluate.html) following the official instructions and put under `./playground/data/eval/gqa/data`. You may need to modify `eval.py` as [this](https://gist.github.com/haotian-liu/db6eddc2a984b4cbcc8a7f26fd523187) due to the missing assets in the GQA v1.2 release.
51
+ 2. Multi-GPU inference.
52
+ ```Shell
53
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/gqa.sh
54
+ ```
55
+
56
+ ### VisWiz
57
+
58
+ 1. Download [`test.json`](https://vizwiz.cs.colorado.edu/VizWiz_final/vqa_data/Annotations.zip) and extract [`test.zip`](https://vizwiz.cs.colorado.edu/VizWiz_final/images/test.zip) to `test`. Put them under `./playground/data/eval/vizwiz`.
59
+ 2. Single-GPU inference.
60
+ ```Shell
61
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/vizwiz.sh
62
+ ```
63
+ 3. Submit the results to the [evaluation server](https://eval.ai/web/challenges/challenge-page/1911/my-submission): `./playground/data/eval/vizwiz/answers_upload`.
64
+
65
+ ### ScienceQA
66
+
67
+ 1. Under `./playground/data/eval/scienceqa`, download `images`, `pid_splits.json`, `problems.json` from the `data/scienceqa` folder of the ScienceQA [repo](https://github.com/lupantech/ScienceQA).
68
+ 2. Single-GPU inference and evaluate.
69
+ ```Shell
70
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/sqa.sh
71
+ ```
72
+
73
+ ### TextVQA
74
+
75
+ 1. Download [`TextVQA_0.5.1_val.json`](https://dl.fbaipublicfiles.com/textvqa/data/TextVQA_0.5.1_val.json) and [images](https://dl.fbaipublicfiles.com/textvqa/images/train_val_images.zip) and extract to `./playground/data/eval/textvqa`.
76
+ 2. Single-GPU inference and evaluate.
77
+ ```Shell
78
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/textvqa.sh
79
+ ```
80
+
81
+ ### POPE
82
+
83
+ 1. Download `coco` from [POPE](https://github.com/AoiDragon/POPE/tree/e3e39262c85a6a83f26cf5094022a782cb0df58d/output/coco) and put under `./playground/data/eval/pope`.
84
+ 2. Single-GPU inference and evaluate.
85
+ ```Shell
86
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/pope.sh
87
+ ```
88
+
89
+ ### MME
90
+
91
+ 1. Download the data following the official instructions [here](https://github.com/BradyFU/Awesome-Multimodal-Large-Language-Models/tree/Evaluation).
92
+ 2. Downloaded images to `MME_Benchmark_release_version`.
93
+ 3. put the official `eval_tool` and `MME_Benchmark_release_version` under `./playground/data/eval/MME`.
94
+ 4. Single-GPU inference and evaluate.
95
+ ```Shell
96
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mme.sh
97
+ ```
98
+
99
+ ### MMBench
100
+
101
+ 1. Download [`mmbench_dev_20230712.tsv`](https://download.openmmlab.com/mmclassification/datasets/mmbench/mmbench_dev_20230712.tsv) and put under `./playground/data/eval/mmbench`.
102
+ 2. Single-GPU inference.
103
+ ```Shell
104
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmbench.sh
105
+ ```
106
+ 3. Submit the results to the [evaluation server](https://opencompass.org.cn/leaderboard-multimodal): `./playground/data/eval/mmbench/answers_upload/mmbench_dev_20230712`.
107
+
108
+ ### MMBench-CN
109
+
110
+ 1. Download [`mmbench_dev_cn_20231003.tsv`](https://download.openmmlab.com/mmclassification/datasets/mmbench/mmbench_dev_cn_20231003.tsv) and put under `./playground/data/eval/mmbench`.
111
+ 2. Single-GPU inference.
112
+ ```Shell
113
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmbench_cn.sh
114
+ ```
115
+ 3. Submit the results to the evaluation server: `./playground/data/eval/mmbench/answers_upload/mmbench_dev_cn_20231003`.
116
+
117
+
118
+ ### SEED-Bench
119
+
120
+ 1. Following the official [instructions](https://github.com/AILab-CVC/SEED-Bench/blob/main/DATASET.md) to download the images and the videos. Put images under `./playground/data/eval/seed_bench/SEED-Bench-image`.
121
+ 2. Extract the video frame in the middle from the downloaded videos, and put them under `./playground/data/eval/seed_bench/SEED-Bench-video-image`. We provide our script `extract_video_frames.py` modified from the official one.
122
+ 3. Multiple-GPU inference and evaluate.
123
+ ```Shell
124
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/v1_5/eval/seed.sh
125
+ ```
126
+ 4. Optionally, submit the results to the leaderboard: `./playground/data/eval/seed_bench/answers_upload` using the official jupyter notebook.
127
+
128
+ ### LLaVA-Bench-in-the-Wild
129
+
130
+ 1. Extract contents of [`llava-bench-in-the-wild`](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild) to `./playground/data/eval/llava-bench-in-the-wild`.
131
+ 2. Single-GPU inference and evaluate.
132
+ ```Shell
133
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/llavabench.sh
134
+ ```
135
+
136
+ ### MM-Vet
137
+
138
+ 1. Extract [`mm-vet.zip`](https://github.com/yuweihao/MM-Vet/releases/download/v1/mm-vet.zip) to `./playground/data/eval/mmvet`.
139
+ 2. Single-GPU inference.
140
+ ```Shell
141
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/mmvet.sh
142
+ ```
143
+ 3. Evaluate the predictions in `./playground/data/eval/mmvet/results` using the official jupyter notebook.
144
+
145
+ ## More Benchmarks
146
+
147
+ Below are awesome benchmarks for multimodal understanding from the research community, that are not initially included in the LLaVA-1.5 release.
148
+
149
+ ### Q-Bench
150
+
151
+ 1. Download [`llvisionqa_dev.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/llvisionqa_dev.json) (for `dev`-subset) and [`llvisionqa_test.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/llvisionqa_test.json) (for `test`-subset). Put them under `./playground/data/eval/qbench`.
152
+ 2. Download and extract [images](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/images_llvisionqa.tar) and put all the images directly under `./playground/data/eval/qbench/images_llviqionqa`.
153
+ 3. Single-GPU inference (change `dev` to `test` for evaluation on test set).
154
+ ```Shell
155
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/qbench.sh dev
156
+ ```
157
+ 4. Submit the results by instruction [here](https://github.com/VQAssessment/Q-Bench#option-1-submit-results): `./playground/data/eval/qbench/llvisionqa_dev_answers.jsonl`.
158
+
159
+ ### Chinese-Q-Bench
160
+
161
+ 1. Download [`质衡-问答-验证集.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/%E8%B4%A8%E8%A1%A1-%E9%97%AE%E7%AD%94-%E9%AA%8C%E8%AF%81%E9%9B%86.json) (for `dev`-subset) and [`质衡-问答-测试集.json`](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/%E8%B4%A8%E8%A1%A1-%E9%97%AE%E7%AD%94-%E6%B5%8B%E8%AF%95%E9%9B%86.json) (for `test`-subset). Put them under `./playground/data/eval/qbench`.
162
+ 2. Download and extract [images](https://huggingface.co/datasets/nanyangtu/LLVisionQA-QBench/resolve/main/images_llvisionqa.tar) and put all the images directly under `./playground/data/eval/qbench/images_llviqionqa`.
163
+ 3. Single-GPU inference (change `dev` to `test` for evaluation on test set).
164
+ ```Shell
165
+ CUDA_VISIBLE_DEVICES=0 bash scripts/v1_5/eval/qbench_zh.sh dev
166
+ ```
167
+ 4. Submit the results by instruction [here](https://github.com/VQAssessment/Q-Bench#option-1-submit-results): `./playground/data/eval/qbench/llvisionqa_zh_dev_answers.jsonl`.
docs/Finetune_Custom_Data.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Finetune LLaVA on Custom Datasets
2
+
3
+ ## Dataset Format
4
+
5
+ Convert your data to a JSON file of a List of all samples. Sample metadata should contain `id` (a unique identifier), `image` (the path to the image), and `conversations` (the conversation data between human and AI).
6
+
7
+ A sample JSON for finetuning LLaVA for generating tag-style captions for Stable Diffusion:
8
+
9
+ ```json
10
+ [
11
+ {
12
+ "id": "997bb945-628d-4724-b370-b84de974a19f",
13
+ "image": "part-000001/997bb945-628d-4724-b370-b84de974a19f.jpg",
14
+ "conversations": [
15
+ {
16
+ "from": "human",
17
+ "value": "<image>\nWrite a prompt for Stable Diffusion to generate this image."
18
+ },
19
+ {
20
+ "from": "gpt",
21
+ "value": "a beautiful painting of chernobyl by nekro, pascal blanche, john harris, greg rutkowski, sin jong hun, moebius, simon stalenhag. in style of cg art. ray tracing. cel shading. hyper detailed. realistic. ue 5. maya. octane render. "
22
+ },
23
+ ]
24
+ },
25
+ ...
26
+ ]
27
+ ```
28
+
29
+ ## Command
30
+
31
+ If you have a limited task-specific data, we recommend finetuning from LLaVA checkpoints with LoRA following this [script](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune_task_lora.sh).
32
+
33
+ If the amount of the task-specific data is sufficient, you can also finetune from LLaVA checkpoints with full-model finetuning following this [script](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/finetune_task.sh).
34
+
35
+ You may need to adjust the hyperparameters to fit each specific dataset and your hardware constraint.
36
+
37
+
docs/Intel.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Intel Platforms
2
+
3
+ * Support [Intel GPU Max Series](https://www.intel.com/content/www/us/en/products/details/discrete-gpus/data-center-gpu/max-series.html)
4
+ * Support [Intel CPU Sapphire Rapides](https://ark.intel.com/content/www/us/en/ark/products/codename/126212/products-formerly-sapphire-rapids.html)
5
+ * Based on [Intel Extension for Pytorch](https://intel.github.io/intel-extension-for-pytorch)
6
+
7
+ More details in [**intel branch**](https://github.com/haotian-liu/LLaVA/tree/intel/docs/intel)
docs/LLaVA_Bench.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLaVA-Bench [[Download](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild)]
2
+
3
+ **-Introduction-** Large commercial multimodal chatbots have been released in this week, including
4
+ - [Multimodal Bing-Chat by Microsoft](https://blogs.bing.com/search/july-2023/Bing-Chat-Enterprise-announced,-multimodal-Visual-Search-rolling-out-to-Bing-Chat) (July 18, 2023)
5
+ - [Multimodal Bard by Google](https://bard.google.com/).
6
+
7
+ These chatbots are presumably supported by proprietary large multimodal models (LMM). Compared with the open-source LMM such as LLaVA, proprietary LMM represent the scaling success upperbound of the current SoTA techniques. They share the goal of developing multimodal chatbots that follow human intents to complete various daily-life visual tasks in the wild. While it remains less explored how to evaluate multimodal chat ability, it provides useful feedback to study open-source LMMs against the commercial multimodal chatbots. In addition to the *LLaVA-Bench (COCO)* dataset we used to develop the early versions of LLaVA, we are releasing [*LLaVA-Bench (In-the-Wild)*](https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild) to the community for the public use.
8
+
9
+ ## LLaVA-Bench (In-the-Wild *[Ongoing work]*)
10
+
11
+ To evaluate the model's capability in more challenging tasks and generalizability to novel domains, we collect a diverse set of 24 images with 60 questions in total, including indoor and outdoor scenes, memes, paintings, sketches, etc, and associate each image with a highly-detailed and manually-curated description and a proper selection of questions. Such design also assesses the model's robustness to different prompts. In this release, we also categorize questions into three categories: conversation (simple QA), detailed description, and complex reasoning. We continue to expand and improve the diversity of the LLaVA-Bench (In-the-Wild). We manually query Bing-Chat and Bard to get the responses.
12
+
13
+ ### Results
14
+
15
+ The score is measured by comparing against a reference answer generated by text-only GPT-4. It is generated by feeding the question, along with the ground truth image annotations as the context. A text-only GPT-4 evaluator rates both answers. We query GPT-4 by putting the reference answer first, and then the answer generated by the candidate model. We upload images at their original resolution to Bard and Bing-Chat to obtain the results.
16
+
17
+ | Approach | Conversation | Detail | Reasoning | Overall |
18
+ |----------------|--------------|--------|-----------|---------|
19
+ | Bard-0718 | 83.7 | 69.7 | 78.7 | 77.8 |
20
+ | Bing-Chat-0629 | 59.6 | 52.2 | 90.1 | 71.5 |
21
+ | LLaVA-13B-v1-336px-0719 (beam=1) | 64.3 | 55.9 | 81.7 | 70.1 |
22
+ | LLaVA-13B-v1-336px-0719 (beam=5) | 68.4 | 59.9 | 84.3 | 73.5 |
23
+
24
+ Note that Bard sometimes refuses to answer questions about images containing humans, and Bing-Chat blurs the human faces in the images. We also provide the benchmark score for the subset without humans.
25
+
26
+ | Approach | Conversation | Detail | Reasoning | Overall |
27
+ |----------------|--------------|--------|-----------|---------|
28
+ | Bard-0718 | 94.9 | 74.3 | 84.3 | 84.6 |
29
+ | Bing-Chat-0629 | 55.8 | 53.6 | 93.5 | 72.6 |
30
+ | LLaVA-13B-v1-336px-0719 (beam=1) | 62.2 | 56.4 | 82.2 | 70.0 |
31
+ | LLaVA-13B-v1-336px-0719 (beam=5) | 65.6 | 61.7 | 85.0 | 73.6 |
docs/LLaVA_from_LLaMA2.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLaVA (based on Llama 2 LLM, Preview)
2
+
3
+ *NOTE: This is a technical preview. We are still running hyperparameter search, and will release the final model soon. If you'd like to contribute to this, please contact us.*
4
+
5
+ :llama: **-Introduction-** [Llama 2 is an open-source LLM released by Meta AI](https://about.fb.com/news/2023/07/llama-2/) today (July 18, 2023). Compared with its early version [Llama 1](https://ai.meta.com/blog/large-language-model-llama-meta-ai/), Llama 2 is more favored in ***stronger language performance***, ***longer context window***, and importantly ***commercially usable***! While Llama 2 is changing the LLM market landscape in the language space, its multimodal ability remains unknown. We quickly develop the LLaVA variant based on the latest Llama 2 checkpoints, and release it to the community for the public use.
6
+
7
+ You need to apply for and download the latest Llama 2 checkpoints to start your own training (apply [here](https://ai.meta.com/resources/models-and-libraries/llama-downloads/))
8
+
9
+
10
+ ## Training
11
+
12
+ Please checkout [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh), [`finetune.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune.sh), [`finetune_lora.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh).
13
+
14
+ ## LLaVA (based on Llama 2), What is different?
15
+
16
+ :volcano: How is the new LLaVA based on Llama 2 different from Llama 1? The comparisons of the training process are described:
17
+ - **Pre-training**. The pre-trained base LLM is changed from Llama 1 to Llama 2
18
+ - **Language instruction-tuning**. The previous LLaVA model starts with Vicuna, which is instruct tuned on ShareGPT data from Llama 1; The new LLaVA model starts with Llama 2 Chat, which is an instruct tuned checkpoint on dialogue data from Llama 2.
19
+ - **Multimodal instruction-tuning**. The same LLaVA-Lighting process is applied.
20
+
21
+
22
+ ### Results
23
+
24
+ - Llama 2 is better at following the instructions of role playing; Llama 2 fails in following the instructions of translation
25
+ - The quantitative evaluation on [LLaVA-Bench](https://github.com/haotian-liu/LLaVA/blob/main/docs/LLaVA_Bench.md) demonstrates on-par performance between Llama 2 and Llama 1 in LLaVA's multimodal chat ability.
26
+
27
+
28
+ <img src="../images/llava_example_cmp.png" width="100%">
29
+
docs/LoRA.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLaVA (LoRA, Preview)
2
+
3
+ NOTE: This is a technical preview, and is not yet ready for production use. We are still running hyperparameter search for the LoRA model, and will release the final model soon. If you'd like to contribute to this, please contact us.
4
+
5
+ You need latest code base for LoRA support (instructions [here](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base))
6
+
7
+ ## Demo (Web UI)
8
+
9
+ Please execute each of the commands below one by one (after the previous one has finished). The commands are the same as launching other demos except for an additional `--model-base` flag to specify the base model to use. Please make sure the base model corresponds to the LoRA checkpoint that you are using. For this technical preview, you need Vicuna v1.1 (7B) checkpoint (if you do not have that already, follow the instructions [here](https://github.com/lm-sys/FastChat#vicuna-weights)).
10
+
11
+ #### Launch a controller
12
+ ```Shell
13
+ python -m llava.serve.controller --host 0.0.0.0 --port 10000
14
+ ```
15
+
16
+ #### Launch a gradio web server.
17
+ ```Shell
18
+ python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
19
+ ```
20
+ You just launched the Gradio web interface. Now, you can open the web interface with the URL printed on the screen. You may notice that there is no model in the model list. Do not worry, as we have not launched any model worker yet. It will be automatically updated when you launch a model worker.
21
+
22
+ #### Launch a model worker
23
+ ```Shell
24
+ python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-vicuna-7b-v1.1-lcs_558k-instruct_80k_3e-lora-preview-alpha --model-base /path/to/vicuna-v1.1
25
+ ```
26
+ Wait until the process finishes loading the model and you see "Uvicorn running on ...". Now, refresh your Gradio web UI, and you will see the model you just launched in the model list.
27
+
28
+ You can launch as many workers as you want, and compare between different model checkpoints in the same Gradio interface. Please keep the `--controller` the same, and modify the `--port` and `--worker` to a different port number for each worker.
29
+
30
+
31
+ ## Training
32
+
33
+ Please see sample training scripts for [LoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh) and [QLoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_qlora.sh).
34
+
35
+ We provide sample DeepSpeed configs, [`zero3.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3.json) is more like PyTorch FSDP, and [`zero3_offload.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3_offload.json) can further save memory consumption by offloading parameters to CPU. `zero3.json` is usually faster than `zero3_offload.json` but requires more GPU memory, therefore, we recommend trying `zero3.json` first, and if you run out of GPU memory, try `zero3_offload.json`. You can also tweak the `per_device_train_batch_size` and `gradient_accumulation_steps` in the config to save memory, and just to make sure that `per_device_train_batch_size` and `gradient_accumulation_steps` remains the same.
36
+
37
+ If you are having issues with ZeRO-3 configs, and there are enough VRAM, you may try [`zero2.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero2.json). This consumes slightly more memory than ZeRO-3, and behaves more similar to PyTorch FSDP, while still supporting parameter-efficient tuning.
38
+
39
+ ## Create Merged Checkpoints
40
+
41
+ ```Shell
42
+ python scripts/merge_lora_weights.py \
43
+ --model-path /path/to/lora_model \
44
+ --model-base /path/to/base_model \
45
+ --save-model-path /path/to/merge_model
46
+ ```
docs/MODEL_ZOO.md ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Zoo
2
+
3
+ **To Use LLaVA-1.6 checkpoints, your llava package version must be newer than 1.2.0. [Instructions](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base) on how to upgrade.**
4
+
5
+ If you are interested in including any other details in Model Zoo, please open an issue :)
6
+
7
+ The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license.
8
+
9
+ ## LLaVA-v1.6
10
+
11
+ | Version | LLM | Schedule | Checkpoint | MMMU | MathVista | VQAv2 | GQA | VizWiz | SQA | TextVQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED-IMG | LLaVA-Bench-Wild | MM-Vet |
12
+ |----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13
+ | LLaVA-1.6 | Vicuna-7B | full_ft-1e | [liuhaotian/llava-v1.6-vicuna-7b](https://huggingface.co/liuhaotian/llava-v1.6-vicuna-7b) | 35.8 | 34.6 | 81.8 | 64.2 | 57.6 | 70.1 | 64.9 | 86.5 | 1519/332 | 67.4 | 60.6 | 70.2 | 81.6 | 43.9 |
14
+ | LLaVA-1.6 | Vicuna-13B | full_ft-1e | [liuhaotian/llava-v1.6-vicuna-13b](https://huggingface.co/liuhaotian/llava-v1.6-vicuna-13b) | 36.2 | 35.3 | 82.8 | 65.4 | 60.5 | 73.6 | 67.1 | 86.2 | 1575/326 | 70 | 64.4 | 71.9 | 87.3 | 48.4 |
15
+ | LLaVA-1.6 | Mistral-7B | full_ft-1e | [liuhaotian/llava-v1.6-mistral-7b](https://huggingface.co/liuhaotian/llava-v1.6-mistral-7b) | 35.3 | 37.7 | 82.2 | 64.8 | 60.0 | 72.8 | 65.7 | 86.7 | 1498/321 | 68.7 | 61.2 | 72.2 | 83.2 | 47.3 |
16
+ | LLaVA-1.6 | Hermes-Yi-34B | full_ft-1e | [liuhaotian/llava-v1.6-34b](https://huggingface.co/liuhaotian/llava-v1.6-34b) | 51.1 | 46.5 | 83.7 | 67.1 | 63.8 | 81.8 | 69.5 | 87.7 | 1631/397 | 79.3 | 79 | 75.9 | 89.6 | 57.4 |
17
+
18
+ *LLaVA-1.6-34B outperforms Gemini Pro on benchmarks like MMMU and MathVista.*
19
+
20
+
21
+ ## LLaVA-v1.5
22
+
23
+ | Version | Size | Schedule | Checkpoint | VQAv2 | GQA | VizWiz | SQA | TextVQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED | LLaVA-Bench-Wild | MM-Vet |
24
+ |----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|
25
+ | LLaVA-1.5 | 7B | full_ft-1e | [liuhaotian/llava-v1.5-7b](https://huggingface.co/liuhaotian/llava-v1.5-7b) | 78.5 | 62.0 | 50.0 | 66.8 | 58.2 | 85.9 | 1510.7 | 64.3 | 58.3 | 58.6 | 65.4 | 31.1 |
26
+ | LLaVA-1.5 | 13B | full_ft-1e | [liuhaotian/llava-v1.5-13b](https://huggingface.co/liuhaotian/llava-v1.5-13b) | 80.0 | 63.3 | 53.6 | 71.6 | 61.3 | 85.9 | 1531.3 | 67.7 | 63.6 | 61.6 | 72.5 | 36.1 |
27
+ | LLaVA-1.5 | 7B | lora-1e | [liuhaotian/llava-v1.5-7b-lora](https://huggingface.co/liuhaotian/llava-v1.5-7b-lora) | 79.1 | 63.0 | 47.8 | 68.4 | 58.2 | 86.4 | 1476.9 | 66.1 | 58.9 | 60.1 | 67.9 | 30.2 |
28
+ | LLaVA-1.5 | 13B | lora-1e | [liuhaotian/llava-v1.5-13b-lora](https://huggingface.co/liuhaotian/llava-v1.5-13b-lora) | 80.0 | 63.3 | 58.9 | 71.2 | 60.2 | 86.7 | 1541.7 | 68.5 | 61.5 | 61.3 | 69.5 | 38.3 |
29
+
30
+ Base model: Vicuna v1.5. Training logs: [wandb](https://api.wandb.ai/links/lht/6orh56wc).
31
+
32
+ <p align="center">
33
+ <img src="../images/llava_v1_5_radar.jpg" width="500px"> <br>
34
+ LLaVA-1.5 achieves SoTA performance across 11 benchmarks.
35
+ </p>
36
+
37
+
38
+ ## LLaVA-v1
39
+
40
+ *Note: We recommend using the most capable LLaVA-v1.5 series above for the best performance.*
41
+
42
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | LLaVA-Bench-Conv | LLaVA-Bench-Detail | LLaVA-Bench-Complex | LLaVA-Bench-Overall | Download |
43
+ |----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|--------------------|---------------------|---------------------|---------------------|
44
+ | Vicuna-13B-v1.3 | CLIP-L-336px | LCS-558K | 1e | LLaVA-Instruct-80K | proj-1e, lora-1e | 64.3 | 55.9 | 81.7 | 70.1 | [LoRA](https://huggingface.co/liuhaotian/llava-v1-0719-336px-lora-vicuna-13b-v1.3) [LoRA-Merged](https://huggingface.co/liuhaotian/llava-v1-0719-336px-lora-merge-vicuna-13b-v1.3) |
45
+ | LLaMA-2-13B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | 56.7 | 58.6 | 80.0 | 67.9 | [ckpt](https://huggingface.co/liuhaotian/llava-llama-2-13b-chat-lightning-preview) |
46
+ | LLaMA-2-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | lora-1e | 51.2 | 58.9 | 71.6 | 62.8 | [LoRA](https://huggingface.co/liuhaotian/llava-llama-2-7b-chat-lightning-lora-preview) |
47
+
48
+
49
+ ## Projector weights
50
+
51
+ These are projector weights we have pretrained. You can use these projector weights for visual instruction tuning. They are just pretrained on image-text pairs and are NOT instruction-tuned, which means they do NOT follow instructions as well as our official models and can output repetitive, lengthy, and garbled outputs. If you want to have nice conversations with LLaVA, use the checkpoints above (LLaVA v1.5).
52
+
53
+ NOTE: These projector weights are only compatible with `llava>=1.0.0`. Please check out the latest codebase if your local code version is below v1.0.0.
54
+
55
+ NOTE: When you use our pretrained projector for visual instruction tuning, it is very important to use the same base LLM and vision encoder as the one we used for pretraining the projector. Otherwise, the performance will be very poor.
56
+
57
+ When using these projector weights to instruction-tune your LMM, please make sure that these options are correctly set as follows,
58
+
59
+ ```Shell
60
+ --mm_use_start_end False
61
+ --mm_use_patch_token False
62
+ ```
63
+
64
+ | Base LLM | Vision Encoder | Projection | Pretrain Data | Pretraining schedule | Download |
65
+ |----------|----------------|---------------|----------------------|----------|----------|
66
+ | Vicuna-13B-v1.5 | CLIP-L-336px | MLP-2x | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-13b-v1.5) |
67
+ | Vicuna-7B-v1.5 | CLIP-L-336px | MLP-2x | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-v1.5-mlp2x-336px-pretrain-vicuna-7b-v1.5) |
68
+ | LLaMA-2-13B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-13b-chat) |
69
+ | LLaMA-2-7B-Chat | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-llama-2-7b-chat) |
70
+ | LLaMA-2-13B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-13b-chat) |
71
+ | LLaMA-2-7B-Chat | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-llama-2-7b-chat) |
72
+ | Vicuna-13B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-13b-v1.3) |
73
+ | Vicuna-7B-v1.3 | CLIP-L-336px | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-336px-pretrain-vicuna-7b-v1.3) |
74
+ | Vicuna-13B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-13b-v1.3) |
75
+ | Vicuna-7B-v1.3 | CLIP-L | Linear | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/llava-pretrain-vicuna-7b-v1.3) |
76
+
77
+
78
+ ## Science QA Checkpoints
79
+
80
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
81
+ |----------|----------------|---------------|----------------------|-----------------|--------------------|---------------------|
82
+ | Vicuna-13B-v1.3 | CLIP-L | LCS-558K | 1e | ScienceQA | full_ft-12e | [ckpt](https://huggingface.co/liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3) |
83
+
84
+
85
+ ## Legacy Models (merged weights)
86
+
87
+ The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license.
88
+
89
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
90
+ |----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|
91
+ | MPT-7B-Chat | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [preview](https://huggingface.co/liuhaotian/LLaVA-Lightning-MPT-7B-preview) |
92
+
93
+
94
+ ## Legacy Models (delta weights)
95
+
96
+ The model weights below are *delta* weights. The usage of LLaVA checkpoints should comply with the base LLM's model license: [LLaMA](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md).
97
+
98
+ You can add our delta to the original LLaMA weights to obtain the LLaVA weights.
99
+
100
+ Instructions:
101
+
102
+ 1. Get the original LLaMA weights in the huggingface format by following the instructions [here](https://huggingface.co/docs/transformers/main/model_doc/llama).
103
+ 2. Use the following scripts to get LLaVA weights by applying our delta. It will automatically download delta weights from our Hugging Face account. In the script below, we use the delta weights of [`liuhaotian/LLaVA-7b-delta-v0`](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) as an example. It can be adapted for other delta weights by changing the `--delta` argument (and base/target accordingly).
104
+
105
+ ```bash
106
+ python3 -m llava.model.apply_delta \
107
+ --base /path/to/llama-7b \
108
+ --target /output/path/to/LLaVA-7B-v0 \
109
+ --delta liuhaotian/LLaVA-7b-delta-v0
110
+ ```
111
+
112
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Finetuning Data | Finetuning schedule | Download |
113
+ |----------|----------------|---------------|----------------------|-----------------|--------------------|------------------|
114
+ | Vicuna-13B-v1.1 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v1-1) |
115
+ | Vicuna-7B-v1.1 | CLIP-L | LCS-558K | 1e | LLaVA-Instruct-80K | full_ft-1e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-Lightning-7B-delta-v1-1) |
116
+ | Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0) |
117
+ | Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | ScienceQA | full_ft-12e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0-science_qa) |
118
+ | Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | LLaVA-Instruct-158K | full_ft-3e | [delta-weights](https://huggingface.co/liuhaotian/LLaVA-7b-delta-v0) |
119
+
120
+
121
+
122
+ ## Legacy Projector weights
123
+
124
+ The following projector weights are deprecated, and the support for them may be removed in the future. They do not support zero-shot inference. Please use the projector weights in the [table above](#projector-weights) if possible.
125
+
126
+ **NOTE**: When you use our pretrained projector for visual instruction tuning, it is very important to **use the same base LLM and vision encoder** as the one we used for pretraining the projector. Otherwise, the performance will be very bad.
127
+
128
+ When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
129
+
130
+ ```Shell
131
+ --mm_use_start_end True
132
+ --mm_use_patch_token False
133
+ ```
134
+
135
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download |
136
+ |----------|----------------|---------------|----------------------|----------|
137
+ | Vicuna-7B-v1.1 | CLIP-L | LCS-558K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v1-1-LCS-558K-blip_caption.bin) |
138
+ | Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption.bin) |
139
+ | Vicuna-7B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-7b-pretrain-projector-v0-CC3M-595K-original_caption.bin) |
140
+
141
+ When using these projector weights to instruction tune your LMM, please make sure that these options are correctly set as follows,
142
+
143
+ ```Shell
144
+ --mm_use_start_end False
145
+ --mm_use_patch_token False
146
+ ```
147
+
148
+ | Base LLM | Vision Encoder | Pretrain Data | Pretraining schedule | Download |
149
+ |----------|----------------|---------------|----------------------|----------|
150
+ | Vicuna-13B-v0 | CLIP-L | CC-595K | 1e | [projector](https://huggingface.co/liuhaotian/LLaVA-Pretrained-Projectors/blob/main/LLaVA-13b-pretrain-projector-v0-CC3M-595K-original_caption-no_im_token.bin) |
docs/ScienceQA.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### ScienceQA
2
+
3
+ #### Prepare Data
4
+ 1. Please see ScienceQA [repo](https://github.com/lupantech/ScienceQA) for setting up the dataset.
5
+ 2. Generate ScienceQA dataset for LLaVA conversation-style format.
6
+
7
+ ```Shell
8
+ python scripts/convert_sqa_to_llava.py \
9
+ convert_to_llava \
10
+ --base-dir /path/to/ScienceQA/data/scienceqa \
11
+ --prompt-format "QCM-LEA" \
12
+ --split {train,val,minival,test,minitest}
13
+ ```
14
+
15
+ #### Training
16
+
17
+ 1. Pretraining
18
+
19
+ You can download our pretrained projector weights from our [Model Zoo](), or train your own projector weights using [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/pretrain.sh).
20
+
21
+ 2. Finetuning
22
+
23
+ See [`finetune_sqa.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_sqa.sh).
24
+
25
+ #### Evaluation
26
+
27
+ 1. Multiple-GPU inference
28
+ You may evaluate this with multiple GPUs, and concatenate the generated jsonl files. Please refer to our script for [batch evaluation](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_batch.sh) and [results gathering](https://github.com/haotian-liu/LLaVA/blob/main/scripts/sqa_eval_gather.sh).
29
+
30
+ 2. Single-GPU inference
31
+
32
+ (a) Generate LLaVA responses on ScienceQA dataset
33
+
34
+ ```Shell
35
+ python -m llava.eval.model_vqa_science \
36
+ --model-path liuhaotian/llava-lcs558k-scienceqa-vicuna-13b-v1.3 \
37
+ --question-file /path/to/ScienceQA/data/scienceqa/llava_test_QCM-LEA.json \
38
+ --image-folder /path/to/ScienceQA/data/scienceqa/images/test \
39
+ --answers-file vqa/results/ScienceQA/test_llava-13b.jsonl \
40
+ --conv-mode llava_v1
41
+ ```
42
+
43
+ (b) Evaluate the generated responses
44
+
45
+ ```Shell
46
+ python eval_science_qa.py \
47
+ --base-dir /path/to/ScienceQA/data/scienceqa \
48
+ --result-file vqa/results/ScienceQA/test_llava-13b.jsonl \
49
+ --output-file vqa/results/ScienceQA/test_llava-13b_output.json \
50
+ --output-result vqa/results/ScienceQA/test_llava-13b_result.json \
51
+ ```
52
+
53
+ For reference, we attach our prediction file [`test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_lcs_558k_sqa_12e_vicuna_v1_3_13b.json) and [`test_sqa_llava_13b_v0.json`](https://github.com/haotian-liu/LLaVA/blob/main/llava/eval/table/results/test_sqa_llava_13b_v0.json) for comparison when reproducing our results, as well as for further analysis in detail.
docs/Windows.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run LLaVA on Windows
2
+
3
+ *NOTE: LLaVA on Windows is not fully supported. Currently we only support 16-bit inference. For a more complete support, please use [WSL2](https://learn.microsoft.com/en-us/windows/wsl/install) for now. More functionalities on Windows is to be added soon, stay tuned.*
4
+
5
+ ## Installation
6
+
7
+ 1. Clone this repository and navigate to LLaVA folder
8
+ ```bash
9
+ git clone https://github.com/haotian-liu/LLaVA.git
10
+ cd LLaVA
11
+ ```
12
+
13
+ 2. Install Package
14
+ ```Shell
15
+ conda create -n llava python=3.10 -y
16
+ conda activate llava
17
+ python -mpip install --upgrade pip # enable PEP 660 support
18
+ pip install torch==2.0.1+cu117 torchvision==0.15.2+cu117 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu117
19
+ pip install -e .
20
+ pip uninstall bitsandbytes
21
+ ```
22
+
23
+ ## Run demo
24
+
25
+ See instructions [here](https://github.com/haotian-liu/LLaVA#demo).
26
+
27
+ Note that quantization (4-bit, 8-bit) is *NOT* supported on Windows. Stay tuned for the 4-bit support on Windows!
docs/macOS.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run LLaVA on macOS
2
+
3
+ *NOTE: LLaVA on macOS is not fully supported. Currently we only support 16-bit inference. More functionalities on macOS is to be added soon, stay tuned.*
4
+
5
+ ## Installation
6
+
7
+ 1. Clone this repository and navigate to LLaVA folder
8
+ ```bash
9
+ git clone https://github.com/haotian-liu/LLaVA.git
10
+ cd LLaVA
11
+ ```
12
+
13
+ 2. Install Package
14
+ ```Shell
15
+ conda create -n llava python=3.10 -y
16
+ conda activate llava
17
+ python -mpip install --upgrade pip # enable PEP 660 support
18
+ pip install -e .
19
+ pip install torch==2.1.0 torchvision==0.16.0
20
+ pip uninstall bitsandbytes
21
+ ```
22
+
23
+ ## Run demo
24
+
25
+ Specify `--device mps` when launching model worker or CLI.
26
+
27
+ See instructions [here](https://github.com/haotian-liu/LLaVA#demo).
28
+
29
+ Note that quantization (4-bit, 8-bit) is *NOT* supported on macOS. Stay tuned for the 4-bit support on macOS!
flash_attn-2.3.6+cu122torch2.1cxx11abiFALSE-cp39-cp39-linux_x86_64.whl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6eed754c1d79b6ec4a695a6125107cf8dba714fc7cb32d093bbab98f3d7171f6
3
+ size 56476853
handler.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import torch
3
+ import os
4
+ import random
5
+ import base64
6
+ import msgpack
7
+ from io import BytesIO
8
+ import numpy as np
9
+
10
+ from transformers import AutoTokenizer
11
+ from llava.constants import MM_TOKEN_INDEX, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN, DEFAULT_VIDEO_TOKEN, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
12
+ from llava.conversation import conv_templates, SeparatorStyle
13
+ from llava.utils import disable_torch_init
14
+ from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria, process_images_v2
15
+ from llava.model.builder import load_pretrained_model
16
+ from llava.model.multimodal_encoder.processor import Blip2ImageTrainProcessor
17
+ from llava.model import LlavaMistralForCausalLM
18
+
19
+
20
+ from transformers import CLIPImageProcessor
21
+ from PIL import Image
22
+ import logging
23
+ import time
24
+ from concurrent.futures import ThreadPoolExecutor, as_completed
25
+ import threading
26
+
27
+ def select_frames(input_frames, num_segments = 10):
28
+
29
+ indices = np.linspace(start=0, stop=len(input_frames)-1, num=num_segments).astype(int)
30
+
31
+ frames = [input_frames[ind] for ind in indices]
32
+
33
+ return frames
34
+
35
+ def load_model(model_path, device_map):
36
+ kwargs = {"device_map": device_map}
37
+ kwargs['torch_dtype'] = torch.float16 #difference with cpu handler but it needs float16 to ensure no memory issue
38
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
39
+ model = LlavaMistralForCausalLM.from_pretrained(
40
+ model_path,
41
+ low_cpu_mem_usage=True,
42
+ **kwargs
43
+ )
44
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN], special_tokens=True)
45
+ model.resize_token_embeddings(len(tokenizer))
46
+
47
+ vision_tower = model.get_vision_tower()
48
+ if not vision_tower.is_loaded:
49
+ vision_tower.load_model(device_map=device_map)
50
+
51
+ return model, tokenizer
52
+
53
+
54
+ class EndpointHandler:
55
+
56
+ def __init__(self):
57
+ model_path = './masp_094_v2'
58
+ disable_torch_init()
59
+ model_path = os.path.expanduser(model_path)
60
+ #print(model_path)
61
+ model_name = get_model_name_from_path(model_path)
62
+
63
+ model, tokenizer = load_model(model_path, device_map={"":0})
64
+
65
+ image_processor = Blip2ImageTrainProcessor(
66
+ image_size=model.config.img_size,
67
+ is_training=False)
68
+
69
+ """
70
+ import os
71
+ from PIL import Image
72
+ input_dir = './v12044gd0000clg1n4fog65p7pag5n6g/video'
73
+ image_paths = os.listdir(input_dir)
74
+ images = [Image.open(os.path.join(input_dir, item)) for item in image_paths]
75
+ num_segments = 10
76
+ images = images[:num_segments]
77
+
78
+ import torch
79
+ device = torch.device('cuda:0')
80
+ image_processor = Blip2ImageTrainProcessor(
81
+ image_size=224,
82
+ is_training=False)
83
+ images_tensor = [image_processor.preprocess(image).cpu().to(device) for image in images]
84
+ """
85
+
86
+ self.tokenizer = tokenizer
87
+ self.device = torch.device('cuda:0') #another difference here
88
+ self.model = model.to(self.device)
89
+
90
+ self.image_processor = image_processor
91
+ self.conv_mode = 'v1'
92
+
93
+ def inference_frames_batch(self, batch_image_lists, batch_prompts, batch_temperatures):
94
+ start_time = time.perf_counter() # Start timer
95
+
96
+ batch_size = len(batch_image_lists)
97
+
98
+ # Process images and prompts for each item in the batch
99
+ images_tensors_list = []
100
+ input_ids_list = []
101
+ for images, prompt in zip(batch_image_lists, batch_prompts):
102
+ # Select frames (ensure consistent number of frames)
103
+ if len(images) > 10:
104
+ images = select_frames(images)
105
+ if len(images) < 10:
106
+ images += [images[-1]] * (10 - len(images)) # Pad to 10 frames
107
+
108
+ # Process images
109
+ images_tensor = process_images_v2(images, self.image_processor, self.model.config)
110
+ images_tensor = images_tensor.half().to(self.device) # Ensure correct dtype and device
111
+ images_tensors_list.append(images_tensor)
112
+
113
+ # Prepare the prompt
114
+ if len(images) == 1:
115
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + prompt
116
+ else:
117
+ qs = DEFAULT_VIDEO_START_TOKEN + DEFAULT_VIDEO_TOKEN + DEFAULT_VIDEO_END_TOKEN + '\n' + prompt
118
+
119
+ # Build conversation and tokenize
120
+ conv = conv_templates[self.conv_mode].copy()
121
+ conv.append_message(conv.roles[0], qs)
122
+ conv.append_message(conv.roles[1], None)
123
+ prompt_text = conv.get_prompt()
124
+
125
+ input_ids = tokenizer_image_token(prompt_text, self.tokenizer, MM_TOKEN_INDEX, return_tensors='pt').squeeze(0)
126
+ input_ids_list.append(input_ids)
127
+
128
+ # Pad input IDs to the same length
129
+ input_ids_padded = torch.nn.utils.rnn.pad_sequence(
130
+ input_ids_list,
131
+ batch_first=True,
132
+ padding_value=self.tokenizer.pad_token_id
133
+ ).to(self.device)
134
+
135
+ # No need to stack images_tensors_list into a tensor
136
+ # Each item in images_tensors_list is a tensor of shape (num_frames, C, H, W)
137
+
138
+ # Prepare stopping criteria
139
+ conv = conv_templates[self.conv_mode].copy()
140
+ stop_str = conv.sep if conv.sep2 is None else conv.sep2
141
+ keywords = [stop_str]
142
+ stopping_criteria = KeywordsStoppingCriteria(keywords, self.tokenizer, input_ids_padded)
143
+
144
+ # Use the first temperature for simplicity
145
+ temperature = batch_temperatures[0]
146
+
147
+ # Perform model inference
148
+ with torch.inference_mode():
149
+ output_ids = self.model.generate(
150
+ input_ids_padded,
151
+ images=images_tensors_list,
152
+ temperature=temperature,
153
+ do_sample=True,
154
+ top_p=None,
155
+ num_beams=1,
156
+ no_repeat_ngram_size=3,
157
+ max_new_tokens=1024,
158
+ use_cache=True,
159
+ stopping_criteria=[stopping_criteria],
160
+ )
161
+
162
+ # Decode outputs
163
+ outputs = []
164
+ for output_id in output_ids:
165
+ output = self.tokenizer.decode(output_id, skip_special_tokens=True).strip()
166
+ output = output.rstrip(stop_str).strip()
167
+ outputs.append(output)
168
+
169
+ end_time = time.perf_counter() # End timer
170
+ latency = end_time - start_time
171
+ print(f"Latency for this batch inference: {latency:.4f} seconds")
172
+
173
+ return outputs
174
+
175
+ def __call__(self, request):
176
+
177
+ # Unpack the images and prompts
178
+ packed_data_list = request['images'] # List of packed image data
179
+ prompt_list = request.get('prompt', [''.encode()] * len(packed_data_list))
180
+ temperature_list = request.get('temperature', ['0.01'.encode()] * len(packed_data_list))
181
+
182
+ # Initialize lists to collect images, prompts, and temperatures
183
+ all_image_lists = [] # List of lists of images
184
+ all_prompts = []
185
+ all_temperatures = []
186
+
187
+ for packed_data, prompt_encoded, temperature_encoded in zip(packed_data_list, prompt_list, temperature_list):
188
+ # Unpack the images
189
+ unpacked_data = msgpack.unpackb(packed_data, raw=False)
190
+ image_list = [Image.open(BytesIO(byte_data)).convert('RGB') for byte_data in unpacked_data]
191
+ all_image_lists.append(image_list)
192
+
193
+ # Decode the prompt
194
+ prompt = prompt_encoded.decode()
195
+ if prompt == '':
196
+ if len(image_list) == 1:
197
+ prompt = "Please describe this image in detail."
198
+ else:
199
+ prompt = "Describe the following video in detail."
200
+ all_prompts.append(prompt)
201
+
202
+ # Decode the temperature
203
+ temperature = float(temperature_encoded.decode())
204
+ all_temperatures.append(temperature)
205
+
206
+ # Now process all_image_lists and all_prompts in batch
207
+ with torch.no_grad():
208
+ outputs = self.inference_frames_batch(all_image_lists, all_prompts, all_temperatures)
209
+
210
+ return {'output': outputs}
211
+
212
+ def benchmark_qps_batched(handler, batched_request, num_batches=10):
213
+ start_time = time.perf_counter()
214
+ completed_samples = 0
215
+
216
+ for _ in range(num_batches):
217
+ handler(batched_request)
218
+ completed_samples += len(batched_request['images'])
219
+
220
+ end_time = time.perf_counter()
221
+ total_time = end_time - start_time
222
+ qps = completed_samples / total_time
223
+ print(f"Processed {completed_samples} samples in {total_time:.2f} seconds. QPS: {qps:.2f}")
224
+
225
+ if __name__ == "__main__":
226
+ # 7347652962333773061
227
+ video_dir = './v12044gd0000cl5c6rfog65i2eoqcqig'
228
+ #video_dir = '/mnt/bn/data-tns-algo-masp/kaili.zhao/data/masp_data/train/human_annotation/video_frames_2fps/7347652962333773061'
229
+ frames = [(int(os.path.splitext(item)[0]), os.path.join(video_dir, item)) for item in os.listdir(video_dir)]
230
+ frames = [item[1] for item in sorted(frames, key=lambda x: x[0])]
231
+ out_frames = [Image.open(frame).convert('RGB') for frame in frames]
232
+
233
+ # out_frames = select_frames(frames)
234
+
235
+ # Number of samples to include in the batch
236
+ batch_size = 4 # Adjust based on GPU memory
237
+
238
+ # Prepare batched data
239
+ batched_packed_data = []
240
+ batched_prompts = []
241
+ batched_temperatures = []
242
+
243
+ for _ in range(batch_size):
244
+ # Convert images to byte format
245
+ byte_images = []
246
+ for img in out_frames:
247
+ byte_io = BytesIO()
248
+ img.save(byte_io, format='JPEG')
249
+ byte_images.append(byte_io.getvalue())
250
+
251
+ # Pack the byte data with msgpack
252
+ packed_data = msgpack.packb(byte_images)
253
+ batched_packed_data.append(packed_data)
254
+
255
+ # Add prompt and temperature for each sample
256
+ batched_prompts.append(''.encode()) # Or specific prompts
257
+ batched_temperatures.append('0.01'.encode())
258
+
259
+ # Create the batched request
260
+ batched_request = {
261
+ 'images': batched_packed_data,
262
+ 'prompt': batched_prompts,
263
+ 'temperature': batched_temperatures,
264
+ }
265
+
266
+ handler = EndpointHandler()
267
+
268
+ # Measure latency for the batched request
269
+ #print("\nMeasuring latency for batched request...")
270
+ response = handler(batched_request)
271
+ print(response)#['output'])
272
+
273
+ # Benchmark QPS with batched requests
274
+ # print("\nBenchmarking QPS with batched requests...")
275
+ # num_batches = 10 # Number of batched requests
276
+ # benchmark_qps_batched(handler, batched_request, num_batches=num_batches)
handler_cpu.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import torch
3
+ import os
4
+ import random
5
+ import base64
6
+ import msgpack
7
+ from io import BytesIO
8
+ import numpy as np
9
+
10
+ from transformers import AutoTokenizer
11
+ from llava.constants import MM_TOKEN_INDEX, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN, DEFAULT_VIDEO_TOKEN, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
12
+ from llava.conversation import conv_templates, SeparatorStyle
13
+ from llava.utils import disable_torch_init
14
+ from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria, process_images_v2
15
+ from llava.model.builder import load_pretrained_model
16
+ from llava.model.multimodal_encoder.processor import Blip2ImageTrainProcessor
17
+ from llava.model import LlavaMistralForCausalLM
18
+
19
+
20
+ from transformers import CLIPImageProcessor
21
+ from PIL import Image
22
+ import logging
23
+
24
+ def select_frames(input_frames, num_segments = 10):
25
+
26
+ indices = np.linspace(start=0, stop=len(input_frames)-1, num=num_segments).astype(int)
27
+
28
+ frames = [input_frames[ind] for ind in indices]
29
+
30
+ return frames
31
+
32
+ def load_model(model_path, device_map):
33
+ kwargs = {"device_map": device_map}
34
+ kwargs['torch_dtype'] = torch.float32
35
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
36
+ model = LlavaMistralForCausalLM.from_pretrained(
37
+ model_path,
38
+ low_cpu_mem_usage=True,
39
+ **kwargs
40
+ )
41
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN], special_tokens=True)
42
+ model.resize_token_embeddings(len(tokenizer))
43
+
44
+ vision_tower = model.get_vision_tower()
45
+ if not vision_tower.is_loaded:
46
+ vision_tower.load_model(device_map=device_map)
47
+
48
+ return model, tokenizer
49
+
50
+
51
+ class EndpointHandler:
52
+
53
+ def __init__(self):
54
+ model_path = './checkpoint-3000'
55
+ disable_torch_init()
56
+ model_path = os.path.expanduser(model_path)
57
+ #print(model_path)
58
+ model_name = get_model_name_from_path(model_path)
59
+
60
+ model, tokenizer = load_model(model_path, device_map={"":0})
61
+
62
+ #tokenizer, model, _, context_len = load_pretrained_model(model_path, None, model_name, device_map={"":0})
63
+ image_processor = Blip2ImageTrainProcessor(
64
+ image_size=model.config.img_size,
65
+ is_training=False)
66
+
67
+ """
68
+ import os
69
+ from PIL import Image
70
+ input_dir = './v12044gd0000clg1n4fog65p7pag5n6g/video'
71
+ image_paths = os.listdir(input_dir)
72
+ images = [Image.open(os.path.join(input_dir, item)) for item in image_paths]
73
+ num_segments = 10
74
+ images = images[:num_segments]
75
+
76
+ import torch
77
+ device = torch.device('cuda:0')
78
+ image_processor = Blip2ImageTrainProcessor(
79
+ image_size=224,
80
+ is_training=False)
81
+ images_tensor = [image_processor.preprocess(image).cpu().to(device) for image in images]
82
+ """
83
+
84
+ self.tokenizer = tokenizer
85
+ self.device = torch.device('cpu')
86
+ self.model = model.to(self.device)
87
+
88
+ self.image_processor = image_processor
89
+ self.conv_mode = 'v1'
90
+
91
+ def inference_frames(self, images, question, temperature):
92
+
93
+ if len(images) > 10:
94
+ images = select_frames(images)
95
+
96
+ conv_mode = self.conv_mode
97
+ image_processor = self.image_processor
98
+ # if isinstance(image_processor, CLIPImageProcessor):
99
+ # images_tensor = [image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0].cpu().to(self.device) for image in images]
100
+ # else:
101
+ # logging.info(f'length of images:{len(images)}')
102
+ #images_tensor = [image_processor.preprocess(image).cpu() for image in images]
103
+ #images_tensor = torch.stack(images_tensor, dim=0).half().to(self.device)
104
+
105
+ images_tensor = process_images_v2(images, image_processor, self.model.config)
106
+ images_tensor = images_tensor.to(self.device)
107
+ # print(images_tensor.shape)
108
+
109
+ qs = question
110
+
111
+ if len(images) == 1:
112
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
113
+ else:
114
+ qs = DEFAULT_VIDEO_START_TOKEN + DEFAULT_VIDEO_TOKEN + DEFAULT_VIDEO_END_TOKEN + '\n' + qs
115
+
116
+ conv = conv_templates[conv_mode].copy()
117
+ conv.append_message(conv.roles[0], qs)
118
+ conv.append_message(conv.roles[1], None)
119
+ prompt = conv.get_prompt()
120
+
121
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, MM_TOKEN_INDEX, return_tensors='pt').unsqueeze(
122
+ 0).to(self.device)
123
+
124
+ stop_str = conv.sep if conv.sep2 is None else conv.sep2
125
+ keywords = [stop_str]
126
+ stopping_criteria = KeywordsStoppingCriteria(keywords, self.tokenizer, input_ids)
127
+
128
+ with torch.inference_mode():
129
+ output_ids = self.model.generate(
130
+ input_ids,
131
+ images=[images_tensor],
132
+ temperature=temperature,
133
+ do_sample=True,
134
+ top_p=None,
135
+ num_beams=1,
136
+ no_repeat_ngram_size=3,
137
+ max_new_tokens=1024,
138
+ use_cache=True,
139
+ stopping_criteria=[stopping_criteria],
140
+ )
141
+
142
+
143
+ outputs = self.tokenizer.decode(output_ids[0], skip_special_tokens=True).strip()
144
+
145
+ outputs = outputs.strip()
146
+ if outputs.endswith(conv.sep):
147
+ outputs = outputs[:-len(stop_str)]
148
+ outputs = outputs.strip()
149
+
150
+
151
+ # outputs = outputs[3:-4].strip()
152
+
153
+ return outputs
154
+
155
+ def __call__(self, request):
156
+
157
+ # Step 5: Unpack the data and convert back to PIL images
158
+ packed_data= request['images'][0]
159
+ unpacked_data = msgpack.unpackb(packed_data, raw=False)
160
+ image_list = [Image.open(BytesIO(byte_data)) for byte_data in unpacked_data]
161
+ prompt = request.get('prompt', [''.encode()])[0].decode()
162
+ temperature = request.get('temperature', ['0.01'.encode()])[0].decode()
163
+ temperature = float(temperature)
164
+
165
+ #print(request)
166
+
167
+ if prompt=='':
168
+ if len(image_list) == 1:
169
+ prompt = "Please describe this image in detail."
170
+ else:
171
+ prompt = "Please describe this video in detail."
172
+ # prompt = "Describe the following video in detail."
173
+
174
+ with torch.no_grad():
175
+ outputs = self.inference_frames(image_list, prompt, temperature)
176
+
177
+
178
+ return {'output': [outputs]}
179
+
180
+
181
+ if __name__ == "__main__":
182
+ video_dir = '/mnt/bn/yukunfeng-nasdrive/xiangchen/masp_data/20231110_ttp/video/v12044gd0000cl5c6rfog65i2eoqcqig'
183
+ frames = [(int(os.path.splitext(item)[0]), os.path.join(video_dir, item)) for item in os.listdir(video_dir)]
184
+ frames = [item[1] for item in sorted(frames, key=lambda x: x[0])]
185
+ out_frames = [Image.open(frame).convert('RGB') for frame in frames]
186
+
187
+ # out_frames = select_frames(frames)
188
+
189
+ request = {}
190
+
191
+ # Step 3: Convert images to byte format
192
+ byte_images = []
193
+ for img in out_frames:
194
+ byte_io = BytesIO()
195
+ img.save(byte_io, format='JPEG')
196
+ byte_images.append(byte_io.getvalue())
197
+
198
+ # Step 4: Pack the byte data with msgpack
199
+ packed_data = msgpack.packb(byte_images)
200
+ request['images'] = [packed_data]
201
+ # request['temperature'] = ['0.2'.encode()]
202
+ request['temperature'] = ['0.01'.encode()]
203
+ # request['prompt'] = ['describe the image in detail'.encode()]
204
+
205
+ #new_request = {}
206
+ #new_request['0'] = request['2']
207
+ handler = EndpointHandler()
208
+ print(handler(request))
209
+
images/demo_cli.gif ADDED

Git LFS Details

  • SHA256: 09227563f4fe04f077587eeb7b7c33ace2fbb8830e6cc9cfce03a25a57c43bfe
  • Pointer size: 133 Bytes
  • Size of remote file: 10 MB
inference_deployment/__init__.py ADDED
File without changes
inference_deployment/convert2inf2.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import torch
3
+ import os
4
+ import random
5
+ from io import BytesIO
6
+ import numpy as np
7
+ import time
8
+ from llava.constants import MM_TOKEN_INDEX, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN, DEFAULT_VIDEO_TOKEN, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
9
+ from llava.conversation import conv_templates, SeparatorStyle
10
+ from llava.utils import disable_torch_init
11
+ from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria, process_images_v2
12
+ from llava.model.builder import load_pretrained_model
13
+ from llava.model.multimodal_encoder.processor import Blip2ImageTrainProcessor
14
+ from llava.model import LlavaMistralForCausalLM
15
+ from llava.model.multimodal_encoder.eva_vit import create_eva_vit_g
16
+ import torch_neuronx
17
+ import torch
18
+ import torch_neuronx
19
+ from llava.model import LlavaMistralForCausalLM
20
+ from transformers import AutoTokenizer
21
+ from llava.constants import MM_TOKEN_INDEX, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN, DEFAULT_VIDEO_TOKEN, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
22
+
23
+
24
+ from transformers import CLIPImageProcessor
25
+ from PIL import Image
26
+ import logging
27
+ from qformer_tian import BertConfig, BertModel
28
+
29
+
30
+ def select_frames(input_frames, num_segments = 10):
31
+
32
+ indices = np.linspace(start=0, stop=len(input_frames)-1, num=num_segments).astype(int)
33
+
34
+ frames = [input_frames[ind] for ind in indices]
35
+
36
+ return frames
37
+
38
+
39
+ def generate_input_ids(tokenizer):
40
+ conv = conv_templates['v1'].copy()
41
+ qs = "Describe the following video in detail."
42
+ qs = DEFAULT_VIDEO_START_TOKEN + DEFAULT_VIDEO_TOKEN + DEFAULT_VIDEO_END_TOKEN + '\n' + qs
43
+ conv.append_message(conv.roles[0], qs)
44
+ conv.append_message(conv.roles[1], None)
45
+ prompt = conv.get_prompt()
46
+ input_ids = tokenizer_image_token(prompt, tokenizer, MM_TOKEN_INDEX, return_tensors='pt').unsqueeze(0)
47
+ return input_ids, conv
48
+
49
+ def uniform_sample(frames, num_segments):
50
+ indices = np.linspace(start=0, stop=len(frames) - 1, num=num_segments).astype(int)
51
+ frames = [frames[ind] for ind in indices]
52
+ return frames
53
+
54
+ save_root = './inf2_weights'
55
+ if not os.path.isdir(save_root):
56
+ os.makedirs(save_root)
57
+
58
+ EVITG_SAVE_PATH = os.path.join(save_root, 'neuron_eva_vit_batch7.pth')
59
+ LAYERNORM_SAVE_PATH = os.path.join(save_root, 'ln_state_dict.pth')
60
+ QUERYTOKEN_SAVE_PATH = os.path.join(save_root, 'query_tokens.pth')
61
+ BERT_SAVE_PATH = os.path.join(save_root, 'neuron_bert.pth')
62
+ POSITION_ENCODING_SAVE_PATH = os.path.join(save_root, 'frame_position_encoding.pth')
63
+ PROJECTOR_SAVE_PATH = os.path.join(save_root, 'projector.pth')
64
+ EMBED_TOKENS_SAVE_PATH = os.path.join(save_root, 'embed_tokens.pth')
65
+
66
+
67
+ model_path = './llava-mistral_videollava_ptv12_250k_samep_only_sopv2_mistralv2_scratch/'
68
+ disable_torch_init()
69
+ #print(model_path)
70
+ device_map={"":'cpu'}
71
+ kwargs = {"device_map": device_map}
72
+ kwargs['torch_dtype'] = torch.float32
73
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
74
+ model = LlavaMistralForCausalLM.from_pretrained(
75
+ model_path,
76
+ low_cpu_mem_usage=True,
77
+ **kwargs
78
+ )
79
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN], special_tokens=True)
80
+ model.resize_token_embeddings(len(tokenizer))
81
+
82
+ model.config.vit_precision == 'fp32'
83
+ vision_tower = model.get_vision_tower()
84
+ vision_tower.is_loaded = False
85
+ vision_tower.load_model(device_map=device_map)
86
+ vision_tower = vision_tower.to(torch.float32)
87
+
88
+ vision_tower = vision_tower.eval()
89
+ print('vision tower hiidden size')
90
+ print(vision_tower.hidden_size)
91
+
92
+ batch_size=7
93
+ img_size=224
94
+ input_shape = (batch_size, 3, img_size, img_size)
95
+ input_data=torch.zeros(input_shape, dtype=torch.float32)
96
+ model_neuronx = torch_neuronx.trace(vision_tower, input_data, compiler_args=["--model-type=transformer"])
97
+ model_neuronx.save(EVITG_SAVE_PATH)
98
+
99
+ image_processor = Blip2ImageTrainProcessor(
100
+ image_size=model.config.img_size,
101
+ is_training=False)
102
+
103
+ input_ids, conv = generate_input_ids(tokenizer)
104
+ device = torch.device('cpu')
105
+ model = model.to(device)
106
+ conv_mode = 'v1'
107
+ NUM_SEGMENTS = 10
108
+
109
+ video_dir = './v12044gd0000cl5c6rfog65i2eoqcqig'
110
+ frames = [(int(os.path.splitext(item)[0]), os.path.join(video_dir, item)) for item in os.listdir(video_dir)]
111
+ frames = [item[1] for item in sorted(frames, key=lambda x: x[0])]
112
+ images = [Image.open(frame).convert('RGB') for frame in frames]
113
+ images = uniform_sample(images, NUM_SEGMENTS)
114
+ images = process_images_v2(images, image_processor, model.config)
115
+
116
+ #save layer norm
117
+ ln_vision = model.get_ln_vision()
118
+ ln_vision = ln_vision.eval()
119
+ ln_state_dict = ln_vision.state_dict()
120
+ torch.save(ln_state_dict, LAYERNORM_SAVE_PATH)
121
+
122
+
123
+ query_tokens = model.get_query_tokens()
124
+ #save query tokens
125
+ query_tokens_state_dict = {'query_tokens': query_tokens.data}
126
+ torch.save(query_tokens_state_dict, QUERYTOKEN_SAVE_PATH)
127
+
128
+ #save qformer
129
+ qformer = model.get_qformer()
130
+ bert_torch = qformer.bert
131
+ bert_torch = bert_torch.eval()
132
+ bert_torch = bert_torch.to(torch.float32)
133
+
134
+
135
+ vision_width = 1408
136
+ cross_attention_freq = 2
137
+ num_query_token = 32
138
+ encoder_config = BertConfig.from_pretrained("bert-base-uncased")
139
+ encoder_config.encoder_width = vision_width
140
+ # insert cross-attention layer every other block
141
+ encoder_config.add_cross_attention = True
142
+ encoder_config.cross_attention_freq = cross_attention_freq
143
+ encoder_config.query_length = num_query_token
144
+ bert = BertModel(encoder_config, add_pooling_layer=False)
145
+ bert.embeddings.word_embeddings = None
146
+ bert.embeddings.position_embeddings = None
147
+
148
+ for layer in bert.encoder.layer:
149
+ layer.output = None
150
+ layer.intermediate = None
151
+
152
+
153
+ bert.load_state_dict(bert_torch.state_dict())
154
+ bert = bert.eval()
155
+
156
+ input_example = (
157
+ torch.zeros(70, 32, 768, dtype=torch.float32),
158
+ torch.zeros(70, 256, 1408, dtype=torch.float32),
159
+ torch.zeros(70, 256, dtype=torch.int64)
160
+ )
161
+ neuron_bert = torch_neuronx.trace(bert, input_example)
162
+ neuron_bert.save(BERT_SAVE_PATH)
163
+
164
+ #save projector and frame position encoding
165
+ frame_position_encoding = model.get_frame_position_encoding()
166
+ projector = model.get_model().mm_projector
167
+
168
+ frame_position_encoding = frame_position_encoding.eval()
169
+ frame_position_encoding = frame_position_encoding.to(torch.float32)
170
+
171
+ projector = projector.eval()
172
+ projector = projector.to(torch.float32)
173
+
174
+ torch.save(frame_position_encoding.state_dict(), POSITION_ENCODING_SAVE_PATH)
175
+ torch.save(projector.state_dict(), PROJECTOR_SAVE_PATH)
176
+
177
+ #save embed_tokenss
178
+ embed_tokens = model.get_model().embed_tokens
179
+ embed_tokens = embed_tokens.eval()
180
+ embed_tokens = embed_tokens.to(torch.float32)
181
+ torch.save(embed_tokens.state_dict(), EMBED_TOKENS_SAVE_PATH)
inference_deployment/predict.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llava.model.multimodal_encoder.processor import Blip2ImageTrainProcessor
2
+ from llava.model import LlavaMistralForCausalLM
3
+ from transformers import AutoTokenizer
4
+ from llava.constants import MM_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_VIDEO_PATCH_TOKEN, DEFAULT_VIDEO_TOKEN, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN
5
+ from llava.conversation import conv_templates
6
+ import torch
7
+ from llava.mm_utils import tokenizer_image_token
8
+ import numpy as np
9
+ from PIL import Image
10
+ import os
11
+
12
+
13
+ NUM_SEGMENTS = 10
14
+
15
+
16
+ def load_model(model_path, device_map):
17
+ kwargs = {"device_map": device_map}
18
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
19
+ model = LlavaMistralForCausalLM.from_pretrained(
20
+ model_path,
21
+ low_cpu_mem_usage=True,
22
+ **kwargs
23
+ )
24
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN], special_tokens=True)
25
+ model.resize_token_embeddings(len(tokenizer))
26
+
27
+ vision_tower = model.get_vision_tower()
28
+ if not vision_tower.is_loaded:
29
+ vision_tower.load_model(device_map=device_map)
30
+
31
+ image_processor = Blip2ImageTrainProcessor(
32
+ image_size=model.config.img_size,
33
+ is_training=False)
34
+ model.to(torch.float16)
35
+ return model, tokenizer, image_processor
36
+
37
+
38
+ def generate_input_ids(tokenizer):
39
+ conv = conv_templates['v1'].copy()
40
+ qs = "Describe the following video in detail."
41
+ qs = DEFAULT_VIDEO_START_TOKEN + DEFAULT_VIDEO_TOKEN + DEFAULT_VIDEO_END_TOKEN + '\n' + qs
42
+ conv.append_message(conv.roles[0], qs)
43
+ conv.append_message(conv.roles[1], None)
44
+ prompt = conv.get_prompt()
45
+ input_ids = tokenizer_image_token(prompt, tokenizer, MM_TOKEN_INDEX, return_tensors='pt').unsqueeze(0)
46
+ return input_ids
47
+
48
+
49
+ def generate_images(frame_folder, image_processor):
50
+ images = load_frames(frame_folder)
51
+ if len(images) > NUM_SEGMENTS:
52
+ images = uniform_sample(images, NUM_SEGMENTS)
53
+
54
+ new_images = []
55
+ for image in images:
56
+ image = image_processor.preprocess(image)
57
+ new_images.append(image)
58
+ if all(x.shape == new_images[0].shape for x in new_images):
59
+ new_images = torch.stack(new_images, dim=0)
60
+ return new_images
61
+
62
+
63
+ def uniform_sample(frames, num_segments):
64
+ indices = np.linspace(start=0, stop=len(frames) - 1, num=num_segments).astype(int)
65
+
66
+ frames = [frames[ind] for ind in indices]
67
+
68
+ return frames
69
+
70
+ def load_frames(frames_dir):
71
+ results = []
72
+ image_files = [(int(os.path.splitext(img)[0]), img) for img in os.listdir(frames_dir) if img.endswith('jpg')]
73
+ image_files = sorted(image_files, key=lambda img: img[0])
74
+
75
+ for frame_name in image_files:
76
+ image_path = f"{frames_dir}/{frame_name[1]}"
77
+ image = Image.open(image_path).convert('RGB')
78
+ results.append(image)
79
+ return results
80
+
81
+
82
+ class MASPVisionWrapper(torch.nn.Module):
83
+
84
+ def __init__(self, vision_tower, qformer, projector, query_tokens, frame_position_encoding, ln_vision):
85
+ super().__init__()
86
+ self.vision_tower = vision_tower
87
+ self.qformer = qformer
88
+ self.projector = projector
89
+ self.query_tokens = query_tokens
90
+ self.ln_vision = ln_vision
91
+ self.frame_position_encoding = frame_position_encoding
92
+
93
+ def forward(self, images):
94
+ # images: [num_frames, 3, image_size, image_size]
95
+ image_features = self.vision_tower(images)
96
+ image_features = self.ln_vision(image_features)
97
+ attn_mask = torch.ones(image_features.size()[:-1], dtype=torch.long).to(image_features.device) # [num_frames, 256]
98
+ query_tokens = self.query_tokens.expand(image_features.shape[0], -1, -1) # [num_frames, 32, 768]
99
+ dtype_ = self.vision_tower.dtype
100
+ image_features = self.qformer.bert(
101
+ query_embeds= query_tokens.to(dtype_),
102
+ encoder_hidden_states=image_features.to(dtype_),
103
+ encoder_attention_mask=attn_mask,
104
+ return_dict=True
105
+ ).last_hidden_state.to(dtype_)
106
+ frame_ids = torch.arange(image_features.shape[0], dtype=torch.long, device=image_features.device) # [num_frames]
107
+ image_features += self.frame_position_encoding(frame_ids).unsqueeze(-2) #[num_frames, 1, 768]
108
+ return self.projector(image_features)
109
+
110
+
111
+ def inference(model_path, frame_folder):
112
+ # prepare
113
+ model, tokenizer, image_processor = load_model(model_path, device_map={"":0})
114
+ input_ids = generate_input_ids(tokenizer)[0].to(model.device) # [token_len]
115
+ images = generate_images(frame_folder, image_processor).to(model.device) # [num_frames, 3, image_size, image_size]
116
+ vision_module = MASPVisionWrapper(
117
+ vision_tower=model.get_vision_tower(),
118
+ qformer=model.get_qformer(),
119
+ projector=model.get_model().mm_projector,
120
+ query_tokens=model.get_query_tokens(),
121
+ frame_position_encoding=model.get_frame_position_encoding(),
122
+ ln_vision=model.get_ln_vision(),
123
+ )
124
+
125
+ # infernece
126
+ with torch.inference_mode():
127
+ # get image feature
128
+ image_features = vision_module(images).flatten(0, 1) # [num_frames * num_query_token, 4096]
129
+ # concat with text features
130
+ vision_token_indice = torch.where(input_ids == MM_TOKEN_INDEX)[0][0]
131
+ pre_text_token = model.get_model().embed_tokens(input_ids[:vision_token_indice])
132
+ post_text_token = model.get_model().embed_tokens(input_ids[vision_token_indice+1:])
133
+ inputs_embeds = torch.cat([pre_text_token, image_features, post_text_token]).unsqueeze(0) # [1, num_token, 4096]
134
+ # llm.generate
135
+ output_ids = model.generate_from_base_class(
136
+ inputs_embeds=inputs_embeds,
137
+ do_sample=True,
138
+ temperature=0.01,
139
+ top_p=None,
140
+ num_beams=1,
141
+ max_new_tokens=1024,
142
+ pad_token_id=tokenizer.eos_token_id,
143
+ use_cache=True,
144
+ )
145
+ output = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
146
+ output = output.strip()
147
+ print(output)
148
+
149
+
150
+ if __name__ == '__main__':
151
+ model_path = '/mnt/bn/algo-masp-nas-2/xiangchen/model/masp_models/llava-thothv2_mar_release_all_data'
152
+ frame_folder = '/mnt/bn/yukunfeng-nasdrive/xiangchen/masp_data/20231110_ttp/video/v12044gd0000cl5c6rfog65i2eoqcqig'
153
+ inference(model_path, frame_folder)
inference_deployment/predict_v09.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llava.model.multimodal_encoder.processor import Blip2ImageTrainProcessor
2
+ from llava.model import LlavaThothForCausalLM
3
+ from transformers import AutoTokenizer
4
+ from llava.constants import MM_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_VIDEO_PATCH_TOKEN, DEFAULT_VIDEO_TOKEN, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN
5
+ from llava.conversation import conv_templates
6
+ import torch
7
+ from llava.mm_utils import tokenizer_image_token, process_images_v2, KeywordsStoppingCriteria
8
+ import numpy as np
9
+ from PIL import Image
10
+ import os
11
+
12
+
13
+ NUM_SEGMENTS = 10
14
+
15
+
16
+ def load_model(model_path, device_map):
17
+ kwargs = {"device_map": device_map}
18
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
19
+ model = LlavaThothForCausalLM.from_pretrained(
20
+ model_path,
21
+ low_cpu_mem_usage=True,
22
+ **kwargs
23
+ )
24
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, DEFAULT_VIDEO_START_TOKEN, DEFAULT_VIDEO_END_TOKEN], special_tokens=True)
25
+ model.resize_token_embeddings(len(tokenizer))
26
+
27
+ vision_tower = model.get_vision_tower()
28
+ if not vision_tower.is_loaded:
29
+ vision_tower.load_model(device_map=device_map)
30
+
31
+ image_processor = Blip2ImageTrainProcessor(
32
+ image_size=model.config.img_size,
33
+ is_training=False)
34
+ model.to(torch.float16)
35
+ return model, tokenizer, image_processor
36
+
37
+
38
+ def generate_input_ids(tokenizer):
39
+ conv = conv_templates['thoth'].copy()
40
+ qs = "Describe the following video in detail."
41
+ qs = DEFAULT_VIDEO_START_TOKEN + DEFAULT_VIDEO_TOKEN + DEFAULT_VIDEO_END_TOKEN + '\n' + qs
42
+ conv.append_message(conv.roles[0], qs)
43
+ conv.append_message(conv.roles[1], None)
44
+ prompt = conv.get_prompt()
45
+ input_ids = tokenizer_image_token(prompt, tokenizer, MM_TOKEN_INDEX, return_tensors='pt').unsqueeze(0)
46
+ return input_ids, conv
47
+
48
+
49
+ def generate_images(frame_folder, image_processor, model_cfg):
50
+ images = load_frames(frame_folder)
51
+ if len(images) > NUM_SEGMENTS:
52
+ images = uniform_sample(images, NUM_SEGMENTS)
53
+ return process_images_v2(images, image_processor, model_cfg)
54
+
55
+
56
+ def uniform_sample(frames, num_segments):
57
+ indices = np.linspace(start=0, stop=len(frames) - 1, num=num_segments).astype(int)
58
+ frames = [frames[ind] for ind in indices]
59
+ return frames
60
+
61
+ def load_frames(frames_dir):
62
+ results = []
63
+ image_files = [(int(os.path.splitext(img)[0]), img) for img in os.listdir(frames_dir) if img.endswith('jpg')]
64
+ image_files = sorted(image_files, key=lambda img: img[0])
65
+
66
+ for frame_name in image_files:
67
+ image_path = f"{frames_dir}/{frame_name[1]}"
68
+ image = Image.open(image_path).convert('RGB')
69
+ results.append(image)
70
+ return results
71
+
72
+
73
+ class MASPVisionWrapper(torch.nn.Module):
74
+
75
+ def __init__(self, vision_tower, qformer, projector, query_tokens, frame_position_encoding, ln_vision):
76
+ super().__init__()
77
+ self.vision_tower = vision_tower
78
+ self.qformer = qformer
79
+ self.projector = projector
80
+ self.query_tokens = query_tokens
81
+ self.ln_vision = ln_vision
82
+ self.frame_position_encoding = frame_position_encoding
83
+
84
+ def forward(self, images):
85
+ # images: [num_frames, patches, 3, image_size, image_size]
86
+ image_features = self.vision_tower(images.flatten(0, 1))
87
+ image_features = self.ln_vision(image_features)
88
+ attn_mask = torch.ones(image_features.size()[:-1], dtype=torch.long).to(image_features.device) # [num_frames * num_patches, 256]
89
+ query_tokens = self.query_tokens.expand(image_features.shape[0], -1, -1) # [num_frames * num_patches, 32, 768]
90
+ dtype_ = self.vision_tower.dtype
91
+ image_features = self.qformer.bert(
92
+ query_embeds= query_tokens.to(dtype_),
93
+ encoder_hidden_states=image_features.to(dtype_),
94
+ encoder_attention_mask=attn_mask,
95
+ return_dict=True
96
+ ).last_hidden_state.to(dtype_)
97
+ frame_ids = torch.arange(images.shape[0], dtype=torch.long, device=image_features.device).unsqueeze(1)
98
+ frame_ids = frame_ids.repeat(1, images.shape[1]).flatten(0, 1) # [num_frames * num_patches]
99
+ image_features += self.frame_position_encoding(frame_ids).unsqueeze(-2) #[num_frames, 1, 768]
100
+ return self.projector(image_features)
101
+
102
+
103
+ def inference(model_path, frame_folder):
104
+ # prepare
105
+ model, tokenizer, image_processor = load_model(model_path, device_map={"":0})
106
+ input_ids, conv = generate_input_ids(tokenizer)
107
+ images = generate_images(frame_folder, image_processor, model.config).to(model.device).half() # [num_frames, patches, 3, image_size, image_size]
108
+ vision_module = MASPVisionWrapper(
109
+ vision_tower=model.get_vision_tower(),
110
+ qformer=model.get_qformer(),
111
+ projector=model.get_model().mm_projector,
112
+ query_tokens=model.get_query_tokens(),
113
+ frame_position_encoding=model.get_frame_position_encoding(),
114
+ ln_vision=model.get_ln_vision(),
115
+ )
116
+ stop_str = conv.sep if conv.sep2 is None else conv.sep2
117
+ keywords = [stop_str]
118
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
119
+ input_ids = input_ids[0].to(model.device) # [token_len]
120
+
121
+ # infernece
122
+ with torch.inference_mode():
123
+ # get image feature
124
+ image_features = vision_module(images).flatten(0, 1) # [num_frames * num_patches * num_query_token, 4096]
125
+ # concat with text features
126
+ vision_token_indice = torch.where(input_ids == MM_TOKEN_INDEX)[0][0]
127
+ pre_text_token = model.get_model().embed_tokens(input_ids[:vision_token_indice])
128
+ post_text_token = model.get_model().embed_tokens(input_ids[vision_token_indice+1:])
129
+ inputs_embeds = torch.cat([pre_text_token, image_features, post_text_token]).unsqueeze(0) # [1, num_token, 4096]
130
+
131
+ # llm.generate
132
+ output_ids = model.generate_from_base_class(
133
+ inputs_embeds=inputs_embeds,
134
+ do_sample=True,
135
+ temperature=0.01,
136
+ top_p=None,
137
+ num_beams=1,
138
+ max_new_tokens=1024,
139
+ pad_token_id=tokenizer.eos_token_id,
140
+ use_cache=True,
141
+ stopping_criteria=[stopping_criteria]
142
+ )
143
+ output = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
144
+ output = output.strip()
145
+ print(output)
146
+
147
+
148
+ if __name__ == '__main__':
149
+ model_path = '/mnt/bn/algo-masp-nas-2/xiangchen/model/masp_models/llava-thothv2_mar_release_all_data'
150
+ frame_folder = '/mnt/bn/yukunfeng-nasdrive/xiangchen/masp_data/20231110_ttp/video/v12044gd0000cl5c6rfog65i2eoqcqig'
151
+ inference(model_path, frame_folder)
inference_deployment/qformer_tian.py ADDED
@@ -0,0 +1,1151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Adapted from salesforce@LAVIS. Below is the original copyright:
3
+ * Copyright (c) 2023, salesforce.com, inc.
4
+ * All rights reserved.
5
+ * SPDX-License-Identifier: BSD-3-Clause
6
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
+ * By Junnan Li
8
+ * Based on huggingface code base
9
+ * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert
10
+ """
11
+
12
+ import math
13
+ import os
14
+ import warnings
15
+ from dataclasses import dataclass
16
+ from typing import Optional, Tuple, Dict, Any
17
+
18
+ import torch
19
+ from torch import Tensor, device, dtype, nn
20
+ import torch.utils.checkpoint
21
+ from torch import nn
22
+ from torch.nn import CrossEntropyLoss
23
+ import torch.nn.functional as F
24
+
25
+ from transformers.activations import ACT2FN
26
+ from transformers.file_utils import (
27
+ ModelOutput,
28
+ )
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ BaseModelOutputWithPoolingAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ MaskedLMOutput,
34
+ MultipleChoiceModelOutput,
35
+ NextSentencePredictorOutput,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutput,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_utils import (
41
+ PreTrainedModel,
42
+ apply_chunking_to_forward,
43
+ find_pruneable_heads_and_indices,
44
+ prune_linear_layer,
45
+ )
46
+ from transformers.utils import logging
47
+ from transformers.models.bert.configuration_bert import BertConfig
48
+ from llava.model.utils import LayerNorm
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+
53
+ class BertEmbeddings(nn.Module):
54
+ """Construct the embeddings from word and position embeddings."""
55
+
56
+ def __init__(self, config):
57
+ super().__init__()
58
+ self.word_embeddings = None
59
+ self.position_embeddings = None
60
+
61
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
62
+ # any TensorFlow checkpoint file
63
+ # self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
64
+ self.LayerNorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
65
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
66
+
67
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
68
+ self.register_buffer(
69
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))
70
+ )
71
+ self.position_embedding_type = getattr(
72
+ config, "position_embedding_type", "absolute"
73
+ )
74
+
75
+ self.config = config
76
+
77
+ def forward(
78
+ self,
79
+ input_ids=None,
80
+ position_ids=None,
81
+ query_embeds=None,
82
+ past_key_values_length=0,
83
+ ):
84
+ seq_length = 0
85
+
86
+ position_ids = self.position_ids[
87
+ :, past_key_values_length : seq_length + past_key_values_length
88
+ ].clone()
89
+
90
+ embeddings = query_embeds
91
+
92
+ embeddings = self.LayerNorm(embeddings)
93
+ embeddings = self.dropout(embeddings)
94
+ return embeddings
95
+
96
+
97
+ class BertSelfAttention(nn.Module):
98
+ def __init__(self, config, is_cross_attention):
99
+ super().__init__()
100
+ self.config = config
101
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
102
+ config, "embedding_size"
103
+ ):
104
+ raise ValueError(
105
+ "The hidden size (%d) is not a multiple of the number of attention "
106
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
107
+ )
108
+
109
+ self.num_attention_heads = config.num_attention_heads
110
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
111
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
112
+
113
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
114
+ if is_cross_attention:
115
+ self.key = nn.Linear(config.encoder_width, self.all_head_size)
116
+ self.value = nn.Linear(config.encoder_width, self.all_head_size)
117
+ else:
118
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
119
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
120
+
121
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
122
+ self.position_embedding_type = getattr(
123
+ config, "position_embedding_type", "absolute"
124
+ )
125
+ if (
126
+ self.position_embedding_type == "relative_key"
127
+ or self.position_embedding_type == "relative_key_query"
128
+ ):
129
+ self.max_position_embeddings = config.max_position_embeddings
130
+ self.distance_embedding = nn.Embedding(
131
+ 2 * config.max_position_embeddings - 1, self.attention_head_size
132
+ )
133
+ self.save_attention = False
134
+
135
+ def save_attn_gradients(self, attn_gradients):
136
+ self.attn_gradients = attn_gradients
137
+
138
+ def get_attn_gradients(self):
139
+ return self.attn_gradients
140
+
141
+ def save_attention_map(self, attention_map):
142
+ self.attention_map = attention_map
143
+
144
+ def get_attention_map(self):
145
+ return self.attention_map
146
+
147
+ def transpose_for_scores(self, x):
148
+ new_x_shape = x.size()[:-1] + (
149
+ self.num_attention_heads,
150
+ self.attention_head_size,
151
+ )
152
+ x = x.view(*new_x_shape)
153
+ return x.permute(0, 2, 1, 3)
154
+
155
+ def forward(
156
+ self,
157
+ hidden_states,
158
+ attention_mask=None,
159
+ head_mask=None,
160
+ encoder_hidden_states=None,
161
+ encoder_attention_mask=None,
162
+ past_key_value=None,
163
+ output_attentions=False,
164
+ ):
165
+
166
+ # If this is instantiated as a cross-attention module, the keys
167
+ # and values come from an encoder; the attention mask needs to be
168
+ # such that the encoder's padding tokens are not attended to.
169
+ is_cross_attention = encoder_hidden_states is not None
170
+
171
+ if is_cross_attention:
172
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
173
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
174
+ attention_mask = encoder_attention_mask
175
+ elif past_key_value is not None:
176
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
177
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
178
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
179
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
180
+ else:
181
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
182
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
183
+
184
+ mixed_query_layer = self.query(hidden_states)
185
+
186
+ query_layer = self.transpose_for_scores(mixed_query_layer)
187
+
188
+ past_key_value = (key_layer, value_layer)
189
+
190
+ # Take the dot product between "query" and "key" to get the raw attention scores.
191
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
192
+
193
+ if (
194
+ self.position_embedding_type == "relative_key"
195
+ or self.position_embedding_type == "relative_key_query"
196
+ ):
197
+ seq_length = hidden_states.size()[1]
198
+ position_ids_l = torch.arange(
199
+ seq_length, dtype=torch.long, device=hidden_states.device
200
+ ).view(-1, 1)
201
+ position_ids_r = torch.arange(
202
+ seq_length, dtype=torch.long, device=hidden_states.device
203
+ ).view(1, -1)
204
+ distance = position_ids_l - position_ids_r
205
+ positional_embedding = self.distance_embedding(
206
+ distance + self.max_position_embeddings - 1
207
+ )
208
+ positional_embedding = positional_embedding.to(
209
+ dtype=query_layer.dtype
210
+ ) # fp16 compatibility
211
+
212
+ if self.position_embedding_type == "relative_key":
213
+ relative_position_scores = torch.einsum(
214
+ "bhld,lrd->bhlr", query_layer, positional_embedding
215
+ )
216
+ attention_scores = attention_scores + relative_position_scores
217
+ elif self.position_embedding_type == "relative_key_query":
218
+ relative_position_scores_query = torch.einsum(
219
+ "bhld,lrd->bhlr", query_layer, positional_embedding
220
+ )
221
+ relative_position_scores_key = torch.einsum(
222
+ "bhrd,lrd->bhlr", key_layer, positional_embedding
223
+ )
224
+ attention_scores = (
225
+ attention_scores
226
+ + relative_position_scores_query
227
+ + relative_position_scores_key
228
+ )
229
+
230
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
231
+ if attention_mask is not None:
232
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
233
+ attention_scores = attention_scores + attention_mask
234
+ # Normalize the attention scores to probabilities.
235
+ attention_probs = nn.Softmax(dim=-1)(attention_scores.to(torch.float32)).to(attention_scores.dtype)
236
+
237
+ if is_cross_attention and self.save_attention:
238
+ self.save_attention_map(attention_probs)
239
+ attention_probs.register_hook(self.save_attn_gradients)
240
+
241
+ # This is actually dropping out entire tokens to attend to, which might
242
+ # seem a bit unusual, but is taken from the original Transformer paper.
243
+ attention_probs_dropped = self.dropout(attention_probs)
244
+
245
+ # Mask heads if we want to
246
+ if head_mask is not None:
247
+ attention_probs_dropped = attention_probs_dropped * head_mask
248
+
249
+ context_layer = torch.matmul(attention_probs_dropped, value_layer)
250
+
251
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
252
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
253
+ context_layer = context_layer.view(*new_context_layer_shape)
254
+
255
+ outputs = (
256
+ (context_layer, attention_probs) if output_attentions else (context_layer,)
257
+ )
258
+
259
+ outputs = outputs + (past_key_value,)
260
+ return outputs
261
+
262
+
263
+ class BertSelfOutput(nn.Module):
264
+ def __init__(self, config):
265
+ super().__init__()
266
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
267
+ # self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
268
+ self.LayerNorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
269
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
270
+
271
+ def forward(self, hidden_states, input_tensor):
272
+ hidden_states = self.dense(hidden_states)
273
+ hidden_states = self.dropout(hidden_states)
274
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
275
+ return hidden_states
276
+
277
+
278
+ class BertAttention(nn.Module):
279
+ def __init__(self, config, is_cross_attention=False):
280
+ super().__init__()
281
+ self.self = BertSelfAttention(config, is_cross_attention)
282
+ self.output = BertSelfOutput(config)
283
+ self.pruned_heads = set()
284
+
285
+ def prune_heads(self, heads):
286
+ if len(heads) == 0:
287
+ return
288
+ heads, index = find_pruneable_heads_and_indices(
289
+ heads,
290
+ self.self.num_attention_heads,
291
+ self.self.attention_head_size,
292
+ self.pruned_heads,
293
+ )
294
+
295
+ # Prune linear layers
296
+ self.self.query = prune_linear_layer(self.self.query, index)
297
+ self.self.key = prune_linear_layer(self.self.key, index)
298
+ self.self.value = prune_linear_layer(self.self.value, index)
299
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
300
+
301
+ # Update hyper params and store pruned heads
302
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
303
+ self.self.all_head_size = (
304
+ self.self.attention_head_size * self.self.num_attention_heads
305
+ )
306
+ self.pruned_heads = self.pruned_heads.union(heads)
307
+
308
+ def forward(
309
+ self,
310
+ hidden_states,
311
+ attention_mask=None,
312
+ head_mask=None,
313
+ encoder_hidden_states=None,
314
+ encoder_attention_mask=None,
315
+ past_key_value=None,
316
+ output_attentions=False,
317
+ ):
318
+ self_outputs = self.self(
319
+ hidden_states,
320
+ attention_mask,
321
+ head_mask,
322
+ encoder_hidden_states,
323
+ encoder_attention_mask,
324
+ past_key_value,
325
+ output_attentions,
326
+ )
327
+ attention_output = self.output(self_outputs[0], hidden_states)
328
+
329
+ outputs = (attention_output,) + self_outputs[
330
+ 1:
331
+ ] # add attentions if we output them
332
+ return outputs
333
+
334
+
335
+ class BertIntermediate(nn.Module):
336
+ def __init__(self, config):
337
+ super().__init__()
338
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
339
+ if isinstance(config.hidden_act, str):
340
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
341
+ else:
342
+ self.intermediate_act_fn = config.hidden_act
343
+
344
+ def forward(self, hidden_states):
345
+ hidden_states = self.dense(hidden_states)
346
+ hidden_states = self.intermediate_act_fn(hidden_states)
347
+ return hidden_states
348
+
349
+
350
+ class BertOutput(nn.Module):
351
+ def __init__(self, config):
352
+ super().__init__()
353
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
354
+ # self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
355
+ self.LayerNorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
356
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
357
+
358
+ def forward(self, hidden_states, input_tensor):
359
+ hidden_states = self.dense(hidden_states)
360
+ hidden_states = self.dropout(hidden_states)
361
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
362
+ return hidden_states
363
+
364
+
365
+ class BertLayer(nn.Module):
366
+ def __init__(self, config, layer_num):
367
+ super().__init__()
368
+ self.config = config
369
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
370
+ self.seq_len_dim = 1
371
+ self.attention = BertAttention(config)
372
+ self.layer_num = layer_num
373
+ if (
374
+ self.config.add_cross_attention
375
+ and layer_num % self.config.cross_attention_freq == 0
376
+ ):
377
+ self.crossattention = BertAttention(
378
+ config, is_cross_attention=self.config.add_cross_attention
379
+ )
380
+ self.has_cross_attention = True
381
+ else:
382
+ self.has_cross_attention = False
383
+ self.intermediate = BertIntermediate(config)
384
+ self.output = BertOutput(config)
385
+
386
+ self.intermediate_query = BertIntermediate(config)
387
+ self.output_query = BertOutput(config)
388
+
389
+ def forward(
390
+ self,
391
+ hidden_states,
392
+ attention_mask=None,
393
+ head_mask=None,
394
+ encoder_hidden_states=None,
395
+ encoder_attention_mask=None,
396
+ past_key_value=None,
397
+ output_attentions=False,
398
+ query_length=0,
399
+ ):
400
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
401
+ self_attn_past_key_value = (
402
+ past_key_value[:2] if past_key_value is not None else None
403
+ )
404
+ self_attention_outputs = self.attention(
405
+ hidden_states,
406
+ attention_mask,
407
+ head_mask,
408
+ output_attentions=output_attentions,
409
+ past_key_value=self_attn_past_key_value,
410
+ )
411
+ attention_output = self_attention_outputs[0]
412
+ outputs = self_attention_outputs[1:-1]
413
+
414
+ present_key_value = self_attention_outputs[-1]
415
+
416
+ if query_length > 0:
417
+ query_attention_output = attention_output[:, :query_length, :]
418
+
419
+ if self.has_cross_attention:
420
+ assert (
421
+ encoder_hidden_states is not None
422
+ ), "encoder_hidden_states must be given for cross-attention layers"
423
+ cross_attention_outputs = self.crossattention(
424
+ query_attention_output,
425
+ attention_mask,
426
+ head_mask,
427
+ encoder_hidden_states,
428
+ encoder_attention_mask,
429
+ output_attentions=output_attentions,
430
+ )
431
+ query_attention_output = cross_attention_outputs[0]
432
+ outputs = (
433
+ outputs + cross_attention_outputs[1:-1]
434
+ ) # add cross attentions if we output attention weights
435
+
436
+ layer_output = apply_chunking_to_forward(
437
+ self.feed_forward_chunk_query,
438
+ self.chunk_size_feed_forward,
439
+ self.seq_len_dim,
440
+ query_attention_output,
441
+ )
442
+ if attention_output.shape[1] > query_length:
443
+ layer_output_text = apply_chunking_to_forward(
444
+ self.feed_forward_chunk,
445
+ self.chunk_size_feed_forward,
446
+ self.seq_len_dim,
447
+ attention_output[:, query_length:, :],
448
+ )
449
+ layer_output = torch.cat([layer_output, layer_output_text], dim=1)
450
+ else:
451
+ layer_output = apply_chunking_to_forward(
452
+ self.feed_forward_chunk,
453
+ self.chunk_size_feed_forward,
454
+ self.seq_len_dim,
455
+ attention_output,
456
+ )
457
+ outputs = (layer_output,) + outputs
458
+
459
+ outputs = outputs + (present_key_value,)
460
+
461
+ return outputs
462
+
463
+ def feed_forward_chunk(self, attention_output):
464
+ intermediate_output = self.intermediate(attention_output)
465
+ layer_output = self.output(intermediate_output, attention_output)
466
+ return layer_output
467
+
468
+ def feed_forward_chunk_query(self, attention_output):
469
+ intermediate_output = self.intermediate_query(attention_output)
470
+ layer_output = self.output_query(intermediate_output, attention_output)
471
+ return layer_output
472
+
473
+
474
+ class BertEncoder(nn.Module):
475
+ def __init__(self, config):
476
+ super().__init__()
477
+ self.config = config
478
+ self.layer = nn.ModuleList(
479
+ [BertLayer(config, i) for i in range(config.num_hidden_layers)]
480
+ )
481
+
482
+ def forward(
483
+ self,
484
+ hidden_states,
485
+ attention_mask=None,
486
+ head_mask=None,
487
+ encoder_hidden_states=None,
488
+ encoder_attention_mask=None,
489
+ past_key_values=None,
490
+ use_cache=None,
491
+ output_attentions=False,
492
+ output_hidden_states=False,
493
+ return_dict=True,
494
+ query_length=0,
495
+ ):
496
+ all_hidden_states = () if output_hidden_states else None
497
+ all_self_attentions = () if output_attentions else None
498
+ all_cross_attentions = (
499
+ () if output_attentions and self.config.add_cross_attention else None
500
+ )
501
+
502
+ next_decoder_cache = () if use_cache else None
503
+
504
+ for i in range(self.config.num_hidden_layers):
505
+ layer_module = self.layer[i]
506
+ if output_hidden_states:
507
+ all_hidden_states = all_hidden_states + (hidden_states,)
508
+
509
+ layer_head_mask = head_mask[i] if head_mask is not None else None
510
+ past_key_value = past_key_values[i] if past_key_values is not None else None
511
+
512
+ if getattr(self.config, "gradient_checkpointing", False) and self.training:
513
+
514
+ if use_cache:
515
+ logger.warn(
516
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
517
+ )
518
+ use_cache = False
519
+
520
+ def create_custom_forward(module):
521
+ def custom_forward(*inputs):
522
+ return module(
523
+ *inputs, past_key_value, output_attentions, query_length
524
+ )
525
+
526
+ return custom_forward
527
+
528
+ layer_outputs = torch.utils.checkpoint.checkpoint(
529
+ create_custom_forward(layer_module),
530
+ hidden_states,
531
+ attention_mask,
532
+ layer_head_mask,
533
+ encoder_hidden_states,
534
+ encoder_attention_mask,
535
+ )
536
+ else:
537
+ layer_outputs = layer_module(
538
+ hidden_states,
539
+ attention_mask,
540
+ layer_head_mask,
541
+ encoder_hidden_states,
542
+ encoder_attention_mask,
543
+ past_key_value,
544
+ output_attentions,
545
+ query_length,
546
+ )
547
+
548
+ hidden_states = layer_outputs[0]
549
+ if use_cache:
550
+ next_decoder_cache += (layer_outputs[-1],)
551
+ if output_attentions:
552
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
553
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
554
+
555
+ if output_hidden_states:
556
+ all_hidden_states = all_hidden_states + (hidden_states,)
557
+
558
+ if not return_dict:
559
+ return tuple(
560
+ v
561
+ for v in [
562
+ hidden_states,
563
+ next_decoder_cache,
564
+ all_hidden_states,
565
+ all_self_attentions,
566
+ all_cross_attentions,
567
+ ]
568
+ if v is not None
569
+ )
570
+ return BaseModelOutputWithPastAndCrossAttentions(
571
+ last_hidden_state=hidden_states,
572
+ past_key_values=next_decoder_cache,
573
+ hidden_states=all_hidden_states,
574
+ attentions=all_self_attentions,
575
+ cross_attentions=all_cross_attentions,
576
+ )
577
+
578
+
579
+ class BertPooler(nn.Module):
580
+ def __init__(self, config):
581
+ super().__init__()
582
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
583
+ self.activation = nn.Tanh()
584
+
585
+ def forward(self, hidden_states):
586
+ # We "pool" the model by simply taking the hidden state corresponding
587
+ # to the first token.
588
+ first_token_tensor = hidden_states[:, 0]
589
+ pooled_output = self.dense(first_token_tensor)
590
+ pooled_output = self.activation(pooled_output)
591
+ return pooled_output
592
+
593
+
594
+ class BertPredictionHeadTransform(nn.Module):
595
+ def __init__(self, config):
596
+ super().__init__()
597
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
598
+ if isinstance(config.hidden_act, str):
599
+ self.transform_act_fn = ACT2FN[config.hidden_act]
600
+ else:
601
+ self.transform_act_fn = config.hidden_act
602
+ # self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
603
+ self.LayerNorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
604
+
605
+ def forward(self, hidden_states):
606
+ hidden_states = self.dense(hidden_states)
607
+ hidden_states = self.transform_act_fn(hidden_states)
608
+ hidden_states = self.LayerNorm(hidden_states)
609
+ return hidden_states
610
+
611
+
612
+ class BertLMPredictionHead(nn.Module):
613
+ def __init__(self, config):
614
+ super().__init__()
615
+ self.transform = BertPredictionHeadTransform(config)
616
+
617
+ # The output weights are the same as the input embeddings, but there is
618
+ # an output-only bias for each token.
619
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
620
+
621
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
622
+
623
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
624
+ self.decoder.bias = self.bias
625
+
626
+ def forward(self, hidden_states):
627
+ hidden_states = self.transform(hidden_states)
628
+ hidden_states = self.decoder(hidden_states)
629
+ return hidden_states
630
+
631
+
632
+ class BertOnlyMLMHead(nn.Module):
633
+ def __init__(self, config):
634
+ super().__init__()
635
+ self.predictions = BertLMPredictionHead(config)
636
+
637
+ def forward(self, sequence_output):
638
+ prediction_scores = self.predictions(sequence_output)
639
+ return prediction_scores
640
+
641
+
642
+ class BertPreTrainedModel(PreTrainedModel):
643
+ """
644
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
645
+ models.
646
+ """
647
+
648
+ config_class = BertConfig
649
+ base_model_prefix = "bert"
650
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
651
+
652
+ def _init_weights(self, module):
653
+ """Initialize the weights"""
654
+ if isinstance(module, (nn.Linear, nn.Embedding)):
655
+ # Slightly different from the TF version which uses truncated_normal for initialization
656
+ # cf https://github.com/pytorch/pytorch/pull/5617
657
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
658
+ elif isinstance(module, nn.LayerNorm):
659
+ module.bias.data.zero_()
660
+ module.weight.data.fill_(1.0)
661
+ if isinstance(module, nn.Linear) and module.bias is not None:
662
+ module.bias.data.zero_()
663
+
664
+
665
+ class BertModel(BertPreTrainedModel):
666
+ """
667
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
668
+ cross-attention is added between the self-attention layers, following the architecture described in `Attention is
669
+ all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
670
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
671
+ argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
672
+ input to the forward pass.
673
+ """
674
+
675
+ def __init__(self, config, add_pooling_layer=False):
676
+ super().__init__(config)
677
+ self.config = config
678
+
679
+ self.embeddings = BertEmbeddings(config)
680
+
681
+ self.encoder = BertEncoder(config)
682
+
683
+ self.pooler = BertPooler(config) if add_pooling_layer else None
684
+
685
+ self.init_weights()
686
+
687
+ def get_input_embeddings(self):
688
+ return self.embeddings.word_embeddings
689
+
690
+ def set_input_embeddings(self, value):
691
+ self.embeddings.word_embeddings = value
692
+
693
+ def _prune_heads(self, heads_to_prune):
694
+ """
695
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
696
+ class PreTrainedModel
697
+ """
698
+ for layer, heads in heads_to_prune.items():
699
+ self.encoder.layer[layer].attention.prune_heads(heads)
700
+
701
+ def get_extended_attention_mask(
702
+ self,
703
+ attention_mask: Tensor,
704
+ input_shape: Tuple[int],
705
+ device: device,
706
+ is_decoder: bool,
707
+ has_query: bool = False,
708
+ ) -> Tensor:
709
+ """
710
+ Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
711
+
712
+ Arguments:
713
+ attention_mask (:obj:`torch.Tensor`):
714
+ Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
715
+ input_shape (:obj:`Tuple[int]`):
716
+ The shape of the input to the model.
717
+ device: (:obj:`torch.device`):
718
+ The device of the input to the model.
719
+
720
+ Returns:
721
+ :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
722
+ """
723
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
724
+ # ourselves in which case we just need to make it broadcastable to all heads.
725
+ if attention_mask.dim() == 3:
726
+ extended_attention_mask = attention_mask[:, None, :, :]
727
+ elif attention_mask.dim() == 2:
728
+ # Provided a padding mask of dimensions [batch_size, seq_length]
729
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
730
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
731
+ if is_decoder:
732
+ batch_size, seq_length = input_shape
733
+
734
+ seq_ids = torch.arange(seq_length, device=device)
735
+ causal_mask = (
736
+ seq_ids[None, None, :].repeat(batch_size, seq_length, 1)
737
+ <= seq_ids[None, :, None]
738
+ )
739
+
740
+ # add a prefix ones mask to the causal mask
741
+ # causal and attention masks must have same type with pytorch version < 1.3
742
+ causal_mask = causal_mask.to(attention_mask.dtype)
743
+
744
+ if causal_mask.shape[1] < attention_mask.shape[1]:
745
+ prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
746
+ if has_query: # UniLM style attention mask
747
+ causal_mask = torch.cat(
748
+ [
749
+ torch.zeros(
750
+ (batch_size, prefix_seq_len, seq_length),
751
+ device=device,
752
+ dtype=causal_mask.dtype,
753
+ ),
754
+ causal_mask,
755
+ ],
756
+ axis=1,
757
+ )
758
+ causal_mask = torch.cat(
759
+ [
760
+ torch.ones(
761
+ (batch_size, causal_mask.shape[1], prefix_seq_len),
762
+ device=device,
763
+ dtype=causal_mask.dtype,
764
+ ),
765
+ causal_mask,
766
+ ],
767
+ axis=-1,
768
+ )
769
+ extended_attention_mask = (
770
+ causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
771
+ )
772
+ else:
773
+ extended_attention_mask = attention_mask[:, None, None, :]
774
+ else:
775
+ raise ValueError(
776
+ "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
777
+ input_shape, attention_mask.shape
778
+ )
779
+ )
780
+
781
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
782
+ # masked positions, this operation will create a tensor which is 0.0 for
783
+ # positions we want to attend and -10000.0 for masked positions.
784
+ # Since we are adding it to the raw scores before the softmax, this is
785
+ # effectively the same as removing these entirely.
786
+ extended_attention_mask = extended_attention_mask.to(
787
+ dtype=self.dtype
788
+ ) # fp16 compatibility
789
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
790
+ return extended_attention_mask
791
+
792
+ def forward(
793
+ self,
794
+ query_embeds=None,
795
+ encoder_hidden_states=None,
796
+ encoder_attention_mask=None,
797
+ ):
798
+ r"""
799
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
800
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
801
+ the model is configured as a decoder.
802
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
803
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
804
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
805
+ - 1 for tokens that are **not masked**,
806
+ - 0 for tokens that are **masked**.
807
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
808
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
809
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
810
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
811
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
812
+ use_cache (:obj:`bool`, `optional`):
813
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
814
+ decoding (see :obj:`past_key_values`).
815
+ """
816
+ output_attentions = self.config.output_attentions
817
+
818
+ output_hidden_states = self.config.output_hidden_states
819
+
820
+ return_dict = True
821
+
822
+ use_cache = False
823
+
824
+ input_ids = None
825
+
826
+ position_ids = None
827
+
828
+ # past_key_values_length
829
+ past_key_values_length = 0
830
+
831
+ query_length = query_embeds.shape[1]
832
+
833
+ embedding_output = self.embeddings(
834
+ input_ids=input_ids,
835
+ position_ids=position_ids,
836
+ query_embeds=query_embeds,
837
+ past_key_values_length=past_key_values_length,
838
+ )
839
+
840
+ input_shape = embedding_output.size()[:-1]
841
+ batch_size = input_shape[-2]
842
+ seq_length = input_shape[-1]
843
+ device = embedding_output.device
844
+
845
+ attention_mask = None
846
+ attention_mask = torch.ones(
847
+ ((batch_size, seq_length + past_key_values_length)), device=device
848
+ )
849
+
850
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
851
+ # ourselves in which case we just need to make it broadcastable to all heads.
852
+ is_decoder = False
853
+ extended_attention_mask = self.get_extended_attention_mask(
854
+ attention_mask, input_shape, device, is_decoder
855
+ )
856
+
857
+ # If a 2D or 3D attention mask is provided for the cross-attention
858
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
859
+ print("encoder_hidden_states.size(): ", encoder_hidden_states.size())
860
+ encoder_batch_size = encoder_hidden_states.size()[-3]
861
+ encoder_sequence_length = encoder_hidden_states.size()[-2]
862
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
863
+ print("encoder_hidden_shape: ", encoder_hidden_shape)
864
+
865
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
866
+
867
+ # Prepare head mask if needed
868
+ # 1.0 in head_mask indicate we keep the head
869
+ # attention_probs has shape bsz x n_heads x N x N
870
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
871
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
872
+ head_mask = None
873
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
874
+
875
+ past_key_values = None
876
+
877
+ encoder_outputs = self.encoder(
878
+ embedding_output,
879
+ attention_mask=extended_attention_mask,
880
+ head_mask=head_mask,
881
+ encoder_hidden_states=encoder_hidden_states,
882
+ encoder_attention_mask=encoder_extended_attention_mask,
883
+ past_key_values=past_key_values,
884
+ use_cache=use_cache,
885
+ output_attentions=output_attentions,
886
+ output_hidden_states=output_hidden_states,
887
+ return_dict=return_dict,
888
+ query_length=query_length,
889
+ )
890
+ sequence_output = encoder_outputs[0]
891
+ pooled_output = None
892
+
893
+ return BaseModelOutputWithPoolingAndCrossAttentions(
894
+ last_hidden_state=sequence_output,
895
+ pooler_output=pooled_output,
896
+ past_key_values=encoder_outputs.past_key_values,
897
+ hidden_states=encoder_outputs.hidden_states,
898
+ attentions=encoder_outputs.attentions,
899
+ cross_attentions=encoder_outputs.cross_attentions,
900
+ )
901
+
902
+
903
+ class BertLMHeadModel(BertPreTrainedModel):
904
+
905
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
906
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
907
+
908
+ def __init__(self, config):
909
+ super().__init__(config)
910
+
911
+ self.bert = BertModel(config, add_pooling_layer=False)
912
+ self.cls = BertOnlyMLMHead(config)
913
+
914
+ self.init_weights()
915
+
916
+ def get_output_embeddings(self):
917
+ return self.cls.predictions.decoder
918
+
919
+ def set_output_embeddings(self, new_embeddings):
920
+ self.cls.predictions.decoder = new_embeddings
921
+
922
+ def forward(
923
+ self,
924
+ input_ids=None,
925
+ attention_mask=None,
926
+ position_ids=None,
927
+ head_mask=None,
928
+ query_embeds=None,
929
+ encoder_hidden_states=None,
930
+ encoder_attention_mask=None,
931
+ labels=None,
932
+ past_key_values=None,
933
+ use_cache=True,
934
+ output_attentions=None,
935
+ output_hidden_states=None,
936
+ return_dict=None,
937
+ return_logits=False,
938
+ is_decoder=True,
939
+ reduction="mean",
940
+ ):
941
+ r"""
942
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
943
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
944
+ the model is configured as a decoder.
945
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
946
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
947
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
948
+ - 1 for tokens that are **not masked**,
949
+ - 0 for tokens that are **masked**.
950
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
951
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
952
+ ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are
953
+ ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]``
954
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
955
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
956
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
957
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
958
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
959
+ use_cache (:obj:`bool`, `optional`):
960
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
961
+ decoding (see :obj:`past_key_values`).
962
+ Returns:
963
+ Example::
964
+ >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig
965
+ >>> import torch
966
+ >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
967
+ >>> config = BertConfig.from_pretrained("bert-base-cased")
968
+ >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config)
969
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
970
+ >>> outputs = model(**inputs)
971
+ >>> prediction_logits = outputs.logits
972
+ """
973
+ return_dict = (
974
+ return_dict if return_dict is not None else self.config.use_return_dict
975
+ )
976
+ if labels is not None:
977
+ use_cache = False
978
+ if past_key_values is not None:
979
+ query_embeds = None
980
+
981
+ outputs = self.bert(
982
+ input_ids,
983
+ attention_mask=attention_mask,
984
+ position_ids=position_ids,
985
+ head_mask=head_mask,
986
+ query_embeds=query_embeds,
987
+ encoder_hidden_states=encoder_hidden_states,
988
+ encoder_attention_mask=encoder_attention_mask,
989
+ past_key_values=past_key_values,
990
+ use_cache=use_cache,
991
+ output_attentions=output_attentions,
992
+ output_hidden_states=output_hidden_states,
993
+ return_dict=return_dict,
994
+ is_decoder=is_decoder,
995
+ )
996
+
997
+ sequence_output = outputs[0]
998
+ if query_embeds is not None:
999
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1000
+
1001
+ prediction_scores = self.cls(sequence_output)
1002
+
1003
+ if return_logits:
1004
+ return prediction_scores[:, :-1, :].contiguous()
1005
+
1006
+ lm_loss = None
1007
+ if labels is not None:
1008
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1009
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1010
+ labels = labels[:, 1:].contiguous()
1011
+ loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
1012
+ lm_loss = loss_fct(
1013
+ shifted_prediction_scores.view(-1, self.config.vocab_size),
1014
+ labels.view(-1),
1015
+ )
1016
+ if reduction == "none":
1017
+ lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
1018
+
1019
+ if not return_dict:
1020
+ output = (prediction_scores,) + outputs[2:]
1021
+ return ((lm_loss,) + output) if lm_loss is not None else output
1022
+
1023
+ return CausalLMOutputWithCrossAttentions(
1024
+ loss=lm_loss,
1025
+ logits=prediction_scores,
1026
+ past_key_values=outputs.past_key_values,
1027
+ hidden_states=outputs.hidden_states,
1028
+ attentions=outputs.attentions,
1029
+ cross_attentions=outputs.cross_attentions,
1030
+ )
1031
+
1032
+ def prepare_inputs_for_generation(
1033
+ self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs
1034
+ ):
1035
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1036
+ if attention_mask is None:
1037
+ attention_mask = input_ids.new_ones(input_ids.shape)
1038
+ query_mask = input_ids.new_ones(query_embeds.shape[:-1])
1039
+ attention_mask = torch.cat([query_mask, attention_mask], dim=-1)
1040
+
1041
+ # cut decoder_input_ids if past is used
1042
+ if past is not None:
1043
+ input_ids = input_ids[:, -1:]
1044
+
1045
+ return {
1046
+ "input_ids": input_ids,
1047
+ "query_embeds": query_embeds,
1048
+ "attention_mask": attention_mask,
1049
+ "past_key_values": past,
1050
+ "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
1051
+ "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
1052
+ "is_decoder": True,
1053
+ }
1054
+
1055
+ def _reorder_cache(self, past, beam_idx):
1056
+ reordered_past = ()
1057
+ for layer_past in past:
1058
+ reordered_past += (
1059
+ tuple(
1060
+ past_state.index_select(0, beam_idx) for past_state in layer_past
1061
+ ),
1062
+ )
1063
+ return reordered_past
1064
+
1065
+
1066
+ class BertForMaskedLM(BertPreTrainedModel):
1067
+
1068
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1069
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
1070
+
1071
+ def __init__(self, config):
1072
+ super().__init__(config)
1073
+
1074
+ self.bert = BertModel(config, add_pooling_layer=False)
1075
+ self.cls = BertOnlyMLMHead(config)
1076
+
1077
+ self.init_weights()
1078
+
1079
+ def get_output_embeddings(self):
1080
+ return self.cls.predictions.decoder
1081
+
1082
+ def set_output_embeddings(self, new_embeddings):
1083
+ self.cls.predictions.decoder = new_embeddings
1084
+
1085
+ def forward(
1086
+ self,
1087
+ input_ids=None,
1088
+ attention_mask=None,
1089
+ position_ids=None,
1090
+ head_mask=None,
1091
+ query_embeds=None,
1092
+ encoder_hidden_states=None,
1093
+ encoder_attention_mask=None,
1094
+ labels=None,
1095
+ output_attentions=None,
1096
+ output_hidden_states=None,
1097
+ return_dict=None,
1098
+ return_logits=False,
1099
+ is_decoder=False,
1100
+ ):
1101
+ r"""
1102
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1103
+ Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
1104
+ config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
1105
+ (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
1106
+ """
1107
+
1108
+ return_dict = (
1109
+ return_dict if return_dict is not None else self.config.use_return_dict
1110
+ )
1111
+
1112
+ outputs = self.bert(
1113
+ input_ids,
1114
+ attention_mask=attention_mask,
1115
+ position_ids=position_ids,
1116
+ head_mask=head_mask,
1117
+ query_embeds=query_embeds,
1118
+ encoder_hidden_states=encoder_hidden_states,
1119
+ encoder_attention_mask=encoder_attention_mask,
1120
+ output_attentions=output_attentions,
1121
+ output_hidden_states=output_hidden_states,
1122
+ return_dict=return_dict,
1123
+ is_decoder=is_decoder,
1124
+ )
1125
+
1126
+ if query_embeds is not None:
1127
+ sequence_output = outputs[0][:, query_embeds.shape[1] :, :]
1128
+ prediction_scores = self.cls(sequence_output)
1129
+
1130
+ if return_logits:
1131
+ return prediction_scores
1132
+
1133
+ masked_lm_loss = None
1134
+ if labels is not None:
1135
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1136
+ masked_lm_loss = loss_fct(
1137
+ prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
1138
+ )
1139
+
1140
+ if not return_dict:
1141
+ output = (prediction_scores,) + outputs[2:]
1142
+ return (
1143
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1144
+ )
1145
+
1146
+ return MaskedLMOutput(
1147
+ loss=masked_lm_loss,
1148
+ logits=prediction_scores,
1149
+ hidden_states=outputs.hidden_states,
1150
+ attentions=outputs.attentions,
1151
+ )
llava/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from .model import LlavaLlamaForCausalLM, LlavaMistralForCausalLM
2
+ try:
3
+ from .model import LlavaGemmaForCausalLM
4
+ except:
5
+ pass
6
+ try:
7
+ from .model import LlavaThothForCausalLM
8
+ except:
9
+ pass
llava/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (358 Bytes). View file
 
llava/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (405 Bytes). View file
 
llava/__pycache__/constants.cpython-310.pyc ADDED
Binary file (669 Bytes). View file
 
llava/__pycache__/constants.cpython-39.pyc ADDED
Binary file (710 Bytes). View file
 
llava/__pycache__/conversation.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
llava/__pycache__/conversation.cpython-39.pyc ADDED
Binary file (11.2 kB). View file
 
llava/__pycache__/mm_utils.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
llava/__pycache__/mm_utils.cpython-39.pyc ADDED
Binary file (11.9 kB). View file
 
llava/__pycache__/utils.cpython-310.pyc ADDED
Binary file (5.98 kB). View file
 
llava/__pycache__/utils.cpython-39.pyc ADDED
Binary file (6.03 kB). View file
 
llava/configs/action_dataset_ablation/finetune_webvid.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ lk_image:
4
+ data_type: image
5
+
6
+ lk_video:
7
+ data_type: frames
8
+ conv_type: multi
9
+ fps: 1.0
10
+ select_datasets: ['webvid10m', 'webvid2m']
11
+ # select_datasets: ['webvid10m', 'webvid2m', 'activitynet', 'vidal', 'hdvila']
llava/configs/action_dataset_ablation/finetune_webvid_act.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ lk_image:
4
+ data_type: image
5
+
6
+ lk_video:
7
+ data_type: frames
8
+ conv_type: multi
9
+ fps: 1.0
10
+ select_datasets: ['webvid10m', 'webvid2m', 'activitynet']
11
+ # select_datasets: ['webvid10m', 'webvid2m', 'activitynet', 'vidal', 'hdvila']
llava/configs/action_dataset_ablation/finetune_webvid_hdvila.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ lk_image:
4
+ data_type: image
5
+
6
+ lk_video:
7
+ data_type: frames
8
+ conv_type: multi
9
+ fps: 1.0
10
+ select_datasets: ['webvid10m', 'webvid2m', 'hdvila']
11
+ # select_datasets: ['webvid10m', 'webvid2m', 'activitynet', 'vidal', 'hdvila']
llava/configs/action_dataset_ablation/finetune_webvid_vidal.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ lk_image:
4
+ data_type: image
5
+
6
+ lk_video:
7
+ data_type: frames
8
+ conv_type: multi
9
+ fps: 1.0
10
+ select_datasets: ['webvid10m', 'webvid2m', 'vidal']
11
+ # select_datasets: ['webvid10m', 'webvid2m', 'activitynet', 'vidal', 'hdvila']
llava/configs/adso_increasing_ablation/finetune_data_pure_gpt4v.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ # m3it:
4
+ # data_type: images
5
+ # sample_ratio: 4
6
+ # tasks:
7
+ # - coco
8
+ # - coco-goi
9
+ # - coco-text
10
+ # - imagenet
11
+ # - coco-itm
12
+ # - iqa
13
+ # - mocheg
14
+ # - vsr
15
+ # - refcoco
16
+ # - science-qa
17
+ # - vqa-v2
18
+ # - gqa
19
+ # - st-vqa
20
+ # - text-vqa
21
+ # - okvqa
22
+ # - a-okvqa
23
+ #
24
+ # tt_vqa:
25
+ # data_type: frames
26
+ # sample_ratio: 1
27
+
28
+ ShareGPT4V:
29
+ data_type: images
30
+ sample_ratio: 1
31
+
32
+ gpt4v_tt_vqa:
33
+ data_type: frames
34
+ fps: 0.5
35
+ sample_ratio: 6
36
+ conv_type: single
37
+ task_types: ['caption', 'qas']
38
+
39
+ gpt4v_public:
40
+ data_type: frames
41
+ fps: 1.0
42
+ sample_ratio: 6
43
+ conv_type: single
44
+ task_types: ['summary', 'detail', 'qa_pairs']
45
+ sample_method: sequential
46
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/data/shared_gpt4v_data/data_130k.json
47
+
48
+ gpt4v_internal:
49
+ data_type: frames
50
+ fps: 2.0
51
+ sample_ratio: 1
52
+ conv_type: single
53
+ task_types: ['summary', 'detail', 'qa_pairs']
54
+
55
+
llava/configs/adso_increasing_ablation/finetune_gpt4v_adso135k.yaml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ # m3it:
4
+ # data_type: images
5
+ # sample_ratio: 4
6
+ # tasks:
7
+ # - coco
8
+ # - coco-goi
9
+ # - coco-text
10
+ # - imagenet
11
+ # - coco-itm
12
+ # - iqa
13
+ # - mocheg
14
+ # - vsr
15
+ # - refcoco
16
+ # - science-qa
17
+ # - vqa-v2
18
+ # - gqa
19
+ # - st-vqa
20
+ # - text-vqa
21
+ # - okvqa
22
+ # - a-okvqa
23
+ #
24
+ tt_vqa:
25
+ data_type: frames
26
+ sample_ratio: 2
27
+ fps: 2.0
28
+ conv_type: single
29
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/dataset/masp/20240208_meta_data_single_135k_caption_160k_QA.json
30
+
31
+ ShareGPT4V:
32
+ data_type: images
33
+ sample_ratio: 1
34
+
35
+ gpt4v_tt_vqa:
36
+ data_type: frames
37
+ fps: 0.5
38
+ sample_ratio: 6
39
+ conv_type: single
40
+ task_types: ['caption', 'qas']
41
+
42
+
43
+ gpt4v_public:
44
+ data_type: frames
45
+ fps: 1.0
46
+ sample_ratio: 6
47
+ conv_type: single
48
+ task_types: ['summary', 'detail', 'qa_pairs']
49
+ sample_method: sequential
50
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/data/shared_gpt4v_data/data_130k.json
51
+
52
+ gpt4v_internal:
53
+ data_type: frames
54
+ fps: 2.0
55
+ sample_ratio: 1
56
+ conv_type: single
57
+ task_types: ['summary', 'detail', 'qa_pairs']
llava/configs/adso_increasing_ablation/finetune_gpt4v_adso185k.yaml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ # m3it:
4
+ # data_type: images
5
+ # sample_ratio: 4
6
+ # tasks:
7
+ # - coco
8
+ # - coco-goi
9
+ # - coco-text
10
+ # - imagenet
11
+ # - coco-itm
12
+ # - iqa
13
+ # - mocheg
14
+ # - vsr
15
+ # - refcoco
16
+ # - science-qa
17
+ # - vqa-v2
18
+ # - gqa
19
+ # - st-vqa
20
+ # - text-vqa
21
+ # - okvqa
22
+ # - a-okvqa
23
+ #
24
+ tt_vqa:
25
+ data_type: frames
26
+ sample_ratio: 3
27
+ fps: 2.0
28
+ conv_type: single
29
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/dataset/masp/20240220_meta_data_single_190k_caption_160k_QA.json
30
+
31
+ ShareGPT4V:
32
+ data_type: images
33
+ sample_ratio: 1
34
+
35
+ gpt4v_tt_vqa:
36
+ data_type: frames
37
+ fps: 0.5
38
+ sample_ratio: 6
39
+ conv_type: single
40
+ task_types: ['caption', 'qas']
41
+
42
+
43
+ gpt4v_public:
44
+ data_type: frames
45
+ fps: 1.0
46
+ sample_ratio: 6
47
+ conv_type: single
48
+ task_types: ['summary', 'detail', 'qa_pairs']
49
+ sample_method: sequential
50
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/data/shared_gpt4v_data/data_130k.json
51
+
52
+ gpt4v_internal:
53
+ data_type: frames
54
+ fps: 2.0
55
+ sample_ratio: 1
56
+ conv_type: single
57
+ task_types: ['summary', 'detail', 'qa_pairs']
llava/configs/adso_increasing_ablation/finetune_gpt4v_adso185k_baseline.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ # m3it:
4
+ # data_type: images
5
+ # sample_ratio: 4
6
+ # tasks:
7
+ # - coco
8
+ # - coco-goi
9
+ # - coco-text
10
+ # - imagenet
11
+ # - coco-itm
12
+ # - iqa
13
+ # - mocheg
14
+ # - vsr
15
+ # - refcoco
16
+ # - science-qa
17
+ # - vqa-v2
18
+ # - gqa
19
+ # - st-vqa
20
+ # - text-vqa
21
+ # - okvqa
22
+ # - a-okvqa
23
+ #
24
+ tt_vqa:
25
+ data_type: frames
26
+ sample_ratio: 3
27
+ fps: 2.0
28
+ conv_type: single
29
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/dataset/masp/20240220_meta_data_single_190k_caption_160k_QA.json
30
+
31
+ ShareGPT4V:
32
+ data_type: images
33
+ sample_ratio: 1
34
+
35
+ gpt4v_tt_vqa:
36
+ data_type: frames
37
+ fps: 0.5
38
+ sample_ratio: 6
39
+ conv_type: single
40
+ task_types: ['caption', 'qas']
41
+
42
+
43
+ lk_video:
44
+ data_type: frames
45
+ conv_type: multi
46
+ fps: 1.0
47
+ sample_ratio: 6
48
+
49
+ gpt4v_internal:
50
+ data_type: frames
51
+ fps: 2.0
52
+ sample_ratio: 1
53
+ conv_type: single
54
+ task_types: ['detail']
55
+
llava/configs/adso_increasing_ablation/finetune_gpt4v_adso185k_no_qa.yaml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ # m3it:
4
+ # data_type: images
5
+ # sample_ratio: 4
6
+ # tasks:
7
+ # - coco
8
+ # - coco-goi
9
+ # - coco-text
10
+ # - imagenet
11
+ # - coco-itm
12
+ # - iqa
13
+ # - mocheg
14
+ # - vsr
15
+ # - refcoco
16
+ # - science-qa
17
+ # - vqa-v2
18
+ # - gqa
19
+ # - st-vqa
20
+ # - text-vqa
21
+ # - okvqa
22
+ # - a-okvqa
23
+ #
24
+ tt_vqa:
25
+ data_type: frames
26
+ sample_ratio: 3
27
+ fps: 2.0
28
+ conv_type: single
29
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/dataset/masp/20240220_meta_data_single_190k_caption_no_QA.json
30
+
31
+ ShareGPT4V:
32
+ data_type: images
33
+ sample_ratio: 1
34
+
35
+ gpt4v_tt_vqa:
36
+ data_type: frames
37
+ fps: 0.5
38
+ sample_ratio: 6
39
+ conv_type: single
40
+ task_types: ['caption', 'qas']
41
+
42
+
43
+ gpt4v_public:
44
+ data_type: frames
45
+ fps: 1.0
46
+ sample_ratio: 6
47
+ conv_type: single
48
+ task_types: ['summary', 'detail', 'qa_pairs']
49
+ sample_method: sequential
50
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/data/shared_gpt4v_data/data_130k.json
51
+
52
+ gpt4v_internal:
53
+ data_type: frames
54
+ fps: 2.0
55
+ sample_ratio: 1
56
+ conv_type: single
57
+ task_types: ['summary', 'detail', 'qa_pairs']
llava/configs/adso_increasing_ablation/finetune_gpt4v_adso65k.yaml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ # m3it:
4
+ # data_type: images
5
+ # sample_ratio: 4
6
+ # tasks:
7
+ # - coco
8
+ # - coco-goi
9
+ # - coco-text
10
+ # - imagenet
11
+ # - coco-itm
12
+ # - iqa
13
+ # - mocheg
14
+ # - vsr
15
+ # - refcoco
16
+ # - science-qa
17
+ # - vqa-v2
18
+ # - gqa
19
+ # - st-vqa
20
+ # - text-vqa
21
+ # - okvqa
22
+ # - a-okvqa
23
+ #
24
+ tt_vqa:
25
+ data_type: frames
26
+ sample_ratio: 2
27
+ fps: 2.0
28
+ conv_type: single
29
+ train_data_path: /mnt/bn/algo-masp-nas-2/baiyi.by/data/ADSO_Anno_Data/batch_20231128/meta_data_single_60k_caption_170k_QA.json
30
+
31
+ ShareGPT4V:
32
+ data_type: images
33
+ sample_ratio: 1
34
+
35
+ gpt4v_tt_vqa:
36
+ data_type: frames
37
+ fps: 0.5
38
+ sample_ratio: 6
39
+ conv_type: single
40
+ task_types: ['caption', 'qas']
41
+
42
+
43
+ gpt4v_public:
44
+ data_type: frames
45
+ fps: 1.0
46
+ sample_ratio: 6
47
+ conv_type: single
48
+ task_types: ['summary', 'detail', 'qa_pairs']
49
+ sample_method: sequential
50
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/data/shared_gpt4v_data/data_130k.json
51
+
52
+ gpt4v_internal:
53
+ data_type: frames
54
+ fps: 2.0
55
+ sample_ratio: 1
56
+ conv_type: single
57
+ task_types: ['summary', 'detail', 'qa_pairs']
llava/configs/finetune_debug.yaml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+ gpt4v_public:
3
+ data_type: frames
4
+ fps: 1.0
5
+ sample_ratio: 6
6
+ conv_type: single
7
+ task_types: ['summary', 'detail', 'qa_pairs']
8
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/data/shared_gpt4v_data/data_130k.json
llava/configs/finetune_gpt4v_adso65k.yaml ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ # m3it:
4
+ # data_type: images
5
+ # sample_ratio: 4
6
+ # tasks:
7
+ # - coco
8
+ # - coco-goi
9
+ # - coco-text
10
+ # - imagenet
11
+ # - coco-itm
12
+ # - iqa
13
+ # - mocheg
14
+ # - vsr
15
+ # - refcoco
16
+ # - science-qa
17
+ # - vqa-v2
18
+ # - gqa
19
+ # - st-vqa
20
+ # - text-vqa
21
+ # - okvqa
22
+ # - a-okvqa
23
+ #
24
+ tt_vqa:
25
+ data_type: frames
26
+ sample_ratio: 2
27
+ fps: 2.0
28
+ conv_type: single
29
+ train_data_path: /mnt/bn/algo-masp-nas-2/baiyi.by/data/ADSO_Anno_Data/batch_20231128/meta_data_single_60k_caption_170k_QA.json
30
+
31
+ ShareGPT4V:
32
+ data_type: images
33
+ sample_ratio: 1
34
+
35
+ gpt4v_tt_vqa:
36
+ data_type: frames
37
+ fps: 0.5
38
+ sample_ratio: 6
39
+ conv_type: single
40
+ task_types: ['caption', 'qas']
41
+
42
+
43
+ gpt4v_public:
44
+ data_type: frames
45
+ fps: 1.0
46
+ sample_ratio: 6
47
+ conv_type: single
48
+ task_types: ['summary', 'detail', 'qa_pairs']
49
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/data/shared_gpt4v_data/data_130k.json
50
+
51
+ gpt4v_internal:
52
+ data_type: frames
53
+ fps: 2.0
54
+ sample_ratio: 1
55
+ conv_type: single
56
+ task_types: ['summary', 'detail', 'qa_pairs']
llava/configs/gpt4v_increasing_ablation/finetune_gpt4v_public500k.yaml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ datasets:
2
+
3
+ # m3it:
4
+ # data_type: images
5
+ # sample_ratio: 4
6
+ # tasks:
7
+ # - coco
8
+ # - coco-goi
9
+ # - coco-text
10
+ # - imagenet
11
+ # - coco-itm
12
+ # - iqa
13
+ # - mocheg
14
+ # - vsr
15
+ # - refcoco
16
+ # - science-qa
17
+ # - vqa-v2
18
+ # - gqa
19
+ # - st-vqa
20
+ # - text-vqa
21
+ # - okvqa
22
+ # - a-okvqa
23
+ #
24
+ # tt_vqa:
25
+ # data_type: frames
26
+ # sample_ratio: 2
27
+ # fps: 2.0
28
+ # conv_type: single
29
+ # train_data_path: /mnt/bn/algo-masp-nas-2/baiyi.by/data/ADSO_Anno_Data/batch_20231128/meta_data_single_60k_caption_170k_QA.json
30
+
31
+ ShareGPT4V:
32
+ data_type: images
33
+ sample_ratio: 1
34
+
35
+
36
+ gpt4v_tt_vqa:
37
+ data_type: frames
38
+ fps: 0.5
39
+ sample_ratio: 6
40
+ conv_type: single
41
+ task_types: ['caption', 'qas']
42
+
43
+
44
+ gpt4v_public:
45
+ data_type: frames
46
+ fps: 1.0
47
+ sample_ratio: 10
48
+ conv_type: single
49
+ task_types: ['summary', 'detail']
50
+ train_data_path: /mnt/bn/algo-masp-nas-2/xiangchen/data/shared_gpt4v_data/data_500k_filtered.json
51
+
52
+ gpt4v_internal:
53
+ data_type: frames
54
+ fps: 2.0
55
+ sample_ratio: 1
56
+ conv_type: single
57
+ task_types: ['summary', 'detail', 'qa_pairs']