Spaces:
Runtime error
Runtime error
Upload 77 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +10 -0
- VideoLLaMA2/.gitignore +58 -0
- VideoLLaMA2/LICENSE +201 -0
- VideoLLaMA2/README.md +372 -0
- VideoLLaMA2/assets/cat_and_chicken.mp4 +3 -0
- VideoLLaMA2/assets/logo.png +3 -0
- VideoLLaMA2/assets/pipeline.png +3 -0
- VideoLLaMA2/assets/sora.mp4 +3 -0
- VideoLLaMA2/assets/sora.png +3 -0
- VideoLLaMA2/pyproject.toml +41 -0
- VideoLLaMA2/requirements.txt +39 -0
- VideoLLaMA2/scripts/custom/finetune.sh +73 -0
- VideoLLaMA2/scripts/custom/finetune_lora.sh +74 -0
- VideoLLaMA2/scripts/custom/finetune_qlora.sh +74 -0
- VideoLLaMA2/scripts/eval/eval_video_cap_msvc.sh +67 -0
- VideoLLaMA2/scripts/eval/eval_video_mcqa_egoschema.sh +41 -0
- VideoLLaMA2/scripts/eval/eval_video_mcqa_mvbench.sh +46 -0
- VideoLLaMA2/scripts/eval/eval_video_mcqa_perception_test_mcqa.sh +45 -0
- VideoLLaMA2/scripts/eval/eval_video_mcqa_videomme.sh +84 -0
- VideoLLaMA2/scripts/eval/eval_video_oqa_activitynet.sh +54 -0
- VideoLLaMA2/scripts/eval/eval_video_oqa_msvd.sh +54 -0
- VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_1_correctness.sh +58 -0
- VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_2_detail.sh +58 -0
- VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_3_context.sh +58 -0
- VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_4_temporal.sh +54 -0
- VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_5_consistency.sh +54 -0
- VideoLLaMA2/scripts/vllava/finetune.sh +73 -0
- VideoLLaMA2/scripts/vllava/pretrain.sh +73 -0
- VideoLLaMA2/scripts/zero2.json +23 -0
- VideoLLaMA2/scripts/zero3.json +28 -0
- VideoLLaMA2/videollama2/__init__.py +114 -0
- VideoLLaMA2/videollama2/constants.py +32 -0
- VideoLLaMA2/videollama2/conversation.py +507 -0
- VideoLLaMA2/videollama2/eval/eval_video_cap_msvc_correctness.py +259 -0
- VideoLLaMA2/videollama2/eval/eval_video_cap_msvc_detailedness.py +257 -0
- VideoLLaMA2/videollama2/eval/eval_video_mcqa_mvbench.py +64 -0
- VideoLLaMA2/videollama2/eval/eval_video_mcqa_videomme.py +277 -0
- VideoLLaMA2/videollama2/eval/eval_video_oqa_activitynet.py +210 -0
- VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_1_correctness.py +210 -0
- VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_2_detailed_orientation.py +210 -0
- VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_3_context.py +212 -0
- VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_4_temporal.py +206 -0
- VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_5_consistency.py +218 -0
- VideoLLaMA2/videollama2/eval/inference_video_cap_msvc.py +120 -0
- VideoLLaMA2/videollama2/eval/inference_video_mcqa_egoschema.py +153 -0
- VideoLLaMA2/videollama2/eval/inference_video_mcqa_mvbench.py +203 -0
- VideoLLaMA2/videollama2/eval/inference_video_mcqa_perception_test_mcqa.py +169 -0
- VideoLLaMA2/videollama2/eval/inference_video_mcqa_videomme.py +304 -0
- VideoLLaMA2/videollama2/eval/inference_video_oqa_activitynet.py +150 -0
- VideoLLaMA2/videollama2/eval/inference_video_oqa_vcgpt_consistency.py +150 -0
.gitattributes
CHANGED
@@ -33,3 +33,13 @@ 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 |
+
VideoLLaMA2/assets/cat_and_chicken.mp4 filter=lfs diff=lfs merge=lfs -text
|
37 |
+
VideoLLaMA2/assets/logo.png filter=lfs diff=lfs merge=lfs -text
|
38 |
+
VideoLLaMA2/assets/pipeline.png filter=lfs diff=lfs merge=lfs -text
|
39 |
+
VideoLLaMA2/assets/sora.mp4 filter=lfs diff=lfs merge=lfs -text
|
40 |
+
VideoLLaMA2/assets/sora.png filter=lfs diff=lfs merge=lfs -text
|
41 |
+
VideoLLaMA2/videollama2/serve/examples/1034346401.mp4 filter=lfs diff=lfs merge=lfs -text
|
42 |
+
VideoLLaMA2/videollama2/serve/examples/desert.jpg filter=lfs diff=lfs merge=lfs -text
|
43 |
+
VideoLLaMA2/videollama2/serve/examples/sample_demo_1.mp4 filter=lfs diff=lfs merge=lfs -text
|
44 |
+
VideoLLaMA2/videollama2/serve/examples/sample_demo_3.mp4 filter=lfs diff=lfs merge=lfs -text
|
45 |
+
VideoLLaMA2/videollama2/serve/examples/sample_demo_9.mp4 filter=lfs diff=lfs merge=lfs -text
|
VideoLLaMA2/.gitignore
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Python
|
2 |
+
__pycache__
|
3 |
+
*.pyc
|
4 |
+
*.egg-info
|
5 |
+
dist
|
6 |
+
|
7 |
+
# Log
|
8 |
+
*.log
|
9 |
+
*.log.*
|
10 |
+
*.json
|
11 |
+
*.jsonl
|
12 |
+
log_dir*/
|
13 |
+
temp*/
|
14 |
+
|
15 |
+
# Data
|
16 |
+
!**/alpaca-data-conversation.json
|
17 |
+
|
18 |
+
# Editor
|
19 |
+
.idea
|
20 |
+
*.swp
|
21 |
+
|
22 |
+
# Other
|
23 |
+
.DS_Store
|
24 |
+
3rd_parties
|
25 |
+
|
26 |
+
# jupyter
|
27 |
+
.ipynb_checkpoints
|
28 |
+
*.ipynb
|
29 |
+
|
30 |
+
# DevContainer
|
31 |
+
!.devcontainer/*
|
32 |
+
|
33 |
+
# Demo
|
34 |
+
serve_images/
|
35 |
+
temp/
|
36 |
+
|
37 |
+
# data folder
|
38 |
+
data/
|
39 |
+
dataset/
|
40 |
+
datasets/
|
41 |
+
|
42 |
+
# training folder
|
43 |
+
wandb
|
44 |
+
ckpts*
|
45 |
+
output
|
46 |
+
output/
|
47 |
+
checkpoints
|
48 |
+
checkpoints/
|
49 |
+
work_dirs*/
|
50 |
+
|
51 |
+
# evaluation folder
|
52 |
+
/eval
|
53 |
+
/eval*
|
54 |
+
|
55 |
+
# pretrained weights
|
56 |
+
pretrained/
|
57 |
+
publish_models/
|
58 |
+
public_models/
|
VideoLLaMA2/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.
|
VideoLLaMA2/README.md
ADDED
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<p align="center">
|
2 |
+
<img src="https://github.com/DAMO-NLP-SG/VideoLLaMA2/blob/e7bc34e0e9a96d77947a75b54399d9f96ccf209d/assets/logo.png" width="150" style="margin-bottom: 0.2;"/>
|
3 |
+
<p>
|
4 |
+
|
5 |
+
<h3 align="center"><a href="https://arxiv.org/abs/2406.07476" style="color:#9C276A">
|
6 |
+
VideoLLaMA 2: Advancing Spatial-Temporal Modeling and Audio Understanding in Video-LLMs</a></h3>
|
7 |
+
<h5 align="center"> If our project helps you, please give us a star ⭐ on GitHub to support us. 🙏🙏 </h2>
|
8 |
+
|
9 |
+
<h5 align="center">
|
10 |
+
|
11 |
+
[](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2-AV)
|
12 |
+
[](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2)
|
13 |
+
[](https://huggingface.co/collections/DAMO-NLP-SG/videollama-2-6669b6b6f0493188305c87ed)
|
14 |
+
[](https://huggingface.co/datasets/DAMO-NLP-SG/Multi-Source-Video-Captioning) <br>
|
15 |
+
[](https://github.com/DAMO-NLP-SG/VideoLLaMA2/blob/main/LICENSE)
|
16 |
+
[](https://hits.seeyoufarm.com)
|
17 |
+
[](https://github.com/DAMO-NLP-SG/VideoLLaMA2/issues?q=is%3Aopen+is%3Aissue)
|
18 |
+
[](https://github.com/DAMO-NLP-SG/VideoLLaMA2/issues?q=is%3Aissue+is%3Aclosed) <br>
|
19 |
+
[](https://huggingface.co/papers/2406.07476)
|
20 |
+
[](https://arxiv.org/abs/2406.07476) <br>
|
21 |
+
|
22 |
+
</h5>
|
23 |
+
|
24 |
+
[](https://paperswithcode.com/sota/zero-shot-video-question-answer-on-egoschema-1?p=videollama-2-advancing-spatial-temporal) <br>
|
25 |
+
[](https://paperswithcode.com/sota/video-question-answering-on-perception-test?p=videollama-2-advancing-spatial-temporal) <br>
|
26 |
+
[](https://paperswithcode.com/sota/video-question-answering-on-mvbench?p=videollama-2-advancing-spatial-temporal) <br>
|
27 |
+
[](https://paperswithcode.com/sota/zero-shot-video-question-answer-on-video-mme-1?p=videollama-2-advancing-spatial-temporal) <br>
|
28 |
+
[](https://paperswithcode.com/sota/zero-shot-video-question-answer-on-video-mme?p=videollama-2-advancing-spatial-temporal) <br>
|
29 |
+
|
30 |
+
<details open><summary>💡 Some other multimodal-LLM projects from our team may interest you ✨. </summary><p>
|
31 |
+
<!-- may -->
|
32 |
+
|
33 |
+
> [**VideoLLaMA 3: Frontier Multimodal Foundation Models for Image and Video Understanding**](https://github.com/DAMO-NLP-SG/VideoLLaMA3) <br>
|
34 |
+
> Boqiang Zhang<sup>* </sup>, Kehan Li<sup>* </sup>, Zesen Cheng<sup>* </sup>, Zhiqiang Hu<sup>* </sup>, Yuqian Yuan<sup>* </sup>, Guanzheng Chen<sup>* </sup>, Sicong Leng<sup>* </sup>, Yuming Jiang<sup>* </sup>, Hang Zhang<sup>* </sup>, Xin Li<sup>* </sup>, Peng Jin, Wenqi Zhang, Fan Wang, Lidong Bing, Deli Zhao <br>
|
35 |
+
[](https://github.com/DAMO-NLP-SG/VideoLLaMA3) [](https://github.com/DAMO-NLP-SG/VideoLLaMA3) [](https://arxiv.org/abs/2501.13106) <br>
|
36 |
+
|
37 |
+
> [**Video-LLaMA: An Instruction-tuned Audio-Visual Language Model for Video Understanding**](https://github.com/DAMO-NLP-SG/Video-LLaMA) <br>
|
38 |
+
> Hang Zhang, Xin Li, Lidong Bing <br>
|
39 |
+
[](https://github.com/DAMO-NLP-SG/Video-LLaMA) [](https://github.com/DAMO-NLP-SG/Video-LLaMA) [](https://arxiv.org/abs/2306.02858) <br>
|
40 |
+
|
41 |
+
> [**VCD: Mitigating Object Hallucinations in Large Vision-Language Models through Visual Contrastive Decoding**](https://arxiv.org/abs/2311.16922) <br>
|
42 |
+
> Sicong Leng<sup>* </sup>, Hang Zhang<sup>* </sup>, Guanzheng Chen, Xin Li, Shijian Lu, Chunyan Miao, Lidong Bing <br>
|
43 |
+
[](https://github.com/DAMO-NLP-SG/VCD) [](https://github.com/DAMO-NLP-SG/VCD) [](https://arxiv.org/abs/2311.16922) <br>
|
44 |
+
|
45 |
+
> [**The Curse of Multi-Modalities: Evaluating Hallucinations of Large Multimodal Models across Language, Visual, and Audio**](https://arxiv.org/abs/2410.12787) <br>
|
46 |
+
> Sicong Leng, Yun Xing, Zesen Cheng, Yang Zhou, Hang Zhang, Xin Li, Deli Zhao, Shijian Lu, Chunyan Miao, Lidong Bing <br>
|
47 |
+
[](https://github.com/DAMO-NLP-SG/CMM) [](https://github.com/DAMO-NLP-SG/CMM) [](https://arxiv.org/abs/2410.12787) <br>
|
48 |
+
|
49 |
+
> [**Breaking the Memory Barrier: Near Infinite Batch Size Scaling for Contrastive Loss**](https://arxiv.org/abs/2410.17243) <br>
|
50 |
+
> Zesen Cheng*, Hang Zhang*, Kehan Li*, Sicong Leng, Zhiqiang Hu, Fei Wu, Deli Zhao, Xin Li, Lidong Bing <br>
|
51 |
+
[](https://github.com/DAMO-NLP-SG/Inf-CLIP) [](https://github.com/DAMO-NLP-SG/Inf-CLIP) [](https://arxiv.org/abs/2410.17243) <br>
|
52 |
+
|
53 |
+
</p></details>
|
54 |
+
|
55 |
+
<div align="center"><video src="https://github.com/DAMO-NLP-SG/VideoLLaMA2/assets/18526640/e0e7951c-f392-42ed-afad-b2c7984d3e38" width="800"></div>
|
56 |
+
|
57 |
+
|
58 |
+
## 📰 News
|
59 |
+
* **[2025.01.21]** 🚀🚀 We are excited to officially launch [VideoLLaMA3](https://github.com/DAMO-NLP-SG/VideoLLaMA3), featuring enhanced performance across image and video benchmarks, along with a variety of easy-to-follow inference cookbooks. Try it out today!
|
60 |
+
* **[2024.10.22]** Release checkpoints of [VideoLLaMA2.1-7B-AV](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-AV). The audio_visual branch code can be seen here: https://github.com/DAMO-NLP-SG/VideoLLaMA2/tree/audio_visual.
|
61 |
+
* **[2024.10.15]** Release checkpoints of [VideoLLaMA2.1-7B-16F-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-Base) and [VideoLLaMA2.1-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-16F).
|
62 |
+
* **[2024.08.14]** Release checkpoints of [VideoLLaMA2-72B-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-72B-Base) and [VideoLLaMA2-72B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-72B).
|
63 |
+
* **[2024.07.30]** Release checkpoints of [VideoLLaMA2-8x7B-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-8x7B-Base) and [VideoLLaMA2-8x7B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-8x7B).
|
64 |
+
* **[2024.06.25]** 🔥🔥 As of Jun 25, our [VideoLLaMA2-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B-16F) is the **Top-1** ~7B-sized VideoLLM on the [MLVU Leaderboard](https://github.com/JUNJIE99/MLVU?tab=readme-ov-file#trophy-mini-leaderboard).
|
65 |
+
* **[2024.06.18]** 🔥🔥 As of Jun 18, our [VideoLLaMA2-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B-16F) is the **Top-1** ~7B-sized VideoLLM on the [VideoMME Leaderboard](https://video-mme.github.io/home_page.html#leaderboard).
|
66 |
+
* **[2024.06.17]** 👋👋 Update technical report with the latest results and the missing references. If you have works closely related to VideoLLaMA 2 but not mentioned in the paper, feel free to let us know.
|
67 |
+
* **[2024.06.14]** 🔥🔥 [Online Demo](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2) is available.
|
68 |
+
* **[2024.06.03]** Release training, evaluation, and serving codes of VideoLLaMA 2.
|
69 |
+
|
70 |
+
|
71 |
+
<img src="https://github.com/DAMO-NLP-SG/VideoLLaMA2/assets/18526640/b9faf24f-bdd2-4728-9385-acea17ea086d" width="800" />
|
72 |
+
|
73 |
+
## 🛠️ Requirements and Installation
|
74 |
+
Basic Dependencies:
|
75 |
+
* Python >= 3.8
|
76 |
+
* Pytorch >= 2.2.0
|
77 |
+
* CUDA Version >= 11.8
|
78 |
+
* transformers == 4.40.0 (for reproducing paper results)
|
79 |
+
* tokenizers == 0.19.1
|
80 |
+
|
81 |
+
**[Online Mode]** Install required packages (better for development):
|
82 |
+
```bash
|
83 |
+
git clone https://github.com/DAMO-NLP-SG/VideoLLaMA2
|
84 |
+
cd VideoLLaMA2
|
85 |
+
pip install -r requirements.txt
|
86 |
+
pip install flash-attn==2.5.8 --no-build-isolation
|
87 |
+
```
|
88 |
+
|
89 |
+
**[Offline Mode]** Install VideoLLaMA2 as a Python package (better for direct use):
|
90 |
+
```bash
|
91 |
+
git clone https://github.com/DAMO-NLP-SG/VideoLLaMA2
|
92 |
+
cd VideoLLaMA2
|
93 |
+
pip install --upgrade pip # enable PEP 660 support
|
94 |
+
pip install -e .
|
95 |
+
pip install flash-attn==2.5.8 --no-build-isolation
|
96 |
+
```
|
97 |
+
|
98 |
+
## 🚀 Main Results
|
99 |
+
|
100 |
+
### Multi-Choice Video QA & Video Captioning
|
101 |
+
<p><img src="https://github.com/user-attachments/assets/e87fe4cf-07ea-4fde-998b-a0c63671c3b4" width="800" "/></p>
|
102 |
+
|
103 |
+
### Open-Ended Video QA
|
104 |
+
<p><img src="https://github.com/user-attachments/assets/80b16c04-75ac-43b8-bc22-6952fdf994bb" width="800" "/></p>
|
105 |
+
|
106 |
+
### Audio QA
|
107 |
+
<p><img src="https://github.com/user-attachments/assets/46e55952-5a54-4564-bcd4-cfa4edd7f36a" width="800" "/></p>
|
108 |
+
|
109 |
+
### Audio-Visual QA
|
110 |
+
<p><img src="https://github.com/user-attachments/assets/8114c1e3-7f93-401b-9ea6-9ce7c96d7b05" width="800" "/></p>
|
111 |
+
|
112 |
+
|
113 |
+
## :earth_americas: Model Zoo
|
114 |
+
### Vision-only Checkpoints
|
115 |
+
| Model Name | Model Type | Visual Encoder | Language Decoder | # Training Frames |
|
116 |
+
|:----------------|:------------:|:----------------|:------------------|:----------------:|
|
117 |
+
| [VideoLLaMA2-7B-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B-Base) | Base | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) | 8 |
|
118 |
+
| [VideoLLaMA2-7B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B) | Chat | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) | 8 |
|
119 |
+
| [VideoLLaMA2-7B-16F-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B-16F-Base) | Base | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) | 16 |
|
120 |
+
| [VideoLLaMA2-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B-16F) | Chat | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mistral-7B-Instruct-v0.2](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2) | 16 |
|
121 |
+
| [VideoLLaMA2-8x7B-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-8x7B-Base) | Base | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mixtral-8x7B-Instruct-v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1) | 8 |
|
122 |
+
| [VideoLLaMA2-8x7B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-8x7B) | Chat | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Mixtral-8x7B-Instruct-v0.1](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1) | 8 |
|
123 |
+
| [VideoLLaMA2-72B-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-72B-Base) | Base | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Qwen2-72B-Instruct](https://huggingface.co/Qwen/Qwen2-72B-Instruct) | 8 |
|
124 |
+
| [VideoLLaMA2-72B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-72B) | Chat | [clip-vit-large-patch14-336](https://huggingface.co/openai/clip-vit-large-patch14-336) | [Qwen2-72B-Instruct](https://huggingface.co/Qwen/Qwen2-72B-Instruct) | 8 |
|
125 |
+
| [VideoLLaMA2.1-7B-16F-Base](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-Base) | Base | [siglip-so400m-patch14-384](https://huggingface.co/google/siglip-so400m-patch14-384) | [Qwen2-7B-Instruct](https://huggingface.co/Qwen/Qwen2-7B-Instruct) | 16 |
|
126 |
+
| [VideoLLaMA2.1-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-16F) | Chat | [siglip-so400m-patch14-384](https://huggingface.co/google/siglip-so400m-patch14-384) | [Qwen2-7B-Instruct](https://huggingface.co/Qwen/Qwen2-7B-Instruct) | 16 |
|
127 |
+
|
128 |
+
|
129 |
+
### Audio-Visual Checkpoints
|
130 |
+
| Model Name | Type | Audio Encoder | Language Decoder |
|
131 |
+
|:-------------------|:----------------|:----------------|:------------------|
|
132 |
+
| [VideoLLaMA2.1-7B-AV](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-AV) | Chat | [Fine-tuned BEATs_iter3+(AS2M)(cpt2)](https://1drv.ms/u/s!AqeByhGUtINrgcpj8ujXH1YUtxooEg?e=E9Ncea) | [VideoLLaMA2.1-7B-16F](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2.1-7B-16F) |
|
133 |
+
|
134 |
+
|
135 |
+
|
136 |
+
## [🤗 Demo](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2)
|
137 |
+
|
138 |
+
It is highly recommended to try our [online demo](https://huggingface.co/spaces/lixin4ever/VideoLLaMA2) first.
|
139 |
+
|
140 |
+
To run a video-based LLM (Large Language Model) web demonstration on your device, you will first need to ensure that you have the necessary model checkpoints prepared, followed by adhering to the steps outlined to successfully launch the demo.
|
141 |
+
|
142 |
+
### Single-model Version
|
143 |
+
|
144 |
+
* Launch a gradio app directly ([VideoLLaMA2-7B](https://huggingface.co/DAMO-NLP-SG/VideoLLaMA2-7B) is adopted by default):
|
145 |
+
```bash
|
146 |
+
python videollama2/serve/gradio_web_server_adhoc.py
|
147 |
+
```
|
148 |
+
|
149 |
+
### Multiple-model Version
|
150 |
+
|
151 |
+
1. Launch a global controller
|
152 |
+
```bash
|
153 |
+
cd /path/to/VideoLLaMA2
|
154 |
+
python -m videollama2.serve.controller --host 0.0.0.0 --port 10000
|
155 |
+
```
|
156 |
+
|
157 |
+
2. Launch a gradio webserver
|
158 |
+
```bash
|
159 |
+
python -m videollama2.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
|
160 |
+
```
|
161 |
+
|
162 |
+
3. Launch one or multiple model workers
|
163 |
+
```bash
|
164 |
+
# export HF_ENDPOINT=https://hf-mirror.com # If you are unable to access Hugging Face, try to uncomment this line.
|
165 |
+
python -m videollama2.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path /PATH/TO/MODEL1
|
166 |
+
python -m videollama2.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40001 --worker http://localhost:40001 --model-path /PATH/TO/MODEL2
|
167 |
+
python -m videollama2.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40002 --worker http://localhost:40002 --model-path /PATH/TO/MODEL3
|
168 |
+
...
|
169 |
+
```
|
170 |
+
|
171 |
+
|
172 |
+
## 🗝️ Training & Evaluation
|
173 |
+
|
174 |
+
### Quick Start
|
175 |
+
|
176 |
+
To facilitate further development on top of our codebase, we provide a quick-start guide on how to train a customized [VideoLLaMA2](https://github.com/DAMO-NLP-SG/VideoLLaMA2) with [VideoLLaVA](https://github.com/PKU-YuanGroup/Video-LLaVA) dataset and evaluate the trained model on the mainstream video-llm benchmarks.
|
177 |
+
|
178 |
+
1. Training Data Structure:
|
179 |
+
```bash
|
180 |
+
VideoLLaMA2
|
181 |
+
├── datasets
|
182 |
+
│ ├── videollava_pt
|
183 |
+
| | ├── llava_image/ # Available at: https://pan.baidu.com/s/17GYcE69FcJjjUM0e4Gad2w?pwd=9ga3 or https://drive.google.com/drive/folders/1QmFj2FcMAoWNCUyiUtdcW0-IOhLbOBcf?usp=drive_link
|
184 |
+
| | ├── valley/ # Available at: https://pan.baidu.com/s/1jluOimE7mmihEBfnpwwCew?pwd=jyjz or https://drive.google.com/drive/folders/1QmFj2FcMAoWNCUyiUtdcW0-IOhLbOBcf?usp=drive_link
|
185 |
+
| | └── valley_llavaimage.json # Available at: https://drive.google.com/file/d/1zGRyVSUMoczGq6cjQFmT0prH67bu2wXD/view, including 703K video-text and 558K image-text pairs
|
186 |
+
│ ├── videollava_sft
|
187 |
+
| | ├── llava_image_tune/ # Available at: https://pan.baidu.com/s/1l-jT6t_DlN5DTklwArsqGw?pwd=o6ko
|
188 |
+
| | ├── videochatgpt_tune/ # Available at: https://pan.baidu.com/s/10hJ_U7wVmYTUo75YHc_n8g?pwd=g1hf
|
189 |
+
| | └── videochatgpt_llavaimage_tune.json # Available at: https://drive.google.com/file/d/1zGRyVSUMoczGq6cjQFmT0prH67bu2wXD/view, including 100K video-centric, 625K image-centric and 40K text-only conversations
|
190 |
+
```
|
191 |
+
2. Command:
|
192 |
+
```bash
|
193 |
+
# VideoLLaMA2-vllava pretraining
|
194 |
+
bash scripts/vllava/pretrain.sh
|
195 |
+
# VideoLLaMA2-vllava finetuning
|
196 |
+
bash scripts/vllava/finetune.sh
|
197 |
+
```
|
198 |
+
3. Evaluation Data Structure:
|
199 |
+
```bash
|
200 |
+
VideoLLaMA2
|
201 |
+
├── eval
|
202 |
+
│ ├── egoschema # Official website: https://github.com/egoschema/EgoSchema
|
203 |
+
| | ├── good_clips_git/ # Available at: https://drive.google.com/drive/folders/1SS0VVz8rML1e5gWq7D7VtP1oxE2UtmhQ
|
204 |
+
| | └── questions.json # Available at: https://github.com/egoschema/EgoSchema/blob/main/questions.json
|
205 |
+
│ ├── mvbench # Official website: https://huggingface.co/datasets/OpenGVLab/MVBench
|
206 |
+
| | ├── video/
|
207 |
+
| | | ├── clever/
|
208 |
+
| | | └── ...
|
209 |
+
| | └── json/
|
210 |
+
| | | ├── action_antonym.json
|
211 |
+
| | | └── ...
|
212 |
+
│ ├── perception_test_mcqa # Official website: https://huggingface.co/datasets/OpenGVLab/MVBench
|
213 |
+
| | ├── videos/ # Available at: https://storage.googleapis.com/dm-perception-test/zip_data/test_videos.zip
|
214 |
+
| | └── mc_question_test.json # Download from https://storage.googleapis.com/dm-perception-test/zip_data/mc_question_test_annotations.zip
|
215 |
+
│ ├── videomme # Official website: https://video-mme.github.io/home_page.html#leaderboard
|
216 |
+
| | ├── test-00000-of-00001.parquet
|
217 |
+
| | ├── videos/
|
218 |
+
| | └── subtitles/
|
219 |
+
│ ├── Activitynet_Zero_Shot_QA # Official website: https://github.com/MILVLG/activitynet-qa
|
220 |
+
| | ├── all_test/ # Available at: https://mbzuaiac-my.sharepoint.com/:u:/g/personal/hanoona_bangalath_mbzuai_ac_ae/EatOpE7j68tLm2XAd0u6b8ABGGdVAwLMN6rqlDGM_DwhVA?e=90WIuW
|
221 |
+
| | ├── test_q.json # Available at: https://github.com/MILVLG/activitynet-qa/tree/master/dataset
|
222 |
+
| | └── test_a.json # Available at: https://github.com/MILVLG/activitynet-qa/tree/master/dataset
|
223 |
+
│ ├── MSVD_Zero_Shot_QA # Official website: https://github.com/xudejing/video-question-answering
|
224 |
+
| | ├── videos/
|
225 |
+
| | ├── test_q.json
|
226 |
+
| | └── test_a.json
|
227 |
+
│ ├── videochatgpt_gen # Official website: https://github.com/mbzuai-oryx/Video-ChatGPT/tree/main/quantitative_evaluation
|
228 |
+
| | ├── Test_Videos/ # Available at: https://mbzuaiac-my.sharepoint.com/:u:/g/personal/hanoona_bangalath_mbzuai_ac_ae/EatOpE7j68tLm2XAd0u6b8ABGGdVAwLMN6rqlDGM_DwhVA?e=90WIuW
|
229 |
+
| | ├── Test_Human_Annotated_Captions/ # Available at: https://mbzuaiac-my.sharepoint.com/personal/hanoona_bangalath_mbzuai_ac_ae/_layouts/15/onedrive.aspx?id=%2Fpersonal%2Fhanoona%5Fbangalath%5Fmbzuai%5Fac%5Fae%2FDocuments%2FVideo%2DChatGPT%2FData%5FCode%5FModel%5FRelease%2FQuantitative%5FEvaluation%2Fbenchamarking%2FTest%5FHuman%5FAnnotated%5FCaptions%2Ezip&parent=%2Fpersonal%2Fhanoona%5Fbangalath%5Fmbzuai%5Fac%5Fae%2FDocuments%2FVideo%2DChatGPT%2FData%5FCode%5FModel%5FRelease%2FQuantitative%5FEvaluation%2Fbenchamarking&ga=1
|
230 |
+
| | ├── generic_qa.json # These three json files available at: https://mbzuaiac-my.sharepoint.com/personal/hanoona_bangalath_mbzuai_ac_ae/_layouts/15/onedrive.aspx?id=%2Fpersonal%2Fhanoona%5Fbangalath%5Fmbzuai%5Fac%5Fae%2FDocuments%2FVideo%2DChatGPT%2FData%5FCode%5FModel%5FRelease%2FQuantitative%5FEvaluation%2Fbenchamarking%2FBenchmarking%5FQA&ga=1
|
231 |
+
| | ├── temporal_qa.json
|
232 |
+
| | └── consistency_qa.json
|
233 |
+
```
|
234 |
+
4. Command:
|
235 |
+
```bash
|
236 |
+
# mvbench evaluation
|
237 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/eval/eval_video_qa_mvbench.sh
|
238 |
+
# activitynet-qa evaluation (need to set azure openai key/endpoint/deployname)
|
239 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 bash scripts/eval/eval_video_qa_mvbench.sh
|
240 |
+
```
|
241 |
+
|
242 |
+
### Data Format
|
243 |
+
|
244 |
+
If you want to train a video-llm on your data, you need to follow the procedures below to prepare the video/image sft data:
|
245 |
+
|
246 |
+
1. Suppose your data structure is like:
|
247 |
+
```bash
|
248 |
+
VideoLLaMA2
|
249 |
+
├── datasets
|
250 |
+
│ ├── custom_sft
|
251 |
+
│ | ├── images
|
252 |
+
│ | ├── videos
|
253 |
+
| | └── custom.json
|
254 |
+
```
|
255 |
+
2. Then you should re-organize the annotated video/image sft data according to the following format:
|
256 |
+
```json
|
257 |
+
[
|
258 |
+
{
|
259 |
+
"id": 0,
|
260 |
+
"video": "images/xxx.jpg",
|
261 |
+
"conversations": [
|
262 |
+
{
|
263 |
+
"from": "human",
|
264 |
+
"value": "<image>\nWhat are the colors of the bus in the image?"
|
265 |
+
},
|
266 |
+
{
|
267 |
+
"from": "gpt",
|
268 |
+
"value": "The bus in the image is white and red."
|
269 |
+
},
|
270 |
+
...
|
271 |
+
],
|
272 |
+
}
|
273 |
+
{
|
274 |
+
"id": 1,
|
275 |
+
"video": "videos/xxx.mp4",
|
276 |
+
"conversations": [
|
277 |
+
{
|
278 |
+
"from": "human",
|
279 |
+
"value": "<video>\nWhat are the main activities that take place in the video?"
|
280 |
+
},
|
281 |
+
{
|
282 |
+
"from": "gpt",
|
283 |
+
"value": "The main activities that take place in the video are the preparation of camera equipment by a man, a group of men riding a helicopter, and a man sailing a boat through the water."
|
284 |
+
},
|
285 |
+
...
|
286 |
+
],
|
287 |
+
},
|
288 |
+
...
|
289 |
+
]
|
290 |
+
```
|
291 |
+
3. Modify the `scripts/custom/finetune.sh`:
|
292 |
+
```bash
|
293 |
+
...
|
294 |
+
--data_path datasets/custom_sft/custom.json
|
295 |
+
--data_folder datasets/custom_sft/
|
296 |
+
--pretrain_mm_mlp_adapter CONNECTOR_DOWNLOAD_PATH (e.g., DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-Base)
|
297 |
+
...
|
298 |
+
```
|
299 |
+
|
300 |
+
## 🤖 Inference
|
301 |
+
|
302 |
+
Video/Image Inference:
|
303 |
+
```python
|
304 |
+
import sys
|
305 |
+
sys.path.append('./')
|
306 |
+
from videollama2 import model_init, mm_infer
|
307 |
+
from videollama2.utils import disable_torch_init
|
308 |
+
|
309 |
+
|
310 |
+
def inference():
|
311 |
+
disable_torch_init()
|
312 |
+
|
313 |
+
# Video Inference
|
314 |
+
modal = 'video'
|
315 |
+
modal_path = 'assets/cat_and_chicken.mp4'
|
316 |
+
instruct = 'What animals are in the video, what are they doing, and how does the video feel?'
|
317 |
+
# Reply:
|
318 |
+
# The video features a kitten and a baby chick playing together. The kitten is seen laying on the floor while the baby chick hops around. The two animals interact playfully with each other, and the video has a cute and heartwarming feel to it.
|
319 |
+
|
320 |
+
# Image Inference
|
321 |
+
modal = 'image'
|
322 |
+
modal_path = 'assets/sora.png'
|
323 |
+
instruct = 'What is the woman wearing, what is she doing, and how does the image feel?'
|
324 |
+
# Reply:
|
325 |
+
# The woman in the image is wearing a black coat and sunglasses, and she is walking down a rain-soaked city street. The image feels vibrant and lively, with the bright city lights reflecting off the wet pavement, creating a visually appealing atmosphere. The woman's presence adds a sense of style and confidence to the scene, as she navigates the bustling urban environment.
|
326 |
+
|
327 |
+
model_path = 'DAMO-NLP-SG/VideoLLaMA2.1-7B-16F'
|
328 |
+
# Base model inference (only need to replace model_path)
|
329 |
+
# model_path = 'DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-Base'
|
330 |
+
model, processor, tokenizer = model_init(model_path)
|
331 |
+
output = mm_infer(processor[modal](modal_path), instruct, model=model, tokenizer=tokenizer, do_sample=False, modal=modal)
|
332 |
+
|
333 |
+
print(output)
|
334 |
+
|
335 |
+
if __name__ == "__main__":
|
336 |
+
inference()
|
337 |
+
```
|
338 |
+
|
339 |
+
## 📑 Citation
|
340 |
+
|
341 |
+
If you find VideoLLaMA useful for your research and applications, please cite using this BibTeX:
|
342 |
+
```bibtex
|
343 |
+
@article{damonlpsg2024videollama2,
|
344 |
+
title={VideoLLaMA 2: Advancing Spatial-Temporal Modeling and Audio Understanding in Video-LLMs},
|
345 |
+
author={Cheng, Zesen and Leng, Sicong and Zhang, Hang and Xin, Yifei and Li, Xin and Chen, Guanzheng and Zhu, Yongxin and Zhang, Wenqi and Luo, Ziyang and Zhao, Deli and Bing, Lidong},
|
346 |
+
journal={arXiv preprint arXiv:2406.07476},
|
347 |
+
year={2024},
|
348 |
+
url = {https://arxiv.org/abs/2406.07476}
|
349 |
+
}
|
350 |
+
|
351 |
+
@article{damonlpsg2023videollama,
|
352 |
+
title = {Video-LLaMA: An Instruction-tuned Audio-Visual Language Model for Video Understanding},
|
353 |
+
author = {Zhang, Hang and Li, Xin and Bing, Lidong},
|
354 |
+
journal = {arXiv preprint arXiv:2306.02858},
|
355 |
+
year = {2023},
|
356 |
+
url = {https://arxiv.org/abs/2306.02858}
|
357 |
+
}
|
358 |
+
```
|
359 |
+
|
360 |
+
## 👍 Acknowledgement
|
361 |
+
The codebase of VideoLLaMA 2 is adapted from [**LLaVA 1.5**](https:github.com/haotian-liu/LLaVA) and [**FastChat**](https://github.com/lm-sys/FastChat). We are also grateful for the following projects our VideoLLaMA 2 arise from:
|
362 |
+
* [**LLaMA 2**](https://github.com/meta-llama/llama), [**Mistral-7B**](https://mistral.ai/news/announcing-mistral-7b/), [**OpenAI CLIP**](https://openai.com/index/clip/), [**Qwen2**](https://huggingface.co/collections/Qwen/qwen2-6659360b33528ced941e557f), [**SigLIP**](https://huggingface.co/collections/google/siglip-659d5e62f0ae1a57ae0e83ba), [**Honeybee**](https://github.com/kakaobrain/honeybee).
|
363 |
+
* [**Video-ChatGPT**](https://github.com/mbzuai-oryx/Video-ChatGPT), [**Video-LLaVA**](https://github.com/PKU-YuanGroup/Video-LLaVA).
|
364 |
+
* [**WebVid**](https://github.com/m-bain/webvid), [**Panda-70M**](https://github.com/snap-research/Panda-70M), [**LanguageBind**](https://github.com/PKU-YuanGroup/LanguageBind), [**InternVid**](https://github.com/OpenGVLab/InternVideo/tree/main/Data/InternVid).
|
365 |
+
* [**VideoChat2**](https://github.com/OpenGVLab/Ask-Anything/tree/main/video_chat2), [**Valley**](https://github.com/RupertLuo/Valley), [**VTimeLLM**](https://github.com/huangb23/VTimeLLM), [**ShareGPT4V**](https://sharegpt4v.github.io/).
|
366 |
+
* [**Magpie**](https://github.com/magpie-align/magpie), [**ALLaVA**](https://github.com/FreedomIntelligence/ALLaVA), [**AVInstruct**](https://github.com/rikeilong/Bay-CAT/tree/main/AVinstruct).
|
367 |
+
|
368 |
+
|
369 |
+
## 🔒 License
|
370 |
+
|
371 |
+
This project is released under the Apache 2.0 license as found in the LICENSE file.
|
372 |
+
The service is a research preview intended for **non-commercial use ONLY**, subject to the model Licenses of LLaMA and Mistral, Terms of Use of the data generated by OpenAI, and Privacy Practices of ShareGPT. Please get in touch with us if you find any potential violations.
|
VideoLLaMA2/assets/cat_and_chicken.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1f24723064ee27ea8fc7a30b4542601ed03a42952c0d20fe918213cf876bfec4
|
3 |
+
size 18956323
|
VideoLLaMA2/assets/logo.png
ADDED
![]() |
Git LFS Details
|
VideoLLaMA2/assets/pipeline.png
ADDED
![]() |
Git LFS Details
|
VideoLLaMA2/assets/sora.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:24e5f0ea3353f23225d00efcdf136fa6dc346301fc34082790e2152c80fa0490
|
3 |
+
size 14978533
|
VideoLLaMA2/assets/sora.png
ADDED
![]() |
Git LFS Details
|
VideoLLaMA2/pyproject.toml
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[build-system]
|
2 |
+
requires = ["pdm-backend"]
|
3 |
+
build-backend = "pdm.backend"
|
4 |
+
|
5 |
+
[project]
|
6 |
+
name = "videollama2"
|
7 |
+
version = "1.0"
|
8 |
+
authors = [
|
9 |
+
{name = "Zesen Cheng", email = "[email protected]"},
|
10 |
+
{name = "Hang Zhang"},
|
11 |
+
{name = "Xin Li"},
|
12 |
+
]
|
13 |
+
description = "Release of VideoLLaMA2"
|
14 |
+
readme = "README.md"
|
15 |
+
requires-python = ">=3.8"
|
16 |
+
classifiers = [
|
17 |
+
"Programming Language :: Python :: 3",
|
18 |
+
"License :: OSI Approved :: Apache Software License",
|
19 |
+
]
|
20 |
+
dependencies = [
|
21 |
+
"torch==2.2.0", "torchvision==0.17.0",
|
22 |
+
"transformers==4.40.0", "tokenizers==0.19.1",
|
23 |
+
"deepspeed==0.13.1", "accelerate==0.26.1",
|
24 |
+
"peft==0.4.0", "timm==1.0.3", "numpy==1.24.4",
|
25 |
+
"decord==0.6.0", "imageio==2.34.0", "imageio-ffmpeg==0.4.9",
|
26 |
+
"moviepy==1.0.3", "opencv-python==4.6.0.66", "pysubs2",
|
27 |
+
"scikit-learn==1.2.2", "huggingface_hub==0.23.4", "sentencepiece==0.1.99",
|
28 |
+
"shortuuid", "einops==0.6.1", "einops-exts==0.0.4",
|
29 |
+
"bitsandbytes==0.43.0", "pydantic>=2.0", "markdown2[all]",
|
30 |
+
"gradio==3.50.0", "gradio_client==0.6.1", "httpx==0.24.1",
|
31 |
+
"requests", "openai", "uvicorn", "fastapi", "tensorboard", "wandb", "tabulate"
|
32 |
+
]
|
33 |
+
|
34 |
+
[project.urls]
|
35 |
+
"Homepage" = "https://github.com/DAMO-NLP-SG/VideoLLaMA2"
|
36 |
+
"Bug Tracker" = "https://github.com/DAMO-NLP-SG/VideoLLaMA2/issues"
|
37 |
+
|
38 |
+
[tool.pdm.build]
|
39 |
+
excludes = ["./.git"]
|
40 |
+
package-dir = "."
|
41 |
+
includes = ["./videollama2"]
|
VideoLLaMA2/requirements.txt
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
--extra-index-url https://download.pytorch.org/whl/cu118
|
2 |
+
# basic dependencies
|
3 |
+
torch==2.2.0
|
4 |
+
torchvision==0.17.0
|
5 |
+
transformers==4.40.0
|
6 |
+
tokenizers==0.19.1
|
7 |
+
deepspeed==0.13.1
|
8 |
+
accelerate==0.26.1
|
9 |
+
peft==0.4.0
|
10 |
+
timm==1.0.3
|
11 |
+
numpy==1.24.4
|
12 |
+
# data processing
|
13 |
+
decord==0.6.0
|
14 |
+
imageio==2.34.0
|
15 |
+
imageio-ffmpeg==0.4.9
|
16 |
+
moviepy==1.0.3
|
17 |
+
opencv-python==4.6.0.66
|
18 |
+
pysubs2
|
19 |
+
# misc
|
20 |
+
scikit-learn==1.2.2
|
21 |
+
huggingface_hub==0.23.4
|
22 |
+
sentencepiece==0.1.99
|
23 |
+
shortuuid
|
24 |
+
einops==0.6.1
|
25 |
+
einops-exts==0.0.4
|
26 |
+
bitsandbytes==0.43.0
|
27 |
+
pydantic>=2.0
|
28 |
+
markdown2[all]
|
29 |
+
gradio==3.50.0
|
30 |
+
gradio_client==0.6.1
|
31 |
+
httpx==0.24.1
|
32 |
+
requests
|
33 |
+
openai
|
34 |
+
uvicorn
|
35 |
+
fastapi
|
36 |
+
tensorboard
|
37 |
+
wandb
|
38 |
+
tabulate
|
39 |
+
spaces==0.29.2
|
VideoLLaMA2/scripts/custom/finetune.sh
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
# Environment Variables
|
4 |
+
ARG_WORLD_SIZE=${1:-1}
|
5 |
+
ARG_NPROC_PER_NODE=${2:-8}
|
6 |
+
ARG_MASTER_ADDR="127.0.0.1"
|
7 |
+
ARG_MASTER_PORT=16666
|
8 |
+
ARG_RANK=${3:-0}
|
9 |
+
|
10 |
+
# Multiple conditions
|
11 |
+
if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
|
12 |
+
WORLD_SIZE=$ARG_WORLD_SIZE
|
13 |
+
NPROC_PER_NODE=$ARG_NPROC_PER_NODE
|
14 |
+
fi
|
15 |
+
if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
|
16 |
+
MASTER_ADDR=$ARG_MASTER_ADDR
|
17 |
+
MASTER_PORT=$ARG_MASTER_PORT
|
18 |
+
RANK=$ARG_RANK
|
19 |
+
fi
|
20 |
+
|
21 |
+
echo "WORLD_SIZE: $WORLD_SIZE"
|
22 |
+
echo "NPROC_PER_NODE: $NPROC_PER_NODE"
|
23 |
+
|
24 |
+
# Training Arguments
|
25 |
+
GLOBAL_BATCH_SIZE=128
|
26 |
+
LOCAL_BATCH_SIZE=4
|
27 |
+
GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
|
28 |
+
|
29 |
+
# Log Arguments
|
30 |
+
export TRANSFORMERS_OFFLINE=1
|
31 |
+
export WANDB_PROJECT=videollama2qwen2_downstream_sft
|
32 |
+
RUN_NAME=siglip_tcv35_7b_16f
|
33 |
+
DATA_DIR=datasets
|
34 |
+
OUTP_DIR=work_dirs
|
35 |
+
|
36 |
+
torchrun --nnodes $WORLD_SIZE \
|
37 |
+
--nproc_per_node $NPROC_PER_NODE \
|
38 |
+
--master_addr=$MASTER_ADDR \
|
39 |
+
--master_port=$MASTER_PORT \
|
40 |
+
--node_rank $RANK \
|
41 |
+
videollama2/train.py \
|
42 |
+
--deepspeed scripts/zero3.json \
|
43 |
+
--model_type videollama2_qwen2 \
|
44 |
+
--model_path Qwen/Qwen2-7B-Instruct \
|
45 |
+
--vision_tower google/siglip-so400m-patch14-384 \
|
46 |
+
--mm_projector_type stc_connector_v35 \
|
47 |
+
--pretrain_mm_mlp_adapter DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-Base/mm_projector.bin \
|
48 |
+
--data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
|
49 |
+
--data_folder ${DATA_DIR}/videollava_sft/ \
|
50 |
+
--mm_vision_select_layer -2 \
|
51 |
+
--image_aspect_ratio pad \
|
52 |
+
--num_frames 16 \
|
53 |
+
--bf16 True \
|
54 |
+
--tf32 True \
|
55 |
+
--fp16 False \
|
56 |
+
--output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
|
57 |
+
--num_train_epochs 1 \
|
58 |
+
--per_device_train_batch_size $LOCAL_BATCH_SIZE \
|
59 |
+
--per_device_eval_batch_size 4 \
|
60 |
+
--gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
|
61 |
+
--save_strategy "steps" \
|
62 |
+
--save_steps 500 \
|
63 |
+
--save_total_limit 99 \
|
64 |
+
--learning_rate 2e-5 \
|
65 |
+
--weight_decay 0. \
|
66 |
+
--warmup_ratio 0.03 \
|
67 |
+
--lr_scheduler_type "cosine" \
|
68 |
+
--logging_steps 1 \
|
69 |
+
--model_max_length 2048 \
|
70 |
+
--gradient_checkpointing True \
|
71 |
+
--dataloader_num_workers 4 \
|
72 |
+
--report_to tensorboard \
|
73 |
+
--run_name $RUN_NAME \
|
VideoLLaMA2/scripts/custom/finetune_lora.sh
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
# Environment Variables
|
4 |
+
ARG_WORLD_SIZE=${1:-1}
|
5 |
+
ARG_NPROC_PER_NODE=${2:-8}
|
6 |
+
ARG_MASTER_ADDR="127.0.0.1"
|
7 |
+
ARG_MASTER_PORT=16666
|
8 |
+
ARG_RANK=${3:-0}
|
9 |
+
|
10 |
+
# Multiple conditions
|
11 |
+
if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
|
12 |
+
WORLD_SIZE=$ARG_WORLD_SIZE
|
13 |
+
NPROC_PER_NODE=$ARG_NPROC_PER_NODE
|
14 |
+
fi
|
15 |
+
if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
|
16 |
+
MASTER_ADDR=$ARG_MASTER_ADDR
|
17 |
+
MASTER_PORT=$ARG_MASTER_PORT
|
18 |
+
RANK=$ARG_RANK
|
19 |
+
fi
|
20 |
+
|
21 |
+
echo "WORLD_SIZE: $WORLD_SIZE"
|
22 |
+
echo "NPROC_PER_NODE: $NPROC_PER_NODE"
|
23 |
+
|
24 |
+
# Training Arguments
|
25 |
+
GLOBAL_BATCH_SIZE=128
|
26 |
+
LOCAL_BATCH_SIZE=4
|
27 |
+
GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
|
28 |
+
|
29 |
+
# Log Arguments
|
30 |
+
export TRANSFORMERS_OFFLINE=1
|
31 |
+
export WANDB_PROJECT=videollama2qwen2_downstream_sft
|
32 |
+
RUN_NAME=siglip_tcv35_7b_16f_lora
|
33 |
+
DATA_DIR=datasets
|
34 |
+
OUTP_DIR=work_dirs
|
35 |
+
|
36 |
+
torchrun --nnodes $WORLD_SIZE \
|
37 |
+
--nproc_per_node $NPROC_PER_NODE \
|
38 |
+
--master_addr=$MASTER_ADDR \
|
39 |
+
--master_port=$MASTER_PORT \
|
40 |
+
--node_rank $RANK \
|
41 |
+
videollama2/train.py \
|
42 |
+
--lora_enable True --lora_r 128 --lora_alpha 256 --mm_projector_lr 2e-5 \
|
43 |
+
--deepspeed scripts/zero3.json \
|
44 |
+
--model_type videollama2_qwen2 \
|
45 |
+
--model_path Qwen/Qwen2-7B-Instruct \
|
46 |
+
--vision_tower google/siglip-so400m-patch14-384 \
|
47 |
+
--mm_projector_type stc_connector_v35 \
|
48 |
+
--pretrain_mm_mlp_adapter DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-Base/mm_projector.bin \
|
49 |
+
--data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
|
50 |
+
--data_folder ${DATA_DIR}/videollava_sft/ \
|
51 |
+
--mm_vision_select_layer -2 \
|
52 |
+
--image_aspect_ratio pad \
|
53 |
+
--num_frames 16 \
|
54 |
+
--bf16 True \
|
55 |
+
--tf32 True \
|
56 |
+
--fp16 False \
|
57 |
+
--output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
|
58 |
+
--num_train_epochs 1 \
|
59 |
+
--per_device_train_batch_size $LOCAL_BATCH_SIZE \
|
60 |
+
--per_device_eval_batch_size 4 \
|
61 |
+
--gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
|
62 |
+
--save_strategy "steps" \
|
63 |
+
--save_steps 500 \
|
64 |
+
--save_total_limit 99 \
|
65 |
+
--learning_rate 2e-5 \
|
66 |
+
--weight_decay 0. \
|
67 |
+
--warmup_ratio 0.03 \
|
68 |
+
--lr_scheduler_type "cosine" \
|
69 |
+
--logging_steps 1 \
|
70 |
+
--model_max_length 2048 \
|
71 |
+
--gradient_checkpointing True \
|
72 |
+
--dataloader_num_workers 4 \
|
73 |
+
--report_to tensorboard \
|
74 |
+
--run_name $RUN_NAME \
|
VideoLLaMA2/scripts/custom/finetune_qlora.sh
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
# Environment Variables
|
4 |
+
ARG_WORLD_SIZE=${1:-1}
|
5 |
+
ARG_NPROC_PER_NODE=${2:-8}
|
6 |
+
ARG_MASTER_ADDR="127.0.0.1"
|
7 |
+
ARG_MASTER_PORT=16666
|
8 |
+
ARG_RANK=${3:-0}
|
9 |
+
|
10 |
+
# Multiple conditions
|
11 |
+
if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
|
12 |
+
WORLD_SIZE=$ARG_WORLD_SIZE
|
13 |
+
NPROC_PER_NODE=$ARG_NPROC_PER_NODE
|
14 |
+
fi
|
15 |
+
if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
|
16 |
+
MASTER_ADDR=$ARG_MASTER_ADDR
|
17 |
+
MASTER_PORT=$ARG_MASTER_PORT
|
18 |
+
RANK=$ARG_RANK
|
19 |
+
fi
|
20 |
+
|
21 |
+
echo "WORLD_SIZE: $WORLD_SIZE"
|
22 |
+
echo "NPROC_PER_NODE: $NPROC_PER_NODE"
|
23 |
+
|
24 |
+
# Training Arguments
|
25 |
+
GLOBAL_BATCH_SIZE=128
|
26 |
+
LOCAL_BATCH_SIZE=4
|
27 |
+
GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
|
28 |
+
|
29 |
+
# Log Arguments
|
30 |
+
export TRANSFORMERS_OFFLINE=1
|
31 |
+
export WANDB_PROJECT=videollama2qwen2_downstream_sft
|
32 |
+
RUN_NAME=siglip_tcv35_7b_16f_qlora
|
33 |
+
DATA_DIR=datasets
|
34 |
+
OUTP_DIR=work_dirs
|
35 |
+
|
36 |
+
torchrun --nnodes $WORLD_SIZE \
|
37 |
+
--nproc_per_node $NPROC_PER_NODE \
|
38 |
+
--master_addr=$MASTER_ADDR \
|
39 |
+
--master_port=$MASTER_PORT \
|
40 |
+
--node_rank $RANK \
|
41 |
+
videollama2/train.py \
|
42 |
+
--lora_enable True --lora_r 128 --lora_alpha 256 --mm_projector_lr 2e-5 --bits 4 \
|
43 |
+
--deepspeed scripts/zero2.json \
|
44 |
+
--model_type videollama2_qwen2 \
|
45 |
+
--model_path Qwen/Qwen2-7B-Instruct \
|
46 |
+
--vision_tower google/siglip-so400m-patch14-384 \
|
47 |
+
--mm_projector_type stc_connector_v35 \
|
48 |
+
--pretrain_mm_mlp_adapter DAMO-NLP-SG/VideoLLaMA2.1-7B-16F-Base/mm_projector.bin \
|
49 |
+
--data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
|
50 |
+
--data_folder ${DATA_DIR}/videollava_sft/ \
|
51 |
+
--mm_vision_select_layer -2 \
|
52 |
+
--image_aspect_ratio pad \
|
53 |
+
--num_frames 16 \
|
54 |
+
--bf16 True \
|
55 |
+
--tf32 True \
|
56 |
+
--fp16 False \
|
57 |
+
--output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
|
58 |
+
--num_train_epochs 1 \
|
59 |
+
--per_device_train_batch_size $LOCAL_BATCH_SIZE \
|
60 |
+
--per_device_eval_batch_size 4 \
|
61 |
+
--gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
|
62 |
+
--save_strategy "steps" \
|
63 |
+
--save_steps 500 \
|
64 |
+
--save_total_limit 99 \
|
65 |
+
--learning_rate 2e-5 \
|
66 |
+
--weight_decay 0. \
|
67 |
+
--warmup_ratio 0.03 \
|
68 |
+
--lr_scheduler_type "cosine" \
|
69 |
+
--logging_steps 1 \
|
70 |
+
--model_max_length 2048 \
|
71 |
+
--gradient_checkpointing True \
|
72 |
+
--dataloader_num_workers 4 \
|
73 |
+
--report_to tensorboard \
|
74 |
+
--run_name $RUN_NAME \
|
VideoLLaMA2/scripts/eval/eval_video_cap_msvc.sh
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/merge.json
|
16 |
+
|
17 |
+
# judge if the number of json lines is 0
|
18 |
+
if [ ! -f "$output_file" ] || [ $(cat "$output_file" | wc -l) -eq 0 ]; then
|
19 |
+
rm -f ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/*.json
|
20 |
+
fi
|
21 |
+
|
22 |
+
if [ ! -f "$output_file" ]; then
|
23 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
24 |
+
# select the GPUs for the task
|
25 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
26 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_cap_msvc.py \
|
27 |
+
--model-path ${CKPT} \
|
28 |
+
--video-folder ${EVAL_DATA_DIR}/msvc \
|
29 |
+
--question-file ${EVAL_DATA_DIR}/msvc/msvc.json \
|
30 |
+
--output-file ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
31 |
+
--num-chunks $CHUNKS \
|
32 |
+
--chunk-idx $IDX &
|
33 |
+
done
|
34 |
+
|
35 |
+
wait
|
36 |
+
|
37 |
+
# Clear out the output file if it exists.
|
38 |
+
> "$output_file"
|
39 |
+
|
40 |
+
#Loop through the indices and concatenate each file.
|
41 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
42 |
+
cat ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
43 |
+
done
|
44 |
+
fi
|
45 |
+
|
46 |
+
|
47 |
+
AZURE_API_KEY=your_key
|
48 |
+
AZURE_API_ENDPOINT=your_endpoint
|
49 |
+
AZURE_API_DEPLOYNAME=your_deployname
|
50 |
+
|
51 |
+
python3 videollama2/eval/eval_video_cap_msvc_correctness.py \
|
52 |
+
--pred-path $output_file \
|
53 |
+
--output-dir ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/correctness_gpt \
|
54 |
+
--output-json ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/correctness_results.json \
|
55 |
+
--api-key $AZURE_API_KEY \
|
56 |
+
--api-endpoint $AZURE_API_ENDPOINT \
|
57 |
+
--api-deployname $AZURE_API_DEPLOYNAME \
|
58 |
+
--num-tasks 4 \
|
59 |
+
|
60 |
+
python3 videollama2/eval/eval_video_cap_msvc_detailedness.py \
|
61 |
+
--pred-path $output_file \
|
62 |
+
--output-dir ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/detailedness_gpt \
|
63 |
+
--output-json ${OUTPUT_DIR}/msvc/answers/${CKPT_NAME}/detailedness_results.json \
|
64 |
+
--api-key $AZURE_API_KEY \
|
65 |
+
--api-endpoint $AZURE_API_ENDPOINT \
|
66 |
+
--api-deployname $AZURE_API_DEPLOYNAME \
|
67 |
+
--num-tasks 4 \
|
VideoLLaMA2/scripts/eval/eval_video_mcqa_egoschema.sh
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/egoschema/answers/${CKPT_NAME}/merge.csv
|
16 |
+
|
17 |
+
if [ ! -f "$output_file" ]; then
|
18 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
19 |
+
# select the GPUs for the task
|
20 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
21 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_mcqa_egoschema.py \
|
22 |
+
--model-path ${CKPT} \
|
23 |
+
--video-folder ${EVAL_DATA_DIR}/egoschema/good_clips_git \
|
24 |
+
--question-file ${EVAL_DATA_DIR}/egoschema/questions.json \
|
25 |
+
--answer-file ${OUTPUT_DIR}/egoschema/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.csv \
|
26 |
+
--num-chunks $CHUNKS \
|
27 |
+
--chunk-idx $IDX &
|
28 |
+
done
|
29 |
+
|
30 |
+
wait
|
31 |
+
|
32 |
+
# Clear out the output file if it exists.
|
33 |
+
> "$output_file"
|
34 |
+
|
35 |
+
echo 'q_uid, answer' >> "$output_file"
|
36 |
+
|
37 |
+
# Loop through the indices and concatenate each file.
|
38 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
39 |
+
cat ${OUTPUT_DIR}/egoschema/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.csv >> "$output_file"
|
40 |
+
done
|
41 |
+
fi
|
VideoLLaMA2/scripts/eval/eval_video_mcqa_mvbench.sh
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/mvbench/answers/${CKPT_NAME}/merge.json
|
16 |
+
|
17 |
+
# judge if the number of json lines is 0
|
18 |
+
if [ ! -f "$output_file" ] || [ $(cat "$output_file" | wc -l) -eq 0 ]; then
|
19 |
+
rm -f ${OUTPUT_DIR}/mvbench/answers/${CKPT_NAME}/*.json
|
20 |
+
fi
|
21 |
+
|
22 |
+
if [ ! -f "$output_file" ]; then
|
23 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
24 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
25 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_mcqa_mvbench.py \
|
26 |
+
--model-path ${CKPT} \
|
27 |
+
--video-folder ${EVAL_DATA_DIR}/mvbench/video \
|
28 |
+
--question-file ${EVAL_DATA_DIR}/mvbench/json \
|
29 |
+
--answer-file ${OUTPUT_DIR}/mvbench/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
30 |
+
--num-chunks $CHUNKS \
|
31 |
+
--chunk-idx $IDX &
|
32 |
+
done
|
33 |
+
|
34 |
+
wait
|
35 |
+
|
36 |
+
# Clear out the output file if it exists.
|
37 |
+
> "$output_file"
|
38 |
+
|
39 |
+
# Loop through the indices and concatenate each file.
|
40 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
41 |
+
cat ${OUTPUT_DIR}/mvbench/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
42 |
+
done
|
43 |
+
fi
|
44 |
+
|
45 |
+
python3 videollama2/eval/eval_video_mcqa_mvbench.py \
|
46 |
+
--pred_path ${output_file} \
|
VideoLLaMA2/scripts/eval/eval_video_mcqa_perception_test_mcqa.sh
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/perception_test_mcqa/answers/${CKPT_NAME}/merge.json
|
16 |
+
|
17 |
+
if [ ! -f "$output_file" ]; then
|
18 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
19 |
+
# select the GPUs for the task
|
20 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
21 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_mcqa_perception_test_mcqa.py \
|
22 |
+
--model-path ${CKPT} \
|
23 |
+
--video-folder ${EVAL_DATA_DIR}/perception_test_mcqa/videos \
|
24 |
+
--question-file ${EVAL_DATA_DIR}/perception_test_mcqa/mc_question_test.json \
|
25 |
+
--answer-file ${OUTPUT_DIR}/perception_test_mcqa/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
26 |
+
--num-chunks $CHUNKS \
|
27 |
+
--chunk-idx $IDX &
|
28 |
+
done
|
29 |
+
|
30 |
+
wait
|
31 |
+
|
32 |
+
# Clear out the output file if it exists.
|
33 |
+
> "$output_file"
|
34 |
+
|
35 |
+
echo "{" >> "$output_file"
|
36 |
+
|
37 |
+
# Loop through the indices and concatenate each file.
|
38 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
39 |
+
cat ${OUTPUT_DIR}/perception_test_mcqa/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
40 |
+
done
|
41 |
+
|
42 |
+
sed -i '$s/.$//' $output_file
|
43 |
+
|
44 |
+
echo "}" >> "$output_file"
|
45 |
+
fi
|
VideoLLaMA2/scripts/eval/eval_video_mcqa_videomme.sh
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/merge.json
|
16 |
+
output_sub_file=${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/merge_sub.json
|
17 |
+
|
18 |
+
# judge if the number of json lines is 0
|
19 |
+
if [ ! -f "$output_file" ] || [ $(cat "$output_file" | wc -l) -eq 0 ]; then
|
20 |
+
rm -f ${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/*.json
|
21 |
+
fi
|
22 |
+
|
23 |
+
|
24 |
+
if [ ! -f "$output_file" ]; then
|
25 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
26 |
+
# select the GPUs for the task
|
27 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
28 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_mcqa_videomme.py \
|
29 |
+
--model-path ${CKPT} \
|
30 |
+
--video-folder ${EVAL_DATA_DIR}/videomme/videos \
|
31 |
+
--subtitle-folder ${EVAL_DATA_DIR}/videomme/subtitles \
|
32 |
+
--question-file ${EVAL_DATA_DIR}/videomme/test-00000-of-00001.parquet \
|
33 |
+
--answer-file ${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
34 |
+
--num-chunks $CHUNKS \
|
35 |
+
--chunk-idx $IDX &
|
36 |
+
done
|
37 |
+
|
38 |
+
wait
|
39 |
+
|
40 |
+
# Clear out the output file if it exists.
|
41 |
+
> "$output_file"
|
42 |
+
|
43 |
+
echo "[" >> "$output_file"
|
44 |
+
|
45 |
+
#Loop through the indices and concatenate each file.
|
46 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
47 |
+
cat ${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
48 |
+
done
|
49 |
+
|
50 |
+
sed -i '$s/.$//' $output_file
|
51 |
+
|
52 |
+
echo "]" >> "$output_file"
|
53 |
+
|
54 |
+
# Clear out the output file if it exists.
|
55 |
+
> "$output_sub_file"
|
56 |
+
|
57 |
+
echo "[" >> "$output_sub_file"
|
58 |
+
|
59 |
+
#Loop through the indices and concatenate each file.
|
60 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
61 |
+
cat ${OUTPUT_DIR}/videomme/answers/${CKPT_NAME}/${CHUNKS}_${IDX}_sub.json >> "$output_sub_file"
|
62 |
+
done
|
63 |
+
|
64 |
+
sed -i '$s/.$//' $output_sub_file
|
65 |
+
|
66 |
+
echo "]" >> "$output_sub_file"
|
67 |
+
fi
|
68 |
+
|
69 |
+
|
70 |
+
python videollama2/eval/eval_video_mcqa_videomme.py \
|
71 |
+
--results_file $output_file \
|
72 |
+
--video_duration_type "short,medium,long" \
|
73 |
+
--return_categories_accuracy \
|
74 |
+
--return_sub_categories_accuracy \
|
75 |
+
--return_task_types_accuracy \
|
76 |
+
--skip_missing \
|
77 |
+
|
78 |
+
python videollama2/eval/eval_video_mcqa_videomme.py \
|
79 |
+
--results_file $output_sub_file \
|
80 |
+
--video_duration_type "short,medium,long" \
|
81 |
+
--return_categories_accuracy \
|
82 |
+
--return_sub_categories_accuracy \
|
83 |
+
--return_task_types_accuracy \
|
84 |
+
--skip_missing \
|
VideoLLaMA2/scripts/eval/eval_video_oqa_activitynet.sh
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/Activitynet_Zero_Shot_QA/answers/${CKPT_NAME}/merge.json
|
16 |
+
|
17 |
+
if [ ! -f "$output_file" ]; then
|
18 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
19 |
+
# select the GPUs for the task
|
20 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
21 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_oqa_activitynet.py \
|
22 |
+
--model-path ${CKPT} \
|
23 |
+
--video-folder ${EVAL_DATA_DIR}/Activitynet_Zero_Shot_QA/all_test \
|
24 |
+
--question-file ${EVAL_DATA_DIR}/Activitynet_Zero_Shot_QA/test_q.json \
|
25 |
+
--answer-file ${EVAL_DATA_DIR}/Activitynet_Zero_Shot_QA/test_a.json \
|
26 |
+
--output-file ${OUTPUT_DIR}/Activitynet_Zero_Shot_QA/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
27 |
+
--num-chunks $CHUNKS \
|
28 |
+
--chunk-idx $IDX &
|
29 |
+
done
|
30 |
+
|
31 |
+
wait
|
32 |
+
|
33 |
+
# Clear out the output file if it exists.
|
34 |
+
> "$output_file"
|
35 |
+
|
36 |
+
#Loop through the indices and concatenate each file.
|
37 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
38 |
+
cat ${OUTPUT_DIR}/Activitynet_Zero_Shot_QA/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
39 |
+
done
|
40 |
+
fi
|
41 |
+
|
42 |
+
|
43 |
+
AZURE_API_KEY=your_key
|
44 |
+
AZURE_API_ENDPOINT=your_endpoint
|
45 |
+
AZURE_API_DEPLOYNAME=your_deployname
|
46 |
+
|
47 |
+
python3 videollama2/eval/eval_video_oqa_activitynet.py \
|
48 |
+
--pred-path ${output_file} \
|
49 |
+
--output-dir ${OUTPUT_DIR}/Activitynet_Zero_Shot_QA/answers/${CKPT_NAME}/gpt \
|
50 |
+
--output-json ${OUTPUT_DIR}/Activitynet_Zero_Shot_QA/answers/${CKPT_NAME}/results.json \
|
51 |
+
--api-key $AZURE_API_KEY \
|
52 |
+
--api-endpoint $AZURE_API_ENDPOINT \
|
53 |
+
--api-deployname $AZURE_API_DEPLOYNAME \
|
54 |
+
--num-tasks 4
|
VideoLLaMA2/scripts/eval/eval_video_oqa_msvd.sh
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/MSVD_Zero_Shot_QA/answers/${CKPT_NAME}/merge.json
|
16 |
+
|
17 |
+
if [ ! -f "$output_file" ]; then
|
18 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
19 |
+
# select the GPUs for the task
|
20 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
21 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_oqa_activitynet.py \
|
22 |
+
--model-path ${CKPT} \
|
23 |
+
--video-folder ${EVAL_DATA_DIR}/MSVD_Zero_Shot_QA/videos \
|
24 |
+
--question-file ${EVAL_DATA_DIR}/MSVD_Zero_Shot_QA/test_q.json \
|
25 |
+
--answer-file ${EVAL_DATA_DIR}/MSVD_Zero_Shot_QA/test_a.json \
|
26 |
+
--output-file ${OUTPUT_DIR}/MSVD_Zero_Shot_QA/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
27 |
+
--num-chunks $CHUNKS \
|
28 |
+
--chunk-idx $IDX &
|
29 |
+
done
|
30 |
+
|
31 |
+
wait
|
32 |
+
|
33 |
+
# Clear out the output file if it exists.
|
34 |
+
> "$output_file"
|
35 |
+
|
36 |
+
#Loop through the indices and concatenate each file.
|
37 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
38 |
+
cat ${OUTPUT_DIR}/MSVD_Zero_Shot_QA/answers/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
39 |
+
done
|
40 |
+
fi
|
41 |
+
|
42 |
+
|
43 |
+
AZURE_API_KEY=your_key
|
44 |
+
AZURE_API_ENDPOINT=your_endpoint
|
45 |
+
AZURE_API_DEPLOYNAME=your_deployname
|
46 |
+
|
47 |
+
python3 videollama2/eval/eval_video_oqa_activitynet.py \
|
48 |
+
--pred-path ${output_file} \
|
49 |
+
--output-dir ${OUTPUT_DIR}/MSVD_Zero_Shot_QA/answers/${CKPT_NAME}/gpt \
|
50 |
+
--output-json ${OUTPUT_DIR}/MSVD_Zero_Shot_QA/answers/${CKPT_NAME}/results.json \
|
51 |
+
--api-key $AZURE_API_KEY \
|
52 |
+
--api-endpoint $AZURE_API_ENDPOINT \
|
53 |
+
--api-deployname $AZURE_API_DEPLOYNAME \
|
54 |
+
--num-tasks 4
|
VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_1_correctness.sh
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/merge.json
|
16 |
+
|
17 |
+
if [ ! -f "$output_file" ]; then
|
18 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
19 |
+
# select the GPUs for the task
|
20 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
21 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_oqa_vcgpt_general.py \
|
22 |
+
--model-path ${CKPT} \
|
23 |
+
--video-folder ${EVAL_DATA_DIR}/videochatgpt_gen/Test_Videos \
|
24 |
+
--question-file ${EVAL_DATA_DIR}/videochatgpt_gen/generic_qa.json \
|
25 |
+
--answer-file ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
26 |
+
--num-chunks $CHUNKS \
|
27 |
+
--chunk-idx $IDX &
|
28 |
+
done
|
29 |
+
|
30 |
+
wait
|
31 |
+
|
32 |
+
# Clear out the output file if it exists.
|
33 |
+
> "$output_file"
|
34 |
+
|
35 |
+
#Loop through the indices and concatenate each file.
|
36 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
37 |
+
cat ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
38 |
+
done
|
39 |
+
|
40 |
+
mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}
|
41 |
+
mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}
|
42 |
+
cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/merge.json
|
43 |
+
cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/merge.json
|
44 |
+
fi
|
45 |
+
|
46 |
+
|
47 |
+
AZURE_API_KEY=your_key
|
48 |
+
AZURE_API_ENDPOINT=your_endpoint
|
49 |
+
AZURE_API_DEPLOYNAME=your_deployname
|
50 |
+
|
51 |
+
python3 videollama2/eval/eval_video_oqa_vcgpt_1_correctness.py \
|
52 |
+
--pred-path ${output_file} \
|
53 |
+
--output-dir ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/gpt \
|
54 |
+
--output-json ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/results.json \
|
55 |
+
--api-key $AZURE_API_KEY \
|
56 |
+
--api-endpoint $AZURE_API_ENDPOINT \
|
57 |
+
--api-deployname $AZURE_API_DEPLOYNAME \
|
58 |
+
--num-tasks 4
|
VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_2_detail.sh
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/merge.json
|
16 |
+
|
17 |
+
if [ ! -f "$output_file" ]; then
|
18 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
19 |
+
# select the GPUs for the task
|
20 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
21 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/run_inference_video_qa_gpt_general.py \
|
22 |
+
--model-path ${CKPT} \
|
23 |
+
--video-folder ${EVAL_DATA_DIR}/videochatgpt_gen/Test_Videos \
|
24 |
+
--question-file ${EVAL_DATA_DIR}/videochatgpt_gen/generic_qa.json \
|
25 |
+
--answer-file ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
26 |
+
--num-chunks $CHUNKS \
|
27 |
+
--chunk-idx $IDX &
|
28 |
+
done
|
29 |
+
|
30 |
+
wait
|
31 |
+
|
32 |
+
# Clear out the output file if it exists.
|
33 |
+
> "$output_file"
|
34 |
+
|
35 |
+
#Loop through the indices and concatenate each file.
|
36 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
37 |
+
cat ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
38 |
+
done
|
39 |
+
|
40 |
+
mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}
|
41 |
+
mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}
|
42 |
+
cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/merge.json
|
43 |
+
cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/merge.json
|
44 |
+
fi
|
45 |
+
|
46 |
+
|
47 |
+
AZURE_API_KEY=your_key
|
48 |
+
AZURE_API_ENDPOINT=your_endpoint
|
49 |
+
AZURE_API_DEPLOYNAME=your_deployname
|
50 |
+
|
51 |
+
python3 videollama2/eval/eval_video_oqa_vcgpt_2_detailed_orientation.py \
|
52 |
+
--pred-path ${output_file} \
|
53 |
+
--output-dir ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/gpt \
|
54 |
+
--output-json ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/results.json \
|
55 |
+
--api-key $AZURE_API_KEY \
|
56 |
+
--api-endpoint $AZURE_API_ENDPOINT \
|
57 |
+
--api-deployname $AZURE_API_DEPLOYNAME \
|
58 |
+
--num-tasks 4
|
VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_3_context.sh
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/merge.json
|
16 |
+
|
17 |
+
if [ ! -f "$output_file" ]; then
|
18 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
19 |
+
# select the GPUs for the task
|
20 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
21 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/run_inference_video_qa_gpt_general.py \
|
22 |
+
--model-path ${CKPT} \
|
23 |
+
--video-folder ${EVAL_DATA_DIR}/videochatgpt_gen/Test_Videos \
|
24 |
+
--question-file ${EVAL_DATA_DIR}/videochatgpt_gen/generic_qa.json \
|
25 |
+
--answer-file ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
26 |
+
--num-chunks $CHUNKS \
|
27 |
+
--chunk-idx $IDX &
|
28 |
+
done
|
29 |
+
|
30 |
+
wait
|
31 |
+
|
32 |
+
# Clear out the output file if it exists.
|
33 |
+
> "$output_file"
|
34 |
+
|
35 |
+
#Loop through the indices and concatenate each file.
|
36 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
37 |
+
cat ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
38 |
+
done
|
39 |
+
|
40 |
+
mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}
|
41 |
+
mkdir -p ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}
|
42 |
+
cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/correctness/${CKPT_NAME}/merge.json
|
43 |
+
cp ${output_file} ${OUTPUT_DIR}/videochatgpt_gen/answers/detail/${CKPT_NAME}/merge.json
|
44 |
+
fi
|
45 |
+
|
46 |
+
|
47 |
+
AZURE_API_KEY=your_key
|
48 |
+
AZURE_API_ENDPOINT=your_endpoint
|
49 |
+
AZURE_API_DEPLOYNAME=your_deployname
|
50 |
+
|
51 |
+
python3 videollama2/eval/eval_video_oqa_vcgpt_3_context.py \
|
52 |
+
--pred-path ${output_file} \
|
53 |
+
--output-dir ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/gpt \
|
54 |
+
--output-json ${OUTPUT_DIR}/videochatgpt_gen/answers/context/${CKPT_NAME}/results.json \
|
55 |
+
--api-key $AZURE_API_KEY \
|
56 |
+
--api-endpoint $AZURE_API_ENDPOINT \
|
57 |
+
--api-deployname $AZURE_API_DEPLOYNAME \
|
58 |
+
--num-tasks 4
|
VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_4_temporal.sh
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/videochatgpt_gen/answers/temporal/${CKPT_NAME}/merge.json
|
16 |
+
|
17 |
+
# if output_file not exists then inference
|
18 |
+
if [ ! -f "$output_file" ]; then
|
19 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
20 |
+
# select the GPUs for the task
|
21 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
22 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_oqa_vcgpt_general.py \
|
23 |
+
--model-path ${CKPT} \
|
24 |
+
--video-folder ${EVAL_DATA_DIR}/videochatgpt_gen/Test_Videos \
|
25 |
+
--question-file ${EVAL_DATA_DIR}/videochatgpt_gen/temporal_qa.json \
|
26 |
+
--answer-file ${OUTPUT_DIR}/videochatgpt_gen/answers/temporal/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
27 |
+
--num-chunks $CHUNKS \
|
28 |
+
--chunk-idx $IDX &
|
29 |
+
done
|
30 |
+
|
31 |
+
wait
|
32 |
+
|
33 |
+
# Clear out the output file if it exists.
|
34 |
+
> "$output_file"
|
35 |
+
|
36 |
+
#Loop through the indices and concatenate each file.
|
37 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
38 |
+
cat ${OUTPUT_DIR}/videochatgpt_gen/answers/temporal/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
39 |
+
done
|
40 |
+
fi
|
41 |
+
|
42 |
+
|
43 |
+
AZURE_API_KEY=your_key
|
44 |
+
AZURE_API_ENDPOINT=your_endpoint
|
45 |
+
AZURE_API_DEPLOYNAME=your_deployname
|
46 |
+
|
47 |
+
python3 videollama2/eval/eval_video_oqa_vcgpt_4_temporal.py \
|
48 |
+
--pred-path ${output_file} \
|
49 |
+
--output-dir ${OUTPUT_DIR}/videochatgpt_gen/answers/temporal/${CKPT_NAME}/gpt \
|
50 |
+
--output-json ${OUTPUT_DIR}/videochatgpt_gen/answers/temporal/${CKPT_NAME}/results.json \
|
51 |
+
--api-key $AZURE_API_KEY \
|
52 |
+
--api-endpoint $AZURE_API_ENDPOINT \
|
53 |
+
--api-deployname $AZURE_API_DEPLOYNAME \
|
54 |
+
--num-tasks 4
|
VideoLLaMA2/scripts/eval/eval_video_oqa_vcgpt_5_consistency.sh
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -x
|
2 |
+
|
3 |
+
EVAL_DATA_DIR=eval
|
4 |
+
OUTPUT_DIR=eval_output
|
5 |
+
CKPT=DAMO-NLP-SG/VideoLLaMA2.1-7B-16F
|
6 |
+
CKPT_NAME=$(echo $CKPT | rev | cut -d'/' -f1 | rev)
|
7 |
+
|
8 |
+
gpu_list="${CUDA_VISIBLE_DEVICES:-0}"
|
9 |
+
IFS=',' read -ra GPULIST <<< "$gpu_list"
|
10 |
+
|
11 |
+
# divide data via the number of GPUs per task
|
12 |
+
GPUS_PER_TASK=1
|
13 |
+
CHUNKS=$((${#GPULIST[@]}/$GPUS_PER_TASK))
|
14 |
+
|
15 |
+
output_file=${OUTPUT_DIR}/videochatgpt_gen/answers/consistency/${CKPT_NAME}/merge.json
|
16 |
+
|
17 |
+
# if output_file not exists then inference
|
18 |
+
if [ ! -f "$output_file" ]; then
|
19 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
20 |
+
# select the GPUs for the task
|
21 |
+
gpu_devices=$(IFS=,; echo "${GPULIST[*]:$(($IDX*$GPUS_PER_TASK)):$GPUS_PER_TASK}")
|
22 |
+
TRANSFORMERS_OFFLINE=1 CUDA_VISIBLE_DEVICES=${gpu_devices} python3 videollama2/eval/inference_video_oqa_vcgpt_consistency.py \
|
23 |
+
--model-path ${CKPT} \
|
24 |
+
--video-folder ${EVAL_DATA_DIR}/videochatgpt_gen/Test_Videos \
|
25 |
+
--question-file ${EVAL_DATA_DIR}/videochatgpt_gen/consistency_qa.json \
|
26 |
+
--answer-file ${OUTPUT_DIR}/videochatgpt_gen/answers/consistency/${CKPT_NAME}/${CHUNKS}_${IDX}.json \
|
27 |
+
--num-chunks $CHUNKS \
|
28 |
+
--chunk-idx $IDX &
|
29 |
+
done
|
30 |
+
|
31 |
+
wait
|
32 |
+
|
33 |
+
# Clear out the output file if it exists.
|
34 |
+
> "$output_file"
|
35 |
+
|
36 |
+
#Loop through the indices and concatenate each file.
|
37 |
+
for IDX in $(seq 0 $((CHUNKS-1))); do
|
38 |
+
cat ${OUTPUT_DIR}/videochatgpt_gen/answers/consistency/${CKPT_NAME}/${CHUNKS}_${IDX}.json >> "$output_file"
|
39 |
+
done
|
40 |
+
fi
|
41 |
+
|
42 |
+
|
43 |
+
AZURE_API_KEY=your_key
|
44 |
+
AZURE_API_ENDPOINT=your_endpoint
|
45 |
+
AZURE_API_DEPLOYNAME=your_deployname
|
46 |
+
|
47 |
+
python3 videollama2/eval/eval_video_oqa_vcgpt_5_consistency.py \
|
48 |
+
--pred-path ${output_file} \
|
49 |
+
--output-dir ${OUTPUT_DIR}/videochatgpt_gen/answers/consistency/${CKPT_NAME}/gpt \
|
50 |
+
--output-json ${OUTPUT_DIR}/videochatgpt_gen/answers/consistency/${CKPT_NAME}/results.json \
|
51 |
+
--api-key $AZURE_API_KEY \
|
52 |
+
--api-endpoint $AZURE_API_ENDPOINT \
|
53 |
+
--api-deployname $AZURE_API_DEPLOYNAME \
|
54 |
+
--num-tasks 4
|
VideoLLaMA2/scripts/vllava/finetune.sh
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
# Environment Variables
|
4 |
+
ARG_WORLD_SIZE=${1:-1}
|
5 |
+
ARG_NPROC_PER_NODE=${2:-8}
|
6 |
+
ARG_MASTER_ADDR="127.0.0.1"
|
7 |
+
ARG_MASTER_PORT=16666
|
8 |
+
ARG_RANK=${3:-0}
|
9 |
+
|
10 |
+
# Multiple conditions
|
11 |
+
if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
|
12 |
+
WORLD_SIZE=$ARG_WORLD_SIZE
|
13 |
+
NPROC_PER_NODE=$ARG_NPROC_PER_NODE
|
14 |
+
fi
|
15 |
+
if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
|
16 |
+
MASTER_ADDR=$ARG_MASTER_ADDR
|
17 |
+
MASTER_PORT=$ARG_MASTER_PORT
|
18 |
+
RANK=$ARG_RANK
|
19 |
+
fi
|
20 |
+
|
21 |
+
echo "WORLD_SIZE: $WORLD_SIZE"
|
22 |
+
echo "NPROC_PER_NODE: $NPROC_PER_NODE"
|
23 |
+
|
24 |
+
# Training Arguments
|
25 |
+
GLOBAL_BATCH_SIZE=128
|
26 |
+
LOCAL_BATCH_SIZE=4
|
27 |
+
GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
|
28 |
+
|
29 |
+
# Log Arguments
|
30 |
+
export TRANSFORMERS_OFFLINE=1
|
31 |
+
export WANDB_PROJECT=videollama2qwen2_vllava
|
32 |
+
RUN_NAME=siglip_tcv35_7b_16f
|
33 |
+
DATA_DIR=datasets
|
34 |
+
OUTP_DIR=work_dirs
|
35 |
+
|
36 |
+
torchrun --nnodes $WORLD_SIZE \
|
37 |
+
--nproc_per_node $NPROC_PER_NODE \
|
38 |
+
--master_addr=$MASTER_ADDR \
|
39 |
+
--master_port=$MASTER_PORT \
|
40 |
+
--node_rank $RANK \
|
41 |
+
videollama2/train.py \
|
42 |
+
--deepspeed scripts/zero3.json \
|
43 |
+
--model_type videollama2_qwen2 \
|
44 |
+
--model_path Qwen/Qwen2-7B-Instruct \
|
45 |
+
--vision_tower google/siglip-so400m-patch14-384 \
|
46 |
+
--mm_projector_type stc_connector_v35 \
|
47 |
+
--pretrain_mm_mlp_adapter ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME}/mm_projector.bin \
|
48 |
+
--data_path ${DATA_DIR}/videollava_sft/videochatgpt_llavaimage_tune.json \
|
49 |
+
--data_folder ${DATA_DIR}/videollava_sft/ \
|
50 |
+
--mm_vision_select_layer -2 \
|
51 |
+
--image_aspect_ratio pad \
|
52 |
+
--num_frames 16 \
|
53 |
+
--bf16 True \
|
54 |
+
--tf32 True \
|
55 |
+
--fp16 False \
|
56 |
+
--output_dir ${OUTP_DIR}/${WANDB_PROJECT}/finetune_${RUN_NAME} \
|
57 |
+
--num_train_epochs 1 \
|
58 |
+
--per_device_train_batch_size $LOCAL_BATCH_SIZE \
|
59 |
+
--per_device_eval_batch_size 4 \
|
60 |
+
--gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
|
61 |
+
--save_strategy "steps" \
|
62 |
+
--save_steps 500 \
|
63 |
+
--save_total_limit 99 \
|
64 |
+
--learning_rate 2e-5 \
|
65 |
+
--weight_decay 0. \
|
66 |
+
--warmup_ratio 0.03 \
|
67 |
+
--lr_scheduler_type "cosine" \
|
68 |
+
--logging_steps 1 \
|
69 |
+
--model_max_length 2048 \
|
70 |
+
--gradient_checkpointing True \
|
71 |
+
--dataloader_num_workers 4 \
|
72 |
+
--report_to tensorboard \
|
73 |
+
--run_name $RUN_NAME \
|
VideoLLaMA2/scripts/vllava/pretrain.sh
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
# Environment Variables
|
4 |
+
ARG_WORLD_SIZE=${1:-1}
|
5 |
+
ARG_NPROC_PER_NODE=${2:-8}
|
6 |
+
ARG_MASTER_ADDR="127.0.0.1"
|
7 |
+
ARG_MASTER_PORT=16666
|
8 |
+
ARG_RANK=${3:-0}
|
9 |
+
|
10 |
+
# Multiple conditions
|
11 |
+
if [ ! -n "$WORLD_SIZE" ] || [ ! -n "$NPROC_PER_NODE" ]; then
|
12 |
+
WORLD_SIZE=$ARG_WORLD_SIZE
|
13 |
+
NPROC_PER_NODE=$ARG_NPROC_PER_NODE
|
14 |
+
fi
|
15 |
+
if [ ! -n "$MASTER_ADDR" ] || [ ! -n "$MASTER_PORT" ] || [ ! -n "$RANK" ]; then
|
16 |
+
MASTER_ADDR=$ARG_MASTER_ADDR
|
17 |
+
MASTER_PORT=$ARG_MASTER_PORT
|
18 |
+
RANK=$ARG_RANK
|
19 |
+
fi
|
20 |
+
|
21 |
+
echo "WORLD_SIZE: $WORLD_SIZE"
|
22 |
+
echo "NPROC_PER_NODE: $NPROC_PER_NODE"
|
23 |
+
|
24 |
+
# Training Arguments
|
25 |
+
GLOBAL_BATCH_SIZE=256
|
26 |
+
LOCAL_BATCH_SIZE=8
|
27 |
+
GRADIENT_ACCUMULATION_STEPS=$[$GLOBAL_BATCH_SIZE/($WORLD_SIZE*$NPROC_PER_NODE*$LOCAL_BATCH_SIZE)]
|
28 |
+
|
29 |
+
# Log Arguments
|
30 |
+
export TRANSFORMERS_OFFLINE=1
|
31 |
+
export WANDB_PROJECT=videollama2qwen2_vllava
|
32 |
+
RUN_NAME=siglip_tcv35_7b_16f
|
33 |
+
DATA_DIR=datasets
|
34 |
+
OUTP_DIR=work_dirs
|
35 |
+
|
36 |
+
torchrun --nnodes $WORLD_SIZE \
|
37 |
+
--nproc_per_node $NPROC_PER_NODE \
|
38 |
+
--master_addr=$MASTER_ADDR \
|
39 |
+
--master_port=$MASTER_PORT \
|
40 |
+
--node_rank $RANK \
|
41 |
+
videollama2/train.py \
|
42 |
+
--deepspeed scripts/zero3.json \
|
43 |
+
--model_type videollama2_qwen2 \
|
44 |
+
--model_path Qwen/Qwen2-7B-Instruct \
|
45 |
+
--vision_tower google/siglip-so400m-patch14-384 \
|
46 |
+
--mm_projector_type stc_connector_v35 \
|
47 |
+
--tune_mm_mlp_adapter True \
|
48 |
+
--data_path ${DATA_DIR}/videollava_pt/valley_llavaimage.json \
|
49 |
+
--data_folder ${DATA_DIR}/videollava_pt/ \
|
50 |
+
--mm_vision_select_layer -2 \
|
51 |
+
--num_frames 16 \
|
52 |
+
--bf16 True \
|
53 |
+
--tf32 True \
|
54 |
+
--fp16 False \
|
55 |
+
--output_dir ${OUTP_DIR}/${WANDB_PROJECT}/pretrain_${RUN_NAME} \
|
56 |
+
--num_train_epochs 1 \
|
57 |
+
--per_device_train_batch_size $LOCAL_BATCH_SIZE \
|
58 |
+
--per_device_eval_batch_size 4 \
|
59 |
+
--gradient_accumulation_steps $GRADIENT_ACCUMULATION_STEPS \
|
60 |
+
--evaluation_strategy "no" \
|
61 |
+
--save_strategy "steps" \
|
62 |
+
--save_steps 500 \
|
63 |
+
--save_total_limit 99 \
|
64 |
+
--learning_rate 1e-3 \
|
65 |
+
--weight_decay 0. \
|
66 |
+
--warmup_ratio 0.03 \
|
67 |
+
--lr_scheduler_type "cosine" \
|
68 |
+
--logging_steps 1 \
|
69 |
+
--model_max_length 2048 \
|
70 |
+
--gradient_checkpointing True \
|
71 |
+
--dataloader_num_workers 4 \
|
72 |
+
--report_to tensorboard \
|
73 |
+
--run_name $RUN_NAME \
|
VideoLLaMA2/scripts/zero2.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"fp16": {
|
3 |
+
"enabled": "auto",
|
4 |
+
"loss_scale": 0,
|
5 |
+
"loss_scale_window": 1000,
|
6 |
+
"initial_scale_power": 16,
|
7 |
+
"hysteresis": 2,
|
8 |
+
"min_loss_scale": 1
|
9 |
+
},
|
10 |
+
"bf16": {
|
11 |
+
"enabled": "auto"
|
12 |
+
},
|
13 |
+
"train_micro_batch_size_per_gpu": "auto",
|
14 |
+
"train_batch_size": "auto",
|
15 |
+
"gradient_accumulation_steps": "auto",
|
16 |
+
"zero_optimization": {
|
17 |
+
"stage": 2,
|
18 |
+
"overlap_comm": true,
|
19 |
+
"contiguous_gradients": true,
|
20 |
+
"sub_group_size": 1e9,
|
21 |
+
"reduce_bucket_size": "auto"
|
22 |
+
}
|
23 |
+
}
|
VideoLLaMA2/scripts/zero3.json
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"fp16": {
|
3 |
+
"enabled": "auto",
|
4 |
+
"loss_scale": 0,
|
5 |
+
"loss_scale_window": 1000,
|
6 |
+
"initial_scale_power": 16,
|
7 |
+
"hysteresis": 2,
|
8 |
+
"min_loss_scale": 1
|
9 |
+
},
|
10 |
+
"bf16": {
|
11 |
+
"enabled": "auto"
|
12 |
+
},
|
13 |
+
"train_micro_batch_size_per_gpu": "auto",
|
14 |
+
"train_batch_size": "auto",
|
15 |
+
"gradient_accumulation_steps": "auto",
|
16 |
+
"zero_optimization": {
|
17 |
+
"stage": 3,
|
18 |
+
"overlap_comm": true,
|
19 |
+
"contiguous_gradients": true,
|
20 |
+
"sub_group_size": 1e9,
|
21 |
+
"reduce_bucket_size": "auto",
|
22 |
+
"stage3_prefetch_bucket_size": "auto",
|
23 |
+
"stage3_param_persistence_threshold": "auto",
|
24 |
+
"stage3_max_live_parameters": 1e9,
|
25 |
+
"stage3_max_reuse_distance": 1e9,
|
26 |
+
"stage3_gather_16bit_weights_on_model_save": true
|
27 |
+
}
|
28 |
+
}
|
VideoLLaMA2/videollama2/__init__.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import copy
|
3 |
+
import warnings
|
4 |
+
import shutil
|
5 |
+
from functools import partial
|
6 |
+
|
7 |
+
import torch
|
8 |
+
|
9 |
+
from .model import load_pretrained_model
|
10 |
+
from .mm_utils import process_image, process_video, tokenizer_multimodal_token, get_model_name_from_path, KeywordsStoppingCriteria
|
11 |
+
from .constants import NUM_FRAMES, DEFAULT_IMAGE_TOKEN, DEFAULT_VIDEO_TOKEN, MODAL_INDEX_MAP
|
12 |
+
|
13 |
+
|
14 |
+
def model_init(model_path=None, **kwargs):
|
15 |
+
model_path = "DAMO-NLP-SG/VideoLLaMA2-7B" if model_path is None else model_path
|
16 |
+
model_name = get_model_name_from_path(model_path)
|
17 |
+
tokenizer, model, processor, context_len = load_pretrained_model(model_path, None, model_name, **kwargs)
|
18 |
+
|
19 |
+
if tokenizer.pad_token is None and tokenizer.unk_token is not None:
|
20 |
+
tokenizer.pad_token = tokenizer.unk_token
|
21 |
+
|
22 |
+
num_frames = model.config.num_frames if hasattr(model.config, "num_frames") else NUM_FRAMES
|
23 |
+
|
24 |
+
processor = {
|
25 |
+
'image': partial(process_image, processor=processor, aspect_ratio=None),
|
26 |
+
'video': partial(process_video, processor=processor, aspect_ratio=None, num_frames=num_frames),
|
27 |
+
}
|
28 |
+
|
29 |
+
return model, processor, tokenizer
|
30 |
+
|
31 |
+
|
32 |
+
def mm_infer(image_or_video, instruct, model, tokenizer, modal='video', **kwargs):
|
33 |
+
"""inference api of VideoLLaMA2 for video understanding.
|
34 |
+
|
35 |
+
Args:
|
36 |
+
model: VideoLLaMA2 model.
|
37 |
+
image_or_video (torch.Tensor): image tensor (1, C, H, W) / video tensor (T, C, H, W).
|
38 |
+
instruct (str): text instruction for understanding video.
|
39 |
+
tokenizer: tokenizer.
|
40 |
+
do_sample (bool): whether to sample.
|
41 |
+
modal (str): inference modality.
|
42 |
+
Returns:
|
43 |
+
str: response of the model.
|
44 |
+
"""
|
45 |
+
|
46 |
+
# 1. text preprocess (tag process & generate prompt).
|
47 |
+
if modal == 'image':
|
48 |
+
modal_token = DEFAULT_IMAGE_TOKEN
|
49 |
+
elif modal == 'video':
|
50 |
+
modal_token = DEFAULT_VIDEO_TOKEN
|
51 |
+
elif modal == 'text':
|
52 |
+
modal_token = ''
|
53 |
+
else:
|
54 |
+
raise ValueError(f"Unsupported modal: {modal}")
|
55 |
+
|
56 |
+
# 1. vision preprocess (load & transform image or video).
|
57 |
+
if modal == 'text':
|
58 |
+
tensor = None
|
59 |
+
else:
|
60 |
+
tensor = image_or_video.half().cuda()
|
61 |
+
tensor = [(tensor, modal)]
|
62 |
+
|
63 |
+
# 2. text preprocess (tag process & generate prompt).
|
64 |
+
if isinstance(instruct, str):
|
65 |
+
message = [{'role': 'user', 'content': modal_token + '\n' + instruct}]
|
66 |
+
elif isinstance(instruct, list):
|
67 |
+
message = copy.deepcopy(instruct)
|
68 |
+
message[0]['content'] = modal_token + '\n' + message[0]['content']
|
69 |
+
else:
|
70 |
+
raise ValueError(f"Unsupported type of instruct: {type(instruct)}")
|
71 |
+
|
72 |
+
if model.config.model_type in ['videollama2', 'videollama2_mistral', 'videollama2_mixtral']:
|
73 |
+
system_message = [
|
74 |
+
{'role': 'system', 'content': (
|
75 |
+
"""<<SYS>>\nYou are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature."""
|
76 |
+
"""\n"""
|
77 |
+
"""If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\n<</SYS>>""")
|
78 |
+
}
|
79 |
+
]
|
80 |
+
else:
|
81 |
+
system_message = []
|
82 |
+
|
83 |
+
message = system_message + message
|
84 |
+
prompt = tokenizer.apply_chat_template(message, tokenize=False, add_generation_prompt=True)
|
85 |
+
|
86 |
+
input_ids = tokenizer_multimodal_token(prompt, tokenizer, modal_token, return_tensors='pt').unsqueeze(0).long().cuda()
|
87 |
+
attention_masks = input_ids.ne(tokenizer.pad_token_id).long().cuda()
|
88 |
+
|
89 |
+
# 3. generate response according to visual signals and prompts.
|
90 |
+
keywords = [tokenizer.eos_token]
|
91 |
+
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
|
92 |
+
|
93 |
+
do_sample = kwargs.get('do_sample', False)
|
94 |
+
temperature = kwargs.get('temperature', 0.2 if do_sample else 0.0)
|
95 |
+
top_p = kwargs.get('top_p', 0.9)
|
96 |
+
max_new_tokens = kwargs.get('max_new_tokens', 2048)
|
97 |
+
|
98 |
+
with torch.inference_mode():
|
99 |
+
output_ids = model.generate(
|
100 |
+
input_ids,
|
101 |
+
attention_mask=attention_masks,
|
102 |
+
images=tensor,
|
103 |
+
do_sample=do_sample,
|
104 |
+
temperature=temperature,
|
105 |
+
max_new_tokens=max_new_tokens,
|
106 |
+
top_p=top_p,
|
107 |
+
use_cache=True,
|
108 |
+
stopping_criteria=[stopping_criteria],
|
109 |
+
pad_token_id=tokenizer.eos_token_id,
|
110 |
+
)
|
111 |
+
|
112 |
+
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
113 |
+
|
114 |
+
return outputs
|
VideoLLaMA2/videollama2/constants.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
2 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
3 |
+
|
4 |
+
LOGDIR = "."
|
5 |
+
|
6 |
+
# Model Constants
|
7 |
+
IGNORE_INDEX = -100
|
8 |
+
|
9 |
+
# Image arguments
|
10 |
+
IMAGE_TOKEN_INDEX = -200
|
11 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
12 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
13 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
14 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
15 |
+
IMAGE_PLACEHOLDER = "<image-placeholder>"
|
16 |
+
|
17 |
+
# Video arguments
|
18 |
+
VIDEO_TOKEN_INDEX = -201
|
19 |
+
DEFAULT_VIDEO_TOKEN = "<video>"
|
20 |
+
NUM_FRAMES = 8
|
21 |
+
MAX_FRAMES = 32
|
22 |
+
NUM_FRAMES_PER_SECOND = 1
|
23 |
+
|
24 |
+
# Audio arguments
|
25 |
+
AUDIO_TOKEN_INDEX = -202
|
26 |
+
DEFAULT_AUDIO_TOKEN = "<audio>"
|
27 |
+
|
28 |
+
MODAL_INDEX_MAP = {
|
29 |
+
"<image>": -200,
|
30 |
+
"<video>": -201,
|
31 |
+
"<audio>": -202,
|
32 |
+
}
|
VideoLLaMA2/videollama2/conversation.py
ADDED
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
import dataclasses
|
3 |
+
from io import BytesIO
|
4 |
+
from enum import auto, Enum
|
5 |
+
from typing import List, Tuple
|
6 |
+
|
7 |
+
from PIL import Image
|
8 |
+
from .constants import LOGDIR, NUM_FRAMES
|
9 |
+
|
10 |
+
|
11 |
+
class SeparatorStyle(Enum):
|
12 |
+
"""Different separator style."""
|
13 |
+
SINGLE = auto()
|
14 |
+
TWO = auto()
|
15 |
+
PLAIN = auto()
|
16 |
+
LLAMA2 = auto()
|
17 |
+
QWEN = auto()
|
18 |
+
|
19 |
+
@dataclasses.dataclass
|
20 |
+
class Conversation:
|
21 |
+
"""A class that keeps all conversation history."""
|
22 |
+
system: str
|
23 |
+
roles: List[str]
|
24 |
+
messages: List[List[str]]
|
25 |
+
offset: int
|
26 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
27 |
+
sep: str = "###"
|
28 |
+
sep2: str = None
|
29 |
+
version: str = "Unknown"
|
30 |
+
|
31 |
+
skip_next: bool = False
|
32 |
+
modality: str = "image"
|
33 |
+
|
34 |
+
def get_prompt(self):
|
35 |
+
messages = self.messages
|
36 |
+
modality_token = f"<{self.modality}>"
|
37 |
+
if len(messages) > 0 and type(messages[0][1]) is tuple:
|
38 |
+
messages = self.messages.copy()
|
39 |
+
init_role, init_msg = messages[0].copy()
|
40 |
+
init_msg = init_msg[0].replace(modality_token, "").strip()
|
41 |
+
if 'mmtag' in self.version:
|
42 |
+
messages[0] = (init_role, init_msg)
|
43 |
+
messages.insert(0, (self.roles[0], "<Image><image></Image>"))
|
44 |
+
messages.insert(1, (self.roles[1], "Received."))
|
45 |
+
else:
|
46 |
+
messages[0] = (init_role, f"{modality_token}\n" + init_msg)
|
47 |
+
|
48 |
+
if self.sep_style == SeparatorStyle.SINGLE:
|
49 |
+
ret = self.system + self.sep
|
50 |
+
for role, message in messages:
|
51 |
+
if message:
|
52 |
+
if type(message) is tuple:
|
53 |
+
message, _, _ = message
|
54 |
+
ret += role + ": " + message + self.sep
|
55 |
+
else:
|
56 |
+
ret += role + ":"
|
57 |
+
elif self.sep_style == SeparatorStyle.TWO:
|
58 |
+
seps = [self.sep, self.sep2]
|
59 |
+
ret = self.system + seps[0]
|
60 |
+
for i, (role, message) in enumerate(messages):
|
61 |
+
if message:
|
62 |
+
if type(message) is tuple:
|
63 |
+
message, _, _ = message
|
64 |
+
ret += role + ": " + message + seps[i % 2]
|
65 |
+
else:
|
66 |
+
ret += role + ":"
|
67 |
+
elif self.sep_style == SeparatorStyle.LLAMA2:
|
68 |
+
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
|
69 |
+
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
70 |
+
ret = ""
|
71 |
+
|
72 |
+
for i, (role, message) in enumerate(messages):
|
73 |
+
if i == 0:
|
74 |
+
assert message, "first message should not be none"
|
75 |
+
assert role == self.roles[0], "first message should come from user"
|
76 |
+
if message:
|
77 |
+
if type(message) is tuple:
|
78 |
+
message, _, _ = message
|
79 |
+
if i == 0: message = wrap_sys(self.system) + message
|
80 |
+
if i % 2 == 0:
|
81 |
+
message = wrap_inst(message)
|
82 |
+
ret += self.sep + message
|
83 |
+
else:
|
84 |
+
ret += " " + message + " " + self.sep2
|
85 |
+
else:
|
86 |
+
ret += ""
|
87 |
+
ret = ret.lstrip(self.sep)
|
88 |
+
elif self.sep_style == SeparatorStyle.QWEN:
|
89 |
+
ret = ""
|
90 |
+
# 1. Add system prompt
|
91 |
+
ret += self.system + self.sep + "\n"
|
92 |
+
# 2. Iterate message
|
93 |
+
for i, (role, message) in enumerate(messages):
|
94 |
+
if i == 0:
|
95 |
+
assert message, "first message should not be none"
|
96 |
+
assert role == self.roles[0], "first message should come from user"
|
97 |
+
if message:
|
98 |
+
if type(message) is tuple:
|
99 |
+
message, _, _ = message
|
100 |
+
# 2.1 Add role and message
|
101 |
+
ret += role + message + self.sep + "\n"
|
102 |
+
else:
|
103 |
+
# 2.2 Add generation prompt
|
104 |
+
ret += role
|
105 |
+
elif self.sep_style == SeparatorStyle.PLAIN:
|
106 |
+
seps = [self.sep, self.sep2]
|
107 |
+
ret = self.system
|
108 |
+
for i, (role, message) in enumerate(messages):
|
109 |
+
if message:
|
110 |
+
if type(message) is tuple:
|
111 |
+
message, _, _ = message
|
112 |
+
ret += role + message + seps[i % 2]
|
113 |
+
else:
|
114 |
+
ret += role
|
115 |
+
else:
|
116 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
117 |
+
|
118 |
+
return ret
|
119 |
+
|
120 |
+
def append_message(self, role, message):
|
121 |
+
self.messages.append([role, message])
|
122 |
+
|
123 |
+
def process_image(self, image, image_process_mode, return_pil=False, image_format='PNG', max_len=800, min_len=400):
|
124 |
+
if image_process_mode == "Pad":
|
125 |
+
def expand2square(pil_img, background_color=(122, 116, 104)):
|
126 |
+
width, height = pil_img.size
|
127 |
+
if width == height:
|
128 |
+
return pil_img
|
129 |
+
elif width > height:
|
130 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
131 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
132 |
+
return result
|
133 |
+
else:
|
134 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
135 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
136 |
+
return result
|
137 |
+
image = expand2square(image)
|
138 |
+
elif image_process_mode in ["Default", "Crop"]:
|
139 |
+
pass
|
140 |
+
elif image_process_mode == "Resize":
|
141 |
+
image = image.resize((336, 336))
|
142 |
+
else:
|
143 |
+
raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
144 |
+
if max(image.size) > max_len:
|
145 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
146 |
+
aspect_ratio = max_hw / min_hw
|
147 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
148 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
149 |
+
W, H = image.size
|
150 |
+
if H > W:
|
151 |
+
H, W = longest_edge, shortest_edge
|
152 |
+
else:
|
153 |
+
H, W = shortest_edge, longest_edge
|
154 |
+
image = image.resize((W, H))
|
155 |
+
if return_pil:
|
156 |
+
return image
|
157 |
+
else:
|
158 |
+
buffered = BytesIO()
|
159 |
+
image.save(buffered, format=image_format)
|
160 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
161 |
+
return img_b64_str
|
162 |
+
|
163 |
+
|
164 |
+
def get_videos(self, return_pil=False):
|
165 |
+
video_frames = []
|
166 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
167 |
+
if i % 2 == 0:
|
168 |
+
if type(msg) is tuple:
|
169 |
+
from decord import VideoReader, cpu
|
170 |
+
import numpy as np
|
171 |
+
# here video is the file path of input video
|
172 |
+
msg, video, image_process_mode = msg
|
173 |
+
if not return_pil:
|
174 |
+
# return filepath
|
175 |
+
video_frames.append(video)
|
176 |
+
else:
|
177 |
+
# read video using decord.VideoReader
|
178 |
+
decord_vr = VideoReader(uri=video, ctx=cpu(0))
|
179 |
+
duration = len(decord_vr)
|
180 |
+
frame_id_list = np.linspace(0, duration-1, NUM_FRAMES, dtype=int)
|
181 |
+
# convert the extracted image frames into PIL objects
|
182 |
+
all_images = [Image.fromarray(f) for f in decord_vr.get_batch(frame_id_list).asnumpy()]
|
183 |
+
video_frames.extend([self.process_image(image, image_process_mode, return_pil=return_pil) for image in all_images])
|
184 |
+
return video_frames
|
185 |
+
|
186 |
+
|
187 |
+
def get_images(self, return_pil=False):
|
188 |
+
images = []
|
189 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
190 |
+
if i % 2 == 0:
|
191 |
+
if type(msg) is tuple:
|
192 |
+
msg, image, image_process_mode = msg
|
193 |
+
image = self.process_image(image, image_process_mode, return_pil=return_pil)
|
194 |
+
images.append(image)
|
195 |
+
|
196 |
+
# import base64
|
197 |
+
# from io import BytesIO
|
198 |
+
# from PIL import Image
|
199 |
+
# # here image is a PIL object
|
200 |
+
# msg, image, image_process_mode = msg
|
201 |
+
# if image_process_mode == "Pad":
|
202 |
+
# def expand2square(pil_img, background_color=(122, 116, 104)):
|
203 |
+
# width, height = pil_img.size
|
204 |
+
# if width == height:
|
205 |
+
# return pil_img
|
206 |
+
# elif width > height:
|
207 |
+
# result = Image.new(pil_img.mode, (width, width), background_color)
|
208 |
+
# result.paste(pil_img, (0, (width - height) // 2))
|
209 |
+
# return result
|
210 |
+
# else:
|
211 |
+
# result = Image.new(pil_img.mode, (height, height), background_color)
|
212 |
+
# result.paste(pil_img, ((height - width) // 2, 0))
|
213 |
+
# return result
|
214 |
+
# image = expand2square(image)
|
215 |
+
# elif image_process_mode in ["Default", "Crop"]:
|
216 |
+
# pass
|
217 |
+
# elif image_process_mode == "Resize":
|
218 |
+
# image = image.resize((336, 336))
|
219 |
+
# else:
|
220 |
+
# raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
221 |
+
# max_hw, min_hw = max(image.size), min(image.size)
|
222 |
+
# aspect_ratio = max_hw / min_hw
|
223 |
+
# max_len, min_len = 800, 400
|
224 |
+
# shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
225 |
+
# longest_edge = int(shortest_edge * aspect_ratio)
|
226 |
+
# W, H = image.size
|
227 |
+
# if longest_edge != max(image.size):
|
228 |
+
# if H > W:
|
229 |
+
# H, W = longest_edge, shortest_edge
|
230 |
+
# else:
|
231 |
+
# H, W = shortest_edge, longest_edge
|
232 |
+
# image = image.resize((W, H))
|
233 |
+
# if return_pil:
|
234 |
+
# images.append(image)
|
235 |
+
# else:
|
236 |
+
# buffered = BytesIO()
|
237 |
+
# image.save(buffered, format="PNG")
|
238 |
+
# img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
239 |
+
# images.append(img_b64_str)
|
240 |
+
return images
|
241 |
+
|
242 |
+
def to_gradio_chatbot(self):
|
243 |
+
ret = []
|
244 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
245 |
+
if i % 2 == 0:
|
246 |
+
if type(msg) is tuple:
|
247 |
+
# import base64
|
248 |
+
# from io import BytesIO
|
249 |
+
# from PIL import Image
|
250 |
+
# msg, image, image_process_mode = msg
|
251 |
+
# max_hw, min_hw = max(image.size), min(image.size)
|
252 |
+
# aspect_ratio = max_hw / min_hw
|
253 |
+
# max_len, min_len = 800, 400
|
254 |
+
# shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
255 |
+
# longest_edge = int(shortest_edge * aspect_ratio)
|
256 |
+
# W, H = image.size
|
257 |
+
# if H > W:
|
258 |
+
# H, W = longest_edge, shortest_edge
|
259 |
+
# else:
|
260 |
+
# H, W = shortest_edge, longest_edge
|
261 |
+
# image = image.resize((W, H))
|
262 |
+
# buffered = BytesIO()
|
263 |
+
# image.save(buffered, format="JPEG")
|
264 |
+
# img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
265 |
+
# img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
|
266 |
+
# display image/video in the textbox
|
267 |
+
msg, image_or_video, image_process_mode = msg
|
268 |
+
##print("imagebox:", image)
|
269 |
+
if isinstance(image_or_video, Image.Image):
|
270 |
+
# image is PIL object
|
271 |
+
img_b64_str = self.process_image(image_or_video, "Default", return_pil=False, image_format='JPEG')
|
272 |
+
img_str = f'<img src="data:image/jpeg;base64,{img_b64_str}" alt="user upload image" />'
|
273 |
+
msg = img_str + msg.replace('<image>', '').strip()
|
274 |
+
else:
|
275 |
+
# video is file path
|
276 |
+
vid_str = f'<video controls playsinline width="500" style="display: inline-block;" src="./file={image_or_video}"></video><br>'
|
277 |
+
msg = vid_str + msg.replace('<video>', '').strip()
|
278 |
+
ret.append([msg, None])
|
279 |
+
else:
|
280 |
+
ret.append([msg, None])
|
281 |
+
else:
|
282 |
+
ret[-1][-1] = msg
|
283 |
+
return ret
|
284 |
+
|
285 |
+
def copy(self):
|
286 |
+
return Conversation(
|
287 |
+
system=self.system,
|
288 |
+
roles=self.roles,
|
289 |
+
messages=[[x, y] for x, y in self.messages],
|
290 |
+
offset=self.offset,
|
291 |
+
sep_style=self.sep_style,
|
292 |
+
sep=self.sep,
|
293 |
+
sep2=self.sep2,
|
294 |
+
version=self.version)
|
295 |
+
|
296 |
+
def dict(self):
|
297 |
+
if (self.modality == "image" and len(self.get_images()) > 0) or \
|
298 |
+
(self.modality == "video" and len(self.get_videos()) > 0):
|
299 |
+
return {
|
300 |
+
"system": self.system,
|
301 |
+
"roles": self.roles,
|
302 |
+
"messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
|
303 |
+
"offset": self.offset,
|
304 |
+
"sep": self.sep,
|
305 |
+
"sep2": self.sep2,
|
306 |
+
"modality": self.modality
|
307 |
+
}
|
308 |
+
return {
|
309 |
+
"system": self.system,
|
310 |
+
"roles": self.roles,
|
311 |
+
"messages": self.messages,
|
312 |
+
"offset": self.offset,
|
313 |
+
"sep": self.sep,
|
314 |
+
"sep2": self.sep2,
|
315 |
+
}
|
316 |
+
|
317 |
+
|
318 |
+
conv_vicuna_v0 = Conversation(
|
319 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
320 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
321 |
+
roles=("Human", "Assistant"),
|
322 |
+
messages=(
|
323 |
+
("Human", "What are the key differences between renewable and non-renewable energy sources?"),
|
324 |
+
("Assistant",
|
325 |
+
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
326 |
+
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
327 |
+
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
328 |
+
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
329 |
+
"renewable and non-renewable energy sources:\n"
|
330 |
+
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
331 |
+
"energy sources are finite and will eventually run out.\n"
|
332 |
+
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
333 |
+
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
334 |
+
"and other negative effects.\n"
|
335 |
+
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
336 |
+
"have lower operational costs than non-renewable sources.\n"
|
337 |
+
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
338 |
+
"locations than non-renewable sources.\n"
|
339 |
+
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
340 |
+
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
341 |
+
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
342 |
+
"non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
|
343 |
+
),
|
344 |
+
offset=2,
|
345 |
+
sep_style=SeparatorStyle.SINGLE,
|
346 |
+
sep="###",
|
347 |
+
)
|
348 |
+
|
349 |
+
conv_llava_plain = Conversation(
|
350 |
+
system="",
|
351 |
+
roles=("", ""),
|
352 |
+
messages=(),
|
353 |
+
offset=0,
|
354 |
+
sep_style=SeparatorStyle.PLAIN,
|
355 |
+
sep="",
|
356 |
+
sep2="\n"
|
357 |
+
)
|
358 |
+
|
359 |
+
conv_llava_v0_mmtag = Conversation(
|
360 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
361 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
362 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
363 |
+
roles=("Human", "Assistant"),
|
364 |
+
messages=(
|
365 |
+
),
|
366 |
+
offset=0,
|
367 |
+
sep_style=SeparatorStyle.SINGLE,
|
368 |
+
sep="###",
|
369 |
+
version="v0_mmtag",
|
370 |
+
)
|
371 |
+
|
372 |
+
conv_llava_v0 = Conversation(
|
373 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
374 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
375 |
+
roles=("Human", "Assistant"),
|
376 |
+
messages=(
|
377 |
+
),
|
378 |
+
offset=0,
|
379 |
+
sep_style=SeparatorStyle.SINGLE,
|
380 |
+
sep="###",
|
381 |
+
)
|
382 |
+
|
383 |
+
conv_vicuna_v1 = Conversation(
|
384 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
385 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
386 |
+
roles=("USER", "ASSISTANT"),
|
387 |
+
version="v1",
|
388 |
+
messages=(),
|
389 |
+
offset=0,
|
390 |
+
sep_style=SeparatorStyle.TWO,
|
391 |
+
sep=" ",
|
392 |
+
sep2="</s>",
|
393 |
+
)
|
394 |
+
|
395 |
+
conv_llava_v1_mmtag = Conversation(
|
396 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
397 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
398 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
399 |
+
roles=("USER", "ASSISTANT"),
|
400 |
+
messages=(),
|
401 |
+
offset=0,
|
402 |
+
sep_style=SeparatorStyle.TWO,
|
403 |
+
sep=" ",
|
404 |
+
sep2="</s>",
|
405 |
+
version="v1_mmtag",
|
406 |
+
)
|
407 |
+
|
408 |
+
conv_llava_v1 = Conversation(
|
409 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
410 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
411 |
+
roles=("USER", "ASSISTANT"),
|
412 |
+
version="v1",
|
413 |
+
messages=(),
|
414 |
+
offset=0,
|
415 |
+
sep_style=SeparatorStyle.TWO,
|
416 |
+
sep=" ",
|
417 |
+
sep2="</s>",
|
418 |
+
)
|
419 |
+
|
420 |
+
conv_llava_llama2 = Conversation(
|
421 |
+
system="You are a helpful language and vision assistant. "
|
422 |
+
"You are able to understand the visual content that the user provides, "
|
423 |
+
"and assist the user with a variety of tasks using natural language.",
|
424 |
+
roles=("USER", "ASSISTANT"),
|
425 |
+
version="llama2",
|
426 |
+
messages=(),
|
427 |
+
offset=0,
|
428 |
+
sep_style=SeparatorStyle.LLAMA2,
|
429 |
+
sep="<s>",
|
430 |
+
sep2="</s>",
|
431 |
+
)
|
432 |
+
|
433 |
+
conv_llama2 = Conversation(
|
434 |
+
system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
|
435 |
+
|
436 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
|
437 |
+
roles=("USER", "ASSISTANT"),
|
438 |
+
version="llama2",
|
439 |
+
messages=(),
|
440 |
+
offset=0,
|
441 |
+
sep_style=SeparatorStyle.LLAMA2,
|
442 |
+
sep="<s>",
|
443 |
+
sep2="</s>",
|
444 |
+
)
|
445 |
+
|
446 |
+
conv_mistral = Conversation(
|
447 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
448 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
449 |
+
roles=("USER", "ASSISTANT"),
|
450 |
+
version="llama2",
|
451 |
+
messages=(),
|
452 |
+
offset=0,
|
453 |
+
sep_style=SeparatorStyle.LLAMA2,
|
454 |
+
sep="",
|
455 |
+
sep2="</s>",
|
456 |
+
)
|
457 |
+
|
458 |
+
conv_qwen = Conversation(
|
459 |
+
system="<|im_start|>system\nYou are a helpful assistant.",
|
460 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
461 |
+
messages=(),
|
462 |
+
offset=0,
|
463 |
+
sep_style=SeparatorStyle.QWEN,
|
464 |
+
sep="<|im_end|>",
|
465 |
+
version="qwen",
|
466 |
+
)
|
467 |
+
|
468 |
+
conv_qwen_plain = Conversation(
|
469 |
+
system="",
|
470 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
471 |
+
messages=(),
|
472 |
+
offset=0,
|
473 |
+
sep_style=SeparatorStyle.PLAIN,
|
474 |
+
sep="<|im_end|>",
|
475 |
+
sep2="<|im_end|>",
|
476 |
+
version="qwen_plain",
|
477 |
+
)
|
478 |
+
|
479 |
+
default_conversation = conv_mistral
|
480 |
+
conv_templates = {
|
481 |
+
"default": conv_vicuna_v0,
|
482 |
+
# pretrain template
|
483 |
+
"plain": conv_llava_plain,
|
484 |
+
# llava v0
|
485 |
+
"v0": conv_vicuna_v0,
|
486 |
+
"v0_plain": conv_llava_plain,
|
487 |
+
"v0_mmtag": conv_llava_v0_mmtag,
|
488 |
+
"llava_v0": conv_llava_v0,
|
489 |
+
# llava v1
|
490 |
+
"v1": conv_vicuna_v1,
|
491 |
+
"v1_mmtag": conv_llava_v1_mmtag,
|
492 |
+
"llava_v1": conv_llava_v1,
|
493 |
+
"vicuna_v1": conv_vicuna_v1,
|
494 |
+
# llava v1.5
|
495 |
+
"llava_llama2": conv_llava_llama2,
|
496 |
+
# llama2
|
497 |
+
"llama2": conv_llama2,
|
498 |
+
# mistral
|
499 |
+
"mistral": conv_mistral,
|
500 |
+
# qwen
|
501 |
+
"qwen": conv_qwen,
|
502 |
+
"qwen_plain": conv_qwen_plain,
|
503 |
+
}
|
504 |
+
|
505 |
+
|
506 |
+
if __name__ == "__main__":
|
507 |
+
print(default_conversation.get_prompt())
|
VideoLLaMA2/videollama2/eval/eval_video_cap_msvc_correctness.py
ADDED
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import os
|
3 |
+
import ast
|
4 |
+
import time
|
5 |
+
import json
|
6 |
+
import argparse
|
7 |
+
from tqdm import tqdm
|
8 |
+
from multiprocessing.pool import Pool
|
9 |
+
|
10 |
+
import openai
|
11 |
+
from openai import AzureOpenAI
|
12 |
+
|
13 |
+
|
14 |
+
def init():
|
15 |
+
client = AzureOpenAI(
|
16 |
+
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
|
17 |
+
api_key=os.getenv("AZURE_OPENAI_KEY"),
|
18 |
+
api_version="2024-02-15-preview"
|
19 |
+
)
|
20 |
+
|
21 |
+
return client
|
22 |
+
|
23 |
+
|
24 |
+
def interaction(client, message_text):
|
25 |
+
completion = client.chat.completions.create(
|
26 |
+
model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
|
27 |
+
messages = message_text,
|
28 |
+
temperature=0.7,
|
29 |
+
max_tokens=800,
|
30 |
+
top_p=0.95,
|
31 |
+
frequency_penalty=0,
|
32 |
+
presence_penalty=0,
|
33 |
+
stop=None
|
34 |
+
)
|
35 |
+
|
36 |
+
return completion
|
37 |
+
|
38 |
+
|
39 |
+
def annotate(prediction_set, caption_files, output_dir):
|
40 |
+
"""
|
41 |
+
Evaluates question and answer pairs using GPT-3
|
42 |
+
Returns a score for correctness.
|
43 |
+
"""
|
44 |
+
|
45 |
+
for file in tqdm(caption_files):
|
46 |
+
key = file[:-5] # Strip file extension
|
47 |
+
qa_set = prediction_set[key]
|
48 |
+
question = qa_set['q']
|
49 |
+
answer = str(qa_set['a'])
|
50 |
+
pred = qa_set['pred']
|
51 |
+
try:
|
52 |
+
message = [
|
53 |
+
{
|
54 |
+
"role": "system",
|
55 |
+
"content":
|
56 |
+
"You are an intelligent chatbot designed for evaluating the factual accuracy of generative outputs for video-based question-answer pairs. "
|
57 |
+
"Your task is to compare the predicted answer with these correct answers and determine if they are factually consistent. Here's how you can accomplish the task:"
|
58 |
+
"------"
|
59 |
+
"##INSTRUCTIONS: "
|
60 |
+
"- Focus on the factual consistency between the predicted answer and the correct answer. The predicted answer should not contain any misinterpretations or misinformation.\n"
|
61 |
+
"- The predicted answer must be factually accurate and align with the video content.\n"
|
62 |
+
"- Consider synonyms or paraphrases as valid matches.\n"
|
63 |
+
"- Evaluate the factual accuracy of the prediction compared to the answer."
|
64 |
+
},
|
65 |
+
{
|
66 |
+
"role": "user",
|
67 |
+
"content":
|
68 |
+
"Please evaluate the following video-based question-answer pair:\n\n"
|
69 |
+
f"Question: {question}\n"
|
70 |
+
f"Correct Answers: {answer}\n"
|
71 |
+
f"Predicted Answer: {pred}\n\n"
|
72 |
+
"Provide your evaluation only as a factual accuracy score where the factual accuracy score is an integer value between 0 and 5, with 5 indicating the highest level of factual consistency. "
|
73 |
+
"Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the factual accuracy score in INTEGER, not STRING."
|
74 |
+
"DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
|
75 |
+
"For example, your response should look like this: {''score': 4.8}."
|
76 |
+
}
|
77 |
+
]
|
78 |
+
completion = interaction(client, message)
|
79 |
+
# Convert response to a Python dictionary.
|
80 |
+
response_message = completion.choices[0].message.content
|
81 |
+
response_dict = ast.literal_eval(response_message)
|
82 |
+
result_qa_pair = [response_dict, qa_set]
|
83 |
+
# # Save the question-answer pairs to a json file.
|
84 |
+
with open(f"{output_dir}/{key}.json", "w") as f:
|
85 |
+
json.dump(result_qa_pair, f)
|
86 |
+
|
87 |
+
except Exception as e:
|
88 |
+
print(f"Error processing file '{key}': {e}")
|
89 |
+
|
90 |
+
time.sleep(1)
|
91 |
+
|
92 |
+
|
93 |
+
def longest_repeating_substring(s):
|
94 |
+
n = len(s)
|
95 |
+
dp = [[0] * (n+1) for _ in range(n+1)]
|
96 |
+
res = ""
|
97 |
+
res_length = 0
|
98 |
+
|
99 |
+
index = 0
|
100 |
+
for i in range(1, n+1):
|
101 |
+
for j in range(i+1, n+1):
|
102 |
+
if (dp[i-1][j-1] > 0 and dp[i-1][j-1] < (j-i)) or s[i-1] == s[j-1]:
|
103 |
+
dp[i][j] = dp[i-1][j-1] + 1
|
104 |
+
if dp[i][j] > res_length:
|
105 |
+
res_length = dp[i][j]
|
106 |
+
index = max(i, index)
|
107 |
+
else:
|
108 |
+
dp[i][j] = 0
|
109 |
+
|
110 |
+
if res_length > 0:
|
111 |
+
for i in range(index-res_length+1, index+1):
|
112 |
+
res = res + s[i-1]
|
113 |
+
|
114 |
+
return res
|
115 |
+
|
116 |
+
|
117 |
+
def main(args):
|
118 |
+
if args.num_chunks > 1:
|
119 |
+
pred_contents = []
|
120 |
+
for _idx in range(args.num_chunks):
|
121 |
+
file = os.path.join(args.pred_path, f"{args.num_chunks}_{_idx}.json")
|
122 |
+
pred_contents += [json.loads(line) for line in open(file)]
|
123 |
+
else:
|
124 |
+
pred_contents = [json.loads(line) for line in open(args.pred_path)]
|
125 |
+
|
126 |
+
# Dictionary to store the count of occurrences for each video_id
|
127 |
+
video_id_counts = {}
|
128 |
+
new_pred_contents = []
|
129 |
+
|
130 |
+
# Iterate through each sample in pred_contents
|
131 |
+
for sample in pred_contents:
|
132 |
+
video_id = sample["video_name"]
|
133 |
+
if video_id in video_id_counts:
|
134 |
+
video_id_counts[video_id] += 1
|
135 |
+
else:
|
136 |
+
video_id_counts[video_id] = 0
|
137 |
+
|
138 |
+
# Create a new sample with the modified key
|
139 |
+
new_sample = sample
|
140 |
+
new_sample["video_name"] = f"{video_id.split('/')[-1].split('.')[0]}_{video_id_counts[video_id]}"
|
141 |
+
new_pred_contents.append(new_sample)
|
142 |
+
|
143 |
+
# Generating list of id's and corresponding files
|
144 |
+
id_list = [x["video_name"] for x in new_pred_contents]
|
145 |
+
caption_files = [f"{id}.json" for id in id_list]
|
146 |
+
|
147 |
+
output_dir = args.output_dir
|
148 |
+
# Generate output directory if not exists.
|
149 |
+
if not os.path.exists(output_dir):
|
150 |
+
os.makedirs(output_dir)
|
151 |
+
|
152 |
+
# Preparing dictionary of question-answer sets
|
153 |
+
prediction_set = {}
|
154 |
+
for sample in new_pred_contents:
|
155 |
+
id = sample["video_name"]
|
156 |
+
# print(sample)
|
157 |
+
question = sample["question"]
|
158 |
+
answer = sample["answer"]
|
159 |
+
pred = sample["pred"]
|
160 |
+
qa_set = {"q": question, "a": answer, "pred": pred}
|
161 |
+
prediction_set[id] = qa_set
|
162 |
+
|
163 |
+
# # Set the OpenAI API key.
|
164 |
+
# openai.api_key = args.api_key # Your API key here
|
165 |
+
# if args.api_base:
|
166 |
+
# openai.api_base = args.api_base # Your API base here
|
167 |
+
num_tasks = args.num_tasks
|
168 |
+
|
169 |
+
# While loop to ensure that all captions are processed.
|
170 |
+
while True:
|
171 |
+
try:
|
172 |
+
# Files that have not been processed yet.
|
173 |
+
completed_files = os.listdir(output_dir)
|
174 |
+
print(f"completed_files: {len(completed_files)}")
|
175 |
+
|
176 |
+
# Files that have not been processed yet.
|
177 |
+
incomplete_files = [f for f in caption_files if f not in completed_files]
|
178 |
+
print(f"incomplete_files: {len(incomplete_files)}")
|
179 |
+
|
180 |
+
# Break the loop when there are no incomplete files
|
181 |
+
if len(incomplete_files) == 0:
|
182 |
+
break
|
183 |
+
if len(incomplete_files) <= num_tasks:
|
184 |
+
num_tasks = 1
|
185 |
+
|
186 |
+
# Split tasks into parts.
|
187 |
+
part_len = len(incomplete_files) // num_tasks
|
188 |
+
all_parts = [incomplete_files[i : i + part_len] for i in range(0, len(incomplete_files), part_len)]
|
189 |
+
task_args = [(prediction_set, part, args.output_dir) for part in all_parts]
|
190 |
+
print("Generate", len(all_parts), "subprocess.")
|
191 |
+
|
192 |
+
# Use a pool of workers to process the files in parallel.
|
193 |
+
# with Pool() as pool:
|
194 |
+
# pool.starmap(annotate, task_args)
|
195 |
+
# import pdb;pdb.set_trace()
|
196 |
+
annotate(*task_args[0])
|
197 |
+
|
198 |
+
except Exception as e:
|
199 |
+
print(f"Error: {e}")
|
200 |
+
|
201 |
+
# Combine all the processed files into one
|
202 |
+
combined_contents = {}
|
203 |
+
json_path = args.output_json
|
204 |
+
|
205 |
+
# Iterate through json files
|
206 |
+
for file_name in os.listdir(output_dir):
|
207 |
+
if file_name.endswith(".json"):
|
208 |
+
file_path = os.path.join(output_dir, file_name)
|
209 |
+
with open(file_path, "r") as json_file:
|
210 |
+
try:
|
211 |
+
content = json.load(json_file)
|
212 |
+
combined_contents[file_name[:-5]] = content
|
213 |
+
except Exception as e:
|
214 |
+
print(f"Error: {e}")
|
215 |
+
pass
|
216 |
+
|
217 |
+
# Calculate average score
|
218 |
+
score_sum = 0
|
219 |
+
count = 0
|
220 |
+
for key, result in combined_contents.items():
|
221 |
+
count += 1
|
222 |
+
try:
|
223 |
+
# key = result[0].keys()[0]
|
224 |
+
# import pdb; pdb.set_trace()
|
225 |
+
for _ in result[0].keys():
|
226 |
+
score_match = result[0][_]
|
227 |
+
score = int(score_match)
|
228 |
+
score_sum += score
|
229 |
+
break
|
230 |
+
except Exception as e:
|
231 |
+
print(f"Error processing file '{key}': {e}")
|
232 |
+
import pdb; pdb.set_trace()
|
233 |
+
average_score = score_sum / count
|
234 |
+
combined_contents["average_score"] = average_score
|
235 |
+
with open(json_path, "w") as json_file:
|
236 |
+
json.dump(combined_contents, json_file, indent=4)
|
237 |
+
print("Average score for correctness:", average_score)
|
238 |
+
|
239 |
+
|
240 |
+
if __name__ == "__main__":
|
241 |
+
parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
|
242 |
+
parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
|
243 |
+
parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
|
244 |
+
parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
|
245 |
+
parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
|
246 |
+
parser.add_argument("--num_chunks", default=1, type=int, help="Result splits")
|
247 |
+
parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
|
248 |
+
parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
|
249 |
+
parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
|
250 |
+
args = parser.parse_args()
|
251 |
+
|
252 |
+
# Set the OpenAI API key.
|
253 |
+
os.environ["AZURE_OPENAI_KEY"] = args.api_key
|
254 |
+
os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
|
255 |
+
os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
|
256 |
+
|
257 |
+
client = init()
|
258 |
+
|
259 |
+
main(args)
|
VideoLLaMA2/videollama2/eval/eval_video_cap_msvc_detailedness.py
ADDED
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import os
|
3 |
+
import ast
|
4 |
+
import time
|
5 |
+
import json
|
6 |
+
import argparse
|
7 |
+
from tqdm import tqdm
|
8 |
+
from multiprocessing.pool import Pool
|
9 |
+
|
10 |
+
import openai
|
11 |
+
from openai import AzureOpenAI
|
12 |
+
|
13 |
+
|
14 |
+
def init():
|
15 |
+
client = AzureOpenAI(
|
16 |
+
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
|
17 |
+
api_key=os.getenv("AZURE_OPENAI_KEY"),
|
18 |
+
api_version="2024-02-15-preview"
|
19 |
+
)
|
20 |
+
|
21 |
+
return client
|
22 |
+
|
23 |
+
|
24 |
+
def interaction(client, message_text):
|
25 |
+
completion = client.chat.completions.create(
|
26 |
+
model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
|
27 |
+
messages = message_text,
|
28 |
+
temperature=0.7,
|
29 |
+
max_tokens=800,
|
30 |
+
top_p=0.95,
|
31 |
+
frequency_penalty=0,
|
32 |
+
presence_penalty=0,
|
33 |
+
stop=None
|
34 |
+
)
|
35 |
+
|
36 |
+
return completion
|
37 |
+
|
38 |
+
|
39 |
+
def annotate(prediction_set, caption_files, output_dir):
|
40 |
+
"""
|
41 |
+
Evaluates question and answer pairs using GPT-3
|
42 |
+
Returns a score for correctness.
|
43 |
+
"""
|
44 |
+
|
45 |
+
for file in tqdm(caption_files):
|
46 |
+
key = file[:-5] # Strip file extension
|
47 |
+
qa_set = prediction_set[key]
|
48 |
+
question = qa_set['q']
|
49 |
+
answer = str(qa_set['a'])
|
50 |
+
pred = qa_set['pred']
|
51 |
+
try:
|
52 |
+
message = [
|
53 |
+
{
|
54 |
+
"role": "system",
|
55 |
+
"content": "You are an intelligent chatbot designed for evaluating the detail orientation of generative outputs for video-based question-answer pairs. "
|
56 |
+
"Your task is to compare the predicted answer with these correct answers and determine its level of detail, considering both completeness and specificity. Here's how you can accomplish the task:"
|
57 |
+
"------"
|
58 |
+
"##INSTRUCTIONS: "
|
59 |
+
"- Check if the predicted answer covers all major points from the video. The response should not leave out any key aspects.\n"
|
60 |
+
"- Evaluate whether the predicted answer includes specific details rather than just generic points. It should provide comprehensive information that is tied to specific elements of the video.\n"
|
61 |
+
"- Consider synonyms or paraphrases as valid matches.\n"
|
62 |
+
"- Provide a single evaluation score that reflects the level of detail orientation of the prediction, considering both completeness and specificity.",
|
63 |
+
},
|
64 |
+
{
|
65 |
+
"role": "user",
|
66 |
+
"content": "Please evaluate the following video-based question-answer pair:\n\n"
|
67 |
+
f"Question: {question}\n"
|
68 |
+
f"Correct Answers: {answer}\n"
|
69 |
+
f"Predicted Answer: {pred}\n\n"
|
70 |
+
"Provide your evaluation only as a detail orientation score where the detail orientation score is an integer value between 0 and 5, with 5 indicating the highest level of detail orientation. "
|
71 |
+
"Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the detail orientation score in INTEGER, not STRING."
|
72 |
+
"DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
|
73 |
+
"For example, your response should look like this: {''score': 4.8}.",
|
74 |
+
},
|
75 |
+
]
|
76 |
+
completion = interaction(client, message)
|
77 |
+
# Convert response to a Python dictionary.
|
78 |
+
response_message = completion.choices[0].message.content
|
79 |
+
response_dict = ast.literal_eval(response_message)
|
80 |
+
result_qa_pair = [response_dict, qa_set]
|
81 |
+
# # Save the question-answer pairs to a json file.
|
82 |
+
with open(f"{output_dir}/{key}.json", "w") as f:
|
83 |
+
json.dump(result_qa_pair, f)
|
84 |
+
|
85 |
+
except Exception as e:
|
86 |
+
print(f"Error processing file '{key}': {e}")
|
87 |
+
|
88 |
+
time.sleep(1)
|
89 |
+
|
90 |
+
|
91 |
+
def longest_repeating_substring(s):
|
92 |
+
n = len(s)
|
93 |
+
dp = [[0] * (n+1) for _ in range(n+1)]
|
94 |
+
res = ""
|
95 |
+
res_length = 0
|
96 |
+
|
97 |
+
index = 0
|
98 |
+
for i in range(1, n+1):
|
99 |
+
for j in range(i+1, n+1):
|
100 |
+
if (dp[i-1][j-1] > 0 and dp[i-1][j-1] < (j-i)) or s[i-1] == s[j-1]:
|
101 |
+
dp[i][j] = dp[i-1][j-1] + 1
|
102 |
+
if dp[i][j] > res_length:
|
103 |
+
res_length = dp[i][j]
|
104 |
+
index = max(i, index)
|
105 |
+
else:
|
106 |
+
dp[i][j] = 0
|
107 |
+
|
108 |
+
if res_length > 0:
|
109 |
+
for i in range(index-res_length+1, index+1):
|
110 |
+
res = res + s[i-1]
|
111 |
+
|
112 |
+
return res
|
113 |
+
|
114 |
+
|
115 |
+
def main(args):
|
116 |
+
if args.num_chunks > 1:
|
117 |
+
pred_contents = []
|
118 |
+
for _idx in range(args.num_chunks):
|
119 |
+
file = os.path.join(args.pred_path, f"{args.num_chunks}_{_idx}.json")
|
120 |
+
pred_contents += [json.loads(line) for line in open(file)]
|
121 |
+
else:
|
122 |
+
pred_contents = [json.loads(line) for line in open(args.pred_path)]
|
123 |
+
|
124 |
+
# Dictionary to store the count of occurrences for each video_id
|
125 |
+
video_id_counts = {}
|
126 |
+
new_pred_contents = []
|
127 |
+
|
128 |
+
# Iterate through each sample in pred_contents
|
129 |
+
for sample in pred_contents:
|
130 |
+
video_id = sample["video_name"]
|
131 |
+
if video_id in video_id_counts:
|
132 |
+
video_id_counts[video_id] += 1
|
133 |
+
else:
|
134 |
+
video_id_counts[video_id] = 0
|
135 |
+
|
136 |
+
# Create a new sample with the modified key
|
137 |
+
new_sample = sample
|
138 |
+
new_sample["video_name"] = f"{video_id.split('/')[-1].split('.')[0]}_{video_id_counts[video_id]}"
|
139 |
+
new_pred_contents.append(new_sample)
|
140 |
+
|
141 |
+
# Generating list of id's and corresponding files
|
142 |
+
id_list = [x["video_name"] for x in new_pred_contents]
|
143 |
+
caption_files = [f"{id}.json" for id in id_list]
|
144 |
+
|
145 |
+
output_dir = args.output_dir
|
146 |
+
# Generate output directory if not exists.
|
147 |
+
if not os.path.exists(output_dir):
|
148 |
+
os.makedirs(output_dir)
|
149 |
+
|
150 |
+
# Preparing dictionary of question-answer sets
|
151 |
+
prediction_set = {}
|
152 |
+
for sample in new_pred_contents:
|
153 |
+
id = sample["video_name"]
|
154 |
+
# print(sample)
|
155 |
+
question = sample["question"]
|
156 |
+
answer = sample["answer"]
|
157 |
+
pred = sample["pred"]
|
158 |
+
qa_set = {"q": question, "a": answer, "pred": pred}
|
159 |
+
prediction_set[id] = qa_set
|
160 |
+
|
161 |
+
# # Set the OpenAI API key.
|
162 |
+
# openai.api_key = args.api_key # Your API key here
|
163 |
+
# if args.api_base:
|
164 |
+
# openai.api_base = args.api_base # Your API base here
|
165 |
+
num_tasks = args.num_tasks
|
166 |
+
|
167 |
+
# While loop to ensure that all captions are processed.
|
168 |
+
while True:
|
169 |
+
try:
|
170 |
+
# Files that have not been processed yet.
|
171 |
+
completed_files = os.listdir(output_dir)
|
172 |
+
print(f"completed_files: {len(completed_files)}")
|
173 |
+
|
174 |
+
# Files that have not been processed yet.
|
175 |
+
incomplete_files = [f for f in caption_files if f not in completed_files]
|
176 |
+
print(f"incomplete_files: {len(incomplete_files)}")
|
177 |
+
|
178 |
+
# Break the loop when there are no incomplete files
|
179 |
+
if len(incomplete_files) == 0:
|
180 |
+
break
|
181 |
+
if len(incomplete_files) <= num_tasks:
|
182 |
+
num_tasks = 1
|
183 |
+
|
184 |
+
# Split tasks into parts.
|
185 |
+
part_len = len(incomplete_files) // num_tasks
|
186 |
+
all_parts = [incomplete_files[i : i + part_len] for i in range(0, len(incomplete_files), part_len)]
|
187 |
+
task_args = [(prediction_set, part, args.output_dir) for part in all_parts]
|
188 |
+
print("Generate", len(all_parts), "subprocess.")
|
189 |
+
|
190 |
+
# Use a pool of workers to process the files in parallel.
|
191 |
+
# with Pool() as pool:
|
192 |
+
# pool.starmap(annotate, task_args)
|
193 |
+
# import pdb;pdb.set_trace()
|
194 |
+
annotate(*task_args[0])
|
195 |
+
|
196 |
+
except Exception as e:
|
197 |
+
print(f"Error: {e}")
|
198 |
+
|
199 |
+
# Combine all the processed files into one
|
200 |
+
combined_contents = {}
|
201 |
+
json_path = args.output_json
|
202 |
+
|
203 |
+
# Iterate through json files
|
204 |
+
for file_name in os.listdir(output_dir):
|
205 |
+
if file_name.endswith(".json"):
|
206 |
+
file_path = os.path.join(output_dir, file_name)
|
207 |
+
with open(file_path, "r") as json_file:
|
208 |
+
try:
|
209 |
+
content = json.load(json_file)
|
210 |
+
combined_contents[file_name[:-5]] = content
|
211 |
+
except Exception as e:
|
212 |
+
print(f"Error: {e}")
|
213 |
+
pass
|
214 |
+
|
215 |
+
# Calculate average score
|
216 |
+
score_sum = 0
|
217 |
+
count = 0
|
218 |
+
for key, result in combined_contents.items():
|
219 |
+
count += 1
|
220 |
+
try:
|
221 |
+
# key = result[0].keys()[0]
|
222 |
+
# import pdb; pdb.set_trace()
|
223 |
+
for _ in result[0].keys():
|
224 |
+
score_match = result[0][_]
|
225 |
+
score = int(score_match)
|
226 |
+
score_sum += score
|
227 |
+
break
|
228 |
+
except Exception as e:
|
229 |
+
print(f"Error processing file '{key}': {e}")
|
230 |
+
import pdb; pdb.set_trace()
|
231 |
+
average_score = score_sum / count
|
232 |
+
combined_contents["average_score"] = average_score
|
233 |
+
with open(json_path, "w") as json_file:
|
234 |
+
json.dump(combined_contents, json_file, indent=4)
|
235 |
+
print("Average score for detailedness:", average_score)
|
236 |
+
|
237 |
+
|
238 |
+
if __name__ == "__main__":
|
239 |
+
parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
|
240 |
+
parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
|
241 |
+
parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
|
242 |
+
parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
|
243 |
+
parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
|
244 |
+
parser.add_argument("--num_chunks", default=1, type=int, help="Result splits")
|
245 |
+
parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
|
246 |
+
parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
|
247 |
+
parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
|
248 |
+
args = parser.parse_args()
|
249 |
+
|
250 |
+
# Set the OpenAI API key.
|
251 |
+
os.environ["AZURE_OPENAI_KEY"] = args.api_key
|
252 |
+
os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
|
253 |
+
os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
|
254 |
+
|
255 |
+
client = init()
|
256 |
+
|
257 |
+
main(args)
|
VideoLLaMA2/videollama2/eval/eval_video_mcqa_mvbench.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import argparse
|
3 |
+
from tabulate import tabulate
|
4 |
+
|
5 |
+
|
6 |
+
tasks = {
|
7 |
+
"Action Sequence": ("action_sequence.json", "star/Charades_v1_480/", "video", True), # has start & end
|
8 |
+
"Action Prediction": ("action_prediction.json", "star/Charades_v1_480/", "video", True), # has start & end
|
9 |
+
"Action Antonym": ("action_antonym.json", "ssv2_video/", "video", False),
|
10 |
+
"Fine-grained Action": ("fine_grained_action.json", "pMoments_in_Time_Raw/videos/", "video", False),
|
11 |
+
"Unexpected Action": ("unexpected_action.json", "FunQA_test/test/", "video", False),
|
12 |
+
"Object Existence": ("object_existence.json", "clevrer/video_validation/", "video", False),
|
13 |
+
"Object Interaction": ("object_interaction.json", "star/Charades_v1_480/", "video", True), # has start & end
|
14 |
+
"Object Shuffle": ("object_shuffle.json", "perception/videos/", "video", False),
|
15 |
+
"Moving Direction": ("moving_direction.json", "clevrer/video_validation/", "video", False),
|
16 |
+
"Action Localization": ("action_localization.json", "sta/sta_video/", "video", True), # has start & end
|
17 |
+
"Scene Transition": ("scene_transition.json", "scene_qa/video/", "video", False),
|
18 |
+
"Action Count": ("action_count.json", "perception/videos/", "video", False),
|
19 |
+
"Moving Count": ("moving_count.json", "clevrer/video_validation/", "video", False),
|
20 |
+
"Moving Attribute": ("moving_attribute.json", "clevrer/video_validation/", "video", False),
|
21 |
+
"State Change": ("state_change.json", "perception/videos/", "video", False),
|
22 |
+
"Fine-grained Pose": ("fine_grained_pose.json", "nturgbd/", "video", False),
|
23 |
+
"Character Order": ("character_order.json", "perception/videos/", "video", False),
|
24 |
+
"Egocentric Navigation": ("egocentric_navigation.json", "vlnqa/", "video", False),
|
25 |
+
"Episodic Reasoning": ("episodic_reasoning.json", "tvqa/frames_fps3_hq/", "frame", True), # has start & end, read frame
|
26 |
+
"Counterfactual Inference": ("counterfactual_inference.json", "clevrer/video_validation/", "video", False),
|
27 |
+
}
|
28 |
+
|
29 |
+
|
30 |
+
def main():
|
31 |
+
args = parse_args()
|
32 |
+
res = [eval(x.strip()) for x in open(args.pred_path, 'r').readlines()]
|
33 |
+
task_types = tasks.keys()
|
34 |
+
task_acc = {x: [] for x in task_types}
|
35 |
+
acc = []
|
36 |
+
for i, x in enumerate(res):
|
37 |
+
value = 1
|
38 |
+
if x['pred'] != x['gt']:
|
39 |
+
value = 0
|
40 |
+
acc.append(value)
|
41 |
+
task_acc[x['task_type']].append(value)
|
42 |
+
acc = sum(acc) * 100 / len(acc)
|
43 |
+
task_acc = {x: sum(task_acc[x]) * 100 / len(task_acc[x]) for x in task_acc}
|
44 |
+
print(f"{args.pred_path}:", acc)
|
45 |
+
task_names = list(tasks.keys())
|
46 |
+
|
47 |
+
table_data = []
|
48 |
+
for i in range(len(task_names) // 4):
|
49 |
+
row_task_names = task_names[i * 4: (i + 1) * 4]
|
50 |
+
row_task_acc = [task_acc[x] for x in row_task_names]
|
51 |
+
table_data.append(row_task_names)
|
52 |
+
table_data.append(row_task_acc)
|
53 |
+
print(tabulate(table_data, floatfmt=".1f"), '\n')
|
54 |
+
|
55 |
+
|
56 |
+
def parse_args():
|
57 |
+
parser = argparse.ArgumentParser(description="Evaluate video captioning.")
|
58 |
+
parser.add_argument("--pred_path", default=r'', help="The path to file containing prediction.")
|
59 |
+
args = parser.parse_args()
|
60 |
+
return args
|
61 |
+
|
62 |
+
|
63 |
+
if __name__ == '__main__':
|
64 |
+
main()
|
VideoLLaMA2/videollama2/eval/eval_video_mcqa_videomme.py
ADDED
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import json
|
4 |
+
import argparse
|
5 |
+
from typing import List, Dict, Optional, Union
|
6 |
+
|
7 |
+
CATEGORIES = [
|
8 |
+
"Knowledge",
|
9 |
+
"Film & Television",
|
10 |
+
"Sports Competition",
|
11 |
+
"Artistic Performance",
|
12 |
+
"Life Record",
|
13 |
+
"Multilingual"
|
14 |
+
]
|
15 |
+
|
16 |
+
SUB_CATEGORIES = [
|
17 |
+
"Humanity & History",
|
18 |
+
"Literature & Art",
|
19 |
+
"Biology & Medicine",
|
20 |
+
"Finance & Commerce",
|
21 |
+
"Astronomy",
|
22 |
+
"Geography",
|
23 |
+
"Law",
|
24 |
+
"Life Tip",
|
25 |
+
"Technology",
|
26 |
+
"Animation",
|
27 |
+
"Movie & TV Show",
|
28 |
+
"Documentary",
|
29 |
+
"News Report",
|
30 |
+
"Esports",
|
31 |
+
"Basketball",
|
32 |
+
"Football",
|
33 |
+
"Athletics",
|
34 |
+
"Other Sports",
|
35 |
+
"Stage Play",
|
36 |
+
"Magic Show",
|
37 |
+
"Variety Show",
|
38 |
+
"Acrobatics",
|
39 |
+
"Handicraft",
|
40 |
+
"Food",
|
41 |
+
"Fashion",
|
42 |
+
"Daily Life",
|
43 |
+
"Travel",
|
44 |
+
"Pet & Animal",
|
45 |
+
"Exercise",
|
46 |
+
"Multilingual"
|
47 |
+
]
|
48 |
+
|
49 |
+
TASK_CATEGORIES = [
|
50 |
+
"Temporal Perception",
|
51 |
+
"Spatial Perception",
|
52 |
+
"Attribute Perception",
|
53 |
+
"Action Recognition",
|
54 |
+
"Object Recognition",
|
55 |
+
"OCR Problems",
|
56 |
+
"Counting Problem",
|
57 |
+
"Temporal Reasoning",
|
58 |
+
"Spatial Reasoning",
|
59 |
+
"Action Reasoning",
|
60 |
+
"Object Reasoning",
|
61 |
+
"Information Synopsis",
|
62 |
+
]
|
63 |
+
|
64 |
+
|
65 |
+
def extract_characters_regex(s):
|
66 |
+
s = s.strip()
|
67 |
+
answer_prefixes = [
|
68 |
+
"The best answer is",
|
69 |
+
"The correct answer is",
|
70 |
+
"The answer is",
|
71 |
+
"The answer",
|
72 |
+
"The best option is"
|
73 |
+
"The correct option is",
|
74 |
+
"Best answer:"
|
75 |
+
"Best option:",
|
76 |
+
]
|
77 |
+
for answer_prefix in answer_prefixes:
|
78 |
+
s = s.replace(answer_prefix, "")
|
79 |
+
|
80 |
+
if len(s.split()) > 10 and not re.search("[ABCD]", s):
|
81 |
+
return ""
|
82 |
+
matches = re.search(r'[ABCD]', s)
|
83 |
+
if matches is None:
|
84 |
+
return ""
|
85 |
+
return matches[0]
|
86 |
+
|
87 |
+
|
88 |
+
def eval_your_results(
|
89 |
+
your_results_path: str,
|
90 |
+
video_types: Optional[Union[List[str], str]] = None,
|
91 |
+
skip_missing: Optional[bool] = True,
|
92 |
+
return_categories_accuracy: Optional[bool] = True,
|
93 |
+
return_sub_categories_accuracy: Optional[bool] = False,
|
94 |
+
return_task_types_accuracy: Optional[bool] = False,
|
95 |
+
gt_answer_key: Optional[str] = "answer",
|
96 |
+
your_answer_key: Optional[str] = "response"
|
97 |
+
|
98 |
+
):
|
99 |
+
"""
|
100 |
+
Evaluate your results against the ground truth
|
101 |
+
|
102 |
+
Args:
|
103 |
+
- your_results_path (str): Path to your results file
|
104 |
+
- video_types (Optional[List[str], str]): List of video types to evaluate.
|
105 |
+
- skip_missing (Optional[bool]): If True, missing files will be skipped. If False, an error will be raised if there are missing files.
|
106 |
+
- return_categories_accuracy (Optional[bool]): If True, the accuracy for each video category will be returned.
|
107 |
+
- return_sub_categories_accuracy (Optional[bool]): If True, the accuracy for each video sub category will be returned.
|
108 |
+
- return_task_types_accuracy (Optional[bool]): If True, the accuracy for each task category will be returned.
|
109 |
+
- gt_answer_key (Optional[str]): Key to access the ground truth answer in the results file.
|
110 |
+
- your_answer_key (Optional[str]): Key to access your answer in the results file.
|
111 |
+
"""
|
112 |
+
|
113 |
+
# Load your results
|
114 |
+
with open(your_results_path, 'r') as f:
|
115 |
+
your_results = json.load(f)
|
116 |
+
|
117 |
+
if isinstance(video_types, str):
|
118 |
+
video_types = video_types.split(",")
|
119 |
+
|
120 |
+
q_type_dict = {}
|
121 |
+
v_type_dict = {}
|
122 |
+
v_sub_type_dict = {}
|
123 |
+
|
124 |
+
|
125 |
+
for video_type in video_types:
|
126 |
+
|
127 |
+
# Filter your results based on video types
|
128 |
+
your_results_video_type = [item for item in your_results if item["duration"] == video_type]
|
129 |
+
|
130 |
+
# Task Categories
|
131 |
+
q_type_dict[video_type] = {}
|
132 |
+
for q_type in TASK_CATEGORIES:
|
133 |
+
q_type_dict[video_type][q_type] = {"correct": 0, "answered": 0}
|
134 |
+
|
135 |
+
# Video categories
|
136 |
+
v_type_dict[video_type] = {}
|
137 |
+
for v_type in CATEGORIES:
|
138 |
+
v_type_dict[video_type][v_type] = {"correct": 0, "answered": 0}
|
139 |
+
|
140 |
+
v_sub_type_dict[video_type] = {}
|
141 |
+
for v_sub_type in SUB_CATEGORIES:
|
142 |
+
v_sub_type_dict[video_type][v_sub_type] = {"correct": 0, "answered": 0}
|
143 |
+
|
144 |
+
if not skip_missing:
|
145 |
+
# Check if the number of files in your results and ground truth are the same
|
146 |
+
assert len(your_results_video_type) == 300, f"Number of files in {video_type} is not 300. Check if there are missing files."
|
147 |
+
|
148 |
+
for item in your_results_video_type:
|
149 |
+
|
150 |
+
if skip_missing and item["missing"]:
|
151 |
+
continue
|
152 |
+
|
153 |
+
# Get the video category, sub category and question category
|
154 |
+
video_category = item["domain"]
|
155 |
+
video_sub_category = item["sub_category"]
|
156 |
+
|
157 |
+
questions = item["questions"]
|
158 |
+
|
159 |
+
for question in questions:
|
160 |
+
q_type = question["task_type"]
|
161 |
+
|
162 |
+
# Get the ground truth and your response
|
163 |
+
gt_answer = question[gt_answer_key]
|
164 |
+
response = question[your_answer_key]
|
165 |
+
|
166 |
+
# Extract the answer from the response
|
167 |
+
extration = extract_characters_regex(response)
|
168 |
+
|
169 |
+
if extration != "":
|
170 |
+
q_type_dict[video_type][q_type]["answered"] += 1
|
171 |
+
q_type_dict[video_type][q_type]["correct"] += extration == gt_answer
|
172 |
+
|
173 |
+
v_type_dict[video_type][video_category]["answered"] += 1
|
174 |
+
v_type_dict[video_type][video_category]["correct"] += extration == gt_answer
|
175 |
+
|
176 |
+
v_sub_type_dict[video_type][video_sub_category]["answered"] += 1
|
177 |
+
v_sub_type_dict[video_type][video_sub_category]["correct"] += extration == gt_answer
|
178 |
+
|
179 |
+
|
180 |
+
# Print the results for each video type
|
181 |
+
for video_type in video_types:
|
182 |
+
|
183 |
+
print("=====================================")
|
184 |
+
print(f"Evaluation on video Type: {video_type}")
|
185 |
+
print("=====================================")
|
186 |
+
if return_categories_accuracy:
|
187 |
+
print("-------------------------------------")
|
188 |
+
print("Video Domains")
|
189 |
+
print("-------------------------------------")
|
190 |
+
for v_type in v_type_dict[video_type]:
|
191 |
+
print(f"{v_type}: {100 * v_type_dict[video_type][v_type]['correct'] / v_type_dict[video_type][v_type]['answered'] if v_type_dict[video_type][v_type]['answered'] > 0 else 0 : .1f}%")
|
192 |
+
if return_sub_categories_accuracy:
|
193 |
+
print("-------------------------------------")
|
194 |
+
print("Video Sub Categories")
|
195 |
+
print("-------------------------------------")
|
196 |
+
for v_sub_type in v_sub_type_dict[video_type]:
|
197 |
+
print(f"{v_sub_type}: {100 * v_sub_type_dict[video_type][v_sub_type]['correct'] / v_sub_type_dict[video_type][v_sub_type]['answered'] if v_sub_type_dict[video_type][v_sub_type]['answered'] > 0 else 0 : .1f}%")
|
198 |
+
if return_task_types_accuracy:
|
199 |
+
print("-------------------------------------")
|
200 |
+
print("Task Categories")
|
201 |
+
print("-------------------------------------")
|
202 |
+
for q_type in q_type_dict[video_type]:
|
203 |
+
print(f"{q_type}: {100 * q_type_dict[video_type][q_type]['correct'] / q_type_dict[video_type][q_type]['answered'] if q_type_dict[video_type][q_type]['answered'] > 0 else 0 : .1f}%")
|
204 |
+
|
205 |
+
print("-------------------------------------")
|
206 |
+
print("Overall Performance")
|
207 |
+
print("-------------------------------------")
|
208 |
+
total_correct = sum([q_type_dict[video_type][q_type]["correct"] for q_type in TASK_CATEGORIES])
|
209 |
+
total_answered = sum([q_type_dict[video_type][q_type]["answered"] for q_type in TASK_CATEGORIES])
|
210 |
+
print(f"Overall: {100 * total_correct / total_answered if total_answered > 0 else 0 : .1f}%")
|
211 |
+
|
212 |
+
print("\n")
|
213 |
+
|
214 |
+
# Print the results for the entire dataset
|
215 |
+
print("=====================================")
|
216 |
+
print("Evaluation on the entire dataset")
|
217 |
+
print("=====================================")
|
218 |
+
|
219 |
+
if return_categories_accuracy:
|
220 |
+
print("-------------------------------------")
|
221 |
+
print("Video Categories")
|
222 |
+
print("-------------------------------------")
|
223 |
+
for v_type in CATEGORIES:
|
224 |
+
total_correct = sum([v_type_dict[video_type][v_type]["correct"] for video_type in video_types])
|
225 |
+
total_answered = sum([v_type_dict[video_type][v_type]["answered"] for video_type in video_types])
|
226 |
+
print(f"{v_type}: {100 * total_correct / total_answered if total_answered > 0 else 0 : .1f}%")
|
227 |
+
|
228 |
+
|
229 |
+
if return_sub_categories_accuracy:
|
230 |
+
print("-------------------------------------")
|
231 |
+
print("Video Sub Categories")
|
232 |
+
print("-------------------------------------")
|
233 |
+
|
234 |
+
for v_sub_type in SUB_CATEGORIES:
|
235 |
+
total_correct = sum([v_sub_type_dict[video_type][v_sub_type]["correct"] for video_type in video_types])
|
236 |
+
total_answered = sum([v_sub_type_dict[video_type][v_sub_type]["answered"] for video_type in video_types])
|
237 |
+
print(f"{v_sub_type}: {100 * total_correct / total_answered if total_answered > 0 else 0 : .1f}%")
|
238 |
+
|
239 |
+
|
240 |
+
if return_task_types_accuracy:
|
241 |
+
print("-------------------------------------")
|
242 |
+
print("Task Categories")
|
243 |
+
print("-------------------------------------")
|
244 |
+
for q_type in TASK_CATEGORIES:
|
245 |
+
|
246 |
+
total_correct = sum([q_type_dict[video_type][q_type]["correct"] for video_type in video_types])
|
247 |
+
total_answered = sum([q_type_dict[video_type][q_type]["answered"] for video_type in video_types])
|
248 |
+
print(f"{q_type}: {100 * total_correct / total_answered if total_answered > 0 else 0 : .1f}%")
|
249 |
+
|
250 |
+
print("-------------------------------------")
|
251 |
+
print("Overall Performance")
|
252 |
+
print("-------------------------------------")
|
253 |
+
total_correct = sum([sum([q_type_dict[video_type][q_type]["correct"] for q_type in TASK_CATEGORIES]) for video_type in video_types])
|
254 |
+
total_answered = sum([sum([q_type_dict[video_type][q_type]["answered"] for q_type in TASK_CATEGORIES]) for video_type in video_types])
|
255 |
+
print(f"Overall: {100 * total_correct / total_answered if total_answered > 0 else 0 : .1f}%")
|
256 |
+
|
257 |
+
|
258 |
+
|
259 |
+
if __name__ == "__main__":
|
260 |
+
parser = argparse.ArgumentParser()
|
261 |
+
parser.add_argument("--results_file", type=str, required=True)
|
262 |
+
parser.add_argument("--video_duration_type", type=str, required=True)
|
263 |
+
parser.add_argument("--return_categories_accuracy", action="store_true")
|
264 |
+
parser.add_argument("--return_sub_categories_accuracy", action="store_true")
|
265 |
+
parser.add_argument("--return_task_types_accuracy", action="store_true")
|
266 |
+
parser.add_argument("--skip_missing", action="store_true")
|
267 |
+
|
268 |
+
args = parser.parse_args()
|
269 |
+
|
270 |
+
eval_your_results(
|
271 |
+
args.results_file,
|
272 |
+
video_types=args.video_duration_type,
|
273 |
+
skip_missing=args.skip_missing,
|
274 |
+
return_categories_accuracy=args.return_categories_accuracy,
|
275 |
+
return_sub_categories_accuracy=args.return_sub_categories_accuracy,
|
276 |
+
return_task_types_accuracy=args.return_task_types_accuracy,
|
277 |
+
)
|
VideoLLaMA2/videollama2/eval/eval_video_oqa_activitynet.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import ast
|
3 |
+
import json
|
4 |
+
import time
|
5 |
+
import argparse
|
6 |
+
import traceback
|
7 |
+
from tqdm import tqdm
|
8 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
9 |
+
|
10 |
+
from openai import AzureOpenAI
|
11 |
+
|
12 |
+
|
13 |
+
def init():
|
14 |
+
client = AzureOpenAI(
|
15 |
+
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
|
16 |
+
api_key=os.getenv("AZURE_OPENAI_KEY"),
|
17 |
+
api_version="2024-02-15-preview"
|
18 |
+
)
|
19 |
+
|
20 |
+
return client
|
21 |
+
|
22 |
+
|
23 |
+
def interaction(client, message_text):
|
24 |
+
completion = client.chat.completions.create(
|
25 |
+
model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
|
26 |
+
messages = message_text,
|
27 |
+
temperature=0.7,
|
28 |
+
max_tokens=800,
|
29 |
+
top_p=0.95,
|
30 |
+
frequency_penalty=0,
|
31 |
+
presence_penalty=0,
|
32 |
+
stop=None
|
33 |
+
)
|
34 |
+
|
35 |
+
return completion
|
36 |
+
|
37 |
+
|
38 |
+
def prompt_gpt(question, answer, pred, key, qa_set, output_dir):
|
39 |
+
message = [
|
40 |
+
{
|
41 |
+
"role": "system",
|
42 |
+
"content":
|
43 |
+
"You are an intelligent chatbot designed for evaluating the correctness of generative outputs for question-answer pairs. "
|
44 |
+
"Your task is to compare the predicted answer with the correct answer and determine if they match meaningfully. Here's how you can accomplish the task:"
|
45 |
+
"------"
|
46 |
+
"##INSTRUCTIONS: "
|
47 |
+
"- Focus on the meaningful match between the predicted answer and the correct answer.\n"
|
48 |
+
"- Consider synonyms or paraphrases as valid matches.\n"
|
49 |
+
"- Evaluate the correctness of the prediction compared to the answer."
|
50 |
+
},
|
51 |
+
{
|
52 |
+
"role": "user",
|
53 |
+
"content":
|
54 |
+
"Please evaluate the following video-based question-answer pair:\n\n"
|
55 |
+
f"Question: {question}\n"
|
56 |
+
f"Correct Answer: {answer}\n"
|
57 |
+
f"Predicted Answer: {pred}\n\n"
|
58 |
+
"Provide your evaluation only as a yes/no and score where the score is an integer value between 0 and 5, with 5 indicating the highest meaningful match. "
|
59 |
+
"Please generate the response in the form of a Python dictionary string with keys 'pred' and 'score', where value of 'pred' is a string of 'yes' or 'no' and value of 'score' is in INTEGER, not STRING."
|
60 |
+
"DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
|
61 |
+
"For example, your response should look like this: {'pred': 'yes', 'score': 4.8}."
|
62 |
+
}
|
63 |
+
]
|
64 |
+
completion = interaction(client, message)
|
65 |
+
# Convert response to a Python dictionary.
|
66 |
+
response_message = completion.choices[0].message.content
|
67 |
+
response_dict = ast.literal_eval(response_message)
|
68 |
+
result_qa_pair = [response_dict, qa_set]
|
69 |
+
# # Save the question-answer pairs to a json file.
|
70 |
+
with open(f"{output_dir}/{key}.json", "w") as f:
|
71 |
+
json.dump(result_qa_pair, f)
|
72 |
+
|
73 |
+
|
74 |
+
def annotate(task_arg):
|
75 |
+
"""
|
76 |
+
Evaluates question and answer pairs using GPT-3
|
77 |
+
Returns a score for correctness.
|
78 |
+
"""
|
79 |
+
prediction_set, caption_files, output_dir, args = task_arg
|
80 |
+
|
81 |
+
for file in tqdm(caption_files):
|
82 |
+
key = file[:-5] # Strip file extension
|
83 |
+
qa_set = prediction_set[key]
|
84 |
+
question = qa_set['q']
|
85 |
+
answer = qa_set['a']
|
86 |
+
pred = qa_set['p']
|
87 |
+
try:
|
88 |
+
prompt_gpt(question, answer, pred, key, qa_set, output_dir)
|
89 |
+
except Exception as e:
|
90 |
+
prompt_gpt(question, answer, pred[:50], key, qa_set, output_dir)
|
91 |
+
traceback.print_exc()
|
92 |
+
|
93 |
+
time.sleep(1)
|
94 |
+
|
95 |
+
|
96 |
+
def main(args):
|
97 |
+
|
98 |
+
file = open(args.pred_path)
|
99 |
+
new_pred_contents = [eval(i.strip()) for i in file.readlines()]
|
100 |
+
|
101 |
+
# Generating list of id's and corresponding files
|
102 |
+
id_list = [x['id'] for x in new_pred_contents]
|
103 |
+
caption_files = [f"{id}.json" for id in id_list]
|
104 |
+
|
105 |
+
output_dir = args.output_dir
|
106 |
+
# Generate output directory if not exists.
|
107 |
+
if not os.path.exists(output_dir):
|
108 |
+
os.makedirs(output_dir)
|
109 |
+
|
110 |
+
# Preparing dictionary of question-answer sets
|
111 |
+
prediction_set = {}
|
112 |
+
for sample in new_pred_contents:
|
113 |
+
id = sample['id']
|
114 |
+
question = sample['question']
|
115 |
+
answer = sample['answer']
|
116 |
+
pred = sample['pred']
|
117 |
+
qa_set = {"q": question, "a": answer, "p": pred}
|
118 |
+
prediction_set[id] = qa_set
|
119 |
+
|
120 |
+
num_tasks = args.num_tasks
|
121 |
+
|
122 |
+
# While loop to ensure that all captions are processed.
|
123 |
+
while True:
|
124 |
+
try:
|
125 |
+
# Files that have not been processed yet.
|
126 |
+
completed_files = os.listdir(output_dir)
|
127 |
+
print(f"completed_files: {len(completed_files)}")
|
128 |
+
|
129 |
+
# Files that have not been processed yet.
|
130 |
+
incomplete_files = [f for f in caption_files if f not in completed_files]
|
131 |
+
print(f"incomplete_files: {len(incomplete_files)}")
|
132 |
+
|
133 |
+
# Break the loop when there are no incomplete files
|
134 |
+
if len(incomplete_files) == 0:
|
135 |
+
break
|
136 |
+
if len(incomplete_files) <= num_tasks:
|
137 |
+
num_tasks = 1
|
138 |
+
|
139 |
+
# Split tasks into parts.
|
140 |
+
part_len = len(incomplete_files) // num_tasks
|
141 |
+
all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
|
142 |
+
task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
|
143 |
+
|
144 |
+
# Use a pool of workers to process the files in parallel.
|
145 |
+
with ThreadPoolExecutor(max_workers=args.num_tasks) as executor:
|
146 |
+
list(tqdm(executor.map(annotate, task_args), total=len(task_args)))
|
147 |
+
|
148 |
+
except Exception as e:
|
149 |
+
print(f"Error: {e}")
|
150 |
+
|
151 |
+
# multiprocessing to combine json files
|
152 |
+
def combine_json(file_name):
|
153 |
+
file_path = os.path.join(output_dir, file_name)
|
154 |
+
with open(file_path, "r") as json_file:
|
155 |
+
content = json.load(json_file)
|
156 |
+
return (file_name[:-5], content)
|
157 |
+
|
158 |
+
files = os.listdir(output_dir)
|
159 |
+
with ThreadPoolExecutor(max_workers=64) as executor:
|
160 |
+
combined_contents = list(tqdm(executor.map(combine_json, files), total=len(files)))
|
161 |
+
|
162 |
+
# Calculate average score and accuracy
|
163 |
+
score_sum = 0
|
164 |
+
count = 0
|
165 |
+
yes_count = 0
|
166 |
+
no_count = 0
|
167 |
+
for key, result in tqdm(combined_contents):
|
168 |
+
try:
|
169 |
+
# Computing score
|
170 |
+
count += 1
|
171 |
+
score_match = result[0]['score']
|
172 |
+
score = int(score_match)
|
173 |
+
score_sum += score
|
174 |
+
|
175 |
+
# Computing accuracy
|
176 |
+
pred = result[0]['pred']
|
177 |
+
if "yes" in pred.lower():
|
178 |
+
yes_count += 1
|
179 |
+
elif "no" in pred.lower():
|
180 |
+
no_count += 1
|
181 |
+
except:
|
182 |
+
print(result)
|
183 |
+
|
184 |
+
average_score = score_sum / count
|
185 |
+
accuracy = yes_count / (yes_count + no_count)
|
186 |
+
print("Yes count:", yes_count)
|
187 |
+
print("No count:", no_count)
|
188 |
+
print("Accuracy:", accuracy)
|
189 |
+
print("Average score:", average_score)
|
190 |
+
|
191 |
+
|
192 |
+
if __name__ == "__main__":
|
193 |
+
parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
|
194 |
+
parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
|
195 |
+
parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
|
196 |
+
parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
|
197 |
+
parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
|
198 |
+
parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
|
199 |
+
parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
|
200 |
+
parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
|
201 |
+
args = parser.parse_args()
|
202 |
+
|
203 |
+
# Set the OpenAI API key.
|
204 |
+
os.environ["AZURE_OPENAI_KEY"] = args.api_key
|
205 |
+
os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
|
206 |
+
os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
|
207 |
+
|
208 |
+
client = init()
|
209 |
+
|
210 |
+
main(args)
|
VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_1_correctness.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import argparse
|
3 |
+
import json
|
4 |
+
import ast
|
5 |
+
import traceback
|
6 |
+
from tqdm import tqdm
|
7 |
+
from multiprocessing.pool import Pool
|
8 |
+
|
9 |
+
from openai import AzureOpenAI
|
10 |
+
|
11 |
+
|
12 |
+
def init():
|
13 |
+
client = AzureOpenAI(
|
14 |
+
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
|
15 |
+
api_key=os.getenv("AZURE_OPENAI_KEY"),
|
16 |
+
api_version="2024-02-15-preview"
|
17 |
+
)
|
18 |
+
|
19 |
+
return client
|
20 |
+
|
21 |
+
|
22 |
+
def interaction(client, message_text):
|
23 |
+
completion = client.chat.completions.create(
|
24 |
+
model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
|
25 |
+
messages = message_text,
|
26 |
+
temperature=0.7,
|
27 |
+
max_tokens=800,
|
28 |
+
top_p=0.95,
|
29 |
+
frequency_penalty=0,
|
30 |
+
presence_penalty=0,
|
31 |
+
stop=None
|
32 |
+
)
|
33 |
+
|
34 |
+
return completion
|
35 |
+
|
36 |
+
|
37 |
+
def annotate(prediction_set, caption_files, output_dir, args):
|
38 |
+
"""
|
39 |
+
Evaluates question and answer pairs using GPT-3
|
40 |
+
Returns a score for correctness.
|
41 |
+
"""
|
42 |
+
|
43 |
+
for file in tqdm(caption_files):
|
44 |
+
key = file[:-5] # Strip file extension
|
45 |
+
qa_set = prediction_set[key]
|
46 |
+
question = qa_set['q']
|
47 |
+
answer = qa_set['a']
|
48 |
+
pred = qa_set['p']
|
49 |
+
try:
|
50 |
+
message = [
|
51 |
+
{
|
52 |
+
"role": "system",
|
53 |
+
"content":
|
54 |
+
"You are an intelligent chatbot designed for evaluating the factual accuracy of generative outputs for video-based question-answer pairs. "
|
55 |
+
"Your task is to compare the predicted answer with the correct answer and determine if they are factually consistent. Here's how you can accomplish the task:"
|
56 |
+
"------"
|
57 |
+
"##INSTRUCTIONS: "
|
58 |
+
"- Focus on the factual consistency between the predicted answer and the correct answer. The predicted answer should not contain any misinterpretations or misinformation.\n"
|
59 |
+
"- The predicted answer must be factually accurate and align with the video content.\n"
|
60 |
+
"- Consider synonyms or paraphrases as valid matches.\n"
|
61 |
+
"- Evaluate the factual accuracy of the prediction compared to the answer."
|
62 |
+
},
|
63 |
+
{
|
64 |
+
"role": "user",
|
65 |
+
"content":
|
66 |
+
"Please evaluate the following video-based question-answer pair:\n\n"
|
67 |
+
f"Question: {question}\n"
|
68 |
+
f"Correct Answer: {answer}\n"
|
69 |
+
f"Predicted Answer: {pred}\n\n"
|
70 |
+
"Provide your evaluation only as a factual accuracy score where the factual accuracy score is an integer value between 0 and 5, with 5 indicating the highest level of factual consistency. "
|
71 |
+
"Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the factual accuracy score in INTEGER, not STRING."
|
72 |
+
"DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
|
73 |
+
"For example, your response should look like this: {''score': 4.8}."
|
74 |
+
}
|
75 |
+
]
|
76 |
+
completion = interaction(client, message)
|
77 |
+
# Convert response to a Python dictionary.
|
78 |
+
response_message = completion.choices[0].message.content
|
79 |
+
response_dict = ast.literal_eval(response_message)
|
80 |
+
result_qa_pair = [response_dict, qa_set]
|
81 |
+
|
82 |
+
# Save the question-answer pairs to a json file.
|
83 |
+
with open(f"{output_dir}/{key}.json", "w") as f:
|
84 |
+
json.dump(result_qa_pair, f)
|
85 |
+
|
86 |
+
except Exception as e:
|
87 |
+
print(f"Error processing file '{key}': {e}")
|
88 |
+
|
89 |
+
|
90 |
+
def main(args):
|
91 |
+
pred_contents = [eval(line) for line in open(args.pred_path, 'r').readlines()]
|
92 |
+
|
93 |
+
# Dictionary to store the count of occurrences for each video_id
|
94 |
+
video_id_counts = {}
|
95 |
+
new_pred_contents = []
|
96 |
+
|
97 |
+
# Iterate through each sample in pred_contents
|
98 |
+
for sample in pred_contents:
|
99 |
+
video_id = sample['video_name']
|
100 |
+
if video_id in video_id_counts:
|
101 |
+
video_id_counts[video_id] += 1
|
102 |
+
else:
|
103 |
+
video_id_counts[video_id] = 0
|
104 |
+
|
105 |
+
# Create a new sample with the modified key
|
106 |
+
new_sample = sample
|
107 |
+
new_sample['video_name'] = f"{video_id}_{video_id_counts[video_id]}"
|
108 |
+
new_pred_contents.append(new_sample)
|
109 |
+
|
110 |
+
# Generating list of id's and corresponding files
|
111 |
+
id_list = [x['video_name'] for x in new_pred_contents]
|
112 |
+
caption_files = [f"{id}.json" for id in id_list]
|
113 |
+
|
114 |
+
output_dir = args.output_dir
|
115 |
+
# Generate output directory if not exists.
|
116 |
+
if not os.path.exists(output_dir):
|
117 |
+
os.makedirs(output_dir)
|
118 |
+
|
119 |
+
# Preparing dictionary of question-answer sets
|
120 |
+
prediction_set = {}
|
121 |
+
for sample in new_pred_contents:
|
122 |
+
id = sample['video_name']
|
123 |
+
question = sample['Q']
|
124 |
+
answer = sample['A']
|
125 |
+
pred = sample['P']
|
126 |
+
qa_set = {"q": question, "a": answer, "p": pred}
|
127 |
+
prediction_set[id] = qa_set
|
128 |
+
|
129 |
+
# Set the OpenAI API key.
|
130 |
+
# openai.api_key = args.api_key
|
131 |
+
num_tasks = args.num_tasks
|
132 |
+
|
133 |
+
# While loop to ensure that all captions are processed.
|
134 |
+
while True:
|
135 |
+
try:
|
136 |
+
# Files that have not been processed yet.
|
137 |
+
completed_files = os.listdir(output_dir)
|
138 |
+
print(f"completed_files: {len(completed_files)}")
|
139 |
+
|
140 |
+
# Files that have not been processed yet.
|
141 |
+
incomplete_files = [f for f in caption_files if f not in completed_files]
|
142 |
+
print(f"incomplete_files: {len(incomplete_files)}")
|
143 |
+
|
144 |
+
# Break the loop when there are no incomplete files
|
145 |
+
if len(incomplete_files) == 0:
|
146 |
+
break
|
147 |
+
if len(incomplete_files) <= num_tasks:
|
148 |
+
num_tasks = 1
|
149 |
+
|
150 |
+
# Split tasks into parts.
|
151 |
+
part_len = len(incomplete_files) // num_tasks
|
152 |
+
all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
|
153 |
+
task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
|
154 |
+
|
155 |
+
# Use a pool of workers to process the files in parallel.
|
156 |
+
with Pool() as pool:
|
157 |
+
pool.starmap(annotate, task_args)
|
158 |
+
|
159 |
+
except Exception as e:
|
160 |
+
traceback.print_exc()
|
161 |
+
|
162 |
+
# Combine all the processed files into one
|
163 |
+
combined_contents = {}
|
164 |
+
json_path = args.output_json
|
165 |
+
|
166 |
+
# Iterate through json files
|
167 |
+
for file_name in tqdm(os.listdir(output_dir)):
|
168 |
+
if file_name.endswith(".json"):
|
169 |
+
file_path = os.path.join(output_dir, file_name)
|
170 |
+
with open(file_path, "r") as json_file:
|
171 |
+
content = json.load(json_file)
|
172 |
+
combined_contents[file_name[:-5]] = content
|
173 |
+
|
174 |
+
# Write combined content to a json file
|
175 |
+
with open(json_path, "w") as json_file:
|
176 |
+
json.dump(combined_contents, json_file)
|
177 |
+
print("All evaluation completed!")
|
178 |
+
|
179 |
+
# Calculate average score
|
180 |
+
score_sum = 0
|
181 |
+
count = 0
|
182 |
+
for key, result in combined_contents.items():
|
183 |
+
count += 1
|
184 |
+
score_match = result[0]['score']
|
185 |
+
score = int(score_match)
|
186 |
+
score_sum += score
|
187 |
+
average_score = score_sum / count
|
188 |
+
|
189 |
+
print("Average score for correctness:", average_score)
|
190 |
+
|
191 |
+
|
192 |
+
if __name__ == "__main__":
|
193 |
+
parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
|
194 |
+
parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
|
195 |
+
parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
|
196 |
+
parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
|
197 |
+
parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
|
198 |
+
parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
|
199 |
+
parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
|
200 |
+
parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
|
201 |
+
args = parser.parse_args()
|
202 |
+
|
203 |
+
# Set the OpenAI API key.
|
204 |
+
os.environ["AZURE_OPENAI_KEY"] = args.api_key
|
205 |
+
os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
|
206 |
+
os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
|
207 |
+
|
208 |
+
client = init()
|
209 |
+
|
210 |
+
main(args)
|
VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_2_detailed_orientation.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import argparse
|
3 |
+
import json
|
4 |
+
import ast
|
5 |
+
from tqdm import tqdm
|
6 |
+
from multiprocessing.pool import Pool
|
7 |
+
|
8 |
+
from openai import AzureOpenAI
|
9 |
+
|
10 |
+
|
11 |
+
def init():
|
12 |
+
client = AzureOpenAI(
|
13 |
+
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
|
14 |
+
api_key=os.getenv("AZURE_OPENAI_KEY"),
|
15 |
+
api_version="2024-02-15-preview"
|
16 |
+
)
|
17 |
+
|
18 |
+
return client
|
19 |
+
|
20 |
+
|
21 |
+
def interaction(client, message_text):
|
22 |
+
completion = client.chat.completions.create(
|
23 |
+
model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
|
24 |
+
messages = message_text,
|
25 |
+
temperature=0.7,
|
26 |
+
max_tokens=800,
|
27 |
+
top_p=0.95,
|
28 |
+
frequency_penalty=0,
|
29 |
+
presence_penalty=0,
|
30 |
+
stop=None
|
31 |
+
)
|
32 |
+
|
33 |
+
return completion
|
34 |
+
|
35 |
+
|
36 |
+
def annotate(prediction_set, caption_files, output_dir, args):
|
37 |
+
"""
|
38 |
+
Evaluates question and answer pairs using GPT-3 and
|
39 |
+
returns a score for detailed orientation.
|
40 |
+
"""
|
41 |
+
for file in tqdm(caption_files):
|
42 |
+
key = file[:-5] # Strip file extension
|
43 |
+
qa_set = prediction_set[key]
|
44 |
+
question = qa_set['q']
|
45 |
+
answer = qa_set['a']
|
46 |
+
pred = qa_set['p']
|
47 |
+
try:
|
48 |
+
# Compute the detailed-orientation score
|
49 |
+
message = [
|
50 |
+
{
|
51 |
+
"role": "system",
|
52 |
+
"content":
|
53 |
+
"You are an intelligent chatbot designed for evaluating the detail orientation of generative outputs for video-based question-answer pairs. "
|
54 |
+
"Your task is to compare the predicted answer with the correct answer and determine its level of detail, considering both completeness and specificity. Here's how you can accomplish the task:"
|
55 |
+
"------"
|
56 |
+
"##INSTRUCTIONS: "
|
57 |
+
"- Check if the predicted answer covers all major points from the video. The response should not leave out any key aspects.\n"
|
58 |
+
"- Evaluate whether the predicted answer includes specific details rather than just generic points. It should provide comprehensive information that is tied to specific elements of the video.\n"
|
59 |
+
"- Consider synonyms or paraphrases as valid matches.\n"
|
60 |
+
"- Provide a single evaluation score that reflects the level of detail orientation of the prediction, considering both completeness and specificity."
|
61 |
+
},
|
62 |
+
{
|
63 |
+
"role": "user",
|
64 |
+
"content":
|
65 |
+
"Please evaluate the following video-based question-answer pair:\n\n"
|
66 |
+
f"Question: {question}\n"
|
67 |
+
f"Correct Answer: {answer}\n"
|
68 |
+
f"Predicted Answer: {pred}\n\n"
|
69 |
+
"Provide your evaluation only as a detail orientation score where the detail orientation score is an integer value between 0 and 5, with 5 indicating the highest level of detail orientation. "
|
70 |
+
"Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the detail orientation score in INTEGER, not STRING."
|
71 |
+
"DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
|
72 |
+
"For example, your response should look like this: {''score': 4.8}."
|
73 |
+
}
|
74 |
+
]
|
75 |
+
|
76 |
+
completion = interaction(client, message)
|
77 |
+
# Convert response to a Python dictionary.
|
78 |
+
response_message = completion.choices[0].message.content
|
79 |
+
response_dict = ast.literal_eval(response_message)
|
80 |
+
result_qa_pair = [response_dict, qa_set]
|
81 |
+
|
82 |
+
# Save the question-answer pairs to a json file.
|
83 |
+
with open(f"{output_dir}/{key}.json", "w") as f:
|
84 |
+
json.dump(result_qa_pair, f)
|
85 |
+
|
86 |
+
except Exception as e:
|
87 |
+
print(f"Error processing file '{key}': {e}")
|
88 |
+
|
89 |
+
|
90 |
+
def main(args):
|
91 |
+
pred_contents = [eval(line) for line in open(args.pred_path, 'r').readlines()]
|
92 |
+
|
93 |
+
# Dictionary to store the count of occurrences for each video_id
|
94 |
+
video_id_counts = {}
|
95 |
+
new_pred_contents = []
|
96 |
+
|
97 |
+
# Iterate through each sample in pred_contents
|
98 |
+
for sample in pred_contents:
|
99 |
+
video_id = sample['video_name']
|
100 |
+
if video_id in video_id_counts:
|
101 |
+
video_id_counts[video_id] += 1
|
102 |
+
else:
|
103 |
+
video_id_counts[video_id] = 0
|
104 |
+
|
105 |
+
# Create a new sample with the modified key
|
106 |
+
new_sample = sample
|
107 |
+
new_sample['video_name'] = f"{video_id}_{video_id_counts[video_id]}"
|
108 |
+
new_pred_contents.append(new_sample)
|
109 |
+
|
110 |
+
# Generating list of id's and corresponding files
|
111 |
+
id_list = [x['video_name'] for x in new_pred_contents]
|
112 |
+
caption_files = [f"{id}.json" for id in id_list]
|
113 |
+
|
114 |
+
output_dir = args.output_dir
|
115 |
+
# Generate output directory if not exists.
|
116 |
+
if not os.path.exists(output_dir):
|
117 |
+
os.makedirs(output_dir)
|
118 |
+
|
119 |
+
# Preparing dictionary of question-answer sets
|
120 |
+
prediction_set = {}
|
121 |
+
for sample in new_pred_contents:
|
122 |
+
id = sample['video_name']
|
123 |
+
question = sample['Q']
|
124 |
+
answer = sample['A']
|
125 |
+
pred = sample['P']
|
126 |
+
qa_set = {"q": question, "a": answer, "p": pred}
|
127 |
+
prediction_set[id] = qa_set
|
128 |
+
|
129 |
+
# Set the OpenAI API key.
|
130 |
+
# openai.api_key = args.api_key
|
131 |
+
num_tasks = args.num_tasks
|
132 |
+
|
133 |
+
# While loop to ensure that all captions are processed.
|
134 |
+
while True:
|
135 |
+
try:
|
136 |
+
# Files that have not been processed yet.
|
137 |
+
completed_files = os.listdir(output_dir)
|
138 |
+
print(f"completed_files: {len(completed_files)}")
|
139 |
+
|
140 |
+
# Files that have not been processed yet.
|
141 |
+
incomplete_files = [f for f in caption_files if f not in completed_files]
|
142 |
+
print(f"incomplete_files: {len(incomplete_files)}")
|
143 |
+
|
144 |
+
# Break the loop when there are no incomplete files
|
145 |
+
if len(incomplete_files) == 0:
|
146 |
+
break
|
147 |
+
if len(incomplete_files) <= num_tasks:
|
148 |
+
num_tasks = 1
|
149 |
+
|
150 |
+
# Split tasks into parts.
|
151 |
+
part_len = len(incomplete_files) // num_tasks
|
152 |
+
all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
|
153 |
+
task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
|
154 |
+
|
155 |
+
# Use a pool of workers to process the files in parallel.
|
156 |
+
with Pool() as pool:
|
157 |
+
pool.starmap(annotate, task_args)
|
158 |
+
|
159 |
+
except Exception as e:
|
160 |
+
print(f"Error: {e}")
|
161 |
+
|
162 |
+
# Combine all the processed files into one
|
163 |
+
combined_contents = {}
|
164 |
+
json_path = args.output_json
|
165 |
+
|
166 |
+
# Iterate through json files
|
167 |
+
for file_name in tqdm(os.listdir(output_dir)):
|
168 |
+
if file_name.endswith(".json"):
|
169 |
+
file_path = os.path.join(output_dir, file_name)
|
170 |
+
with open(file_path, "r") as json_file:
|
171 |
+
content = json.load(json_file)
|
172 |
+
combined_contents[file_name[:-5]] = content
|
173 |
+
|
174 |
+
# Write combined content to a json file
|
175 |
+
with open(json_path, "w") as json_file:
|
176 |
+
json.dump(combined_contents, json_file)
|
177 |
+
print("All evaluation completed!")
|
178 |
+
|
179 |
+
# Calculate average score
|
180 |
+
score_sum = 0
|
181 |
+
count = 0
|
182 |
+
for key, result in combined_contents.items():
|
183 |
+
count += 1
|
184 |
+
score_match = result[0]['score']
|
185 |
+
score = int(score_match)
|
186 |
+
score_sum += score
|
187 |
+
average_score = score_sum / count
|
188 |
+
|
189 |
+
print("Average score for detailed orientation:", average_score)
|
190 |
+
|
191 |
+
|
192 |
+
if __name__ == "__main__":
|
193 |
+
parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
|
194 |
+
parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
|
195 |
+
parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
|
196 |
+
parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
|
197 |
+
parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
|
198 |
+
parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
|
199 |
+
parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
|
200 |
+
parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
|
201 |
+
args = parser.parse_args()
|
202 |
+
|
203 |
+
# Set the OpenAI API key.
|
204 |
+
os.environ["AZURE_OPENAI_KEY"] = args.api_key
|
205 |
+
os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
|
206 |
+
os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
|
207 |
+
|
208 |
+
client = init()
|
209 |
+
|
210 |
+
main(args)
|
VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_3_context.py
ADDED
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import argparse
|
3 |
+
import json
|
4 |
+
import ast
|
5 |
+
import traceback
|
6 |
+
from tqdm import tqdm
|
7 |
+
from multiprocessing.pool import Pool
|
8 |
+
|
9 |
+
from openai import AzureOpenAI
|
10 |
+
|
11 |
+
|
12 |
+
def init():
|
13 |
+
client = AzureOpenAI(
|
14 |
+
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
|
15 |
+
api_key=os.getenv("AZURE_OPENAI_KEY"),
|
16 |
+
api_version="2024-02-15-preview"
|
17 |
+
)
|
18 |
+
|
19 |
+
return client
|
20 |
+
|
21 |
+
|
22 |
+
def interaction(client, message_text):
|
23 |
+
completion = client.chat.completions.create(
|
24 |
+
model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
|
25 |
+
messages = message_text,
|
26 |
+
temperature=0.7,
|
27 |
+
max_tokens=800,
|
28 |
+
top_p=0.95,
|
29 |
+
frequency_penalty=0,
|
30 |
+
presence_penalty=0,
|
31 |
+
stop=None
|
32 |
+
)
|
33 |
+
|
34 |
+
return completion
|
35 |
+
|
36 |
+
|
37 |
+
def annotate(prediction_set, caption_files, output_dir, args):
|
38 |
+
"""
|
39 |
+
Evaluates question and answer pairs using GPT-3 and
|
40 |
+
returns a score for contextual understanding.
|
41 |
+
"""
|
42 |
+
|
43 |
+
for file in tqdm(caption_files):
|
44 |
+
key = file[:-5] # Strip file extension
|
45 |
+
qa_set = prediction_set[key]
|
46 |
+
question = qa_set['q']
|
47 |
+
answer = qa_set['a']
|
48 |
+
pred = qa_set['p']
|
49 |
+
try:
|
50 |
+
# Compute the contextual understanding score
|
51 |
+
message = [
|
52 |
+
{
|
53 |
+
"role": "system",
|
54 |
+
"content":
|
55 |
+
"You are an intelligent chatbot designed for evaluating the contextual understanding of generative outputs for video-based question-answer pairs. "
|
56 |
+
"Your task is to compare the predicted answer with the correct answer and determine if the generated response aligns with the overall context of the video content. Here's how you can accomplish the task:"
|
57 |
+
"------"
|
58 |
+
"##INSTRUCTIONS: "
|
59 |
+
"- Evaluate whether the predicted answer aligns with the overall context of the video content. It should not provide information that is out of context or misaligned.\n"
|
60 |
+
"- The predicted answer must capture the main themes and sentiments of the video.\n"
|
61 |
+
"- Consider synonyms or paraphrases as valid matches.\n"
|
62 |
+
"- Provide your evaluation of the contextual understanding of the prediction compared to the answer."
|
63 |
+
},
|
64 |
+
{
|
65 |
+
"role": "user",
|
66 |
+
"content":
|
67 |
+
"Please evaluate the following video-based question-answer pair:\n\n"
|
68 |
+
f"Question: {question}\n"
|
69 |
+
f"Correct Answer: {answer}\n"
|
70 |
+
f"Predicted Answer: {pred}\n\n"
|
71 |
+
"Provide your evaluation only as a contextual understanding score where the contextual understanding score is an integer value between 0 and 5, with 5 indicating the highest level of contextual understanding. "
|
72 |
+
"Please generate the response in the form of a Python dictionary string with keys 'score', where its value is contextual understanding score in INTEGER, not STRING."
|
73 |
+
"DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
|
74 |
+
"For example, your response should look like this: {''score': 4.8}."
|
75 |
+
}
|
76 |
+
]
|
77 |
+
|
78 |
+
completion = interaction(client, message)
|
79 |
+
# Convert response to a Python dictionary.
|
80 |
+
response_message = completion.choices[0].message.content
|
81 |
+
response_dict = ast.literal_eval(response_message)
|
82 |
+
result_qa_pair = [response_dict, qa_set]
|
83 |
+
|
84 |
+
# Save the question-answer pairs to a json file.
|
85 |
+
with open(f"{output_dir}/{key}.json", "w") as f:
|
86 |
+
json.dump(result_qa_pair, f)
|
87 |
+
|
88 |
+
except Exception as e:
|
89 |
+
print(f"Error processing file '{key}': {e}")
|
90 |
+
|
91 |
+
|
92 |
+
def main(args):
|
93 |
+
pred_contents = [eval(line) for line in open(args.pred_path, 'r').readlines()]
|
94 |
+
|
95 |
+
# Dictionary to store the count of occurrences for each video_id
|
96 |
+
video_id_counts = {}
|
97 |
+
new_pred_contents = []
|
98 |
+
|
99 |
+
# Iterate through each sample in pred_contents
|
100 |
+
for sample in pred_contents:
|
101 |
+
video_id = sample['video_name']
|
102 |
+
if video_id in video_id_counts:
|
103 |
+
video_id_counts[video_id] += 1
|
104 |
+
else:
|
105 |
+
video_id_counts[video_id] = 0
|
106 |
+
|
107 |
+
# Create a new sample with the modified key
|
108 |
+
new_sample = sample
|
109 |
+
new_sample['video_name'] = f"{video_id}_{video_id_counts[video_id]}"
|
110 |
+
new_pred_contents.append(new_sample)
|
111 |
+
|
112 |
+
# Generating list of id's and corresponding files
|
113 |
+
id_list = [x['video_name'] for x in new_pred_contents]
|
114 |
+
caption_files = [f"{id}.json" for id in id_list]
|
115 |
+
|
116 |
+
output_dir = args.output_dir
|
117 |
+
# Generate output directory if not exists.
|
118 |
+
if not os.path.exists(output_dir):
|
119 |
+
os.makedirs(output_dir)
|
120 |
+
|
121 |
+
# Preparing dictionary of question-answer sets
|
122 |
+
prediction_set = {}
|
123 |
+
for sample in new_pred_contents:
|
124 |
+
id = sample['video_name']
|
125 |
+
question = sample['Q']
|
126 |
+
answer = sample['A']
|
127 |
+
pred = sample['P']
|
128 |
+
qa_set = {"q": question, "a": answer, "p": pred}
|
129 |
+
prediction_set[id] = qa_set
|
130 |
+
|
131 |
+
# Set the OpenAI API key.
|
132 |
+
# openai.api_key = args.api_key
|
133 |
+
num_tasks = args.num_tasks
|
134 |
+
|
135 |
+
# While loop to ensure that all captions are processed.
|
136 |
+
while True:
|
137 |
+
try:
|
138 |
+
# Files that have not been processed yet.
|
139 |
+
completed_files = os.listdir(output_dir)
|
140 |
+
print(f"completed_files: {len(completed_files)}")
|
141 |
+
|
142 |
+
# Files that have not been processed yet.
|
143 |
+
incomplete_files = [f for f in caption_files if f not in completed_files]
|
144 |
+
print(f"incomplete_files: {len(incomplete_files)}")
|
145 |
+
|
146 |
+
# Break the loop when there are no incomplete files
|
147 |
+
if len(incomplete_files) == 0:
|
148 |
+
break
|
149 |
+
if len(incomplete_files) <= num_tasks:
|
150 |
+
num_tasks = 1
|
151 |
+
|
152 |
+
# Split tasks into parts.
|
153 |
+
part_len = len(incomplete_files) // num_tasks
|
154 |
+
all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
|
155 |
+
task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
|
156 |
+
|
157 |
+
# Use a pool of workers to process the files in parallel.
|
158 |
+
with Pool() as pool:
|
159 |
+
pool.starmap(annotate, task_args)
|
160 |
+
|
161 |
+
except Exception as e:
|
162 |
+
print(f"Error: {e}")
|
163 |
+
|
164 |
+
# Combine all the processed files into one
|
165 |
+
combined_contents = {}
|
166 |
+
json_path = args.output_json
|
167 |
+
|
168 |
+
# Iterate through json files
|
169 |
+
for file_name in tqdm(os.listdir(output_dir)):
|
170 |
+
if file_name.endswith(".json"):
|
171 |
+
file_path = os.path.join(output_dir, file_name)
|
172 |
+
with open(file_path, "r") as json_file:
|
173 |
+
content = json.load(json_file)
|
174 |
+
combined_contents[file_name[:-5]] = content
|
175 |
+
|
176 |
+
# Write combined content to a json file
|
177 |
+
with open(json_path, "w") as json_file:
|
178 |
+
json.dump(combined_contents, json_file)
|
179 |
+
print("All evaluation completed!")
|
180 |
+
|
181 |
+
# Calculate average score
|
182 |
+
score_sum = 0
|
183 |
+
count = 0
|
184 |
+
for key, result in combined_contents.items():
|
185 |
+
count += 1
|
186 |
+
score_match = result[0]['score']
|
187 |
+
score = int(score_match)
|
188 |
+
score_sum += score
|
189 |
+
average_score = score_sum / count
|
190 |
+
|
191 |
+
print("Average score for contextual understanding:", average_score)
|
192 |
+
|
193 |
+
|
194 |
+
if __name__ == "__main__":
|
195 |
+
parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
|
196 |
+
parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
|
197 |
+
parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
|
198 |
+
parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
|
199 |
+
parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
|
200 |
+
parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
|
201 |
+
parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
|
202 |
+
parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
|
203 |
+
args = parser.parse_args()
|
204 |
+
|
205 |
+
# Set the OpenAI API key.
|
206 |
+
os.environ["AZURE_OPENAI_KEY"] = args.api_key
|
207 |
+
os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
|
208 |
+
os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
|
209 |
+
|
210 |
+
client = init()
|
211 |
+
|
212 |
+
main(args)
|
VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_4_temporal.py
ADDED
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import argparse
|
3 |
+
import json
|
4 |
+
import ast
|
5 |
+
import traceback
|
6 |
+
from tqdm import tqdm
|
7 |
+
from multiprocessing.pool import Pool
|
8 |
+
|
9 |
+
from openai import AzureOpenAI
|
10 |
+
|
11 |
+
|
12 |
+
def init():
|
13 |
+
client = AzureOpenAI(
|
14 |
+
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
|
15 |
+
api_key=os.getenv("AZURE_OPENAI_KEY"),
|
16 |
+
api_version="2024-02-15-preview"
|
17 |
+
)
|
18 |
+
|
19 |
+
return client
|
20 |
+
|
21 |
+
|
22 |
+
def interaction(client, message_text):
|
23 |
+
completion = client.chat.completions.create(
|
24 |
+
model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
|
25 |
+
messages = message_text,
|
26 |
+
temperature=0.7,
|
27 |
+
max_tokens=800,
|
28 |
+
top_p=0.95,
|
29 |
+
frequency_penalty=0,
|
30 |
+
presence_penalty=0,
|
31 |
+
stop=None
|
32 |
+
)
|
33 |
+
|
34 |
+
return completion
|
35 |
+
|
36 |
+
|
37 |
+
def annotate(prediction_set, caption_files, output_dir, args):
|
38 |
+
|
39 |
+
for file in tqdm(caption_files):
|
40 |
+
key = file[:-5] # Strip file extension
|
41 |
+
qa_set = prediction_set[key]
|
42 |
+
question = qa_set['q']
|
43 |
+
answer = qa_set['a']
|
44 |
+
pred = qa_set['p']
|
45 |
+
try:
|
46 |
+
message = [
|
47 |
+
{
|
48 |
+
"role": "system",
|
49 |
+
"content":
|
50 |
+
"You are an intelligent chatbot designed for evaluating the temporal understanding of generative outputs for video-based question-answer pairs. "
|
51 |
+
"Your task is to compare the predicted answer with the correct answer and determine if they correctly reflect the temporal sequence of events in the video content. Here's how you can accomplish the task:"
|
52 |
+
"------"
|
53 |
+
"##INSTRUCTIONS: "
|
54 |
+
"- Focus on the temporal consistency between the predicted answer and the correct answer. The predicted answer should correctly reflect the sequence of events or details as they are presented in the video content.\n"
|
55 |
+
"- Consider synonyms or paraphrases as valid matches, but only if the temporal order is maintained.\n"
|
56 |
+
"- Evaluate the temporal accuracy of the prediction compared to the answer."
|
57 |
+
},
|
58 |
+
{
|
59 |
+
"role": "user",
|
60 |
+
"content":
|
61 |
+
"Please evaluate the following video-based question-answer pair:\n\n"
|
62 |
+
f"Question: {question}\n"
|
63 |
+
f"Correct Answer: {answer}\n"
|
64 |
+
f"Predicted Answer: {pred}\n\n"
|
65 |
+
"Provide your evaluation only as a temporal accuracy score where the temporal accuracy score is an integer value between 0 and 5, with 5 indicating the highest level of temporal consistency. "
|
66 |
+
"Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the temporal accuracy score in INTEGER, not STRING."
|
67 |
+
"DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
|
68 |
+
"For example, your response should look like this: {''score': 4.8}."
|
69 |
+
}
|
70 |
+
]
|
71 |
+
|
72 |
+
completion = interaction(client, message)
|
73 |
+
# Convert response to a Python dictionary.
|
74 |
+
response_message = completion.choices[0].message.content
|
75 |
+
response_dict = ast.literal_eval(response_message)
|
76 |
+
result_qa_pair = [response_dict, qa_set]
|
77 |
+
|
78 |
+
# Save the question-answer pairs to a json file.
|
79 |
+
with open(f"{output_dir}/{key}.json", "w") as f:
|
80 |
+
json.dump(result_qa_pair, f)
|
81 |
+
|
82 |
+
except Exception as e:
|
83 |
+
print(f"Error processing file '{key}': {e}")
|
84 |
+
|
85 |
+
|
86 |
+
def main(args):
|
87 |
+
pred_contents = [eval(line) for line in open(args.pred_path, 'r').readlines()]
|
88 |
+
|
89 |
+
# Dictionary to store the count of occurrences for each video_id
|
90 |
+
video_id_counts = {}
|
91 |
+
new_pred_contents = []
|
92 |
+
|
93 |
+
# Iterate through each sample in pred_contents
|
94 |
+
for sample in pred_contents:
|
95 |
+
video_id = sample['video_name']
|
96 |
+
if video_id in video_id_counts:
|
97 |
+
video_id_counts[video_id] += 1
|
98 |
+
else:
|
99 |
+
video_id_counts[video_id] = 0
|
100 |
+
|
101 |
+
# Create a new sample with the modified key
|
102 |
+
new_sample = sample
|
103 |
+
new_sample['video_name'] = f"{video_id}_{video_id_counts[video_id]}"
|
104 |
+
new_pred_contents.append(new_sample)
|
105 |
+
|
106 |
+
# Generating list of id's and corresponding files
|
107 |
+
id_list = [x['video_name'] for x in new_pred_contents]
|
108 |
+
caption_files = [f"{id}.json" for id in id_list]
|
109 |
+
|
110 |
+
output_dir = args.output_dir
|
111 |
+
# Generate output directory if not exists.
|
112 |
+
if not os.path.exists(output_dir):
|
113 |
+
os.makedirs(output_dir)
|
114 |
+
|
115 |
+
# Preparing dictionary of question-answer sets
|
116 |
+
prediction_set = {}
|
117 |
+
for sample in new_pred_contents:
|
118 |
+
id = sample['video_name']
|
119 |
+
question = sample['Q']
|
120 |
+
answer = sample['A']
|
121 |
+
pred = sample['P']
|
122 |
+
qa_set = {"q": question, "a": answer, "p": pred}
|
123 |
+
prediction_set[id] = qa_set
|
124 |
+
|
125 |
+
# Set the OpenAI API key.
|
126 |
+
# openai.api_key = args.api_key
|
127 |
+
num_tasks = args.num_tasks
|
128 |
+
|
129 |
+
# While loop to ensure that all captions are processed.
|
130 |
+
while True:
|
131 |
+
try:
|
132 |
+
# Files that have not been processed yet.
|
133 |
+
completed_files = os.listdir(output_dir)
|
134 |
+
print(f"completed_files: {len(completed_files)}")
|
135 |
+
|
136 |
+
# Files that have not been processed yet.
|
137 |
+
incomplete_files = [f for f in caption_files if f not in completed_files]
|
138 |
+
print(f"incomplete_files: {len(incomplete_files)}")
|
139 |
+
|
140 |
+
# Break the loop when there are no incomplete files
|
141 |
+
if len(incomplete_files) == 0:
|
142 |
+
break
|
143 |
+
if len(incomplete_files) <= num_tasks:
|
144 |
+
num_tasks = 1
|
145 |
+
|
146 |
+
# Split tasks into parts.
|
147 |
+
part_len = len(incomplete_files) // num_tasks
|
148 |
+
all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
|
149 |
+
task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
|
150 |
+
|
151 |
+
# Use a pool of workers to process the files in parallel.
|
152 |
+
with Pool() as pool:
|
153 |
+
pool.starmap(annotate, task_args)
|
154 |
+
|
155 |
+
except Exception as e:
|
156 |
+
print(f"Error: {e}")
|
157 |
+
|
158 |
+
# Combine all the processed files into one
|
159 |
+
combined_contents = {}
|
160 |
+
json_path = args.output_json
|
161 |
+
|
162 |
+
# Iterate through json files
|
163 |
+
for file_name in os.listdir(output_dir):
|
164 |
+
if file_name.endswith(".json"):
|
165 |
+
file_path = os.path.join(output_dir, file_name)
|
166 |
+
with open(file_path, "r") as json_file:
|
167 |
+
content = json.load(json_file)
|
168 |
+
combined_contents[file_name[:-5]] = content
|
169 |
+
|
170 |
+
# Write combined content to a json file
|
171 |
+
with open(json_path, "w") as json_file:
|
172 |
+
json.dump(combined_contents, json_file)
|
173 |
+
print("All evaluation completed!")
|
174 |
+
|
175 |
+
# Calculate average score
|
176 |
+
score_sum = 0
|
177 |
+
count = 0
|
178 |
+
for key, result in combined_contents.items():
|
179 |
+
count += 1
|
180 |
+
score_match = result[0]['score']
|
181 |
+
score = int(score_match)
|
182 |
+
score_sum += score
|
183 |
+
average_score = score_sum / count
|
184 |
+
|
185 |
+
print("Average score temporal understanding:", average_score)
|
186 |
+
|
187 |
+
|
188 |
+
if __name__ == "__main__":
|
189 |
+
parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
|
190 |
+
parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
|
191 |
+
parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
|
192 |
+
parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
|
193 |
+
parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
|
194 |
+
parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
|
195 |
+
parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
|
196 |
+
parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
|
197 |
+
args = parser.parse_args()
|
198 |
+
|
199 |
+
# Set the OpenAI API key.
|
200 |
+
os.environ["AZURE_OPENAI_KEY"] = args.api_key
|
201 |
+
os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
|
202 |
+
os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
|
203 |
+
|
204 |
+
client = init()
|
205 |
+
|
206 |
+
main(args)
|
VideoLLaMA2/videollama2/eval/eval_video_oqa_vcgpt_5_consistency.py
ADDED
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import argparse
|
3 |
+
import json
|
4 |
+
import ast
|
5 |
+
import traceback
|
6 |
+
from tqdm import tqdm
|
7 |
+
from multiprocessing.pool import Pool
|
8 |
+
|
9 |
+
from openai import AzureOpenAI
|
10 |
+
|
11 |
+
|
12 |
+
def init():
|
13 |
+
client = AzureOpenAI(
|
14 |
+
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
|
15 |
+
api_key=os.getenv("AZURE_OPENAI_KEY"),
|
16 |
+
api_version="2024-02-15-preview"
|
17 |
+
)
|
18 |
+
|
19 |
+
return client
|
20 |
+
|
21 |
+
|
22 |
+
def interaction(client, message_text):
|
23 |
+
completion = client.chat.completions.create(
|
24 |
+
model=os.getenv("AZURE_OPENAI_DEPLOYNAME"),
|
25 |
+
messages = message_text,
|
26 |
+
temperature=0.7,
|
27 |
+
max_tokens=800,
|
28 |
+
top_p=0.95,
|
29 |
+
frequency_penalty=0,
|
30 |
+
presence_penalty=0,
|
31 |
+
stop=None
|
32 |
+
)
|
33 |
+
|
34 |
+
return completion
|
35 |
+
|
36 |
+
|
37 |
+
def annotate(prediction_set, caption_files, output_dir, args):
|
38 |
+
"""
|
39 |
+
Evaluates question and answer pairs using GPT-3 and
|
40 |
+
returns a score for consistency.
|
41 |
+
"""
|
42 |
+
|
43 |
+
for file in tqdm(caption_files):
|
44 |
+
key = file[:-5] # Strip file extension
|
45 |
+
qa_set = prediction_set[key]
|
46 |
+
question1 = qa_set['q1']
|
47 |
+
question2 = qa_set['q2']
|
48 |
+
answer = qa_set['a']
|
49 |
+
pred1 = qa_set['p1']
|
50 |
+
pred2 = qa_set['p2']
|
51 |
+
try:
|
52 |
+
message = [
|
53 |
+
{
|
54 |
+
"role": "system",
|
55 |
+
"content":
|
56 |
+
"You are an intelligent chatbot designed for evaluating the consistency of generative outputs for similar video-based question-answer pairs. "
|
57 |
+
"You will be given two very similar questions, a common answer common to both the questions and predicted answers for the two questions ."
|
58 |
+
"Your task is to compare the predicted answers for two very similar question, with a common correct answer and determine if they are consistent. Here's how you can accomplish the task:"
|
59 |
+
"------"
|
60 |
+
"##INSTRUCTIONS: "
|
61 |
+
"- Focus on the consistency between the two predicted answers and the correct answer. Both predicted answers should correspond to the correct answer and to each other, and should not contain any contradictions or significant differences in the conveyed information.\n"
|
62 |
+
"- Both predicted answers must be consistent with each other and the correct answer, in terms of the information they provide about the video content.\n"
|
63 |
+
"- Consider synonyms or paraphrases as valid matches, but only if they maintain the consistency in the conveyed information.\n"
|
64 |
+
"- Evaluate the consistency of the two predicted answers compared to the correct answer."
|
65 |
+
},
|
66 |
+
{
|
67 |
+
"role": "user",
|
68 |
+
"content":
|
69 |
+
"Please evaluate the following video-based question-answer pair:\n\n"
|
70 |
+
f"Question 1: {question1}\n"
|
71 |
+
f"Question 2: {question2}\n"
|
72 |
+
f"Correct Answer: {answer}\n"
|
73 |
+
f"Predicted Answer to Question 1: {pred1}\n"
|
74 |
+
f"Predicted Answer to Question 2: {pred2}\n\n"
|
75 |
+
"Provide your evaluation only as a consistency score where the consistency score is an integer value between 0 and 5, with 5 indicating the highest level of consistency. "
|
76 |
+
"Please generate the response in the form of a Python dictionary string with keys 'score', where its value is the consistency score in INTEGER, not STRING."
|
77 |
+
"DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. "
|
78 |
+
"For example, your response should look like this: {''score': 4.8}."
|
79 |
+
}
|
80 |
+
]
|
81 |
+
|
82 |
+
completion = interaction(client, message)
|
83 |
+
# Convert response to a Python dictionary.
|
84 |
+
response_message = completion.choices[0].message.content
|
85 |
+
response_dict = ast.literal_eval(response_message)
|
86 |
+
result_qa_pair = [response_dict, qa_set]
|
87 |
+
|
88 |
+
# Save the question-answer pairs to a json file.
|
89 |
+
with open(f"{output_dir}/{key}.json", "w") as f:
|
90 |
+
json.dump(result_qa_pair, f)
|
91 |
+
|
92 |
+
except Exception as e:
|
93 |
+
print(f"Error processing file '{key}': {e}")
|
94 |
+
|
95 |
+
|
96 |
+
def main(args):
|
97 |
+
pred_contents = [eval(line) for line in open(args.pred_path, 'r').readlines()]
|
98 |
+
|
99 |
+
# Dictionary to store the count of occurrences for each video_id
|
100 |
+
video_id_counts = {}
|
101 |
+
new_pred_contents = []
|
102 |
+
|
103 |
+
# Iterate through each sample in pred_contents
|
104 |
+
for sample in pred_contents:
|
105 |
+
video_id = sample['video_name']
|
106 |
+
if video_id in video_id_counts:
|
107 |
+
video_id_counts[video_id] += 1
|
108 |
+
else:
|
109 |
+
video_id_counts[video_id] = 0
|
110 |
+
|
111 |
+
# Create a new sample with the modified key
|
112 |
+
new_sample = sample
|
113 |
+
new_sample['video_name'] = f"{video_id}_{video_id_counts[video_id]}"
|
114 |
+
new_pred_contents.append(new_sample)
|
115 |
+
|
116 |
+
# Generating list of id's and corresponding files
|
117 |
+
id_list = [x['video_name'] for x in new_pred_contents]
|
118 |
+
caption_files = [f"{id}.json" for id in id_list]
|
119 |
+
|
120 |
+
output_dir = args.output_dir
|
121 |
+
# Generate output directory if not exists.
|
122 |
+
if not os.path.exists(output_dir):
|
123 |
+
os.makedirs(output_dir)
|
124 |
+
|
125 |
+
# Preparing dictionary of question-answer sets
|
126 |
+
prediction_set = {}
|
127 |
+
for sample in new_pred_contents:
|
128 |
+
id = sample['video_name']
|
129 |
+
question1 = sample['Q1']
|
130 |
+
question2 = sample['Q2']
|
131 |
+
answer = sample['A']
|
132 |
+
pred1 = sample['P1']
|
133 |
+
pred2 = sample['P2']
|
134 |
+
qa_set = {"q1": question1, "q2": question2, "a": answer, "p1": pred1, "p2": pred2}
|
135 |
+
prediction_set[id] = qa_set
|
136 |
+
|
137 |
+
# Set the OpenAI API key.
|
138 |
+
# openai.api_key = args.api_key
|
139 |
+
num_tasks = args.num_tasks
|
140 |
+
|
141 |
+
# While loop to ensure that all captions are processed.
|
142 |
+
while True:
|
143 |
+
try:
|
144 |
+
# Files that have not been processed yet.
|
145 |
+
completed_files = os.listdir(output_dir)
|
146 |
+
print(f"completed_files: {len(completed_files)}")
|
147 |
+
|
148 |
+
# Files that have not been processed yet.
|
149 |
+
incomplete_files = [f for f in caption_files if f not in completed_files]
|
150 |
+
print(f"incomplete_files: {len(incomplete_files)}")
|
151 |
+
|
152 |
+
# Break the loop when there are no incomplete files
|
153 |
+
if len(incomplete_files) == 0:
|
154 |
+
break
|
155 |
+
if len(incomplete_files) <= num_tasks:
|
156 |
+
num_tasks = 1
|
157 |
+
|
158 |
+
# Split tasks into parts.
|
159 |
+
part_len = len(incomplete_files) // num_tasks
|
160 |
+
all_parts = [incomplete_files[i:i + part_len] for i in range(0, len(incomplete_files), part_len)]
|
161 |
+
task_args = [(prediction_set, part, args.output_dir, args) for part in all_parts]
|
162 |
+
|
163 |
+
# Use a pool of workers to process the files in parallel.
|
164 |
+
with Pool() as pool:
|
165 |
+
pool.starmap(annotate, task_args)
|
166 |
+
|
167 |
+
except Exception as e:
|
168 |
+
print(f"Error: {e}")
|
169 |
+
|
170 |
+
# Combine all the processed files into one
|
171 |
+
combined_contents = {}
|
172 |
+
json_path = args.output_json
|
173 |
+
|
174 |
+
# Iterate through json files
|
175 |
+
for file_name in os.listdir(output_dir):
|
176 |
+
if file_name.endswith(".json"):
|
177 |
+
file_path = os.path.join(output_dir, file_name)
|
178 |
+
with open(file_path, "r") as json_file:
|
179 |
+
content = json.load(json_file)
|
180 |
+
combined_contents[file_name[:-5]] = content
|
181 |
+
|
182 |
+
# Write combined content to a json file
|
183 |
+
with open(json_path, "w") as json_file:
|
184 |
+
json.dump(combined_contents, json_file)
|
185 |
+
print("All evaluation completed!")
|
186 |
+
|
187 |
+
# Calculate average score
|
188 |
+
score_sum = 0
|
189 |
+
count = 0
|
190 |
+
for key, result in combined_contents.items():
|
191 |
+
count += 1
|
192 |
+
score_match = result[0]['score']
|
193 |
+
score = int(score_match)
|
194 |
+
score_sum += score
|
195 |
+
average_score = score_sum / count
|
196 |
+
|
197 |
+
print("Average score for consistency:", average_score)
|
198 |
+
|
199 |
+
|
200 |
+
if __name__ == "__main__":
|
201 |
+
parser = argparse.ArgumentParser(description="question-answer-generation-using-gpt-3")
|
202 |
+
parser.add_argument("--pred-path", required=True, help="The path to file containing prediction.")
|
203 |
+
parser.add_argument("--output-dir", required=True, help="The path to save annotation json files.")
|
204 |
+
parser.add_argument("--output-json", required=True, help="The path to save annotation final combined json file.")
|
205 |
+
parser.add_argument("--num-tasks", required=True, type=int, help="Number of splits.")
|
206 |
+
parser.add_argument("--api-key", required=True, type=str, help="Azure Openai API key.")
|
207 |
+
parser.add_argument("--api-endpoint", required=True, type=str, help="Azure Openai API endpoint.")
|
208 |
+
parser.add_argument("--api-deployname", required=True, type=str, help="Azure Openai API deployname.")
|
209 |
+
args = parser.parse_args()
|
210 |
+
|
211 |
+
# Set the OpenAI API key.
|
212 |
+
os.environ["AZURE_OPENAI_KEY"] = args.api_key
|
213 |
+
os.environ["AZURE_OPENAI_ENDPOINT"] = args.api_endpoint
|
214 |
+
os.environ["AZURE_OPENAI_DEPLOYNAME"] = args.api_deployname
|
215 |
+
|
216 |
+
client = init()
|
217 |
+
|
218 |
+
main(args)
|
VideoLLaMA2/videollama2/eval/inference_video_cap_msvc.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import os
|
3 |
+
import argparse
|
4 |
+
import json
|
5 |
+
import warnings
|
6 |
+
from tqdm import tqdm
|
7 |
+
|
8 |
+
from torch.utils.data import Dataset, DataLoader
|
9 |
+
|
10 |
+
import sys
|
11 |
+
sys.path.append('./')
|
12 |
+
from videollama2 import model_init, mm_infer
|
13 |
+
from videollama2.utils import disable_torch_init
|
14 |
+
|
15 |
+
# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
|
16 |
+
warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
|
17 |
+
|
18 |
+
|
19 |
+
def split_list(lst, n):
|
20 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
21 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
22 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
23 |
+
|
24 |
+
|
25 |
+
def get_chunk(lst, n, k):
|
26 |
+
chunks = split_list(lst, n)
|
27 |
+
return chunks[k]
|
28 |
+
|
29 |
+
|
30 |
+
class MSVCDataset(Dataset):
|
31 |
+
|
32 |
+
video_formats = ['.mp4', '.webm', '.avi', '.mov', '.mkv']
|
33 |
+
|
34 |
+
def __init__(self, folder, questions, processor):
|
35 |
+
self.folder = folder
|
36 |
+
self.questions = questions
|
37 |
+
self.processor = processor
|
38 |
+
|
39 |
+
def __len__(self):
|
40 |
+
return len(self.questions)
|
41 |
+
|
42 |
+
def __getitem__(self, idx):
|
43 |
+
sample = self.questions[idx]
|
44 |
+
|
45 |
+
video_name = sample['video_path']
|
46 |
+
question = sample['question']
|
47 |
+
answer = sample['captions']
|
48 |
+
|
49 |
+
video_path = os.path.join(self.folder, video_name)
|
50 |
+
video_tensor = self.processor(video_path)
|
51 |
+
|
52 |
+
return {
|
53 |
+
'video': video_tensor,
|
54 |
+
'video_name': video_name,
|
55 |
+
'question': question,
|
56 |
+
'answer': answer,
|
57 |
+
}
|
58 |
+
|
59 |
+
|
60 |
+
def collate_fn(batch):
|
61 |
+
vid = [x['video'] for x in batch]
|
62 |
+
v_id = [x['video_name'] for x in batch]
|
63 |
+
qus = [x['question'] for x in batch]
|
64 |
+
ans = [x['answer'] for x in batch]
|
65 |
+
return vid, v_id, qus, ans
|
66 |
+
|
67 |
+
|
68 |
+
def run_inference(args):
|
69 |
+
disable_torch_init()
|
70 |
+
|
71 |
+
model, processor, tokenizer = model_init(args.model_path)
|
72 |
+
|
73 |
+
gt_questions = json.load(open(args.question_file, "r"))
|
74 |
+
gt_questions = get_chunk(gt_questions, args.num_chunks, args.chunk_idx)
|
75 |
+
|
76 |
+
answer_file = os.path.join(args.output_file)
|
77 |
+
os.makedirs(os.path.dirname(args.output_file), exist_ok=True)
|
78 |
+
ans_file = open(answer_file, "w")
|
79 |
+
|
80 |
+
assert args.batch_size == 1, "Batch size must be 1 for inference"
|
81 |
+
dataset = MSVCDataset(args.video_folder, gt_questions, processor['video'])
|
82 |
+
dataloader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, collate_fn=collate_fn)
|
83 |
+
|
84 |
+
# Iterate over each sample in the ground truth file
|
85 |
+
for idx, (video_tensors, video_names, questions, answers) in enumerate(tqdm(dataloader)):
|
86 |
+
video_tensor = video_tensors[0]
|
87 |
+
video_name = video_names[0]
|
88 |
+
question = questions[0]
|
89 |
+
answer = answers[0]
|
90 |
+
|
91 |
+
output = mm_infer(
|
92 |
+
video_tensor,
|
93 |
+
question,
|
94 |
+
model=model,
|
95 |
+
tokenizer=tokenizer,
|
96 |
+
modal='video',
|
97 |
+
do_sample=False,
|
98 |
+
)
|
99 |
+
|
100 |
+
sample_set = {'video_name': video_name, 'question': question, 'answer': answer, 'pred': output}
|
101 |
+
ans_file.write(json.dumps(sample_set) + "\n")
|
102 |
+
|
103 |
+
ans_file.close()
|
104 |
+
|
105 |
+
|
106 |
+
if __name__ == "__main__":
|
107 |
+
parser = argparse.ArgumentParser()
|
108 |
+
|
109 |
+
parser.add_argument('--model-path', help='', required=True)
|
110 |
+
parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
|
111 |
+
parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
|
112 |
+
parser.add_argument('--output-file', help='Directory to save the model results JSON.', required=True)
|
113 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
114 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
115 |
+
parser.add_argument("--device", type=str, required=False, default='cuda:0')
|
116 |
+
parser.add_argument("--batch-size", type=int, required=False, default=1)
|
117 |
+
parser.add_argument("--num-workers", type=int, required=False, default=8)
|
118 |
+
args = parser.parse_args()
|
119 |
+
|
120 |
+
run_inference(args)
|
VideoLLaMA2/videollama2/eval/inference_video_mcqa_egoschema.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import math
|
4 |
+
import json
|
5 |
+
import argparse
|
6 |
+
import warnings
|
7 |
+
import traceback
|
8 |
+
|
9 |
+
from tqdm import tqdm
|
10 |
+
from torch.utils.data import Dataset, DataLoader
|
11 |
+
|
12 |
+
import sys
|
13 |
+
sys.path.append('./')
|
14 |
+
from videollama2 import model_init, mm_infer
|
15 |
+
from videollama2.utils import disable_torch_init
|
16 |
+
|
17 |
+
# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
|
18 |
+
warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
|
19 |
+
|
20 |
+
|
21 |
+
def split_list(lst, n):
|
22 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
23 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
24 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
25 |
+
|
26 |
+
|
27 |
+
def get_chunk(lst, n, k):
|
28 |
+
chunks = split_list(lst, n)
|
29 |
+
return chunks[k]
|
30 |
+
|
31 |
+
|
32 |
+
class EgoschemaDataset(Dataset):
|
33 |
+
|
34 |
+
video_formats = ['.mp4', '.avi', '.mov', '.mkv']
|
35 |
+
|
36 |
+
def __init__(self, data_folder, data_list, processor):
|
37 |
+
self.data_folder = data_folder
|
38 |
+
self.data_list = data_list
|
39 |
+
self.processor = processor
|
40 |
+
|
41 |
+
def __len__(self):
|
42 |
+
return len(self.data_list)
|
43 |
+
|
44 |
+
def __getitem__(self, idx):
|
45 |
+
line = self.data_list[idx]
|
46 |
+
q_uid = line['q_uid']
|
47 |
+
|
48 |
+
for fmt in self.video_formats: # Added this line
|
49 |
+
temp_path = os.path.join(self.data_folder, f"{q_uid}{fmt}")
|
50 |
+
if os.path.exists(temp_path):
|
51 |
+
video_path = temp_path
|
52 |
+
break
|
53 |
+
|
54 |
+
video_tensor = self.processor(video_path)
|
55 |
+
|
56 |
+
question = line['question']
|
57 |
+
a0 = line['option 0']
|
58 |
+
a1 = line['option 1']
|
59 |
+
a2 = line['option 2']
|
60 |
+
a3 = line['option 3']
|
61 |
+
a4 = line['option 4']
|
62 |
+
axs = [a0, a1, a2, a3, a4]
|
63 |
+
ops = ['(A)', '(B)', '(C)', '(D)', '(E)']
|
64 |
+
|
65 |
+
instruct = f'Select the best answer to the following multiple-choice question based on the video.\n{question}\nOptions:\n(A) {a0}\n(B) {a1}\n(C) {a2}\n(D) {a3}\n(E) {a4}\nAnswer with the option\'s letter from the given choices directly and only give the best option. The best answer is: '
|
66 |
+
|
67 |
+
return {
|
68 |
+
'q_uid': q_uid,
|
69 |
+
'video': video_tensor,
|
70 |
+
'instruct': instruct,
|
71 |
+
}
|
72 |
+
|
73 |
+
|
74 |
+
def build_egoschema_eval(args, processor):
|
75 |
+
questions = json.load(open(args.question_file, "r"))
|
76 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
77 |
+
dataset = EgoschemaDataset(args.video_folder, questions, processor)
|
78 |
+
dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers)
|
79 |
+
|
80 |
+
return dataloader
|
81 |
+
|
82 |
+
|
83 |
+
def egoschema_dump(ans_file, line, outputs):
|
84 |
+
for idx, output in enumerate(outputs):
|
85 |
+
q_uid = line['q_uid'][idx]
|
86 |
+
instruct = line['instruct'][idx]
|
87 |
+
letters = ['A', 'B', 'C', 'D', 'E']
|
88 |
+
|
89 |
+
output = output.replace('answer', '')
|
90 |
+
output = output.replace('Answer', '')
|
91 |
+
pred_answer = re.findall('[\(\ ]*[A-E][\)\ ]*', output)
|
92 |
+
try:
|
93 |
+
|
94 |
+
assert len(pred_answer) >= 1, 'The video \"{}\" instruct: \n\"{}\"\n output: \n\"{}\"\n is not in the expected format'.format(line['q_uid'], instruct, output)
|
95 |
+
pred_answer = pred_answer[0].strip()
|
96 |
+
pred_answer = pred_answer.strip('()')
|
97 |
+
pred_idx = letters.index(pred_answer)
|
98 |
+
except:
|
99 |
+
traceback.print_exc()
|
100 |
+
pred_idx = 2
|
101 |
+
|
102 |
+
ans_file.write(f'{q_uid}, {pred_idx}\n')
|
103 |
+
|
104 |
+
|
105 |
+
def run_inference(args):
|
106 |
+
disable_torch_init()
|
107 |
+
|
108 |
+
model, processor, tokenizer = model_init(args.model_path)
|
109 |
+
|
110 |
+
answer_file = os.path.expanduser(args.answer_file)
|
111 |
+
os.makedirs(os.path.dirname(answer_file), exist_ok=True)
|
112 |
+
ans_file = open(answer_file, "w")
|
113 |
+
|
114 |
+
val_loader = build_egoschema_eval(args, processor['video'])
|
115 |
+
|
116 |
+
# Iterate over each sample in the ground truth file
|
117 |
+
for i, line in enumerate(tqdm(val_loader)):
|
118 |
+
video_tensor = line['video'][0]
|
119 |
+
instruct = line['instruct'][0]
|
120 |
+
|
121 |
+
try:
|
122 |
+
pred = mm_infer(
|
123 |
+
video_tensor,
|
124 |
+
instruct,
|
125 |
+
model=model,
|
126 |
+
tokenizer=tokenizer,
|
127 |
+
modal='video',
|
128 |
+
do_sample=False,
|
129 |
+
)
|
130 |
+
except:
|
131 |
+
traceback.print_exc()
|
132 |
+
pred = 'C'
|
133 |
+
|
134 |
+
egoschema_dump(ans_file, line, [pred])
|
135 |
+
|
136 |
+
ans_file.close()
|
137 |
+
|
138 |
+
|
139 |
+
if __name__ == "__main__":
|
140 |
+
parser = argparse.ArgumentParser(description='Multiple-Choice Video QA Evaluation Script.')
|
141 |
+
|
142 |
+
parser.add_argument('--model-path', help='', required=True)
|
143 |
+
parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
|
144 |
+
parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
|
145 |
+
parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
|
146 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
147 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
148 |
+
parser.add_argument("--device", type=str, required=False, default='cuda:0')
|
149 |
+
parser.add_argument("--batch-size", type=int, default=1)
|
150 |
+
parser.add_argument("--num-workers", type=int, default=8)
|
151 |
+
args = parser.parse_args()
|
152 |
+
|
153 |
+
run_inference(args)
|
VideoLLaMA2/videollama2/eval/inference_video_mcqa_mvbench.py
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import math
|
4 |
+
import json
|
5 |
+
import argparse
|
6 |
+
import warnings
|
7 |
+
import traceback
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import numpy as np
|
11 |
+
from PIL import Image
|
12 |
+
from tqdm import tqdm
|
13 |
+
from decord import VideoReader, cpu
|
14 |
+
from torch.utils.data import Dataset, DataLoader
|
15 |
+
|
16 |
+
import sys
|
17 |
+
sys.path.append('./')
|
18 |
+
from videollama2 import model_init, mm_infer
|
19 |
+
from videollama2.utils import disable_torch_init
|
20 |
+
|
21 |
+
# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
|
22 |
+
warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
|
23 |
+
|
24 |
+
|
25 |
+
def split_list(lst, n):
|
26 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
27 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
28 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
29 |
+
|
30 |
+
|
31 |
+
def get_chunk(lst, n, k):
|
32 |
+
chunks = split_list(lst, n)
|
33 |
+
return chunks[k]
|
34 |
+
|
35 |
+
|
36 |
+
class MVBenchDataset(Dataset):
|
37 |
+
|
38 |
+
def __init__(self, data_list, processor):
|
39 |
+
self.data_list = data_list
|
40 |
+
self.processor = processor
|
41 |
+
|
42 |
+
def __len__(self):
|
43 |
+
return len(self.data_list)
|
44 |
+
|
45 |
+
def __getitem__(self, idx):
|
46 |
+
bound = (None, None)
|
47 |
+
if self.data_list[idx]['bound']:
|
48 |
+
bound = (self.data_list[idx]['data']['start'], self.data_list[idx]['data']['end'])
|
49 |
+
video_path = os.path.join(self.data_list[idx]['prefix'], self.data_list[idx]['data']['video'])
|
50 |
+
torch_imgs = self.processor(video_path, s=bound[0], e=bound[1])
|
51 |
+
question = self.data_list[idx]['data']['question']
|
52 |
+
options = self.data_list[idx]['data']['candidates']
|
53 |
+
answer = self.data_list[idx]['data']['answer']
|
54 |
+
task_type = self.data_list[idx]['task_type']
|
55 |
+
|
56 |
+
answer_idx = -1
|
57 |
+
letters = []
|
58 |
+
options_string = ''
|
59 |
+
for option_idx, c in enumerate(options):
|
60 |
+
letters.append(f"{chr(ord('A') + option_idx)}")
|
61 |
+
options_string += f"({chr(ord('A') + option_idx)}) {c}\n"
|
62 |
+
if c == answer:
|
63 |
+
answer_idx = option_idx
|
64 |
+
|
65 |
+
instruct = f'Question: {question}\nOptions:\n{options_string}Answer with the option\'s letter from the given choices directly and only give the best option.'
|
66 |
+
|
67 |
+
return {
|
68 |
+
'video': torch_imgs,
|
69 |
+
'video_path': video_path,
|
70 |
+
'instruct': instruct,
|
71 |
+
'letters': letters,
|
72 |
+
'options': options,
|
73 |
+
'answer_idx': answer_idx,
|
74 |
+
'task_type': task_type
|
75 |
+
}
|
76 |
+
|
77 |
+
|
78 |
+
tasks = {
|
79 |
+
"Action Sequence": ("action_sequence.json", "star/Charades_v1_480/", "video", True), # has start & end
|
80 |
+
"Action Prediction": ("action_prediction.json", "star/Charades_v1_480/", "video", True), # has start & end
|
81 |
+
"Action Antonym": ("action_antonym.json", "ssv2_video/", "video", False),
|
82 |
+
"Fine-grained Action": ("fine_grained_action.json", "Moments_in_Time_Raw/videos/", "video", False),
|
83 |
+
"Unexpected Action": ("unexpected_action.json", "FunQA_test/test/", "video", False),
|
84 |
+
"Object Existence": ("object_existence.json", "clevrer/video_validation/", "video", False),
|
85 |
+
"Object Interaction": ("object_interaction.json", "star/Charades_v1_480/", "video", True), # has start & end
|
86 |
+
"Object Shuffle": ("object_shuffle.json", "perception/videos/", "video", False),
|
87 |
+
"Moving Direction": ("moving_direction.json", "clevrer/video_validation/", "video", False),
|
88 |
+
"Action Localization": ("action_localization.json", "sta/sta_video/", "video", True), # has start & end
|
89 |
+
"Scene Transition": ("scene_transition.json", "scene_qa/video/", "video", False),
|
90 |
+
"Action Count": ("action_count.json", "perception/videos/", "video", False),
|
91 |
+
"Moving Count": ("moving_count.json", "clevrer/video_validation/", "video", False),
|
92 |
+
"Moving Attribute": ("moving_attribute.json", "clevrer/video_validation/", "video", False),
|
93 |
+
"State Change": ("state_change.json", "perception/videos/", "video", False),
|
94 |
+
"Fine-grained Pose": ("fine_grained_pose.json", "nturgbd/", "video", False),
|
95 |
+
"Character Order": ("character_order.json", "perception/videos/", "video", False),
|
96 |
+
"Egocentric Navigation": ("egocentric_navigation.json", "vlnqa/", "video", False),
|
97 |
+
"Episodic Reasoning": ("episodic_reasoning.json", "tvqa/frames_fps3_hq/", "frame", True), # has start & end, read frame
|
98 |
+
"Counterfactual Inference": ("counterfactual_inference.json", "clevrer/video_validation/", "video", False),
|
99 |
+
}
|
100 |
+
|
101 |
+
|
102 |
+
def build_mvbench_eval(args, processor):
|
103 |
+
data_list = []
|
104 |
+
for task_name, task in tasks.items():
|
105 |
+
json_file = os.path.join(args.question_file, task[0])
|
106 |
+
vis_folder = os.path.join(args.video_folder, task[1])
|
107 |
+
with open(json_file, 'r') as f:
|
108 |
+
json_data = json.load(f)
|
109 |
+
for data in json_data:
|
110 |
+
data_list.append({
|
111 |
+
'task_type': task_name,
|
112 |
+
'prefix': vis_folder,
|
113 |
+
'data_type': task[2],
|
114 |
+
'bound': task[3],
|
115 |
+
'data': data
|
116 |
+
})
|
117 |
+
data_list = get_chunk(data_list, args.num_chunks, args.chunk_idx)
|
118 |
+
dataset = MVBenchDataset(data_list, processor)
|
119 |
+
dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers)
|
120 |
+
|
121 |
+
return dataloader
|
122 |
+
|
123 |
+
|
124 |
+
def mvbench_dump(vid, instruct, letters, options, output):
|
125 |
+
|
126 |
+
output = output.replace('answer', '')
|
127 |
+
output = output.replace('Answer', '')
|
128 |
+
pred_answer = re.findall(f'[\(,\ ]*[{letters[0]}-{letters[-1]}][\),\ ]*', output)
|
129 |
+
try:
|
130 |
+
find_flag = False
|
131 |
+
if len(pred_answer) == 0:
|
132 |
+
for idx, opt in enumerate(options):
|
133 |
+
# Arabic numerals -> English words
|
134 |
+
if opt.lower() in output.lower():
|
135 |
+
pred_idx = idx
|
136 |
+
find_flag = True
|
137 |
+
break
|
138 |
+
else:
|
139 |
+
pred_answer = pred_answer[0].strip()
|
140 |
+
pred_answer = pred_answer.strip('()')
|
141 |
+
pred_idx = letters.index(pred_answer)
|
142 |
+
find_flag = True
|
143 |
+
|
144 |
+
assert find_flag, 'The video \"{}\" instruct: \n\"{}\"\n output: \n\"{}\"\n is not in the expected format'.format(vid, instruct, output)
|
145 |
+
except:
|
146 |
+
traceback.print_exc()
|
147 |
+
pred_idx = 2
|
148 |
+
|
149 |
+
return pred_idx
|
150 |
+
|
151 |
+
|
152 |
+
def run_inference(args):
|
153 |
+
disable_torch_init()
|
154 |
+
|
155 |
+
model, processor, tokenizer = model_init(args.model_path)
|
156 |
+
|
157 |
+
answer_file = os.path.expanduser(args.answer_file)
|
158 |
+
os.makedirs(os.path.dirname(answer_file), exist_ok=True)
|
159 |
+
ans_file = open(answer_file, "w")
|
160 |
+
|
161 |
+
val_loader = build_mvbench_eval(args, processor['video'])
|
162 |
+
|
163 |
+
# NOTE: only support batch size 1 for now
|
164 |
+
for i, line in enumerate(tqdm(val_loader)):
|
165 |
+
vid = line['video_path'][0]
|
166 |
+
video_tensor = line['video'][0]
|
167 |
+
task_type = line['task_type'][0]
|
168 |
+
instruct = line['instruct'][0]
|
169 |
+
letters = list(zip(*line['letters']))[0]
|
170 |
+
options = list(zip(*line['options']))[0]
|
171 |
+
answer_idx = line['answer_idx'][0].item()
|
172 |
+
|
173 |
+
output = mm_infer(
|
174 |
+
video_tensor,
|
175 |
+
instruct,
|
176 |
+
model=model,
|
177 |
+
tokenizer=tokenizer,
|
178 |
+
modal='video',
|
179 |
+
do_sample=False,
|
180 |
+
)
|
181 |
+
|
182 |
+
pred_idx = mvbench_dump(vid, instruct, letters, options, output)
|
183 |
+
|
184 |
+
ans_file.write(json.dumps({"vid": vid, "task_type": task_type, "pred": pred_idx, "gt": answer_idx}) + '\n')
|
185 |
+
|
186 |
+
ans_file.close()
|
187 |
+
|
188 |
+
|
189 |
+
if __name__ == "__main__":
|
190 |
+
parser = argparse.ArgumentParser()
|
191 |
+
|
192 |
+
parser.add_argument('--model-path', help='', required=True)
|
193 |
+
parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
|
194 |
+
parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
|
195 |
+
parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
|
196 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
197 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
198 |
+
parser.add_argument("--device", type=str, required=False, default='cuda:0')
|
199 |
+
parser.add_argument("--batch-size", type=int, default=1)
|
200 |
+
parser.add_argument("--num-workers", type=int, default=8)
|
201 |
+
args = parser.parse_args()
|
202 |
+
|
203 |
+
run_inference(args)
|
VideoLLaMA2/videollama2/eval/inference_video_mcqa_perception_test_mcqa.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import math
|
4 |
+
import json
|
5 |
+
import argparse
|
6 |
+
import warnings
|
7 |
+
import traceback
|
8 |
+
from tqdm import tqdm
|
9 |
+
|
10 |
+
import torch
|
11 |
+
from torch.utils.data import Dataset, DataLoader
|
12 |
+
|
13 |
+
import sys
|
14 |
+
sys.path.append('./')
|
15 |
+
from videollama2 import model_init, mm_infer
|
16 |
+
from videollama2.utils import disable_torch_init
|
17 |
+
|
18 |
+
|
19 |
+
def split_list(lst, n):
|
20 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
21 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
22 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
23 |
+
|
24 |
+
|
25 |
+
def get_chunk(lst, n, k):
|
26 |
+
chunks = split_list(lst, n)
|
27 |
+
return chunks[k]
|
28 |
+
|
29 |
+
|
30 |
+
class PerceptionTestMCQADataset(Dataset):
|
31 |
+
|
32 |
+
video_formats = ['.mp4', '.avi', '.mov', '.mkv']
|
33 |
+
|
34 |
+
def __init__(self, data_list, processor):
|
35 |
+
self.data_list = data_list
|
36 |
+
self.processor = processor
|
37 |
+
|
38 |
+
def __len__(self):
|
39 |
+
return len(self.data_list)
|
40 |
+
|
41 |
+
def __getitem__(self, idx):
|
42 |
+
line = self.data_list[idx]
|
43 |
+
video_name = line['metadata']['video_id']
|
44 |
+
mc_questions = line['mc_question']
|
45 |
+
|
46 |
+
for fmt in self.video_formats: # Added this line
|
47 |
+
temp_path = os.path.join(args.video_folder, f"{video_name}{fmt}")
|
48 |
+
if os.path.exists(temp_path):
|
49 |
+
video_path = temp_path
|
50 |
+
break
|
51 |
+
|
52 |
+
video_tensor = self.processor(video_path)
|
53 |
+
|
54 |
+
instructs = []
|
55 |
+
qids = []
|
56 |
+
ops = []
|
57 |
+
for q in mc_questions:
|
58 |
+
question = q['question']
|
59 |
+
qid = q['id']
|
60 |
+
options = q['options']
|
61 |
+
instruct = f'Question: {question}\nOptions:\n(A) {options[0]}\n(B) {options[1]}\n(C) {options[2]}\nAnswer with the option\'s letter from the given choices directly and only give the best option.'
|
62 |
+
|
63 |
+
instructs.append(instruct)
|
64 |
+
qids.append(qid)
|
65 |
+
ops.append(options)
|
66 |
+
|
67 |
+
return {
|
68 |
+
'video': video_tensor,
|
69 |
+
'video_id': video_name,
|
70 |
+
'instructs': instructs,
|
71 |
+
'question_ids': qids,
|
72 |
+
'options': ops,
|
73 |
+
}
|
74 |
+
|
75 |
+
|
76 |
+
def collate_fn(batch):
|
77 |
+
vid = [x['video'] for x in batch]
|
78 |
+
v_id = [x['video_id'] for x in batch]
|
79 |
+
ins = [x['instructs'] for x in batch]
|
80 |
+
q_ids = [x['question_ids'] for x in batch]
|
81 |
+
ops = [x['options'] for x in batch]
|
82 |
+
vid = torch.stack(vid, dim=0)
|
83 |
+
return vid, v_id, ins, q_ids, ops
|
84 |
+
|
85 |
+
|
86 |
+
def run_inference(args):
|
87 |
+
disable_torch_init()
|
88 |
+
|
89 |
+
model, processor, tokenizer = model_init(args.model_path)
|
90 |
+
|
91 |
+
questions = json.load(open(args.question_file, "r"))
|
92 |
+
questions = list(questions.values())
|
93 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
94 |
+
|
95 |
+
assert args.batch_size == 1, "Batch size must be 1 for inference"
|
96 |
+
dataset = PerceptionTestMCQADataset(questions, processor['video'])
|
97 |
+
dataloader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, collate_fn=collate_fn)
|
98 |
+
|
99 |
+
answer_file = os.path.expanduser(args.answer_file)
|
100 |
+
os.makedirs(os.path.dirname(answer_file), exist_ok=True)
|
101 |
+
ans_file = open(answer_file, "w")
|
102 |
+
|
103 |
+
# Iterate over each sample in the ground truth file
|
104 |
+
for i, (video_tensor, video_id, instructs, question_ids, options) in enumerate(tqdm(dataloader)):
|
105 |
+
|
106 |
+
# reduce batch dimension
|
107 |
+
video_tensor = video_tensor[0]
|
108 |
+
video_id = video_id[0]
|
109 |
+
instructs = instructs[0]
|
110 |
+
question_ids = question_ids[0]
|
111 |
+
options = options[0]
|
112 |
+
|
113 |
+
qas = []
|
114 |
+
for idx, instruct in enumerate(instructs):
|
115 |
+
letters = ['(A)', '(B)', '(C)']
|
116 |
+
question_id = question_ids[idx]
|
117 |
+
_options = options[idx]
|
118 |
+
|
119 |
+
output = mm_infer(
|
120 |
+
video_tensor,
|
121 |
+
instruct,
|
122 |
+
model=model,
|
123 |
+
tokenizer=tokenizer,
|
124 |
+
modal='video',
|
125 |
+
do_sample=False,
|
126 |
+
)
|
127 |
+
|
128 |
+
output = output.replace('answer', '')
|
129 |
+
output = output.replace('Answer', '')
|
130 |
+
pred_answer = re.findall('\(*[A-C]\)*', output)
|
131 |
+
try:
|
132 |
+
assert len(pred_answer) >= 1, 'The video \"{}\" instruct: \n\"{}\"\n output: \n\"{}\"\n is not in the expected format'.format(video_id, instruct, output)
|
133 |
+
pred_answer = pred_answer[0].strip()
|
134 |
+
# if not pred_answer.startswith('('):
|
135 |
+
pred_answer = pred_answer.strip('()')
|
136 |
+
pred_answer = f'({pred_answer})'
|
137 |
+
pred_idx = letters.index(pred_answer)
|
138 |
+
except:
|
139 |
+
traceback.print_exc()
|
140 |
+
tmp_options = [x.lower() for x in _options]
|
141 |
+
if output.lower() in tmp_options:
|
142 |
+
tmp_options = [x.lower() for x in _options]
|
143 |
+
pred_idx = tmp_options.index(output.lower())
|
144 |
+
else:
|
145 |
+
pred_idx = 2
|
146 |
+
|
147 |
+
qas.append({'id': question_id, 'answer_id': pred_idx, 'answer': _options[pred_idx]})
|
148 |
+
|
149 |
+
ans_file.write('\"{}\": {},\n'.format(video_id, json.dumps(qas)))
|
150 |
+
|
151 |
+
ans_file.close()
|
152 |
+
|
153 |
+
|
154 |
+
if __name__ == "__main__":
|
155 |
+
parser = argparse.ArgumentParser()
|
156 |
+
|
157 |
+
parser.add_argument('--model-path', help='', required=True)
|
158 |
+
parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
|
159 |
+
parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
|
160 |
+
parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
|
161 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
162 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
163 |
+
parser.add_argument("--device", type=str, required=False, default='cuda:0')
|
164 |
+
parser.add_argument("--model_max_length", type=int, required=False, default=2048)
|
165 |
+
parser.add_argument("--batch-size", type=int, required=False, default=1)
|
166 |
+
parser.add_argument("--num-workers", type=int, required=False, default=8)
|
167 |
+
args = parser.parse_args()
|
168 |
+
|
169 |
+
run_inference(args)
|
VideoLLaMA2/videollama2/eval/inference_video_mcqa_videomme.py
ADDED
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import math
|
4 |
+
import json
|
5 |
+
import copy
|
6 |
+
import argparse
|
7 |
+
import warnings
|
8 |
+
import traceback
|
9 |
+
|
10 |
+
import cv2
|
11 |
+
import torch
|
12 |
+
import pysubs2
|
13 |
+
import numpy as np
|
14 |
+
import pyarrow.parquet as pq
|
15 |
+
from tqdm import tqdm
|
16 |
+
from torch.utils.data import Dataset, DataLoader
|
17 |
+
|
18 |
+
import sys
|
19 |
+
sys.path.append('./')
|
20 |
+
from videollama2 import model_init, mm_infer
|
21 |
+
from videollama2.utils import disable_torch_init
|
22 |
+
|
23 |
+
# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
|
24 |
+
warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
|
25 |
+
|
26 |
+
|
27 |
+
def split_list(lst, n):
|
28 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
29 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
30 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
31 |
+
|
32 |
+
|
33 |
+
def get_chunk(lst, n, k):
|
34 |
+
chunks = split_list(lst, n)
|
35 |
+
return chunks[k]
|
36 |
+
|
37 |
+
|
38 |
+
def get_seq_frames(total_num_frames, desired_num_frames):
|
39 |
+
"""
|
40 |
+
Calculate the indices of frames to extract from a video.
|
41 |
+
|
42 |
+
Parameters:
|
43 |
+
total_num_frames (int): Total number of frames in the video.
|
44 |
+
desired_num_frames (int): Desired number of frames to extract.
|
45 |
+
|
46 |
+
Returns:
|
47 |
+
list: List of indices of frames to extract.
|
48 |
+
"""
|
49 |
+
|
50 |
+
# Calculate the size of each segment from which a frame will be extracted
|
51 |
+
seg_size = float(total_num_frames - 1) / desired_num_frames
|
52 |
+
|
53 |
+
seq = []
|
54 |
+
for i in range(desired_num_frames):
|
55 |
+
# Calculate the start and end indices of each segment
|
56 |
+
start = int(np.round(seg_size * i))
|
57 |
+
end = int(np.round(seg_size * (i + 1)))
|
58 |
+
|
59 |
+
# Append the middle index of the segment to the list
|
60 |
+
seq.append((start + end) // 2)
|
61 |
+
|
62 |
+
return seq
|
63 |
+
|
64 |
+
|
65 |
+
class VideoMMEDataset(Dataset):
|
66 |
+
|
67 |
+
video_formats = ['.mp4', '.avi', '.mov', '.mkv']
|
68 |
+
|
69 |
+
def __init__(self, video_folder, subtitle_folder, data_list, processor):
|
70 |
+
self.video_folder = video_folder
|
71 |
+
self.subtitle_folder = subtitle_folder
|
72 |
+
self.data_list = data_list
|
73 |
+
self.processor = processor
|
74 |
+
|
75 |
+
def __len__(self):
|
76 |
+
return len(self.data_list)
|
77 |
+
|
78 |
+
def __getitem__(self, idx):
|
79 |
+
line = self.data_list[idx]
|
80 |
+
|
81 |
+
video_ytid = line['url'].split('watch?v=')[-1]
|
82 |
+
|
83 |
+
for fmt in self.video_formats: # Added this line
|
84 |
+
temp_path = os.path.join(self.video_folder, f'{video_ytid}{fmt}')
|
85 |
+
if os.path.exists(temp_path):
|
86 |
+
video_path = temp_path
|
87 |
+
break
|
88 |
+
|
89 |
+
subtitle_path = os.path.join(self.subtitle_folder, f'{video_ytid}.srt')
|
90 |
+
|
91 |
+
try:
|
92 |
+
video_tensor = self.processor(video_path)
|
93 |
+
num_frames = video_tensor.shape[0]
|
94 |
+
except:
|
95 |
+
traceback.print_exc()
|
96 |
+
print(f'It occurs error when reading {video_ytid}')
|
97 |
+
video_tensor = None
|
98 |
+
num_frames = 0
|
99 |
+
|
100 |
+
if video_tensor is not None and os.path.exists(subtitle_path):
|
101 |
+
cv2_vr = cv2.VideoCapture(video_path)
|
102 |
+
duration = int(cv2_vr.get(cv2.CAP_PROP_FRAME_COUNT))
|
103 |
+
fps = cv2_vr.get(cv2.CAP_PROP_FPS)
|
104 |
+
selected_frame_ids = get_seq_frames(duration, num_frames)
|
105 |
+
|
106 |
+
subs = pysubs2.load(subtitle_path, encoding="utf-8")
|
107 |
+
subtitles = []
|
108 |
+
for seleced_frame_id in selected_frame_ids:
|
109 |
+
sub_text = ""
|
110 |
+
cur_time = pysubs2.make_time(fps=fps, frames=seleced_frame_id)
|
111 |
+
for sub in subs:
|
112 |
+
if sub.start < cur_time and sub.end > cur_time:
|
113 |
+
sub_text = sub.text.replace("\\N", " ")
|
114 |
+
break
|
115 |
+
if sub_text.strip():
|
116 |
+
subtitles.append(sub_text)
|
117 |
+
subtitles = "\n".join(subtitles)
|
118 |
+
else:
|
119 |
+
subtitles = ""
|
120 |
+
|
121 |
+
return {
|
122 |
+
'video': video_tensor,
|
123 |
+
'subtitle': subtitles,
|
124 |
+
'record': line,
|
125 |
+
}
|
126 |
+
|
127 |
+
|
128 |
+
def collate_fn(batch):
|
129 |
+
vid = [x['video'] for x in batch]
|
130 |
+
sub = [x['subtitle'] for x in batch]
|
131 |
+
rcs = [x['record'] for x in batch]
|
132 |
+
return vid, sub, rcs
|
133 |
+
|
134 |
+
|
135 |
+
def load_parquet(parquet_file):
|
136 |
+
table = pq.read_table(parquet_file)
|
137 |
+
|
138 |
+
# Convert PyArrow Table to pandas DataFrame
|
139 |
+
df = table.to_pandas()
|
140 |
+
|
141 |
+
jsons = []
|
142 |
+
for record in df.itertuples():
|
143 |
+
|
144 |
+
if len(jsons) < int(record.video_id):
|
145 |
+
jsons.append({
|
146 |
+
"video_id": record.video_id,
|
147 |
+
"youtube_id": record.videoID,
|
148 |
+
"url": record.url,
|
149 |
+
"duration": record.duration,
|
150 |
+
"domain": record.domain,
|
151 |
+
"sub_category": record.sub_category,
|
152 |
+
"questions": [
|
153 |
+
{
|
154 |
+
"question_id": record.question_id,
|
155 |
+
"task_type": record.task_type,
|
156 |
+
"question": record.question,
|
157 |
+
"choices": list(record.options),
|
158 |
+
"answer": record.answer,
|
159 |
+
}
|
160 |
+
]
|
161 |
+
})
|
162 |
+
else:
|
163 |
+
jsons[-1]['questions'].append({
|
164 |
+
"question_id": record.question_id,
|
165 |
+
"task_type": record.task_type,
|
166 |
+
"question": record.question,
|
167 |
+
"choices": list(record.options),
|
168 |
+
"answer": record.answer,
|
169 |
+
})
|
170 |
+
|
171 |
+
return jsons
|
172 |
+
|
173 |
+
|
174 |
+
def build_videomme_eval(args, processor):
|
175 |
+
# convert parquet to json
|
176 |
+
questions = load_parquet(args.question_file)
|
177 |
+
# questions = json.load(open(args.question_file, "r"))
|
178 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
179 |
+
dataset = VideoMMEDataset(args.video_folder, args.subtitle_folder, questions, processor)
|
180 |
+
dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, collate_fn=collate_fn)
|
181 |
+
|
182 |
+
return dataloader
|
183 |
+
|
184 |
+
|
185 |
+
def videomme_dump(record, instruct, options, output):
|
186 |
+
letters = ['A', 'B', 'C', 'D']
|
187 |
+
|
188 |
+
digit2word = {
|
189 |
+
'1': 'one',
|
190 |
+
'2': 'two',
|
191 |
+
'3': 'three',
|
192 |
+
'4': 'four',
|
193 |
+
'5': 'five',
|
194 |
+
'6': 'six',
|
195 |
+
'7': 'seven',
|
196 |
+
'8': 'eight',
|
197 |
+
'9': 'nine',
|
198 |
+
'0': 'zero',
|
199 |
+
}
|
200 |
+
|
201 |
+
output = output.replace('answer', '')
|
202 |
+
output = output.replace('Answer', '')
|
203 |
+
pred_answer = re.findall('[\(\ \[]*([A-D])[\)\.\ \]]*', output)
|
204 |
+
try:
|
205 |
+
find_flag = False
|
206 |
+
if len(pred_answer) == 0:
|
207 |
+
for idx, opt in enumerate(options):
|
208 |
+
# Arabic numerals -> English words
|
209 |
+
opt2 = opt
|
210 |
+
if opt in digit2word:
|
211 |
+
opt2 = digit2word[opt]
|
212 |
+
if opt.lower() in output.lower() or opt2.lower() in output.lower():
|
213 |
+
pred_idx = idx
|
214 |
+
find_flag = True
|
215 |
+
break
|
216 |
+
else:
|
217 |
+
pred_answer = pred_answer[0].strip()
|
218 |
+
pred_answer = pred_answer.strip('()')
|
219 |
+
pred_idx = letters.index(pred_answer)
|
220 |
+
find_flag = True
|
221 |
+
|
222 |
+
assert find_flag, 'The video \"{}\" instruct: \n\"{}\"\n output: \n\"{}\"\n is not in the expected format'.format(record['youtube_id'], instruct, output)
|
223 |
+
except:
|
224 |
+
traceback.print_exc()
|
225 |
+
pred_idx = 2
|
226 |
+
|
227 |
+
return letters[pred_idx]
|
228 |
+
|
229 |
+
|
230 |
+
def run_inference(args):
|
231 |
+
disable_torch_init()
|
232 |
+
|
233 |
+
# Initialize the model
|
234 |
+
model, processor, tokenizer = model_init(args.model_path)
|
235 |
+
|
236 |
+
answer_file = os.path.expanduser(args.answer_file)
|
237 |
+
answer_sub_file = answer_file.replace('.json', '_sub.json')
|
238 |
+
os.makedirs(os.path.dirname(answer_file), exist_ok=True)
|
239 |
+
ans_file = open(answer_file, "w")
|
240 |
+
ans_sub_file = open(answer_sub_file, "w")
|
241 |
+
|
242 |
+
val_loader = build_videomme_eval(args, processor['video'])
|
243 |
+
|
244 |
+
# Iterate over each sample in the ground truth file
|
245 |
+
for i, (videos, subtitles, records) in enumerate(tqdm(val_loader)):
|
246 |
+
video_tensor = videos[0]
|
247 |
+
subtitle = subtitles[0]
|
248 |
+
record = records[0]
|
249 |
+
|
250 |
+
new_record = copy.deepcopy(record)
|
251 |
+
new_record_sub = copy.deepcopy(record)
|
252 |
+
|
253 |
+
if video_tensor is None:
|
254 |
+
new_record['missing'] = True
|
255 |
+
ans_file.write(json.dumps(new_record) + ",\n")
|
256 |
+
new_record_sub['missing'] = True
|
257 |
+
ans_sub_file.write(json.dumps(new_record_sub) + ",\n")
|
258 |
+
continue
|
259 |
+
else:
|
260 |
+
new_record['missing'] = False
|
261 |
+
new_record_sub['missing'] = False
|
262 |
+
|
263 |
+
questions = record['questions']
|
264 |
+
for idx, question in enumerate(questions):
|
265 |
+
q = question['question']
|
266 |
+
choices = question['choices']
|
267 |
+
options = [re.findall('[A-D]\. (.*).', c)[0] for c in choices]
|
268 |
+
|
269 |
+
instruct = "Select the best answer to the following multiple-choice question based on the video. Respond with only the letter (A, B, C, or D) of the correct option.\n"
|
270 |
+
instruct += f"{q}\n"
|
271 |
+
for cho_idx, cho in enumerate(choices):
|
272 |
+
instruct += f"{cho}\n"
|
273 |
+
# instruct += "The best option is: "
|
274 |
+
instruct += "Answer with the option\'s letter from the given choices directly and only give the best option. The best answer is: "
|
275 |
+
output = mm_infer(video_tensor, instruct, model=model, tokenizer=tokenizer, modal='video', do_sample=False)
|
276 |
+
new_record['questions'][idx]['response'] = videomme_dump(record, instruct, options, output)
|
277 |
+
|
278 |
+
instruct = f"This video's subtitles are listed below:\n{subtitle}\n" + instruct
|
279 |
+
output = mm_infer(video_tensor, instruct, model=model, tokenizer=tokenizer, modal='video', do_sample=False)
|
280 |
+
new_record_sub['questions'][idx]['response'] = videomme_dump(record, instruct, options, output)
|
281 |
+
|
282 |
+
ans_file.write(json.dumps(new_record) + ",\n")
|
283 |
+
ans_sub_file.write(json.dumps(new_record_sub) + ",\n")
|
284 |
+
|
285 |
+
ans_file.close()
|
286 |
+
ans_sub_file.close()
|
287 |
+
|
288 |
+
|
289 |
+
if __name__ == "__main__":
|
290 |
+
parser = argparse.ArgumentParser()
|
291 |
+
|
292 |
+
parser.add_argument('--model-path', help='', required=True)
|
293 |
+
parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
|
294 |
+
parser.add_argument('--subtitle-folder', help='Directory containing subtitle files.', required=True)
|
295 |
+
parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
|
296 |
+
parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
|
297 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
298 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
299 |
+
parser.add_argument("--device", type=str, required=False, default='cuda:0')
|
300 |
+
parser.add_argument("--batch-size", type=int, default=1)
|
301 |
+
parser.add_argument("--num-workers", type=int, default=8)
|
302 |
+
args = parser.parse_args()
|
303 |
+
|
304 |
+
run_inference(args)
|
VideoLLaMA2/videollama2/eval/inference_video_oqa_activitynet.py
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import math
|
4 |
+
import argparse
|
5 |
+
import warnings
|
6 |
+
import traceback
|
7 |
+
from tqdm import tqdm
|
8 |
+
|
9 |
+
from torch.utils.data import Dataset, DataLoader
|
10 |
+
|
11 |
+
import sys
|
12 |
+
sys.path.append('./')
|
13 |
+
from videollama2 import model_init, mm_infer
|
14 |
+
from videollama2.utils import disable_torch_init
|
15 |
+
|
16 |
+
# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
|
17 |
+
warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
|
18 |
+
|
19 |
+
|
20 |
+
def split_list(lst, n):
|
21 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
22 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
23 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
24 |
+
|
25 |
+
|
26 |
+
def get_chunk(lst, n, k):
|
27 |
+
chunks = split_list(lst, n)
|
28 |
+
return chunks[k]
|
29 |
+
|
30 |
+
|
31 |
+
class ActivitynetDataset(Dataset):
|
32 |
+
|
33 |
+
video_formats = ['.mp4', '.webm', '.avi', '.mov', '.mkv']
|
34 |
+
|
35 |
+
def __init__(self, questions, answers, processor):
|
36 |
+
self.questions = questions
|
37 |
+
self.answers = answers
|
38 |
+
self.processor = processor
|
39 |
+
|
40 |
+
def __len__(self):
|
41 |
+
return len(self.questions)
|
42 |
+
|
43 |
+
def __getitem__(self, idx):
|
44 |
+
sample = self.questions[idx]
|
45 |
+
answer = self.answers[idx]
|
46 |
+
|
47 |
+
video_name = sample['video_name']
|
48 |
+
question = sample['question']
|
49 |
+
question_id = sample['question_id']
|
50 |
+
answer = answer['answer']
|
51 |
+
|
52 |
+
video_path = None
|
53 |
+
for fmt in self.video_formats: # Added this line
|
54 |
+
temp_path = os.path.join(args.video_folder, f"v_{video_name}{fmt}")
|
55 |
+
if os.path.exists(temp_path):
|
56 |
+
video_path = temp_path
|
57 |
+
break
|
58 |
+
# BUG: compatibility for MSVD, MSRVTT, TGIF
|
59 |
+
temp_path = os.path.join(args.video_folder, f"{video_name}{fmt}")
|
60 |
+
if os.path.exists(temp_path):
|
61 |
+
video_path = temp_path
|
62 |
+
break
|
63 |
+
|
64 |
+
if video_path is None:
|
65 |
+
raise FileNotFoundError(f"Video file not found for {os.path.join(args.video_folder, video_name)}")
|
66 |
+
|
67 |
+
video_tensor = self.processor(video_path)
|
68 |
+
|
69 |
+
return {
|
70 |
+
'video': video_tensor,
|
71 |
+
'video_name': video_name,
|
72 |
+
'question': question,
|
73 |
+
'question_id': question_id,
|
74 |
+
'answer': answer,
|
75 |
+
}
|
76 |
+
|
77 |
+
|
78 |
+
def collate_fn(batch):
|
79 |
+
vid = [x['video'] for x in batch]
|
80 |
+
v_id = [x['video_name'] for x in batch]
|
81 |
+
qus = [x['question'] for x in batch]
|
82 |
+
qid = [x['question_id'] for x in batch]
|
83 |
+
ans = [x['answer'] for x in batch]
|
84 |
+
return vid, v_id, qus, qid, ans
|
85 |
+
|
86 |
+
|
87 |
+
def run_inference(args):
|
88 |
+
disable_torch_init()
|
89 |
+
|
90 |
+
# Initialize the model
|
91 |
+
model, processor, tokenizer = model_init(args.model_path)
|
92 |
+
|
93 |
+
gt_questions = json.load(open(args.question_file, "r"))
|
94 |
+
gt_questions = get_chunk(gt_questions, args.num_chunks, args.chunk_idx)
|
95 |
+
gt_answers = json.load(open(args.answer_file, "r"))
|
96 |
+
gt_answers = get_chunk(gt_answers, args.num_chunks, args.chunk_idx)
|
97 |
+
|
98 |
+
assert args.batch_size == 1, "Batch size must be 1 for inference"
|
99 |
+
dataset = ActivitynetDataset(gt_questions, gt_answers, processor['video'])
|
100 |
+
dataloader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, collate_fn=collate_fn)
|
101 |
+
|
102 |
+
answer_file = os.path.join(args.output_file)
|
103 |
+
os.makedirs(os.path.dirname(args.output_file), exist_ok=True)
|
104 |
+
ans_file = open(answer_file, "w")
|
105 |
+
|
106 |
+
# Iterate over each sample in the ground truth file
|
107 |
+
for i, (video_tensors, video_names, questions, question_ids, answers) in enumerate(tqdm(dataloader)):
|
108 |
+
video_tensor = video_tensors[0]
|
109 |
+
video_name = video_names[0]
|
110 |
+
question = questions[0]
|
111 |
+
question_id = question_ids[0]
|
112 |
+
answer = answers[0]
|
113 |
+
|
114 |
+
# question = question + '\n' + 'Answer the question using a single word or a short phrase with multiple words.'
|
115 |
+
|
116 |
+
try:
|
117 |
+
output = mm_infer(
|
118 |
+
video_tensor,
|
119 |
+
question,
|
120 |
+
model=model,
|
121 |
+
tokenizer=tokenizer,
|
122 |
+
modal='video',
|
123 |
+
do_sample=False,
|
124 |
+
)
|
125 |
+
except:
|
126 |
+
traceback.print_exc()
|
127 |
+
output = "error"
|
128 |
+
|
129 |
+
sample_set = {'id': question_id, 'question': question, 'answer': answer, 'pred': output}
|
130 |
+
ans_file.write(json.dumps(sample_set) + "\n")
|
131 |
+
|
132 |
+
ans_file.close()
|
133 |
+
|
134 |
+
|
135 |
+
if __name__ == "__main__":
|
136 |
+
parser = argparse.ArgumentParser()
|
137 |
+
|
138 |
+
parser.add_argument('--model-path', help='', required=True)
|
139 |
+
parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
|
140 |
+
parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
|
141 |
+
parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
|
142 |
+
parser.add_argument('--output-file', help='Directory to save the model results JSON.', required=True)
|
143 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
144 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
145 |
+
parser.add_argument("--device", type=str, required=False, default='cuda:0')
|
146 |
+
parser.add_argument("--batch-size", type=int, required=False, default=1)
|
147 |
+
parser.add_argument("--num-workers", type=int, required=False, default=8)
|
148 |
+
args = parser.parse_args()
|
149 |
+
|
150 |
+
run_inference(args)
|
VideoLLaMA2/videollama2/eval/inference_video_oqa_vcgpt_consistency.py
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import math
|
4 |
+
import json
|
5 |
+
import argparse
|
6 |
+
import warnings
|
7 |
+
from tqdm import tqdm
|
8 |
+
|
9 |
+
import torch
|
10 |
+
from torch.utils.data import Dataset, DataLoader
|
11 |
+
|
12 |
+
import sys
|
13 |
+
sys.path.append('./')
|
14 |
+
from videollama2 import model_init, mm_infer
|
15 |
+
from videollama2.utils import disable_torch_init
|
16 |
+
|
17 |
+
# NOTE: Ignore TypedStorage warning, which refers to this link~(https://github.com/pytorch/pytorch/issues/97207#issuecomment-1494781560)
|
18 |
+
warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
|
19 |
+
|
20 |
+
|
21 |
+
def split_list(lst, n):
|
22 |
+
"""Split a list into n (roughly) equal-sized chunks"""
|
23 |
+
chunk_size = math.ceil(len(lst) / n) # integer division
|
24 |
+
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
|
25 |
+
|
26 |
+
|
27 |
+
def get_chunk(lst, n, k):
|
28 |
+
chunks = split_list(lst, n)
|
29 |
+
return chunks[k]
|
30 |
+
|
31 |
+
|
32 |
+
class VCGPTDataset(Dataset):
|
33 |
+
|
34 |
+
video_formats = ['.mp4', '.webm', '.avi', '.mov', '.mkv']
|
35 |
+
|
36 |
+
def __init__(self, data_list, processor):
|
37 |
+
self.data_list = data_list
|
38 |
+
self.processor = processor
|
39 |
+
|
40 |
+
def __len__(self):
|
41 |
+
return len(self.data_list)
|
42 |
+
|
43 |
+
def __getitem__(self, idx):
|
44 |
+
line = self.data_list[idx]
|
45 |
+
question1 = line['Q1']
|
46 |
+
question2 = line['Q2']
|
47 |
+
answer = line['A']
|
48 |
+
video_name = line['video_name']
|
49 |
+
|
50 |
+
for fmt in self.video_formats: # Added this line
|
51 |
+
temp_path = os.path.join(args.video_folder, f"{video_name}{fmt}")
|
52 |
+
if os.path.exists(temp_path):
|
53 |
+
video_path = temp_path
|
54 |
+
break
|
55 |
+
|
56 |
+
video_tensor = self.processor(video_path)
|
57 |
+
|
58 |
+
return {
|
59 |
+
'video': video_tensor,
|
60 |
+
'video_name': video_name,
|
61 |
+
'question1': question1,
|
62 |
+
'question2': question2,
|
63 |
+
'answer': answer,
|
64 |
+
}
|
65 |
+
|
66 |
+
|
67 |
+
def collate_fn(batch):
|
68 |
+
vid = [x['video'] for x in batch]
|
69 |
+
v_id = [x['video_name'] for x in batch]
|
70 |
+
qus1 = [x['question1'] for x in batch]
|
71 |
+
qus2 = [x['question2'] for x in batch]
|
72 |
+
ans = [x['answer'] for x in batch]
|
73 |
+
vid = torch.stack(vid, dim=0)
|
74 |
+
return vid, v_id, qus1, qus2, ans
|
75 |
+
|
76 |
+
|
77 |
+
def run_inference(args):
|
78 |
+
disable_torch_init()
|
79 |
+
|
80 |
+
# Initialize the model
|
81 |
+
model, processor, tokenizer = model_init(args.model_path)
|
82 |
+
|
83 |
+
questions = json.load(open(args.question_file, "r"))
|
84 |
+
questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
|
85 |
+
|
86 |
+
assert args.batch_size == 1, "Batch size must be 1 for inference"
|
87 |
+
dataset = VCGPTDataset(questions, processor['video'])
|
88 |
+
dataloader = DataLoader(dataset, shuffle=False, batch_size=args.batch_size, num_workers=args.num_workers, collate_fn=collate_fn)
|
89 |
+
|
90 |
+
answer_file = os.path.expanduser(args.answer_file)
|
91 |
+
os.makedirs(os.path.dirname(answer_file), exist_ok=True)
|
92 |
+
ans_file = open(answer_file, "w")
|
93 |
+
|
94 |
+
output_list = [] # List to store the output results
|
95 |
+
|
96 |
+
# Iterate over each sample in the ground truth file
|
97 |
+
for i, (video_tensors, video_names, questions1, questions2, answers) in enumerate(tqdm(dataloader)):
|
98 |
+
|
99 |
+
# reduce batch dimension
|
100 |
+
video_tensor = video_tensors[0]
|
101 |
+
video_name = video_names[0]
|
102 |
+
question1 = questions1[0]
|
103 |
+
question2 = questions2[0]
|
104 |
+
answer = answers[0]
|
105 |
+
|
106 |
+
output1 = mm_infer(
|
107 |
+
video_tensor,
|
108 |
+
question1,
|
109 |
+
model=model,
|
110 |
+
tokenizer=tokenizer,
|
111 |
+
modal='video',
|
112 |
+
do_sample=False,
|
113 |
+
)
|
114 |
+
|
115 |
+
output2 = mm_infer(
|
116 |
+
video_tensor,
|
117 |
+
question2,
|
118 |
+
model=model,
|
119 |
+
tokenizer=tokenizer,
|
120 |
+
do_sample=False,
|
121 |
+
modal='video',
|
122 |
+
)
|
123 |
+
|
124 |
+
qa = {'video_name': video_name, 'Q1': question1, 'Q2': question2, 'A': answer, 'P1': output1, 'P2': output2}
|
125 |
+
|
126 |
+
ans_file.write(json.dumps(qa) + "\n")
|
127 |
+
|
128 |
+
ans_file.close()
|
129 |
+
|
130 |
+
|
131 |
+
if __name__ == "__main__":
|
132 |
+
parser = argparse.ArgumentParser()
|
133 |
+
|
134 |
+
# Define the command-line arguments
|
135 |
+
parser.add_argument('--model-path', help='', required=True)
|
136 |
+
parser.add_argument('--model_base', help='', default=None, type=str, required=False)
|
137 |
+
parser.add_argument('--video-folder', help='Directory containing video files.', required=True)
|
138 |
+
parser.add_argument('--question-file', help='Path to the ground truth file containing question.', required=True)
|
139 |
+
parser.add_argument('--answer-file', help='Path to the ground truth file containing answers.', required=True)
|
140 |
+
parser.add_argument("--conv-mode", type=str, default="llava_v1")
|
141 |
+
parser.add_argument("--num-chunks", type=int, default=1)
|
142 |
+
parser.add_argument("--chunk-idx", type=int, default=0)
|
143 |
+
parser.add_argument("--device", type=str, required=False, default='cuda:0')
|
144 |
+
parser.add_argument("--model_max_length", type=int, required=False, default=2048)
|
145 |
+
parser.add_argument("--batch-size", type=int, required=False, default=1)
|
146 |
+
parser.add_argument("--num-workers", type=int, required=False, default=8)
|
147 |
+
|
148 |
+
args = parser.parse_args()
|
149 |
+
|
150 |
+
run_inference(args)
|