jirvin16 commited on
Commit
134cb11
Β·
0 Parent(s):

Initial commit

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. .gitattributes +35 -0
  2. .gitignore +2 -0
  3. README.md +14 -0
  4. requirements.txt +283 -0
  5. static/logo.png +0 -0
  6. static/logo.svg +0 -0
  7. videollava/__init__.py +1 -0
  8. videollava/constants.py +27 -0
  9. videollava/conversation.py +381 -0
  10. videollava/eval/aid_fmow_ucmerced_utils.py +94 -0
  11. videollava/eval/ben_utils.py +114 -0
  12. videollava/eval/cdvqa_utils.py +127 -0
  13. videollava/eval/classification_segmentation.py +151 -0
  14. videollava/eval/datasets_into_geochat_format.py +293 -0
  15. videollava/eval/eval_classification.py +151 -0
  16. videollava/eval/eval_geochat_referring.py +330 -0
  17. videollava/eval/eval_referring.py +351 -0
  18. videollava/eval/geochat_bench.py +228 -0
  19. videollava/eval/geochat_eval_fmow.py +205 -0
  20. videollava/eval/geochat_geovlm_infer.py +262 -0
  21. videollava/eval/geochat_referring_2.py +459 -0
  22. videollava/eval/geochat_s2looking_utils.py +400 -0
  23. videollava/eval/geochat_utils.py +94 -0
  24. videollava/eval/infer_eval.py +386 -0
  25. videollava/eval/infer_utils.py +253 -0
  26. videollava/eval/qfabric_utils.py +98 -0
  27. videollava/eval/s2looking_utils.py +78 -0
  28. videollava/eval/xbd_utils.py +82 -0
  29. videollava/mm_utils.py +104 -0
  30. videollava/model/__init__.py +2 -0
  31. videollava/model/apply_delta.py +48 -0
  32. videollava/model/builder.py +166 -0
  33. videollava/model/consolidate.py +29 -0
  34. videollava/model/language_model/llava_llama.py +111 -0
  35. videollava/model/language_model/llava_mpt.py +113 -0
  36. videollava/model/language_model/mpt/adapt_tokenizer.py +41 -0
  37. videollava/model/language_model/mpt/attention.py +300 -0
  38. videollava/model/language_model/mpt/blocks.py +41 -0
  39. videollava/model/language_model/mpt/configuration_mpt.py +118 -0
  40. videollava/model/language_model/mpt/custom_embedding.py +11 -0
  41. videollava/model/language_model/mpt/flash_attn_triton.py +484 -0
  42. videollava/model/language_model/mpt/hf_prefixlm_converter.py +415 -0
  43. videollava/model/language_model/mpt/meta_init_context.py +94 -0
  44. videollava/model/language_model/mpt/modeling_mpt.py +331 -0
  45. videollava/model/language_model/mpt/norm.py +56 -0
  46. videollava/model/language_model/mpt/param_init_fns.py +181 -0
  47. videollava/model/llava_arch.py +390 -0
  48. videollava/model/make_delta.py +52 -0
  49. videollava/model/multimodal_encoder/builder.py +24 -0
  50. videollava/model/multimodal_encoder/clip_encoder.py +78 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: TEOChat
3
+ emoji: 🏒
4
+ colorFrom: green
5
+ colorTo: pink
6
+ sdk: gradio
7
+ sdk_version: 4.44.1
8
+ app_file: videollava/serve/teochat_demo.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ short_description: A new vision-language assistant for temporal EO data.
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
requirements.txt ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.26.1
2
+ affine==2.4.0
3
+ aiofiles==23.2.1
4
+ aiohttp==3.8.4
5
+ aiosignal==1.3.1
6
+ altair==5.2.0
7
+ annotated-types==0.7.0
8
+ anyio==3.6.2
9
+ appdirs==1.4.4
10
+ argon2-cffi==21.3.0
11
+ argon2-cffi-bindings==21.2.0
12
+ arrow==1.2.3
13
+ asttokens==2.2.1
14
+ async-timeout==4.0.2
15
+ attrs==23.1.0
16
+ av==11.0.0
17
+ backcall==0.2.0
18
+ beautifulsoup4==4.12.2
19
+ bitsandbytes==0.41.0
20
+ bleach==6.0.0
21
+ blessed==1.20.0
22
+ braceexpand==0.1.7
23
+ Brotli==1.0.9
24
+ certifi==2024.2.2
25
+ cffi==1.15.1
26
+ chardet==4.0.0
27
+ charset-normalizer==3.1.0
28
+ click==8.1.7
29
+ click-plugins==1.1.1
30
+ cligj==0.7.2
31
+ cloudpickle==2.2.1
32
+ cmake==3.26.3
33
+ comm==0.2.1
34
+ contourpy==1.0.7
35
+ coverage==7.4.4
36
+ croniter==1.3.14
37
+ cycler==0.11.0
38
+ cytoolz==0.12.2
39
+ dask==2023.11.0
40
+ dateutils==0.6.12
41
+ debugpy==1.6.7
42
+ decorator==5.1.1
43
+ decord==0.6.0
44
+ deepdiff==6.3.0
45
+ deepspeed==0.14.0
46
+ defusedxml==0.7.1
47
+ distro==1.9.0
48
+ dnspython==2.6.1
49
+ docker-pycreds==0.4.0
50
+ efficientnet-pytorch==0.7.1
51
+ einops==0.6.1
52
+ einops-exts==0.0.4
53
+ email_validator==2.2.0
54
+ exceptiongroup==1.2.0
55
+ executing==1.2.0
56
+ fastapi==0.111.1
57
+ fastapi-cli==0.0.4
58
+ fastjsonschema==2.16.3
59
+ ffmpy==0.3.1
60
+ filelock==3.13.1
61
+ Fiona==1.9.3
62
+ fire==0.5.0
63
+ fonttools==4.39.3
64
+ fqdn==1.5.1
65
+ frozenlist==1.3.3
66
+ fschat==0.2.36
67
+ fsspec==2023.12.2
68
+ ftfy==6.1.3
69
+ fvcore==0.1.5.post20221221
70
+ gdown==5.1.0
71
+ geojson==3.0.1
72
+ gitdb==4.0.10
73
+ GitPython==3.1.31
74
+ gradio==4.39.0
75
+ gradio_client==1.1.1
76
+ h11==0.14.0
77
+ h5py==3.9.0
78
+ hjson==3.1.0
79
+ httpcore==1.0.5
80
+ httptools==0.6.1
81
+ httpx==0.27.0
82
+ huggingface-hub==0.20.3
83
+ idna==3.4
84
+ imagecodecs==2021.8.26
85
+ imageio==2.33.1
86
+ importlib-metadata==7.0.1
87
+ importlib-resources==5.12.0
88
+ iniconfig==2.0.0
89
+ inquirer==3.1.3
90
+ iopath==0.1.10
91
+ ipykernel==6.28.0
92
+ ipython==8.15.0
93
+ ipython-genutils==0.2.0
94
+ ipywidgets==8.1.3
95
+ isoduration==20.11.0
96
+ itsdangerous==2.1.2
97
+ jedi==0.18.2
98
+ Jinja2==3.1.2
99
+ joblib==1.2.0
100
+ jsonpointer==2.3
101
+ jsonschema==4.17.3
102
+ jupyter_client==8.6.0
103
+ jupyter_core==5.5.0
104
+ jupyter-events==0.6.3
105
+ jupyter_server==2.5.0
106
+ jupyter_server_terminals==0.4.4
107
+ jupyterlab-pygments==0.2.2
108
+ jupyterlab_widgets==3.0.11
109
+ kaleido==0.2.1
110
+ kiwisolver==1.4.4
111
+ kornia==0.7.3
112
+ linkify-it-py==2.0.2
113
+ lit==16.0.2
114
+ locket==1.0.0
115
+ markdown-it-py==2.2.0
116
+ markdown2==2.4.12
117
+ MarkupSafe==2.1.2
118
+ matplotlib==3.7.1
119
+ matplotlib-inline==0.1.6
120
+ mdit-py-plugins==0.3.3
121
+ mdurl==0.1.2
122
+ mistune==2.0.5
123
+ mkl-fft==1.3.8
124
+ mkl-random==1.2.4
125
+ mkl-service==2.4.0
126
+ mpmath==1.3.0
127
+ multidict==6.0.4
128
+ munch==2.5.0
129
+ nbclassic==0.5.5
130
+ nbclient==0.7.4
131
+ nbconvert==7.3.1
132
+ nbformat==5.8.0
133
+ nest-asyncio==1.6.0
134
+ networkx==3.1
135
+ nh3==0.2.15
136
+ ninja==1.11.1.1
137
+ nltk==3.8.1
138
+ notebook==6.5.4
139
+ notebook_shim==0.2.3
140
+ numpy==1.26.4
141
+ open_clip_torch==2.26.1
142
+ openai==0.28.1
143
+ opencv-python==4.7.0.72
144
+ ordered-set==4.1.0
145
+ orjson==3.9.12
146
+ packaging==23.1
147
+ pandas==2.0.1
148
+ pandocfilters==1.5.0
149
+ parameterized==0.9.0
150
+ parso==0.8.3
151
+ partd==1.4.1
152
+ pathtools==0.1.2
153
+ peft==0.7.1
154
+ pexpect==4.8.0
155
+ pickleshare==0.7.5
156
+ pillow==10.3.0
157
+ pip==23.0.1
158
+ platformdirs==3.10.0
159
+ plotly==5.22.0
160
+ pluggy==1.4.0
161
+ portalocker==2.8.2
162
+ pprintpp==0.4.0
163
+ pretrainedmodels==0.7.4
164
+ prometheus-client==0.16.0
165
+ prompt-toolkit==3.0.43
166
+ protobuf==4.22.3
167
+ psutil==5.9.5
168
+ ptyprocess==0.7.0
169
+ pure-eval==0.2.2
170
+ py-cpuinfo==9.0.0
171
+ pycountry==23.12.11
172
+ pycountry-convert==0.7.2
173
+ pycparser==2.21
174
+ pydantic==2.8.2
175
+ pydantic_core==2.20.1
176
+ pydub==0.25.1
177
+ Pygments==2.15.1
178
+ PyJWT==2.6.0
179
+ pynvml==11.5.0
180
+ pyparsing==3.0.9
181
+ pyproj==3.5.0
182
+ pyrsistent==0.19.3
183
+ PySocks==1.7.1
184
+ pytest==8.1.1
185
+ pytest-cov==4.1.0
186
+ pytest-mock==3.14.0
187
+ python-dateutil==2.8.2
188
+ python-dotenv==1.0.1
189
+ python-editor==1.0.4
190
+ python-json-logger==2.0.7
191
+ python-multipart==0.0.9
192
+ pytorch-lightning==2.0.2
193
+ pytorchvideo==0.1.3
194
+ pytz==2023.3
195
+ pywavelets==1.5.0
196
+ PyYAML==6.0.1
197
+ pyzmq==25.1.2
198
+ rasterio==1.3.6
199
+ readchar==4.0.5
200
+ regex==2023.12.25
201
+ repoze.lru==0.7
202
+ requests==2.31.0
203
+ reverse-geocoder==1.5.1
204
+ rfc3339-validator==0.1.4
205
+ rfc3986-validator==0.1.1
206
+ rich==13.3.4
207
+ Rtree==1.0.1
208
+ ruff==0.5.2
209
+ safetensors==0.4.2
210
+ scikit-image==0.19.3
211
+ scikit-learn==1.2.2
212
+ scipy==1.11.4
213
+ seaborn==0.13.2
214
+ segmentation-models-pytorch==0.3.2
215
+ semantic-version==2.10.0
216
+ Send2Trash==1.8.0
217
+ sentencepiece==0.1.99
218
+ sentry-sdk==1.21.0
219
+ setproctitle==1.3.2
220
+ setuptools==66.0.0
221
+ shapely==2.0.1
222
+ shellingham==1.5.4
223
+ shortuuid==1.0.11
224
+ six==1.16.0
225
+ smmap==5.0.0
226
+ sniffio==1.3.0
227
+ snuggs==1.4.7
228
+ soupsieve==2.4.1
229
+ stack-data==0.6.2
230
+ starlette==0.37.2
231
+ starsessions==1.3.0
232
+ svgwrite==1.4.3
233
+ sympy==1.11.1
234
+ tabulate==0.9.0
235
+ tenacity==8.5.0
236
+ tensorboardX==2.6.2.2
237
+ termcolor==2.3.0
238
+ terminado==0.17.1
239
+ threadpoolctl==3.1.0
240
+ tifffile==2021.7.2
241
+ tiktoken==0.6.0
242
+ timm==0.6.12
243
+ tinycss2==1.2.1
244
+ tokenizers==0.13.3
245
+ tomli==2.0.1
246
+ tomlkit==0.12.0
247
+ toolz==0.12.1
248
+ torchaudio==2.2.1
249
+ torchgeo==0.6.0
250
+ torchinfo==1.7.2
251
+ torchmetrics==0.11.4
252
+ torchvision==0.17.1
253
+ tornado==6.3.3
254
+ tqdm==4.65.0
255
+ traitlets==5.9.0
256
+ transformers==4.31.0
257
+ Tree==0.2.4
258
+ triton==2.2.0
259
+ typer==0.12.3
260
+ typing_extensions==4.9.0
261
+ tzdata==2023.3
262
+ uc-micro-py==1.0.2
263
+ uri-template==1.2.0
264
+ urllib3==2.1.0
265
+ utm==0.7.0
266
+ uvicorn==0.21.1
267
+ uvloop==0.19.0
268
+ wandb==0.15.0
269
+ watchfiles==0.22.0
270
+ wavedrom==2.0.3.post3
271
+ wcwidth==0.2.13
272
+ webcolors==1.13
273
+ webdataset==0.2.86
274
+ webencodings==0.5.1
275
+ websocket-client==1.5.1
276
+ websockets==11.0.2
277
+ wheel==0.38.4
278
+ widgetsnbextension==4.0.11
279
+ yacs==0.1.8
280
+ yarl==1.9.2
281
+ zipp==3.17.0
282
+ --extra-index-url https://download.pytorch.org/whl/cu113
283
+ torch==2.2.1
static/logo.png ADDED
static/logo.svg ADDED
videollava/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .model import LlavaLlamaForCausalLM
videollava/constants.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_TOKEN_INDEX = -200
10
+ DEFAULT_IMAGE_TOKEN = "<image>"
11
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
12
+ DEFAULT_IM_START_TOKEN = "<im_start>"
13
+ DEFAULT_IM_END_TOKEN = "<im_end>"
14
+ IMAGE_PLACEHOLDER = "<image-placeholder>"
15
+
16
+ # ======================================================================================================
17
+ DEFAULT_VIDEO_TOKEN = "<video>"
18
+ DEFAULT_VIDEO_PATCH_TOKEN = "<im_patch>"
19
+ DEFAULT_VID_START_TOKEN = "<vid_start>"
20
+ DEFAULT_VID_END_TOKEN = "<vid_end>"
21
+ VIDEO_PLACEHOLDER = "<video-placeholder>"
22
+ # ======================================================================================================
23
+
24
+ MAX_IMAGE_LENGTH = 16
25
+ MAX_VIDEO_LENGTH = 1 # current video datasets only have 1 video?
26
+
27
+ PAD_LENGTH = 620
videollava/conversation.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from enum import auto, Enum
3
+ from typing import List, Tuple
4
+
5
+
6
+ class SeparatorStyle(Enum):
7
+ """Different separator style."""
8
+ SINGLE = auto()
9
+ TWO = auto()
10
+ MPT = auto()
11
+ PLAIN = auto()
12
+ LLAMA_2 = auto()
13
+
14
+
15
+ @dataclasses.dataclass
16
+ class Conversation:
17
+ """A class that keeps all conversation history."""
18
+ system: str
19
+ roles: List[str]
20
+ messages: List[List[str]]
21
+ offset: int
22
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
23
+ sep: str = "###"
24
+ sep2: str = None
25
+ version: str = "Unknown"
26
+
27
+ skip_next: bool = False
28
+
29
+ def get_prompt(self):
30
+ messages = self.messages
31
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
32
+ messages = self.messages.copy()
33
+ init_role, init_msg = messages[0].copy()
34
+ init_msg = init_msg[0].replace("<image>", "").strip()
35
+ if 'mmtag' in self.version:
36
+ messages[0] = (init_role, init_msg)
37
+ messages.insert(0, (self.roles[0], "<Image><image></Image>"))
38
+ messages.insert(1, (self.roles[1], "Received."))
39
+ else:
40
+ messages[0] = (init_role, "<image>\n" + init_msg)
41
+
42
+ if self.sep_style == SeparatorStyle.SINGLE:
43
+ ret = self.system + self.sep
44
+ for role, message in messages:
45
+ if message:
46
+ if type(message) is tuple:
47
+ message, _, _ = message
48
+ ret += role + ": " + message + self.sep
49
+ else:
50
+ ret += role + ":"
51
+ elif self.sep_style == SeparatorStyle.TWO:
52
+ seps = [self.sep, self.sep2]
53
+ ret = self.system + seps[0]
54
+ for i, (role, message) in enumerate(messages):
55
+ if message:
56
+ if type(message) is tuple:
57
+ message, _, _ = message
58
+ ret += role + ": " + message + seps[i % 2]
59
+ else:
60
+ ret += role + ":"
61
+ elif self.sep_style == SeparatorStyle.MPT:
62
+ ret = self.system + self.sep
63
+ for role, message in messages:
64
+ if message:
65
+ if type(message) is tuple:
66
+ message, _, _ = message
67
+ ret += role + message + self.sep
68
+ else:
69
+ ret += role
70
+ elif self.sep_style == SeparatorStyle.LLAMA_2:
71
+ wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
72
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
73
+ ret = ""
74
+
75
+ for i, (role, message) in enumerate(messages):
76
+ if i == 0:
77
+ assert message, "first message should not be none"
78
+ assert role == self.roles[0], "first message should come from user"
79
+ if message:
80
+ if type(message) is tuple:
81
+ message, _, _ = message
82
+ if i == 0: message = wrap_sys(self.system) + message
83
+ if i % 2 == 0:
84
+ message = wrap_inst(message)
85
+ ret += self.sep + message
86
+ else:
87
+ ret += " " + message + " " + self.sep2
88
+ else:
89
+ ret += ""
90
+ ret = ret.lstrip(self.sep)
91
+ elif self.sep_style == SeparatorStyle.PLAIN:
92
+ seps = [self.sep, self.sep2]
93
+ ret = self.system
94
+ for i, (role, message) in enumerate(messages):
95
+ if message:
96
+ if type(message) is tuple:
97
+ message, _, _ = message
98
+ ret += message + seps[i % 2]
99
+ else:
100
+ ret += ""
101
+ else:
102
+ raise ValueError(f"Invalid style: {self.sep_style}")
103
+
104
+ return ret
105
+
106
+ def append_message(self, role, message):
107
+ self.messages.append([role, message])
108
+
109
+ def get_images(self, return_pil=False):
110
+ images = []
111
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
112
+ if i % 2 == 0:
113
+ if type(msg) is tuple:
114
+ import base64
115
+ from io import BytesIO
116
+ from PIL import Image
117
+ msg, image, image_process_mode = msg
118
+ if image_process_mode == "Pad":
119
+ def expand2square(pil_img, background_color=(122, 116, 104)):
120
+ width, height = pil_img.size
121
+ if width == height:
122
+ return pil_img
123
+ elif width > height:
124
+ result = Image.new(pil_img.mode, (width, width), background_color)
125
+ result.paste(pil_img, (0, (width - height) // 2))
126
+ return result
127
+ else:
128
+ result = Image.new(pil_img.mode, (height, height), background_color)
129
+ result.paste(pil_img, ((height - width) // 2, 0))
130
+ return result
131
+ image = expand2square(image)
132
+ elif image_process_mode in ["Default", "Crop"]:
133
+ pass
134
+ elif image_process_mode == "Resize":
135
+ image = image.resize((336, 336))
136
+ else:
137
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
138
+ max_hw, min_hw = max(image.size), min(image.size)
139
+ aspect_ratio = max_hw / min_hw
140
+ max_len, min_len = 800, 400
141
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
142
+ longest_edge = int(shortest_edge * aspect_ratio)
143
+ W, H = image.size
144
+ if longest_edge != max(image.size):
145
+ if H > W:
146
+ H, W = longest_edge, shortest_edge
147
+ else:
148
+ H, W = shortest_edge, longest_edge
149
+ image = image.resize((W, H))
150
+ if return_pil:
151
+ images.append(image)
152
+ else:
153
+ buffered = BytesIO()
154
+ image.save(buffered, format="PNG")
155
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
156
+ images.append(img_b64_str)
157
+ return images
158
+
159
+ def to_gradio_chatbot(self):
160
+ ret = []
161
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
162
+ if i % 2 == 0:
163
+ if type(msg) is tuple:
164
+ import base64
165
+ from io import BytesIO
166
+ msg, image, image_process_mode = msg
167
+ max_hw, min_hw = max(image.size), min(image.size)
168
+ aspect_ratio = max_hw / min_hw
169
+ max_len, min_len = 800, 400
170
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
171
+ longest_edge = int(shortest_edge * aspect_ratio)
172
+ W, H = image.size
173
+ if H > W:
174
+ H, W = longest_edge, shortest_edge
175
+ else:
176
+ H, W = shortest_edge, longest_edge
177
+ image = image.resize((W, H))
178
+ buffered = BytesIO()
179
+ image.save(buffered, format="JPEG")
180
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
181
+ img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
182
+ msg = img_str + msg.replace('<image>', '').strip()
183
+ ret.append([msg, None])
184
+ else:
185
+ ret.append([msg, None])
186
+ else:
187
+ ret[-1][-1] = msg
188
+ return ret
189
+
190
+ def copy(self):
191
+ return Conversation(
192
+ system=self.system,
193
+ roles=self.roles,
194
+ messages=[[x, y] for x, y in self.messages],
195
+ offset=self.offset,
196
+ sep_style=self.sep_style,
197
+ sep=self.sep,
198
+ sep2=self.sep2,
199
+ version=self.version)
200
+
201
+ def dict(self):
202
+ if len(self.get_images()) > 0:
203
+ return {
204
+ "system": self.system,
205
+ "roles": self.roles,
206
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
207
+ "offset": self.offset,
208
+ "sep": self.sep,
209
+ "sep2": self.sep2,
210
+ }
211
+ return {
212
+ "system": self.system,
213
+ "roles": self.roles,
214
+ "messages": self.messages,
215
+ "offset": self.offset,
216
+ "sep": self.sep,
217
+ "sep2": self.sep2,
218
+ }
219
+
220
+
221
+ conv_vicuna_v0 = Conversation(
222
+ system="A chat between a curious human and an artificial intelligence assistant. "
223
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
224
+ roles=("Human", "Assistant"),
225
+ messages=(
226
+ ("Human", "What are the key differences between renewable and non-renewable energy sources?"),
227
+ ("Assistant",
228
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
229
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
230
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
231
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
232
+ "renewable and non-renewable energy sources:\n"
233
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
234
+ "energy sources are finite and will eventually run out.\n"
235
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
236
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
237
+ "and other negative effects.\n"
238
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
239
+ "have lower operational costs than non-renewable sources.\n"
240
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
241
+ "locations than non-renewable sources.\n"
242
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
243
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
244
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
245
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
246
+ ),
247
+ offset=2,
248
+ sep_style=SeparatorStyle.SINGLE,
249
+ sep="###",
250
+ )
251
+
252
+ conv_vicuna_v1 = Conversation(
253
+ system="A chat between a curious user and an artificial intelligence assistant. "
254
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
255
+ roles=("USER", "ASSISTANT"),
256
+ version="v1",
257
+ messages=(),
258
+ offset=0,
259
+ sep_style=SeparatorStyle.TWO,
260
+ sep=" ",
261
+ sep2="</s>",
262
+ )
263
+
264
+ conv_llama_2 = Conversation(
265
+ 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.
266
+
267
+ 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.""",
268
+ roles=("USER", "ASSISTANT"),
269
+ version="llama_v2",
270
+ messages=(),
271
+ offset=0,
272
+ sep_style=SeparatorStyle.LLAMA_2,
273
+ sep="<s>",
274
+ sep2="</s>",
275
+ )
276
+
277
+ conv_llava_llama_2 = Conversation(
278
+ system="You are a helpful language and vision assistant. "
279
+ "You are able to understand the visual content that the user provides, "
280
+ "and assist the user with a variety of tasks using natural language.",
281
+ roles=("USER", "ASSISTANT"),
282
+ version="llama_v2",
283
+ messages=(),
284
+ offset=0,
285
+ sep_style=SeparatorStyle.LLAMA_2,
286
+ sep="<s>",
287
+ sep2="</s>",
288
+ )
289
+
290
+ conv_mpt = Conversation(
291
+ system="""<|im_start|>system
292
+ A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
293
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
294
+ version="mpt",
295
+ messages=(),
296
+ offset=0,
297
+ sep_style=SeparatorStyle.MPT,
298
+ sep="<|im_end|>",
299
+ )
300
+
301
+ conv_llava_plain = Conversation(
302
+ system="",
303
+ roles=("", ""),
304
+ messages=(
305
+ ),
306
+ offset=0,
307
+ sep_style=SeparatorStyle.PLAIN,
308
+ sep="\n",
309
+ )
310
+
311
+ conv_llava_v0 = Conversation(
312
+ system="A chat between a curious human and an artificial intelligence assistant. "
313
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
314
+ roles=("Human", "Assistant"),
315
+ messages=(
316
+ ),
317
+ offset=0,
318
+ sep_style=SeparatorStyle.SINGLE,
319
+ sep="###",
320
+ )
321
+
322
+ conv_llava_v0_mmtag = Conversation(
323
+ system="A chat between a curious user and an artificial intelligence assistant. "
324
+ "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."
325
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
326
+ roles=("Human", "Assistant"),
327
+ messages=(
328
+ ),
329
+ offset=0,
330
+ sep_style=SeparatorStyle.SINGLE,
331
+ sep="###",
332
+ version="v0_mmtag",
333
+ )
334
+
335
+ conv_llava_v1 = Conversation(
336
+ system="A chat between a curious human and an artificial intelligence assistant. "
337
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
338
+ roles=("USER", "ASSISTANT"),
339
+ version="v1",
340
+ messages=(),
341
+ offset=0,
342
+ sep_style=SeparatorStyle.TWO,
343
+ sep=" ",
344
+ sep2="</s>",
345
+ )
346
+
347
+ conv_llava_v1_mmtag = Conversation(
348
+ system="A chat between a curious user and an artificial intelligence assistant. "
349
+ "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."
350
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
351
+ roles=("USER", "ASSISTANT"),
352
+ messages=(),
353
+ offset=0,
354
+ sep_style=SeparatorStyle.TWO,
355
+ sep=" ",
356
+ sep2="</s>",
357
+ version="v1_mmtag",
358
+ )
359
+
360
+ default_conversation = conv_vicuna_v1
361
+ conv_templates = {
362
+ "default": conv_vicuna_v0,
363
+ "v0": conv_vicuna_v0,
364
+ "v1": conv_vicuna_v1,
365
+ "vicuna_v1": conv_vicuna_v1,
366
+ "llama_2": conv_llama_2,
367
+
368
+ "plain": conv_llava_plain,
369
+ "v0_plain": conv_llava_plain,
370
+ "llava_v0": conv_llava_v0,
371
+ "v0_mmtag": conv_llava_v0_mmtag,
372
+ "llava_v1": conv_llava_v1,
373
+ "v1_mmtag": conv_llava_v1_mmtag,
374
+ "llava_llama_2": conv_llava_llama_2,
375
+
376
+ "mpt": conv_mpt,
377
+ }
378
+
379
+
380
+ if __name__ == "__main__":
381
+ print(default_conversation.get_prompt())
videollava/eval/aid_fmow_ucmerced_utils.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import numpy as np
3
+ from tqdm import tqdm
4
+ from pathlib import Path
5
+
6
+ from infer_utils import run_inference_single
7
+ # For the purposes of an experiment, change the infer_utils to:
8
+ # from infer_utils_mod import run_inference_single
9
+
10
+ def run_aid_fmow_ucmerced_inference(
11
+ model,
12
+ dataset_path,
13
+ processor,
14
+ tokenizer,
15
+ conv_mode,
16
+ use_video_data=False,
17
+ open_prompt=None,
18
+ repeat_frames=None,
19
+ prompt_strategy="interleave",
20
+ chronological_prefix=True,
21
+ data_frac=1,
22
+ data_size=None,
23
+ delete_system_prompt=False,
24
+ last_image=False,
25
+ print_prompt=False,
26
+ **kwargs
27
+ ):
28
+ for k, v in kwargs.items():
29
+ print("WARNING: Unused argument:", k, v)
30
+
31
+ try:
32
+ with open(dataset_path) as f:
33
+ data = json.load(f)
34
+ except:
35
+ data = []
36
+ with open(dataset_path) as f:
37
+ for line in f:
38
+ question = json.loads(line)
39
+ question["id"] = question["question_id"]
40
+ question["conversations"] = [
41
+ {"value": "This is a satellite image: <video> " + question["text"]},
42
+ {"value": question["ground_truth"]}
43
+ ]
44
+ question["video"] = [question["image"]]
45
+ data.append(question)
46
+
47
+ if data_size is not None:
48
+ data_size = min(data_size, len(data))
49
+ idx = np.random.choice(len(data), data_size, replace=False)
50
+ data = [data[i] for i in idx]
51
+ elif data_frac < 1:
52
+ idx = np.random.choice(len(data), int(len(data) * data_frac), replace=False)
53
+ data = [data[i] for i in idx]
54
+
55
+ vision_key = "video" if "video" in data[0] else "image"
56
+
57
+ answers = {}
58
+ for question in tqdm(data):
59
+ question_id = question["id"]
60
+ inp = question["conversations"][0]['value']
61
+ if open_prompt == "open":
62
+ # Use an open framing for the question
63
+ inp = inp.split("Which")[0] + "Which class does this image belong to?"
64
+ elif open_prompt == "multi-open":
65
+ inp = inp.split("Which")[0] + "What classes does this image belong to?"
66
+ answer_str = question["conversations"][1]['value']
67
+ if 'metadata' not in question:
68
+ question['metadata'] = None
69
+ metadata = question['metadata']
70
+ image_paths = question[vision_key]
71
+
72
+ outputs = run_inference_single(
73
+ model=model,
74
+ processor=processor,
75
+ tokenizer=tokenizer,
76
+ conv_mode=conv_mode,
77
+ inp=inp,
78
+ image_paths=image_paths,
79
+ metadata=metadata,
80
+ use_video_data=use_video_data,
81
+ repeat_frames=repeat_frames,
82
+ prompt_strategy=prompt_strategy,
83
+ chronological_prefix=chronological_prefix,
84
+ delete_system_prompt=delete_system_prompt,
85
+ last_image=last_image,
86
+ print_prompt=print_prompt
87
+ )
88
+
89
+ answers[question_id] = {
90
+ "predicted": outputs,
91
+ "ground_truth": answer_str
92
+ }
93
+
94
+ return answers
videollava/eval/ben_utils.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import numpy as np
3
+ from tqdm import tqdm
4
+ from pathlib import Path
5
+
6
+ from videollava.constants import DEFAULT_IMAGE_TOKEN
7
+
8
+ from infer_utils import run_inference_single
9
+
10
+
11
+ def run_ben_inference(
12
+ model,
13
+ dataset_path,
14
+ processor,
15
+ tokenizer,
16
+ conv_mode,
17
+ use_video_data=False,
18
+ open_prompt=None,
19
+ repeat_frames=None,
20
+ prompt_strategy="interleave",
21
+ chronological_prefix=True,
22
+ data_frac=1,
23
+ data_size=None,
24
+ delete_system_prompt=False,
25
+ last_image=False,
26
+ start_ind=None,
27
+ end_ind=None,
28
+ print_prompt=False,
29
+ **kwargs
30
+ ):
31
+ for k, v in kwargs.items():
32
+ print("WARNING: Unused argument:", k, v)
33
+
34
+ dataset_path = Path(dataset_path)
35
+ data_dir = dataset_path.parent
36
+ questions_path = data_dir / dataset_path.name.replace(".json", "_questions.json")
37
+ answers_path = data_dir / dataset_path.name.replace(".json", "_answers.json")
38
+ images_path = data_dir / dataset_path.name.replace(".json", "_images.json")
39
+
40
+ with open(questions_path) as json_data:
41
+ questionsJSON = json.load(json_data)
42
+
43
+ with open(answers_path) as json_data:
44
+ answersJSON = json.load(json_data)
45
+
46
+ with open(images_path) as json_data:
47
+ imagesJSON = json.load(json_data)
48
+
49
+ if data_size is not None:
50
+ data_size = min(data_size, len(questionsJSON))
51
+ idx = np.random.choice(len(questionsJSON), data_size, replace=False)
52
+ imagesJSON = [imagesJSON[i] for i in idx]
53
+ elif data_frac < 1:
54
+ idx = np.random.choice(len(questionsJSON), int(len(questionsJSON) * data_frac), replace=False)
55
+ imagesJSON = [imagesJSON[i] for i in idx]
56
+
57
+ if 'LRBEN' in str(dataset_path):
58
+ image_folder = 'Images_LR'
59
+ else:
60
+ image_folder = 'Data'
61
+
62
+ # Get the image IDs of test images
63
+ images_ids = [img['id'] for img in imagesJSON['images'] if img['active']]
64
+
65
+ if start_ind is not None and end_ind is not None:
66
+ print("Subsetting data from index", start_ind, "to", end_ind)
67
+ images_ids = images_ids[start_ind:end_ind]
68
+ elif start_ind is not None:
69
+ print("Subsetting data from index", start_ind, "to end")
70
+ images_ids = images_ids[start_ind:]
71
+ elif end_ind is not None:
72
+ print("Subsetting data from start to index", end_ind)
73
+ images_ids = images_ids[:end_ind]
74
+
75
+ # Store all predicted answers
76
+ answers = {}
77
+ # Read image corresponding to each ID and get its associated question and answer
78
+ for id in tqdm(images_ids):
79
+
80
+ image_paths = [str(data_dir / image_folder / (str(id)+'.tif'))]
81
+
82
+ for questionid in imagesJSON['images'][id]['questions_ids']:
83
+ question = questionsJSON['questions'][questionid]
84
+ if not question['active']:
85
+ continue
86
+ inp = question["question"] + " Answer with one word or number."
87
+ inp = DEFAULT_IMAGE_TOKEN + '\n' + inp
88
+ type_str = question["type"]
89
+ answer_str = answersJSON['answers'][question["answers_ids"][0]]['answer']
90
+
91
+ outputs = run_inference_single(
92
+ model=model,
93
+ processor=processor,
94
+ tokenizer=tokenizer,
95
+ conv_mode=conv_mode,
96
+ inp=inp,
97
+ image_paths=image_paths,
98
+ metadata=None,
99
+ use_video_data=use_video_data,
100
+ repeat_frames=repeat_frames,
101
+ prompt_strategy=prompt_strategy,
102
+ chronological_prefix=chronological_prefix,
103
+ delete_system_prompt=delete_system_prompt,
104
+ last_image=last_image,
105
+ print_prompt=print_prompt
106
+ )
107
+
108
+ answers[f"{id}_{questionid}"] = {
109
+ "predicted": outputs,
110
+ "ground_truth": answer_str,
111
+ "task": type_str
112
+ }
113
+
114
+ return answers
videollava/eval/cdvqa_utils.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import numpy as np
3
+ from tqdm import tqdm
4
+ from pathlib import Path
5
+
6
+ from videollava.constants import DEFAULT_VIDEO_TOKEN
7
+
8
+ from infer_utils import run_inference_single
9
+
10
+
11
+ def run_cdvqa_inference(
12
+ model,
13
+ dataset_path,
14
+ processor,
15
+ tokenizer,
16
+ conv_mode,
17
+ use_video_data=False,
18
+ open_prompt=None,
19
+ repeat_frames=None,
20
+ prompt_strategy="interleave",
21
+ chronological_prefix=True,
22
+ data_frac=1,
23
+ data_size=None,
24
+ delete_system_prompt=False,
25
+ last_image=False,
26
+ start_ind=None,
27
+ end_ind=None,
28
+ print_prompt=False,
29
+ **kwargs
30
+ ):
31
+ for k, v in kwargs.items():
32
+ print("WARNING: Unused argument:", k, v)
33
+
34
+ dataset_path = Path(dataset_path)
35
+ data_dir = dataset_path.parent
36
+ questions_path = data_dir / dataset_path.name.replace(".json", "_questions.json")
37
+ answers_path = data_dir / dataset_path.name.replace(".json", "_answers.json")
38
+ images_path = data_dir / dataset_path.name.replace(".json", "_images.json")
39
+
40
+ with open(questions_path) as json_data:
41
+ questionsJSON = json.load(json_data)
42
+
43
+ with open(answers_path) as json_data:
44
+ answersJSON = json.load(json_data)
45
+
46
+ with open(images_path) as json_data:
47
+ imagesJSON = json.load(json_data)
48
+
49
+ if data_size is not None:
50
+ data_size = min(data_size, len(questionsJSON))
51
+ idx = np.random.choice(len(questionsJSON), data_size, replace=False)
52
+ imagesJSON = [imagesJSON[i] for i in idx]
53
+ elif data_frac < 1:
54
+ idx = np.random.choice(len(questionsJSON), int(len(questionsJSON) * data_frac), replace=False)
55
+ imagesJSON = [imagesJSON[i] for i in idx]
56
+
57
+ # Get the image IDs of test images
58
+ images_ids = [img['id'] for img in imagesJSON['images'] if img['active']]
59
+
60
+ if start_ind is not None and end_ind is not None:
61
+ print("Subsetting data from index", start_ind, "to", end_ind)
62
+ images_ids = images_ids[start_ind:end_ind]
63
+ elif start_ind is not None:
64
+ print("Subsetting data from index", start_ind, "to end")
65
+ images_ids = images_ids[start_ind:]
66
+ elif end_ind is not None:
67
+ print("Subsetting data from start to index", end_ind)
68
+ images_ids = images_ids[:end_ind]
69
+
70
+ # Store all predicted answers
71
+ answers = {}
72
+ # Read image corresponding to each ID and get its associated question and answer
73
+ for id in tqdm(images_ids):
74
+ file_name = imagesJSON['images'][id]['file_name']
75
+
76
+ image_paths = [
77
+ str(data_dir / "second_dataset" / "im1" / file_name),
78
+ str(data_dir / "second_dataset" / "im2" / file_name),
79
+ ]
80
+
81
+ for questionid in imagesJSON['images'][id]['questions_ids']:
82
+ question = questionsJSON['questions'][questionid]
83
+ if not question['active']:
84
+ continue
85
+ inp = "This is a pair of satellite images capturing the same location at different times: "
86
+ inp = inp + DEFAULT_VIDEO_TOKEN + '\n'
87
+ inp = inp + question["question"]
88
+ type_str = question["type"]
89
+ answer_str = answersJSON['answers'][question["answers_ids"][0]]['answer']
90
+
91
+ if type_str in ["change_or_not", "increase_or_not", "decrease_or_not"]:
92
+ inp = inp + " Answer with yes or no."
93
+
94
+ elif type_str == "change_ratio":
95
+ inp = inp + " Choose from one of the following options: 0, 0_to_10, 10_to_20, 20_to_30, 30_to_40, 40_to_50, 50_to_60, 60_to_70, 70_to_80, 80_to_90, 90_to_100."
96
+
97
+ elif type_str == "change_ratio_types":
98
+ inp = inp + " Choose from one of the following options: 0, 0_to_10, 10_to_20, 20_to_30, 30_to_40, 40_to_50, 50_to_60, 60_to_70."
99
+
100
+ else: # smallest_change, largest_change, change_to_what
101
+ inp = inp + " Choose from one of the following options: buildings, low_vegetation, nonvegetated ground surface, playgrounds, trees, water."
102
+ answer_str = answer_str.replace("NVG_surface", "nonvegetated ground surface")
103
+
104
+ outputs = run_inference_single(
105
+ model=model,
106
+ processor=processor,
107
+ tokenizer=tokenizer,
108
+ conv_mode=conv_mode,
109
+ inp=inp,
110
+ image_paths=image_paths,
111
+ metadata=None,
112
+ use_video_data=use_video_data,
113
+ repeat_frames=repeat_frames,
114
+ prompt_strategy=prompt_strategy,
115
+ chronological_prefix=chronological_prefix,
116
+ delete_system_prompt=delete_system_prompt,
117
+ last_image=last_image,
118
+ print_prompt=print_prompt
119
+ )
120
+
121
+ answers[f"{id}_{questionid}"] = {
122
+ "predicted": outputs,
123
+ "ground_truth": answer_str,
124
+ "task": type_str
125
+ }
126
+
127
+ return answers
videollava/eval/classification_segmentation.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import numpy as np
3
+ from infer_utils import create_mask
4
+ from shapely.wkt import loads
5
+ from collections import defaultdict
6
+ from tqdm import tqdm
7
+
8
+ def clean_string(s):
9
+ return s.replace(' ', '-').replace('.', '').lower()
10
+
11
+ def get_class_dict(dataset):
12
+ if dataset == "qfabric":
13
+ class_dict = {
14
+ "temporal_region_based_question_answering: What is the development status in this region [bbox] in image N?":
15
+ {
16
+ "prior-construction": 1,
17
+ "greenland ": 2,
18
+ "land-cleared": 3,
19
+ "excavation": 4,
20
+ "materials-dumped": 5,
21
+ "construction-started": 6,
22
+ "construction-midway": 7,
23
+ "construction-done": 8,
24
+ "operational": 9
25
+ },
26
+ "region_based_question_answering: Identify the type of urban development that has occurred in this area [bbox].":
27
+ {
28
+ "residential": 10,
29
+ "commercial": 11,
30
+ "industrial": 12,
31
+ "road": 13,
32
+ "demolition": 14,
33
+ "mega-projects": 15
34
+ }
35
+ }
36
+ elif dataset == "xbd":
37
+ class_dict = {
38
+ "classification: Classify the level of damage experienced by the building at location [bbox] in the second image. Choose from: No damage, Minor Damage, Major Damage, Destroyed.":
39
+ {
40
+ "no-damage": 1,
41
+ "minor-damage": 2,
42
+ "major-damage": 3,
43
+ "destroyed": 4,
44
+ }
45
+ }
46
+ else:
47
+ raise ValueError(f"Dataset {dataset} should not be evaluated on segmentation classification.")
48
+ return class_dict
49
+
50
+
51
+
52
+ def classification_segmentation(answer_path, dataset, per_class_f1=False, height=256, width=256):
53
+ """
54
+ Given the path to the answer file, this function creates segmentation masks on the original polygon for the predicted and ground truth classes.
55
+ Returns the class-weighted per-pixel F1 between predicted and ground-truth masks.
56
+ """
57
+ with open(answer_path) as f:
58
+ results = json.load(f)
59
+
60
+ classes = get_class_dict(dataset)
61
+ class_stats = defaultdict(lambda: {'tp': 0, 'fp': 0, 'fn': 0, 'count': 0})
62
+
63
+ for result in tqdm(results.values()):
64
+ if result['task'] not in classes:
65
+ continue
66
+ class_dict = classes[result['task']]
67
+ predicted_class = clean_string(result['predicted'])
68
+ try:
69
+ ground_truth_class = clean_string(result["ground_truth"])
70
+ except:
71
+ ground_truth_class = clean_string(result["original_answer"])
72
+ original_polygon = loads(result['original_input_polygon'])
73
+
74
+ pred_msk = np.zeros((height, width), dtype='uint8')
75
+ gt_msk = np.zeros((height, width), dtype='uint8')
76
+ _msk = create_mask(original_polygon, im_size=(height, width))
77
+
78
+ if predicted_class not in class_dict or ground_truth_class not in class_dict:
79
+ continue
80
+
81
+ pred_label = class_dict[predicted_class]
82
+ gt_label = class_dict[ground_truth_class]
83
+ pred_msk[_msk > 0] = pred_label
84
+ gt_msk[_msk > 0] = gt_label
85
+
86
+ for label in class_dict.values():
87
+ pred_mask = (pred_msk == label)
88
+ gt_mask = (gt_msk == label)
89
+ tp = np.sum(pred_mask & gt_mask)
90
+ fp = np.sum(pred_mask & ~gt_mask)
91
+ fn = np.sum(~pred_mask & gt_mask)
92
+
93
+ class_stats[label]['tp'] += tp
94
+ class_stats[label]['fp'] += fp
95
+ class_stats[label]['fn'] += fn
96
+ class_stats[label]['count'] += np.sum(gt_mask)
97
+
98
+
99
+ scores_dict = {}
100
+
101
+ for task, class_info in classes.items():
102
+ print(f"Task: {task}")
103
+ class_f1_scores = {}
104
+ weighted_f1_score = 0
105
+ total_weight = 0
106
+
107
+ tp = 0
108
+ fp = 0
109
+ fn = 0
110
+ for class_name, class_label in class_info.items():
111
+ stats = class_stats[class_label]
112
+ total_samples = sum(stats['count'] for label, stats in class_stats.items() if label in class_info.values())
113
+
114
+ if stats['tp'] + stats['fp'] == 0 or stats['tp'] + stats['fn'] == 0:
115
+ f1 = 0.0
116
+ else:
117
+ precision = stats['tp'] / (stats['tp'] + stats['fp'])
118
+ recall = stats['tp'] / (stats['tp'] + stats['fn'])
119
+ if precision + recall == 0:
120
+ f1 = 0.0
121
+ else:
122
+ f1 = 2 * (precision * recall) / (precision + recall)
123
+ class_f1_scores[class_name] = f1
124
+
125
+ if stats['count'] > 0:
126
+ prevalence_inv = total_samples / stats['count']
127
+ weighted_f1_score += f1 * prevalence_inv
128
+ total_weight += prevalence_inv
129
+
130
+ tp += stats['tp']
131
+ fp += stats['fp']
132
+ fn += stats['fn']
133
+
134
+ if tp + fp == 0 or tp + fn == 0:
135
+ micro_f1 = 0.0
136
+ else:
137
+ micro_f1 = tp / (tp + 0.5 * (fp + fn))
138
+
139
+ if total_weight > 0:
140
+ weighted_f1_score /= total_weight
141
+ else:
142
+ weighted_f1_score = 0.0
143
+
144
+ scores_dict[task] = (class_f1_scores, weighted_f1_score)
145
+ print(f"Per-class F1 scores: {class_f1_scores}")
146
+ if dataset == 'qfabric':
147
+ print(f"Micro average F1 score: ", micro_f1)
148
+ else:
149
+ print(f"Weighted average F1 score: {weighted_f1_score}")
150
+
151
+ return scores_dict
videollava/eval/datasets_into_geochat_format.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import re
3
+ import json
4
+
5
+ def qfabric_semiconverted_to_geochat_dataset_format(json_file):
6
+ with open(json_file) as f:
7
+ data = json.load(f)
8
+ for conversation_group in data:
9
+ for item in conversation_group["conversations"]:
10
+ # Remove satellite specifications
11
+ item["value"] = re.sub(r"This is a satellite image :", "", item["value"])
12
+ item["value"] = re.sub(r"This is a satellite image:", "", item["value"])
13
+ item["value"] = re.sub(r"This is a high resolution, optical satellite image .*?:\s*", "", item["value"])
14
+ item["value"] = re.sub(r"This is a high resolution, optical satellite image.*?:\s*", "", item["value"])
15
+ item["value"] = re.sub(r"This is a satellite image from .*?:\s*", "", item["value"])
16
+ item["value"] = re.sub(r"This is a satellite image from.*?:\s*", "", item["value"])
17
+ # Remove strings around <identify> that are redundant
18
+ item["value"] = re.sub(r'What is <identify>|this area {<', lambda x: '[identify]' if 'What is [identify]' in x.group() else '{<', item["value"])
19
+ # Switch out <video> for <image>
20
+ item["value"] = re.sub(r'<video>', '', item["value"])
21
+ # Get rid of "this region" immediately before the bounding box
22
+ item["value"] = re.sub(r'this region {<', '{<', item["value"])
23
+ # Check for the presence of '<identify>' and modify the string accordingly
24
+ if '[identify]' in item["value"]:
25
+ # Find the position of '<identify>' and the position of the first occurrence of '>}' after '<identify>'
26
+ identify_index = item["value"].find('[identify]')
27
+ identify_word_index = item["value"].find('Identify ', identify_index + 8)
28
+ # if identify_word_index != -1:
29
+ # item["value"] = item["value"][:identify_word_index] + item["value"][identify_word_index + 8:]
30
+ closing_brace_index = item["value"].find('>}', identify_index)
31
+ return data
32
+
33
+ def fmow_to_geochat_dataset_format(json_file):
34
+ with open(json_file) as f:
35
+ data = json.load(f)
36
+ for i, entry in enumerate(data):
37
+ video_count = len(entry.get("video", []))
38
+ if video_count > 1:
39
+ original_videos = entry["video"]
40
+ for idx in range(video_count):
41
+ new_entry = entry.copy()
42
+ new_entry['video'] = [original_videos[idx]]
43
+ new_entry['image'] = original_videos[idx]
44
+ new_entry['linked_id'] = entry['id']
45
+ new_entry['img_idx_from_video_lst_id'] = idx
46
+ data.append(new_entry)
47
+ else:
48
+ new_entry = entry.copy()
49
+ new_entry['image'] = original_videos[0]
50
+ for conversation_group in data:
51
+ for item in conversation_group["conversations"]:
52
+ item["value"] = re.sub(r"This is a satellite image :", "", item["value"])
53
+ item["value"] = re.sub(r"This is a satellite image:", "", item["value"])
54
+ item["value"] = re.sub(r"This is a high resolution, optical satellite image .*?:\s*", "", item["value"])
55
+ item["value"] = re.sub(r"This is a high resolution, optical satellite image.*?:\s*", "", item["value"])
56
+ item["value"] = re.sub(r"This is a satellite image from .*?:\s*", "", item["value"])
57
+ item["value"] = re.sub(r"This is a satellite image from.*?:\s*", "", item["value"])
58
+ item["value"] = re.sub(r"This is a sequence of low-resolution, optical satellite images capturing the same location at different times: ", "", item["value"])
59
+ item["value"] = re.sub(r"This is a sequence of high-resolution, optical satellite images capturing the same location at different times:", "", item["value"])
60
+ item["value"] = re.sub(r"This is a sequence of satellite images capturing the same location at different times:", "", item["value"])
61
+ item["value"] = re.sub(r"This is a sequence of satellite images from .*? the same location at different times:", "", item["value"])
62
+ item["value"] = re.sub(r'This is a high resolution,? optical satellite image .*:\s*<image>\n', '\n', item["value"])
63
+ item["value"] = re.sub(r'^This is a high[- ]resolution,? .*?image:\s*<image>\n', '\n', item["value"], flags=re.IGNORECASE | re.DOTALL)
64
+
65
+ # Switch out <video> for <image>
66
+ item["value"] = re.sub(r'<video>', '', item["value"])
67
+ # Get rid of "this region" immediately before the bounding box
68
+ item["value"] = re.sub(r'this region {<', '{<', item["value"])
69
+ # Which class
70
+ item["value"] = re.sub(r'Which of the following classes does this sequence of images belong to', 'Which of the following classes does this image belong to', item["value"])
71
+ # Please answer using one of the following classes:
72
+ item["value"] = re.sub(r'Please answer using only one of the following classes:', 'Please use one of the following classes:', item["value"])
73
+ # Check for the presence of '<identify>' and modify the string accordingly
74
+ if '[identify]' in item["value"]:
75
+ # Find the position of '<identify>' and the position of the first occurrence of '>}' after '<identify>'
76
+ identify_index = item["value"].find('[identify]')
77
+ for i, entry in enumerate(data):
78
+ video_count = len(entry.get("video", []))
79
+ if video_count > 1:
80
+ data.pop(i)
81
+ return data
82
+
83
+ def xbd_to_geochat_dataset_format(json_file):
84
+
85
+ with open(json_file) as f:
86
+ data = json.load(f)
87
+
88
+ new_data = []
89
+ for i, entry in enumerate(data):
90
+ if entry["task"].startswith("localization"):
91
+ new_entry=entry.copy()
92
+ new_entry['image'] = entry['video'][0]
93
+ new_data.append(new_entry)
94
+ if entry["task"].startswith("classification"):
95
+ new_entry=entry.copy()
96
+ new_entry['image'] = entry['video'][1]
97
+ new_data.append(new_entry)
98
+ # Auxiliary tasks all look at the second image
99
+ else:
100
+ new_entry=entry.copy()
101
+ new_entry['image'] = entry['video'][1]
102
+ new_data.append(new_entry)
103
+
104
+ for conversation_group in new_data:
105
+ localization=False
106
+ classification=False
107
+ #Β Add a [refer] token to localization tasks
108
+ if conversation_group["task"].startswith("localization") or "identify" in conversation_group["task"].lower():
109
+ localization=True
110
+ # Add a [identify] token to classification tasks
111
+ if conversation_group["task"].startswith("classification"):
112
+ classification=True
113
+
114
+ for item in conversation_group["conversations"]:
115
+ item["value"] = re.sub(r"This is a satellite image :", "", item["value"])
116
+ item["value"] = re.sub(r"This is a satellite image:", "", item["value"])
117
+ item["value"] = re.sub(r"This is a high resolution, optical satellite image .*?:\s*", "", item["value"])
118
+ item["value"] = re.sub(r"This is a high resolution, optical satellite image.*?:\s*", "", item["value"])
119
+ item["value"] = re.sub(r"This is a satellite image from .*?:\s*", "", item["value"])
120
+ item["value"] = re.sub(r"These are two satellite images from .*? capturing the same location at different times: ", "", item["value"])
121
+ item["value"] = re.sub(r"These are two low-resolution, optical satellite images capturing the same location at different times:", "", item["value"])
122
+ item["value"] = re.sub(r"These are two high-resolution, optical satellite images capturing the same location at different times:", "", item["value"])
123
+ item["value"] = re.sub(r"These are two high-resolution, optical satellite images from .*? capturing the same location at different times:", "", item["value"])
124
+ item["value"] = re.sub(r"These are two satellite images capturing the same location at different times:", "", item["value"])
125
+ item["value"] = re.sub(r"These are two satellite images from .*? capturing the same location at different times:", "", item["value"])
126
+ item["value"] = re.sub(r'These are two high-resolution,? optical satellite images .*:\s*<image>\n', '<image>\n', item["value"])
127
+ item["value"] = re.sub(r'These are two high resolution,? optical satellite images .*:\s*<image>\n', '<image>\n', item["value"])
128
+ item["value"] = re.sub(r'^This is a high[- ]resolution,? .*?image:\s*<image>\n', '<image>\n', item["value"], flags=re.IGNORECASE | re.DOTALL)
129
+
130
+ # Switch out <video> for <image>
131
+ if classification:
132
+ item["value"] = re.sub(r'<video> \n', '<image> \n [identify] ', item["value"])
133
+ item["value"] = re.sub(r' in the second image.', '.', item["value"])
134
+ elif localization:
135
+ item["value"] = re.sub(r'<video> \n', '<image> \n [refer] ', item["value"])
136
+ item["value"] = re.sub(r'Image 1', 'the image', item["value"])
137
+ else:
138
+ item["value"] = re.sub(r'<video> \n', '<image> \n ', item["value"])
139
+
140
+ # Replace temporal/multi-image wording for auxiliary tasks
141
+ replacements = {
142
+ 'Are there any buildings in the first image which have been damaged in the second image? Answer with one word.': 'Are there any damaged buildings in the image? Answer with one word.',
143
+ 'Have any buildings in the first image been damaged in the second image? Answer with one word.': 'Have any buildings been damaged in the area? Answer with one word.',
144
+ 'What disaster has occurred between the first and second image?': 'What disaster has occurred here?',
145
+ 'Identify the buildings in the first image which were severely damaged or destroyed in the second image. Include a bounding box of the form [x_min, y_min, x_max, y_max] for each identified building in your response. If there are no such buildings, do not output a bounding box.': 'Identify the severely damaged or destroyed buildings in the image. Include a bounding box of the form [x_min, y_min, x_max, y_max] for each identified building in your response. If there are no such buildings, do not output a bounding box.'
146
+ }
147
+ for old, new in replacements.items():
148
+ item['value'] = re.sub(re.escape(old), new, item['value'])
149
+
150
+
151
+ # Get rid of "this region" immediately before the bounding box
152
+ item["value"] = re.sub(r'this region {<', '{<', item["value"])
153
+ # Which class
154
+ item["value"] = re.sub(r'Which of the following classes does this sequence of images belong to', 'Which of the following classes does this image belong to', item["value"])
155
+ # Please answer using one of the following classes:
156
+ item["value"] = re.sub(r'Please answer using only one of the following classes:', 'Please use one of the following classes:', item["value"])
157
+ # Replace bounding box format [79, 27, 85, 81] with {<79><27><85><81>|<0>}
158
+ item["value"] = re.sub(r'\[(\d+), (\d+), (\d+), (\d+)\]', r'{<\1><\2><\3><\4>|<0>}', item["value"])
159
+ # Replace bounding box format [x_min, y_min, x_max, y_max] with {<x_min><y_min><x_max><y_max>|<0>}
160
+ item["value"] = re.sub(r'\[(x_min), (y_min), (x_max), (y_max)\]', r'{<\1><\2><\3><\4>|<0>}', item["value"])
161
+ return new_data
162
+
163
+ def s2looking_to_geochat_dataset_format(json_file):
164
+ with open(json_file) as f:
165
+ data = json.load(f)
166
+
167
+ question = "<image>\n [refer] Identify all buildings in the image."
168
+
169
+ new_dataset = []
170
+ for elem in data:
171
+ for i in range(2):
172
+ new_item = {}
173
+ new_item['id'] = elem['id'] + '_' + str(i)
174
+ new_item['metadata'] = elem['metadata'][i]
175
+ new_item['original_input_polygon'] = elem['original_input_polygon']
176
+ new_item['task'] = elem['task']
177
+ new_item['image'] = elem['video'][i]
178
+ new_item['geovlm_id'] = i
179
+ new_item['original_conversation'] = elem['conversations']
180
+ new_item['conversations'] = [
181
+ {
182
+ "from": "human",
183
+ "value": question
184
+ },
185
+ {
186
+ "from": "gpt",
187
+ "value": ""
188
+ }
189
+ ]
190
+ new_dataset.append(new_item)
191
+
192
+ data = new_dataset
193
+
194
+ for conversation_group in data:
195
+ for item in conversation_group["conversations"]:
196
+ # Check if the sentence starts with "This is" or "These are" and contains "<image>"
197
+ if (item["value"].startswith("This is") or item["value"].startswith("These are")) and "<image>" in item["value"]:
198
+ colon_index = item["value"].find(":")
199
+ if colon_index != -1 and item["value"][colon_index+1:].strip().startswith("<image>"):
200
+ item["value"] = item["value"][colon_index+1:].strip()
201
+ item["value"] = re.sub(r"This is a sequence of high-resolution, optical satellite images from Maxar's GeoEye-1, QuickBird-2, WorldView-2, or WorldView-3 capturing the same location at different times:", "", item["value"])
202
+ item["value"] = re.sub(r"This is a sequence of low-resolution, optical satellite images from Sentinel-2 capturing the same location at different times:", "", item["value"])
203
+ item["value"] = re.sub(r"This is a satellite image :", "", item["value"])
204
+ item["value"] = re.sub(r"This is a satellite image:", "", item["value"])
205
+ item["value"] = re.sub(r"This is a high resolution, optical satellite image .*?:\s*", "", item["value"])
206
+ item["value"] = re.sub(r"This is a high resolution, optical satellite image.*?:\s*", "", item["value"])
207
+ item["value"] = re.sub(r"This is a satellite image from .*?:\s*", "", item["value"])
208
+ item["value"] = re.sub(r"This is a satellite image from.*?:\s*", "", item["value"])
209
+ # This one is the one I'm referring to:
210
+ item["value"] = re.sub(r'^This is a sequence of.*times:$', '', item["value"])
211
+ item["value"] = re.sub(r"This is a sequence of high-resolution, optical satellite images from .*? capturing the same location at different times:", "", item["value"])
212
+ item["value"] = re.sub(r"This is a sequence of low-resolution, optical satellite images capturing the same location at different times: ", "", item["value"])
213
+ item["value"] = re.sub(r"This is a sequence of high-resolution, optical satellite images capturing the same location at different times:", "", item["value"])
214
+ item["value"] = re.sub(r"This is a sequence of satellite images capturing the same location at different times:", "", item["value"])
215
+ item["value"] = re.sub(r"This is a sequence of satellite images from .*? the same location at different times:", "", item["value"])
216
+ item["value"] = re.sub(r"These are two high-resolution, optical satellite images capturing the same location at different times:", "", item["value"])
217
+ item["value"] = re.sub(r"This is a sequence of images from the satellites GaoFen, SuperView and BeiJing-2, capturing the same location at different times:", "", item["value"])
218
+
219
+ # Switch out <video> for <image>
220
+ item["value"] = re.sub(r'<video>', '', item["value"])
221
+ # Get rid of "this region" immediately before the bounding box
222
+ item["value"] = re.sub(r'this region {<', '{<', item["value"])
223
+ # Which class
224
+ item["value"] = re.sub(r'Which of the following classes does this sequence of images belong to', 'Which of the following classes does this image belong to', item["value"])
225
+ # Please answer using one of the following classes:
226
+ item["value"] = re.sub(r'Please answer using only one of the following classes:', 'Please use one of the following classes:', item["value"])
227
+ # Check for the presence of '<identify>' and modify the string accordingly
228
+ if '[identify]' in item["value"]:
229
+ # Find the position of '<identify>' and the position of the first occurrence of '>}' after '<identify>'
230
+ identify_index = item["value"].find('[identify]')
231
+ closing_brace_index = item["value"].find('>}', identify_index)
232
+
233
+ # Fix the bounding box format:
234
+ for conversation_group in data:
235
+ for item in conversation_group["conversations"]:
236
+ # Replace bounding box format [79, 27, 85, 81] with {<79><27><85><81>|<0>}
237
+ item["value"] = re.sub(r'\[(\d+), (\d+), (\d+), (\d+)\]', r'{<\1><\2><\3><\4>|<0>}', item["value"])
238
+ # Replace bounding box format [x_min, y_min, x_max, y_max] with {<x_min><y_min><x_max><y_max>|<0>}
239
+ item["value"] = re.sub(r'\[(x_min), (y_min), (x_max), (y_max)\]', r'{<\1><\2><\3><\4>|<0>}', item["value"])
240
+ for i, entry in enumerate(data):
241
+ video_count = len(entry.get("video", []))
242
+ if video_count > 1:
243
+ data.pop(i)
244
+ return data
245
+
246
+ def check_file(file_path):
247
+ with open(file_path, 'r') as file:
248
+ data = json.load(file)
249
+ for conversation_group in data:
250
+ for item in conversation_group["conversations"]:
251
+ if '<image>' not in item["value"]:
252
+ if item["from"] != 'gpt':
253
+ print(f"Missing <image> in: {item}")
254
+ if any(sentence.strip().startswith(('This is', 'These are')) for sentence in item["value"].split('.')):
255
+ print(f"Starts with 'This is' or 'These are' in: {item}")
256
+ if __name__ == "__main__":
257
+
258
+ # Paths to datasets
259
+ fmow_0 = "/scr/geovlm/fmow_low_res_val.json"
260
+ fmow_1 = "/scr/geovlm/fmow_high_res_val.json"
261
+
262
+ qfabric_0 = '/scr/geovlm/QFabric/test_geochat_seqlen_5_256.json'
263
+ qfabric_1 = '/scr/geovlm/QFabric/test_geochat_seqlen_2_256.json'
264
+
265
+ xbd_0 = '/scr/geovlm/xbd_test_auxiliary_multi_image.json'
266
+ xbd_1 = '/scr/geovlm/xbd_test_canon_classification.json'
267
+ xbd_2 = '/scr/geovlm/xbd_test_canon_localization.json'
268
+
269
+ print("Running conversion on all datasets, storing updated datasets in variables")
270
+
271
+ from tqdm import tqdm
272
+
273
+ dataset_formats = [
274
+ (fmow_to_geochat_dataset_format, fmow_0),
275
+ (fmow_to_geochat_dataset_format, fmow_1),
276
+ ]
277
+ formatted_datasets = []
278
+ for format_func, dataset in tqdm(dataset_formats, desc="Converting datasets"):
279
+ if "xbd_test_auxiliary" in dataset:
280
+ formatted_datasets.append(format_func(dataset))
281
+
282
+ fmow_0_formatted, fmow_1_formatted = formatted_datasets
283
+
284
+ # Write the formatted data for fmow_0 into a JSON file named geochat_fmow_RECENT_format_low_res.json
285
+ with open('/scr/geovlm/geochat_fmow_RECENT_format_low_res.json', 'w') as file:
286
+ json.dump(fmow_0_formatted, file)
287
+
288
+ # Write the formatted data for fmow_1 into a JSON file named geochat_fmow_RECENT_format_low_res_AGG.json
289
+ with open('/scr/geovlm/geochat_fmow_RECENT_format_high_res.json', 'w') as file:
290
+ json.dump(fmow_1_formatted, file)
291
+
292
+ check_file('/scr/geovlm/geochat_fmow_RECENT_format_low_res.json')
293
+ check_file('/scr/geovlm/geochat_fmow_RECENT_format_high_res.json')
videollava/eval/eval_classification.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Segmentation metric code dapted from code for XView2: A Strong Baseline
3
+ Xview2_Strong_Baseline/legacy/xview2_metrics.py
4
+ Xview2_Strong_Baseline/legacy/create_masks.py
5
+ """
6
+ # add python path
7
+ # import sys
8
+ # import os
9
+ # sys.path.append('/deep/u/emily712/aicc-win24-geo-vlm/videollava/')
10
+
11
+ import json
12
+ import string
13
+ import numpy as np
14
+ import cv2
15
+ from collections import defaultdict, Counter
16
+ from nltk.tokenize import word_tokenize
17
+ from shapely.geometry import Polygon
18
+ from pathlib import Path
19
+ from sklearn.metrics import f1_score
20
+ from tqdm import tqdm
21
+
22
+
23
+ def compute_tp_fn_fp(pred: np.ndarray, targ: np.ndarray, c: int):
24
+ """
25
+ Computes the number of TPs, FNs, FPs, between a prediction (x) and a target (y) for the desired class (c)
26
+
27
+ Args:
28
+ pred (np.ndarray): prediction
29
+ targ (np.ndarray): target
30
+ c (int): positive class
31
+ """
32
+ TP = np.logical_and(pred == c, targ == c).sum()
33
+ FN = np.logical_and(pred != c, targ == c).sum()
34
+ FP = np.logical_and(pred == c, targ != c).sum()
35
+ return [TP, FN, FP]
36
+
37
+
38
+ def accuracy_precision_recall(answer_path, dataset, ignore_punctuation=True, verbose=True):
39
+ # Replace with the path to the answers file
40
+ if type(answer_path) == dict:
41
+ results = answer_path
42
+ else:
43
+ with open(answer_path) as json_data:
44
+ results = json.load(json_data)
45
+
46
+ task_total = defaultdict(int)
47
+ task_tp = defaultdict(int)
48
+
49
+ binary_classification = defaultdict(bool)
50
+ binary_fp = defaultdict(int)
51
+ binary_fn = defaultdict(int)
52
+
53
+ # Dictionary of dictionaries. Key: task. Value: {class: count}
54
+ ground_truths = defaultdict(dict)
55
+
56
+ values = defaultdict(list)
57
+
58
+ accepted_tasks = [
59
+ "temporal_question_answering",
60
+ "region_based_question_answering",
61
+ "temporal_region_based_question_answering",
62
+ "question_answering",
63
+ "temporal_referring_expression",
64
+ "rural_urban",
65
+ "comp",
66
+ "presence",
67
+ "count",
68
+ "change_to_what",
69
+ "smallest_change",
70
+ "change_or_not",
71
+ "change_ratio",
72
+ "largest_change",
73
+ "change_ratio_types",
74
+ "increase_or_not",
75
+ "decrease_or_not"
76
+ ]
77
+
78
+ for result in results.values():
79
+ if "task" in result and not any(result["task"].startswith(task) for task in accepted_tasks):
80
+ continue
81
+
82
+ # Clean predicted string if necessary
83
+ result["predicted"] = result["predicted"].lower()
84
+ result["ground_truth"] = result["ground_truth"].lower()
85
+ if ignore_punctuation:
86
+ result["predicted"] = ''.join(ch for ch in result["predicted"] if ch not in string.punctuation)
87
+ result["ground_truth"] = ''.join(ch for ch in result["ground_truth"] if ch not in string.punctuation)
88
+ if verbose:
89
+ values["predicted"].append(result["predicted"])
90
+ values["ground_truth"].append(result["ground_truth"])
91
+ values["correct_incorrect"].append("Correct" if result["predicted"] == result["ground_truth"] else "Incorrect")
92
+ if "task" not in result:
93
+ result["task"] = dataset
94
+
95
+ # True positive
96
+ if result["predicted"] == result["ground_truth"]:
97
+ task_tp[result["task"]] += 1
98
+ task_total[result["task"]] += 1
99
+
100
+ # If binary classification (yes/no question), calculate precision and recall metrics
101
+ binary_classification[result["task"]] = binary_classification[result["task"]] or (result["ground_truth"] in ["yes", "no"])
102
+ if binary_classification[result["task"]]:
103
+ if result["predicted"] != "no" and result["ground_truth"] == "no":
104
+ binary_fp[result["task"]] += 1
105
+ if result["predicted"] != "yes" and result["ground_truth"] == "yes":
106
+ binary_fn[result["task"]] += 1
107
+
108
+ # Update ground truth counts for the task
109
+ task = result["task"]
110
+ class_label = result["ground_truth"]
111
+ ground_truths[task][class_label] = ground_truths[task].get(class_label, 0) + 1
112
+
113
+ # Print tab separated values
114
+ if verbose:
115
+ max_len = max(len(v) for v in values["ground_truth"]) + 5
116
+ print("Predicted" + " " * (max_len - 9) + "\tGround Truth" + " " * (max_len - 12) + "\tCorrect/Incorrect")
117
+ for i in range(len(values["predicted"])):
118
+ print(values["predicted"][i] + " " * (max_len - len(values["predicted"][i])) + "\t" + values["ground_truth"][i] + " " * (max_len - len(values["ground_truth"][i])) + "\t" + values["correct_incorrect"][i])
119
+
120
+ total_tp = 0
121
+ total_predictions = 0
122
+ for task in task_tp:
123
+ acc_string = "Accuracy"
124
+ if ignore_punctuation:
125
+ acc_string += " (ignoring punctuation)"
126
+ print(f"{acc_string} for {task}: {round((task_tp[task] / task_total[task]), 4) * 100}%")
127
+
128
+ if binary_classification[task]:
129
+ if (task_tp[task] + binary_fp[task]) > 0:
130
+ print(f"Precision (ignoring punctuation) for {task}: {round((task_tp[task] / (task_tp[task] + binary_fp[task])), 3) * 100}%")
131
+ if (task_tp[task] + binary_fn[task]) > 0:
132
+ print(f"Recall (ignoring punctuation) for {task}: {round((task_tp[task] / (task_tp[task] + binary_fn[task])), 3) * 100}%")
133
+
134
+ majority_class = max(ground_truths[task], key=ground_truths[task].get)
135
+ majority_class_percentage = (ground_truths[task][majority_class] / task_total[task]) * 100
136
+ print(f"Majority class for {task}: {majority_class}, Percentage: {round(majority_class_percentage, 4)}%")
137
+
138
+ total_tp += task_tp[task]
139
+ total_predictions += task_total[task]
140
+
141
+ if total_predictions == 0:
142
+ print("No predictions made.")
143
+ else:
144
+ total_accuracy = (total_tp / total_predictions) * 100
145
+ print(f"Overall Accuracy: {round(total_accuracy, 3)}%")
146
+
147
+ # For testing accuracy/precision/recall on a particular script without running inference
148
+ if __name__ == '__main__':
149
+ root_dir = '/deep/u/jirvin16/aicc/aicc-win24-geo-vlm/videollava/scripts/geovlm/eval/QFabric/answers/'
150
+ answer_path = root_dir + "video-llava-7b-8bit-lora-final-no-metadata-zero-gc-acc8-freq-no-geochat-checkpoint-8000_qfabric_test_aux_data_test_prompt_strategy_interleave_chronological_prefix_True_load_8bit_True_load_4bit_False_delete_system_prompt_False.json"
151
+ accuracy_precision_recall(answer_path, dataset="qfabric", ignore_punctuation=True, verbose=False)
videollava/eval/eval_geochat_referring.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ calc_iou_individual adapted from calculate_mean_ap.py
3
+ author: Timothy C. Arlen
4
+ date: 28 Feb 2018
5
+ """
6
+
7
+ import sys
8
+ from os.path import dirname, abspath
9
+ sys.path.append(dirname(dirname(dirname(dirname(abspath(__file__))))))
10
+
11
+ from collections import defaultdict
12
+ import numpy as np
13
+ import json
14
+ import ast
15
+ import re
16
+ import cv2
17
+ from shapely import wkt, Polygon, box
18
+ from infer_utils import create_mask
19
+ from matplotlib.path import Path
20
+ from tqdm import tqdm
21
+
22
+ from eval_referring import referring_expression
23
+ import matplotlib.pyplot as plt
24
+ import time
25
+ import math
26
+ from matplotlib.path import Path
27
+
28
+ def convert_geochat_string(build, img_size=256):
29
+ """
30
+ Convert the raw str geochat output {<40><89><56><100>|<57>}, {<0><89><56><100>|<57>}
31
+ to a list of rotated bboxes.
32
+ """
33
+ build = build.strip('{}')
34
+ bbox_segments = build.split("}{")
35
+ # Regular expression to find all numbers inside angle brackets
36
+ pattern = r"<(\d+)>"
37
+
38
+ # Extract numbers, convert them to integers, and collect into a list
39
+ bboxes = [
40
+ list(map(int, re.findall(pattern, segment)))
41
+ for segment in bbox_segments
42
+ ]
43
+
44
+ rotated_bboxes = []
45
+ for bbox in bboxes:
46
+ try:
47
+ xmin, ymin, xmax, ymax, angle = [float(v) for v in bbox]
48
+ except:
49
+ print("Warning - Malformed bbox: ", bbox)
50
+ print("Original string: ", build)
51
+ print()
52
+ continue
53
+
54
+ # Convert percentages to pixel coordinates
55
+ xmin = xmin * img_size / 100
56
+ ymin = ymin * img_size / 100
57
+ xmax = xmax * img_size / 100
58
+ ymax = ymax * img_size / 100
59
+
60
+ # Calculate rectangle dimensions
61
+ rect_width = xmax - xmin
62
+ rect_height = ymax - ymin
63
+ center_x = xmin + rect_width / 2
64
+ center_y = ymin + rect_height / 2
65
+
66
+ # Calculate corners before rotation
67
+ corners = np.array([
68
+ [xmin, ymin],
69
+ [xmax, ymin],
70
+ [xmax, ymax],
71
+ [xmin, ymax]
72
+ ])
73
+
74
+ # Rotate corners
75
+ angle_rad = math.radians(angle)
76
+ cos_angle = math.cos(angle_rad)
77
+ sin_angle = math.sin(angle_rad)
78
+ rotated_corners = []
79
+ for x, y in corners:
80
+ tx = x - center_x
81
+ ty = y - center_y
82
+ rotated_x = tx * cos_angle - ty * sin_angle + center_x
83
+ rotated_y = tx * sin_angle + ty * cos_angle + center_y
84
+ rotated_corners.append([rotated_x, rotated_y])
85
+
86
+ rotated_bboxes.append(np.array(rotated_corners))
87
+
88
+ return rotated_bboxes
89
+
90
+ def create_geochat_mask(buildings, img_size=(256, 256)):
91
+ """
92
+ Given a list of buildings in an image, this function
93
+ - creates an img_size * img_size numpy array for the image
94
+ - returns the mask for all buildings
95
+ Input:
96
+ - buildings: List of geochat strings representing buildings
97
+ - img_size: Tuple indicating the size of the image (height, width)
98
+ """
99
+ mask = np.zeros(img_size, np.uint8)
100
+
101
+ # Fill in with ones the pixels that are inside the buildings (rotated bboxes)
102
+ for bbox in buildings:
103
+ path = Path(bbox)
104
+ x, y = np.meshgrid(np.arange(img_size[1]), np.arange(img_size[0]))
105
+ points = np.vstack((x.flatten(), y.flatten())).T
106
+ mask[path.contains_points(points).reshape(img_size)] = 1
107
+
108
+ return mask
109
+
110
+ def calc_iou_individual(pred_box, gt_box):
111
+ """Calculate IoU of single predicted and ground truth box
112
+ Args:
113
+ pred_box (list of floats): location of predicted object as
114
+ [xmin, ymin, xmax, ymax]
115
+ gt_box (list of floats): location of ground truth object as
116
+ [xmin, ymin, xmax, ymax]
117
+ Returns:
118
+ float: value of the IoU for the two boxes.
119
+ Raises:
120
+ AssertionError: if the box is obviously malformed
121
+ """
122
+ x1_t, y1_t, x2_t, y2_t = gt_box
123
+ try:
124
+ x1_p, y1_p, x2_p, y2_p = pred_box
125
+ except:
126
+ return 0.0
127
+
128
+ if (x1_p > x2_p) or (y1_p > y2_p):
129
+ print("Prediction box is malformed? pred box: {}".format(pred_box))
130
+ if (x1_t > x2_t) or (y1_t > y2_t):
131
+ print("Ground Truth box is malformed? true box: {}".format(gt_box))
132
+
133
+ if (x2_t < x1_p or x2_p < x1_t or y2_t < y1_p or y2_p < y1_t):
134
+ return 0.0
135
+
136
+ far_x = np.min([x2_t, x2_p])
137
+ near_x = np.max([x1_t, x1_p])
138
+ far_y = np.min([y2_t, y2_p])
139
+ near_y = np.max([y1_t, y1_p])
140
+
141
+ inter_area = (far_x - near_x + 1) * (far_y - near_y + 1)
142
+ true_box_area = (x2_t - x1_t + 1) * (y2_t - y1_t + 1)
143
+ pred_box_area = (x2_p - x1_p + 1) * (y2_p - y1_p + 1)
144
+ iou = inter_area / (true_box_area + pred_box_area - inter_area)
145
+
146
+ return iou
147
+
148
+ def get_single_image_bound_results(gt_wkts, pred_geochat_string, img_size=256):
149
+ """
150
+ Calculates upper bound and lower bound number of true_pos, false_pos, false_neg from single batch of boxes.
151
+ Args:
152
+ gt_wkts (list of strs): list of wkt strings of input polygons, scaled to raw pixel value
153
+ pred_boxes (list of lists): list of list of boxes, where each box is formatted
154
+ as [x_min, y_min, x_max, y_max] on scale from 0-100
155
+ img_size (int): dimensions of the image. defaults to 256.
156
+ Returns:
157
+ tuple of dicts: true positives (int), false positives (int), false negatives (int)
158
+ """
159
+ if isinstance(gt_wkts, str):
160
+ gt_polygons = [wkt.loads(gt_wkts)]
161
+ else:
162
+ gt_polygons = [wkt.loads(gt_wkt) for gt_wkt in gt_wkts]
163
+
164
+ lb_preds = convert_geochat_string(pred_geochat_string, img_size)
165
+ # get mask of all gt_polygons and lb_preds
166
+ gt_mask = create_mask(gt_polygons, (img_size, img_size))
167
+ lb_preds_mask = create_geochat_mask(lb_preds, (img_size, img_size))
168
+
169
+ # get lower bound intersection and union masks
170
+ intersection = np.logical_and(gt_mask, lb_preds_mask)
171
+ union = np.logical_or(gt_mask, lb_preds_mask)
172
+
173
+ # compute lb metrics
174
+ fp = np.sum(np.logical_and(lb_preds_mask, np.logical_not(gt_mask)))
175
+ tp = np.sum(np.logical_and(lb_preds_mask, gt_mask))
176
+ fn = np.sum(np.logical_and(np.logical_not(lb_preds_mask), gt_mask))
177
+ lb_stats = {'true_pos': tp, 'false_pos': fp, 'false_neg': fn, 'intersection': np.sum(intersection), 'union': np.sum(union)}
178
+
179
+ # get upper bound intersection and union masks
180
+ ub_pred_mask = np.logical_and(gt_mask, lb_preds_mask)
181
+ intersection = np.logical_and(ub_pred_mask, gt_mask)
182
+ union = np.logical_or(gt_mask, ub_pred_mask)
183
+
184
+ # compute ub metrics
185
+ ub_fp = np.sum(np.logical_and(ub_pred_mask, np.logical_not(gt_mask)))
186
+ ub_tp = np.sum(np.logical_and(ub_pred_mask, gt_mask))
187
+ ub_fn = np.sum(np.logical_and(np.logical_not(ub_pred_mask), gt_mask))
188
+ ub_stats = {'true_pos': ub_tp, 'false_pos': ub_fp, 'false_neg': ub_fn, 'intersection': np.sum(intersection), 'union': np.sum(union)}
189
+
190
+ return lb_stats, ub_stats
191
+
192
+ def get_geochat_dataset(image_id):
193
+ if image_id.startswith("P"):
194
+ dataset = "SOTA"
195
+ elif image_id.startswith("train"):
196
+ dataset = "FAST"
197
+ else:
198
+ dataset = "SIOR"
199
+ return dataset
200
+
201
+ def calc_precision_recall(img_results):
202
+ """Calculates precision and recall from the set of images
203
+ Args:
204
+ img_results (dict): dictionary formatted like:
205
+ {
206
+ 'img_id1': {'true_pos': int, 'false_pos': int, 'false_neg': int},
207
+ 'img_id2': ...
208
+ ...
209
+ }
210
+ Returns:
211
+ tuple: of floats of (precision, recall)
212
+ """
213
+ true_pos = 0; false_pos = 0; false_neg = 0
214
+ for _, res in img_results.items():
215
+ true_pos += res['true_pos']
216
+ false_pos += res['false_pos']
217
+ false_neg += res['false_neg']
218
+
219
+ try:
220
+ precision = true_pos/(true_pos + false_pos)
221
+ except ZeroDivisionError:
222
+ precision = 0.0
223
+ try:
224
+ recall = true_pos/(true_pos + false_neg)
225
+ except ZeroDivisionError:
226
+ recall = 0.0
227
+
228
+ return (precision, recall)
229
+
230
+
231
+ DIMENSIONS = {'FAST': 600,
232
+ 'SIOR': 800,
233
+ 'SOTA': 1024}
234
+
235
+
236
+ def referring_expression(answer_path, dataset, verbose=False, saving_path_root=None, img_size=256):
237
+ # Replace with the path to the answers file
238
+ if type(answer_path) == dict:
239
+ results = answer_path
240
+ else:
241
+ with open(answer_path) as json_data:
242
+ results = json.load(json_data)
243
+
244
+ img_results = {}
245
+ ub_results = {}
246
+ lb_results = {}
247
+ num_bboxes = 0
248
+ # Loop over results and get precision, recall overall
249
+ for id, result in tqdm(results.items()):
250
+
251
+ if dataset == "geochat_xbd":
252
+ pred = result['predicted']
253
+
254
+ dataset = get_geochat_dataset(id)
255
+ img_size = (DIMENSIONS[dataset])
256
+ pred = convert_geochat_string(pred, img_size)
257
+
258
+ ground_truth = result['ground_truth']
259
+ ground_truth = np.array(ground_truth)
260
+ num_bboxes += len(ground_truth)
261
+
262
+ img_results[id] = get_single_image_results(ground_truth, pred, iou_thr=0.5)
263
+
264
+ continue
265
+
266
+ try:
267
+ if 'referring_expression' not in result['task']:
268
+ continue # no bounding box outputs for temporal_referring_expression
269
+ except:
270
+ pass
271
+
272
+ # TODO: clean the following todos
273
+
274
+ # TODO: LOOP THROUGH IDENTIFY TASKS/QUESTIONS IN THE DATASET
275
+
276
+ # TODO: HANDLE WHEN THERE ARE NO BOUNDING BOXES IN GROUND TRUTH for auxiliary tasks
277
+ if not result['original_input_polygon']:
278
+ first_open_bracket_ind = result["predicted"].find("{")
279
+ last_close_bracket_ind = result["predicted"].rfind("}")
280
+ if last_close_bracket_ind != -1 and first_open_bracket_ind != -1:
281
+ parsed_predicted = result["predicted"][first_open_bracket_ind:last_close_bracket_ind+1]
282
+ else:
283
+ parsed_predicted = ""
284
+ predicted_boxes = convert_geochat_string(parsed_predicted)
285
+ # If ground truth contains no boxes: all predictions are false positives
286
+ false_pos = len(predicted_boxes)
287
+ false_pos_pixels = np.sum(create_geochat_mask(predicted_boxes))
288
+ img_results[id] = {'true_pos': 0, 'false_pos': false_pos, 'false_neg': 0, 'intersection':0, 'union':false_pos_pixels}
289
+ ub_results[id] = {'true_pos': 0, 'false_pos': false_pos_pixels, 'false_neg': 0, 'intersection':0, 'union':false_pos_pixels}
290
+ lb_results[id] = {'true_pos': 0, 'false_pos': false_pos_pixels, 'false_neg': 0, 'intersection':0, 'union':false_pos_pixels}
291
+ continue
292
+ else: #Β Ground truth contains boxes: find predicted Geochat boxes
293
+ first_open_bracket_ind = result["predicted"].find("{")
294
+ last_close_bracket_ind = result["predicted"].rfind("}")
295
+ if last_close_bracket_ind != -1 and first_open_bracket_ind != -1:
296
+ parsed_predicted = result["predicted"][first_open_bracket_ind:last_close_bracket_ind+1]
297
+ else:
298
+ parsed_predicted = ""
299
+ gt_wkts = result['original_input_polygon']
300
+ lb_results[id], ub_results[id] = get_single_image_bound_results(gt_wkts, parsed_predicted)
301
+
302
+ if len(ub_results) != 0:
303
+ ub_intersection = np.sum([res['intersection'] for res in ub_results.values()])
304
+ ub_union = np.sum([res['union'] for res in ub_results.values()])
305
+ lb_intersection = np.sum([res['intersection'] for res in lb_results.values()])
306
+ lb_union = np.sum([res['union'] for res in lb_results.values()])
307
+ print("Upper bound IOU: ", ub_intersection / ub_union if ub_union != 0 else 0)
308
+ print("Lower bound IOU: ", lb_intersection / lb_union if lb_union != 0 else 0)
309
+ ub_precision, ub_recall = calc_precision_recall(ub_results)
310
+ lb_precision, lb_recall = calc_precision_recall(lb_results)
311
+ print('Lower bound precision: ', lb_precision)
312
+ print('Lower bound recall: ', lb_recall)
313
+ print("Upper bound F1: ", 2 * (ub_precision * ub_recall) / (ub_precision + ub_recall) if (ub_precision + ub_recall) != 0 else 0)
314
+ print("Lower bound F1: ", 2 * (lb_precision * lb_recall) / (lb_precision + lb_recall) if (lb_precision + lb_recall) != 0 else 0)
315
+
316
+ print("[email protected]: ", np.sum([res['true_pos'] for res in img_results.values()]) / num_bboxes)
317
+
318
+ if type(answer_path) == dict:
319
+ return
320
+
321
+ if saving_path_root:
322
+ with open(f"{saving_path_root}/referring_expression_scores.json", 'w') as f:
323
+ json.dump(img_results, f)
324
+
325
+ if __name__ == '__main__':
326
+ answer_path = "scripts/geovlm/eval/xBD/answers/ckpt14000-geochat-bench_interleave_test.json"
327
+ referring_expression(answer_path, dataset="geochat_xbd")
328
+ #answer_path = "scripts/geochat/eval/xBD/geochat_xbd_test_auxiliary_dict.json"
329
+ # referring_expression(answer_path, dataset="xbd")
330
+
videollava/eval/eval_referring.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code adapted from calculate_mean_ap.py
3
+ author: Timothy C. Arlen
4
+ date: 28 Feb 2018
5
+ """
6
+ import sys
7
+ sys.path.append('/deep/u/joycech/aicc-working/videollava')
8
+
9
+ from collections import defaultdict
10
+ import numpy as np
11
+ import json
12
+ import ast
13
+ import re
14
+ import cv2
15
+ from shapely import wkt, Polygon, box
16
+ from infer_utils import create_mask, create_mask_s2looking
17
+
18
+
19
+ def calc_iou_individual(pred_box, gt_box):
20
+ """Calculate IoU of single predicted and ground truth box
21
+ Args:
22
+ pred_box (list of floats): location of predicted object as
23
+ [xmin, ymin, xmax, ymax]
24
+ gt_box (list of floats): location of ground truth object as
25
+ [xmin, ymin, xmax, ymax]
26
+ Returns:
27
+ float: value of the IoU for the two boxes.
28
+ Raises:
29
+ AssertionError: if the box is obviously malformed
30
+ """
31
+ x1_t, y1_t, x2_t, y2_t = gt_box
32
+ try:
33
+ x1_p, y1_p, x2_p, y2_p = pred_box
34
+ except:
35
+ print("Prediction box is malformed? pred box: {}".format(pred_box))
36
+ return 0.0
37
+
38
+ if (x1_p > x2_p) or (y1_p > y2_p):
39
+ print("Prediction box is malformed? pred box: {}".format(pred_box))
40
+ return 0.0
41
+ if (x1_t > x2_t) or (y1_t > y2_t):
42
+ raise AssertionError(
43
+ "Ground Truth box is malformed? true box: {}".format(gt_box))
44
+
45
+ if (x2_t < x1_p or x2_p < x1_t or y2_t < y1_p or y2_p < y1_t):
46
+ return 0.0
47
+
48
+ far_x = np.min([x2_t, x2_p])
49
+ near_x = np.max([x1_t, x1_p])
50
+ far_y = np.min([y2_t, y2_p])
51
+ near_y = np.max([y1_t, y1_p])
52
+
53
+ inter_area = (far_x - near_x + 1) * (far_y - near_y + 1)
54
+ true_box_area = (x2_t - x1_t + 1) * (y2_t - y1_t + 1)
55
+ pred_box_area = (x2_p - x1_p + 1) * (y2_p - y1_p + 1)
56
+ iou = inter_area / (true_box_area + pred_box_area - inter_area)
57
+
58
+ return iou
59
+
60
+ def get_single_image_bound_results(gt_wkts, pred_boxes, img_size=256, dataset=None, id=None, predicted_mask=None, split=None, question=None):
61
+ """
62
+ Calculates upper bound and lower bound number of true_pos, false_pos, false_neg from single batch of boxes.
63
+ Args:
64
+ gt_wkts (list of strs): list of wkt strings of input polygons, scaled to raw pixel value
65
+ pred_boxes (list of lists): list of list of boxes, where each box is formatted
66
+ as [x_min, y_min, x_max, y_max] on scale from 0-100
67
+ img_size (int): dimensions of the image. defaults to 256.
68
+ Returns:
69
+ tuple of dicts: true positives (int), false positives (int), false negatives (int)
70
+ """
71
+ lb_preds = [[num * img_size / 100 for num in box] for box in pred_boxes]
72
+ # add error handling for this type of outputs: [0, 10, 12, 22], [0, 6, 12, 19], [0, 0], [31, 0]
73
+ try:
74
+ lb_preds = [box(*pred_box) for pred_box in lb_preds]
75
+ except:
76
+ lb_preds = []
77
+ for pred_box in pred_boxes:
78
+ if len(pred_box) == 4:
79
+ lb_preds.append(box(*pred_box))
80
+
81
+ if isinstance(gt_wkts, str):
82
+ gt_polygons = [wkt.loads(gt_wkts)]
83
+ elif gt_wkts is None:
84
+ gt_polygons = []
85
+ else:
86
+ gt_polygons = [wkt.loads(gt_wkt) for gt_wkt in gt_wkts]
87
+
88
+ # get mask of all gt_polygons and lb_preds
89
+ if dataset == None:
90
+ gt_mask = create_mask(gt_polygons, (img_size, img_size))
91
+ else:
92
+ gt_mask = create_mask_s2looking(id, split=split, question=question)
93
+ #gt_mask = create_mask(gt_polygons, (img_size, img_size))
94
+
95
+ if dataset != "geochat_s2looking":
96
+ lb_preds_mask = create_mask(lb_preds, (img_size, img_size))
97
+ else:
98
+ lb_preds_mask = predicted_mask
99
+
100
+
101
+ # get lower bound intersection and union masks
102
+ intersection = np.logical_and(gt_mask, lb_preds_mask)
103
+ union = np.logical_or(gt_mask, lb_preds_mask)
104
+
105
+ # compute lb metrics
106
+ lower_bound_iou = np.sum(intersection) / np.sum(union)
107
+ if np.sum(intersection) == 0 and np.sum(union) == 0:
108
+ return None, None
109
+ if np.isnan(lower_bound_iou):
110
+ lower_bound_iou = 0
111
+
112
+
113
+ fp = np.sum(np.logical_and(lb_preds_mask, np.logical_not(gt_mask)))
114
+ tp = np.sum(np.logical_and(lb_preds_mask, gt_mask))
115
+ fn = np.sum(np.logical_and(np.logical_not(lb_preds_mask), gt_mask))
116
+ lb_stats = {'true_pos': tp,
117
+ 'false_pos': fp,
118
+ 'false_neg': fn,
119
+ 'intersection': np.sum(intersection),
120
+ 'union': np.sum(union)}
121
+
122
+ return lb_stats
123
+
124
+ def get_single_image_results(gt_boxes, pred_boxes, iou_thr):
125
+ """Calculates number of true_pos, false_pos, false_neg from single batch of boxes.
126
+ Args:
127
+ gt_boxes (list of list of floats): list of locations of ground truth
128
+ objects as [xmin, ymin, xmax, ymax]
129
+ pred_boxes (dict): dict of dicts of 'boxes' (formatted like `gt_boxes`)
130
+ and 'scores'
131
+ iou_thr (float): value of IoU to consider as threshold for a
132
+ true prediction.
133
+ Returns:
134
+ dict: true positives (int), false positives (int), false negatives (int)
135
+ """
136
+
137
+ all_pred_indices = range(len(pred_boxes))
138
+ all_gt_indices = range(len(gt_boxes))
139
+ if len(all_pred_indices) == 0:
140
+ tp = 0
141
+ fp = 0
142
+ fn = len(gt_boxes)
143
+ return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}
144
+ if len(all_gt_indices) == 0:
145
+ tp = 0
146
+ fp = len(pred_boxes)
147
+ fn = 0
148
+ return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}
149
+
150
+ gt_idx_thr = []
151
+ pred_idx_thr = []
152
+ ious = []
153
+ for ipb, pred_box in enumerate(pred_boxes):
154
+ for igb, gt_box in enumerate(gt_boxes):
155
+ iou = calc_iou_individual(pred_box, gt_box)
156
+ if iou > iou_thr:
157
+ gt_idx_thr.append(igb)
158
+ pred_idx_thr.append(ipb)
159
+ ious.append(iou)
160
+
161
+ args_desc = np.argsort(ious)[::-1]
162
+ if len(args_desc) == 0:
163
+ # No matches
164
+ tp = 0
165
+ fp = len(pred_boxes)
166
+ fn = len(gt_boxes)
167
+ else:
168
+ gt_match_idx = []
169
+ pred_match_idx = []
170
+ for idx in args_desc:
171
+ gt_idx = gt_idx_thr[idx]
172
+ pr_idx = pred_idx_thr[idx]
173
+ # If the boxes are unmatched, add them to matches
174
+ if (gt_idx not in gt_match_idx) and (pr_idx not in pred_match_idx):
175
+ gt_match_idx.append(gt_idx)
176
+ pred_match_idx.append(pr_idx)
177
+ tp = len(gt_match_idx)
178
+ fp = len(pred_boxes) - len(pred_match_idx)
179
+ fn = len(gt_boxes) - len(gt_match_idx)
180
+
181
+ return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}
182
+
183
+ def calc_precision_recall(img_results):
184
+ """Calculates precision and recall from the set of images
185
+ Args:
186
+ img_results (dict): dictionary formatted like:
187
+ {
188
+ 'img_id1': {'true_pos': int, 'false_pos': int, 'false_neg': int},
189
+ 'img_id2': ...
190
+ ...
191
+ }
192
+ Returns:
193
+ tuple: of floats of (precision, recall)
194
+ """
195
+ true_pos = 0; false_pos = 0; false_neg = 0
196
+ for _, res in img_results.items():
197
+ true_pos += res['true_pos']
198
+ false_pos += res['false_pos']
199
+ false_neg += res['false_neg']
200
+
201
+ try:
202
+ precision = true_pos/(true_pos + false_pos)
203
+ except ZeroDivisionError:
204
+ precision = 0.0
205
+ print(true_pos, "true_pos", false_pos, "false_pos", false_neg, "false_neg")
206
+ try:
207
+ recall = true_pos/(true_pos + false_neg)
208
+ except ZeroDivisionError:
209
+ recall = 0.0
210
+
211
+ return (precision, recall)
212
+
213
+ def extract_bboxes(input_string):
214
+ """
215
+ Takes as an input a string like in the image, there are two buildings that have been changed. the first building is located at [0.0, 0.69, 0.45, 0.9] and the second building is located at [0.46, 0.69, 0.99, 0.91]
216
+ Returns a list of bounding boxes in the format [x_min, y_min, x_max, y_max]
217
+ Input:
218
+ input_string (str): string containing the bounding boxes
219
+ Returns:
220
+ list of lists: list of bounding boxes
221
+ """
222
+ matches = re.findall(r'\[\[.*?\]\]', input_string)
223
+ return [ast.literal_eval(match) for match in matches]
224
+
225
+
226
+ def referring_expression(answer_path, dataset, verbose=False, saving_path_root=None, img_size=256, split=None):
227
+ if type(answer_path) == dict:
228
+ results = answer_path
229
+ else:
230
+ with open(answer_path) as json_data:
231
+ results = json.load(json_data)
232
+
233
+ img_results = {}
234
+ lb_results = {}
235
+ # Loop over results and get precision, recall overall
236
+ for id, result in results.items():
237
+ if 'temporal_referring_expression' in result['task']:
238
+ if not "s2looking" in dataset:
239
+ continue # no bounding box outputs for temporal_referring_expression
240
+
241
+ # for the geochat s2looking predictions, we work directly with the predicted mask instead of the bounding boxes
242
+ if dataset == 'geochat_s2looking':
243
+ if 'referring_expression' in result['task'] or 'localization' in result['task']:
244
+ lb_res = get_single_image_bound_results(result['original_input_polygon'], [], dataset=dataset, id=id, predicted_mask=result['predicted_mask'], split=split, question=result["question"])
245
+ if lb_res != None:
246
+ lb_results[id] = lb_res
247
+ continue
248
+ elif 'question_answering' in result['task']:
249
+ continue
250
+
251
+ if 'referring_expression' in result['task'] or 'largest building' in result['task'] or "canonical" in result['task'] or 'localization' in result['task'] \
252
+ or 'geochat_referring' in result['task']:
253
+ # No bounding boxes in predicted string
254
+ if "[" not in result["predicted"]:
255
+ # Ground truth has no bounding boxes
256
+ if result["ground_truth"].startswith("There are no") or "no" in result["ground_truth"] or "No" in result["ground_truth"]:
257
+ # Discard true negatives
258
+ continue
259
+ # Ground truth has bounding boxes, not identified by the model --> all false negatives
260
+ else:
261
+ false_neg = "[" + result["ground_truth"] + "]"
262
+ false_neg = false_neg.replace(".", "")
263
+
264
+ try:
265
+ false_neg = len(ast.literal_eval(false_neg))
266
+ except:
267
+ # count the number of opening '[' in the string
268
+ false_neg = false_neg.count('[') - 1
269
+ if not "s2looking" in dataset:
270
+ gt_mask = create_mask(wkt.loads(result['original_input_polygon']), (img_size, img_size))
271
+ else:
272
+ gt_mask = create_mask_s2looking(id, split=split, question=result['question'])
273
+ # gt_mask = create_mask(wkt.loads(result['original_input_polygon']), (img_size, img_size))
274
+ img_results[id] = {'true_pos': 0, 'false_pos': 0, 'false_neg': false_neg, 'intersection':0, 'union':false_neg}
275
+ false_neg = np.sum(gt_mask)
276
+ lb_results[id] = {'true_pos': 0, 'false_pos': 0, 'false_neg': false_neg, 'intersection':0, 'union':false_neg}
277
+
278
+ # Bounding boxes in predicted and output string --> compare bounding boxes
279
+ else:
280
+
281
+ # To deal with cases where the model outputs an incomplete bounding box (e.g. "[24, 76,")
282
+ first_open_bracket_ind = result["predicted"].find("[")
283
+ last_close_bracket_ind = result["predicted"].rfind("]")
284
+ if last_close_bracket_ind != -1 and first_open_bracket_ind != -1:
285
+ parsed_predicted = result["predicted"][first_open_bracket_ind:last_close_bracket_ind+1]
286
+ else:
287
+ parsed_predicted = ""
288
+
289
+ # Load list of predicted bounding boxes
290
+ try:
291
+ predicted_boxes = ast.literal_eval("[" + parsed_predicted + "]")
292
+ except:
293
+ match = re.search(r'\[\[.*\]\]', result["predicted"])
294
+ if match:
295
+ predicted_boxes = ast.literal_eval(match.group())
296
+ else:
297
+ predicted_boxes = []
298
+
299
+ predicted_boxes = [[coord * 100 if coord < 1 else coord for coord in box] for box in predicted_boxes]
300
+
301
+ # Load list of ground truth bounding boxes
302
+ if result["ground_truth"].startswith("There are no") or "no" in result["ground_truth"].lower():
303
+ # If ground truth contains no boxes
304
+ ground_truth_boxes = []
305
+ first_open_bracket_ind = result["ground_truth"].find("[")
306
+ last_close_bracket_ind = result["ground_truth"].rfind("]")
307
+ if last_close_bracket_ind != -1 and first_open_bracket_ind != -1:
308
+ parsed_gt = result["ground_truth"][first_open_bracket_ind:last_close_bracket_ind+1]
309
+ else:
310
+ parsed_gt = ""
311
+ try:
312
+ ground_truth_boxes = ast.literal_eval("[" + parsed_gt + "]")
313
+ except:
314
+ match = re.search(r'\[\[.*\]\]', result["ground_truth"])
315
+ if match:
316
+ ground_truth_boxes = ast.literal_eval(match.group())
317
+ else:
318
+ ground_truth_boxes = []
319
+
320
+ # Get mask results from the two previous parsings
321
+ gt_wkts = result['original_input_polygon']
322
+ img_results[id] = get_single_image_results(ground_truth_boxes, predicted_boxes, iou_thr=0.5) ######
323
+
324
+ if 'referring_expression' in result['task'] or 'largest building' in result['task'] or "canonical" in result['task'] or 'localization' in result['task']:
325
+ if not "s2looking" in dataset:
326
+ lb_results[id] = get_single_image_bound_results(gt_wkts, predicted_boxes)
327
+ elif dataset=="s2looking":
328
+ lb_results[id] = get_single_image_bound_results(gt_wkts, predicted_boxes, dataset=dataset, id=id, split=split, question=result["question"])
329
+ else:
330
+ lb_results[id] = get_single_image_bound_results(gt_wkts, predicted_boxes, predicted_mask=result['predicted_mask'], split=split, question=result["question"])
331
+
332
+ precision, recall = calc_precision_recall(img_results)
333
+ print("Referring expression results (precision, recall): ", precision, recall)
334
+ print("[email protected]: ", np.sum([res['true_pos'] for res in img_results.values()]) / len(results.keys()))
335
+
336
+ if len(lb_results) != 0:
337
+ lb_intersection = np.sum([res['intersection'] for res in lb_results.values()])
338
+ lb_union = np.sum([res['union'] for res in lb_results.values()])
339
+ print("Lower bound IOU: ", lb_intersection / lb_union if lb_union != 0 else 0)
340
+ lb_precision, lb_recall = calc_precision_recall(lb_results)
341
+ print('Lower bound precision: ', lb_precision)
342
+ print('Lower bound recall: ', lb_recall)
343
+ print("Lower bound F1: ", 2 * (lb_precision * lb_recall) / (lb_precision + lb_recall) if (lb_precision + lb_recall) != 0 else 0)
344
+
345
+ if saving_path_root:
346
+ with open(f"{saving_path_root}/referring_expression_scores.json", 'w') as f:
347
+ json.dump(img_results, f)
348
+
349
+ if __name__ == '__main__':
350
+ answer_path = "scripts/geovlm/eval/xBD/answers/ckpt14000-old-aux-xbd-test-canon-auxiliary_interleave.json"
351
+ referring_expression(answer_path, dataset="xbd")
videollava/eval/geochat_bench.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ from eval_geochat_referring import get_single_image_results, convert_geochat_string
4
+
5
+ from collections import defaultdict
6
+ import numpy as np
7
+ import json
8
+ import ast
9
+ import re
10
+ import cv2
11
+ from shapely import wkt, Polygon, box
12
+ from infer_utils import create_mask
13
+ from matplotlib.path import Path
14
+ from tqdm import tqdm
15
+ import matplotlib.pyplot as plt
16
+ import time
17
+ import math
18
+ from matplotlib.path import Path
19
+
20
+
21
+
22
+ DIMENSIONS = {'FAST': 600,
23
+ 'SIOR': 800,
24
+ 'SOTA': 1024}
25
+
26
+ def calc_iou_individual_rotated(pred_box, gt_box, img_size=None):
27
+ """Calculate IoU of single predicted and ground truth box
28
+ Args:
29
+ pred_box (list of floats): location of predicted object as
30
+ [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
31
+ gt_box (list of floats): location of ground truth object as
32
+ [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
33
+ Returns:
34
+ float: value of the IoU for the two boxes.
35
+ Raises:
36
+ AssertionError: if the box is obviously malformed
37
+ """
38
+
39
+ pred_box = np.array(pred_box)
40
+ gt_box = np.array(gt_box)
41
+ pred_box = pred_box.reshape(4, 2)
42
+ gt_box = gt_box.reshape(4, 2)
43
+ pred_polygon = Polygon(pred_box)
44
+ gt_polygon = Polygon(gt_box)
45
+ intersection = pred_polygon.intersection(gt_polygon).area
46
+ union = pred_polygon.union(gt_polygon).area
47
+ iou = intersection / union
48
+
49
+ return iou
50
+
51
+
52
+ def get_single_image_results_rotated(gt_boxes, pred_boxes, iou_thr, img_size=None):
53
+ """Calculates number of true_pos, false_pos, false_neg from single batch of boxes.
54
+ Args:
55
+ gt_boxes (list of list of floats): list of locations of ground truth
56
+ objects as [[x1,y1], [x2,y2], ...]
57
+ pred_boxes (dict): dict of dicts of 'boxes'
58
+ [[x1,y1], [x2,y2], ...]
59
+ iou_thr (float): value of IoU to consider as threshold for a
60
+ true prediction.
61
+ Returns:
62
+ dict: true positives (int), false positives (int), false negatives (int)
63
+ """
64
+
65
+ all_pred_indices = range(len(pred_boxes))
66
+ all_gt_indices = range(len(gt_boxes))
67
+ if len(all_pred_indices) == 0:
68
+ tp = 0
69
+ fp = 0
70
+ fn = len(gt_boxes)
71
+ return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}
72
+ if len(all_gt_indices) == 0:
73
+ tp = 0
74
+ fp = len(pred_boxes)
75
+ fn = 0
76
+ return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}
77
+
78
+ gt_idx_thr = []
79
+ pred_idx_thr = []
80
+ ious = []
81
+ for ipb, pred_box in enumerate(pred_boxes):
82
+ for igb, gt_box in enumerate(gt_boxes):
83
+ iou = calc_iou_individual_rotated(pred_box, gt_box, img_size)
84
+ if iou > iou_thr:
85
+ gt_idx_thr.append(igb)
86
+ pred_idx_thr.append(ipb)
87
+ ious.append(iou)
88
+
89
+ args_desc = np.argsort(ious)[::-1]
90
+ if len(args_desc) == 0:
91
+ # No matches
92
+ tp = 0
93
+ fp = len(pred_boxes)
94
+ fn = len(gt_boxes)
95
+ else:
96
+ gt_match_idx = []
97
+ pred_match_idx = []
98
+ for idx in args_desc:
99
+ gt_idx = gt_idx_thr[idx]
100
+ pr_idx = pred_idx_thr[idx]
101
+ # If the boxes are unmatched, add them to matches
102
+ if (gt_idx not in gt_match_idx) and (pr_idx not in pred_match_idx):
103
+ gt_match_idx.append(gt_idx)
104
+ pred_match_idx.append(pr_idx)
105
+ tp = len(gt_match_idx)
106
+ fp = len(pred_boxes) - len(pred_match_idx)
107
+ fn = len(gt_boxes) - len(gt_match_idx)
108
+
109
+ return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}
110
+
111
+
112
+ def accuracy0_5(answer_path, dataset, aux_dataset="scripts/geochat_bench_dict.json"):
113
+ # Replace with the path to the answers file
114
+ results = None
115
+ if dataset != "geochat_xbd":
116
+
117
+ if type(answer_path) == dict:
118
+ results = answer_path
119
+ else:
120
+ results = []
121
+ with open(answer_path) as json_data:
122
+ for line in json_data:
123
+ results.append(json.loads(line))
124
+
125
+ with open(aux_dataset) as json_data:
126
+ aux_results = json.load(json_data)
127
+
128
+ img_results = {}
129
+ num_bboxes = 0
130
+
131
+ if dataset != "geochat_xbd":
132
+ print("Number of images in Geochat: ", len(aux_results))
133
+ print("Number of images predicted: ", len(results))
134
+
135
+ i = 0
136
+ # Loop over results and get precision, recall overall
137
+ for id, result in tqdm(aux_results.items()):
138
+
139
+ if dataset == "geochat_xbd":
140
+ pred = result['answer']
141
+
142
+ img_size = DIMENSIONS[result['dataset']]
143
+ pred = convert_geochat_string(pred, img_size)
144
+
145
+ ground_truth = result['ground_truth']
146
+ ground_truth = np.array(ground_truth)
147
+ num_bboxes += len(ground_truth)
148
+
149
+ img_results[id] = get_single_image_results_rotated(ground_truth, pred, iou_thr=0.5)
150
+
151
+ else:
152
+
153
+ geochat_id = id.split(".")[0]
154
+
155
+ img_size = DIMENSIONS[aux_results[geochat_id]['dataset']]
156
+ ground_truth = result['ground_truth']
157
+ ground_truth = np.array(ground_truth)
158
+ num_bboxes += len(ground_truth)
159
+
160
+ parsed_predicted = results[i]['predicted']
161
+ # Load list of predicted and round truth bounding boxes for a single image
162
+ try:
163
+ predicted_boxes = ast.literal_eval("[" + parsed_predicted + "]")
164
+ except:
165
+ match = re.search(r'\[\[.*\]\]', parsed_predicted)
166
+ if match:
167
+ predicted_boxes = ast.literal_eval(match.group())
168
+ else:
169
+ predicted_boxes = []
170
+
171
+ predicted_boxes = [[coord * 100 if coord < 1 else coord for coord in box] for box in predicted_boxes]
172
+
173
+ # scale by img_size
174
+ predicted_boxes = [[coord * img_size / 100 for coord in box] for box in predicted_boxes]
175
+
176
+ assert results[i]['ground_truth'] == result['ground_truth']
177
+
178
+ # convert the pred bboxes [xmin, ymin, xmax, ymax] to [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
179
+ pred_bboxes = []
180
+ for bbox in predicted_boxes:
181
+ x1, y1, x2, y2 = bbox
182
+ pred_bboxes.append([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
183
+
184
+ img_results[id] = get_single_image_results_rotated(ground_truth, pred_bboxes, iou_thr=0.5, img_size=img_size)
185
+
186
+ i+=1
187
+
188
+
189
+ acc = np.sum([res['true_pos'] for res in img_results.values()]) / num_bboxes
190
+ print("[email protected]: ", acc)
191
+ return acc
192
+
193
+
194
+
195
+ if __name__ == '__main__':
196
+ print("Geochat bench")
197
+ geochat_path = "scripts/geochat_bench_dict.json"
198
+ answer_path = "scripts/geochat_bench_dict.json"
199
+ acc_geochat = accuracy0_5(answer_path, dataset="geochat_xbd")
200
+ print()
201
+
202
+
203
+ print("Teochat bench")
204
+ answer_path = "/deep/u/idormoy/aicc-win24-geo-vlm/videollava/scripts/geovlm/eval/QFabric/answers/geochat-referring-checkpoint14000_prompt_strategy_interleave_chronological_prefix_True_load_8bit_True_load_4bit_False_delete_system_prompt_False_tmp_0_end.json"
205
+ acc_teochat = accuracy0_5(answer_path, dataset="geochat")
206
+ print()
207
+
208
+
209
+ print("Teochat-T bench")
210
+ answer_path = "/deep/u/idormoy/aicc-win24-geo-vlm/videollava/videollava/eval/video/geochat-bench-ckpt8000-FIXED_prompt_strategy_interleave_chronological_prefix_True_load_8bit_False_load_4bit_True_delete_system_prompt_False_tmp_0_end (1).json"
211
+ acc_teochatT = accuracy0_5(answer_path, dataset="geochat")
212
+ print()
213
+
214
+
215
+
216
+ print("VideoLLaVA bench")
217
+ answer_path = "/deep/u/idormoy/aicc-win24-geo-vlm/videollava/videollava/eval/video/geochat-referring-Video-LLaVA-7B_prompt_strategy_interleave_chronological_prefix_True_load_8bit_False_load_4bit_True_delete_system_prompt_False_tmp_0_end (1).json"
218
+ acc_videollava = accuracy0_5(answer_path, dataset="geochat")
219
+ print()
220
+
221
+
222
+
223
+ print("Overall accuracies")
224
+ print("Geochat: ", acc_geochat)
225
+ print("Teochat: ", acc_teochat)
226
+ print("Teochat-T: ", acc_teochatT)
227
+ print("VideoLLaVA: ", acc_videollava)
228
+
videollava/eval/geochat_eval_fmow.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+ import os
4
+ import json
5
+ from tqdm import tqdm
6
+ import shortuuid
7
+ import sys
8
+
9
+ sys.path.append('/deep/u/emily712/GeoChat')
10
+
11
+ from geochat.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
12
+ from geochat.conversation import conv_templates, SeparatorStyle
13
+ from geochat.model.builder import load_pretrained_model
14
+ from geochat.utils import disable_torch_init
15
+ from geochat.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
16
+ from eval_classification import *
17
+
18
+ from PIL import Image
19
+ import math
20
+ import numpy as np
21
+
22
+ def aggregate_accuracy(answers_file, output_file):
23
+ """
24
+ Parses geochat inference output and aggregates votes on single images
25
+ across an image sequence into the format needed for geovlm-style evaluation.
26
+
27
+ params:
28
+ - answers_file: path to the file containing geochat inference output
29
+ - output_file: path to the file where the aggregated output will be saved
30
+ """
31
+ with open(answers_file, 'r') as f:
32
+ answers = [json.loads(line) for line in f]
33
+ print(answers)
34
+ # dictionary that will contain parsed output
35
+ votes = {}
36
+
37
+ # parse answers so that predictions with the same linked_id
38
+ # are aggregated into a single item with 'predictions' containing
39
+ # a list of values. All other keys should be the same
40
+ for answer in answers:
41
+ print(answer)
42
+ print(answer['linked_id'])
43
+ id = answer['linked_id']
44
+ print(id)
45
+ if id not in votes:
46
+ item = {}
47
+ item['predicted'] = [answer['predicted']]
48
+ item['ground_truth'] = answer['ground_truth']
49
+ item['task'] = answer['task']
50
+ item['question'] = answer['question']
51
+ item['id'] = answer['id']
52
+ votes[id] = item
53
+ else:
54
+ votes['linked_id']['predicted'].append(answer['predicted'])
55
+
56
+ # implement voting so that each list in 'predicted' attribute
57
+ # is reduced to the most common value
58
+ for linked_id, predicted_dict in votes.items():
59
+ predicted = predicted_dict['predicted']
60
+ unique, counts = np.unique(predicted, return_counts=True)
61
+ index = np.argmax(counts)
62
+ votes[linked_id]['predicted'] = unique[index]
63
+
64
+ with open(output_file, 'w') as f:
65
+ json.dump(votes, f)
66
+
67
+
68
+ def split_list(lst, n):
69
+ """Split a list into n (roughly) equal-sized chunks"""
70
+ chunk_size = math.ceil(len(lst) / n) # integer division
71
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
72
+
73
+
74
+ def get_chunk(lst, n, k):
75
+ chunks = split_list(lst, n)
76
+ return chunks[k]
77
+
78
+
79
+ def eval_model(args):
80
+ # Model
81
+ disable_torch_init()
82
+ model_path = os.path.expanduser(args.model_path)
83
+ model_name = get_model_name_from_path(model_path)
84
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, cache_dir=args.cache_dir)
85
+
86
+ with open(args.question_file, 'r') as f:
87
+ questions = json.load(f)
88
+ #questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
89
+
90
+ questions = get_chunk(questions, args.num_chunks, args.chunk_idx)
91
+ answers_file = os.path.expanduser(args.answers_file)
92
+ os.makedirs(os.path.dirname(answers_file), exist_ok=True)
93
+
94
+ ans_file = open(answers_file, "w")
95
+
96
+ skipped_count = 0
97
+
98
+ for i in tqdm(range(0,len(questions),args.batch_size)):
99
+ input_batch=[]
100
+ input_image_batch=[]
101
+ count=i
102
+ image_folder=[]
103
+ batch_end = min(i + args.batch_size, len(questions))
104
+
105
+ for j in range(i,batch_end):
106
+ if 'image' not in questions[j]:
107
+ print(f"Skipped entry [{skipped_count}]")
108
+ skipped_count += 1
109
+ continue
110
+
111
+ print(questions[j])
112
+ image_file=questions[j]['image']
113
+ qs=questions[j]['conversations'][0]['value']
114
+
115
+ if model.config.mm_use_im_start_end:
116
+ qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
117
+ else:
118
+ qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
119
+
120
+ conv = conv_templates[args.conv_mode].copy()
121
+ conv.append_message(conv.roles[0], qs)
122
+ conv.append_message(conv.roles[1], None)
123
+ prompt = conv.get_prompt()
124
+
125
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
126
+ input_batch.append(input_ids)
127
+
128
+ image = Image.open(os.path.join(args.image_folder, image_file))
129
+
130
+ image_folder.append(image)
131
+
132
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
133
+ keywords = [stop_str]
134
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
135
+
136
+ if len(input_batch) == 0:
137
+ print("All images here were skipped")
138
+ continue
139
+
140
+ max_length = max(tensor.size(1) for tensor in input_batch)
141
+
142
+ final_input_list = [torch.cat((torch.zeros((1,max_length - tensor.size(1)), dtype=tensor.dtype,device=tensor.get_device()), tensor),dim=1) for tensor in input_batch]
143
+ final_input_tensors=torch.cat(final_input_list,dim=0)
144
+ image_tensor_batch = image_processor.preprocess(image_folder,crop_size ={'height': 504, 'width': 504},size = {'shortest_edge': 504}, return_tensors='pt')['pixel_values']
145
+
146
+ with torch.inference_mode():
147
+ output_ids = model.generate( final_input_tensors, images=image_tensor_batch.half().cuda(), do_sample=False , temperature=args.temperature, top_p=args.top_p, num_beams=1, max_new_tokens=256,length_penalty=2.0, use_cache=True)
148
+
149
+ input_token_len = final_input_tensors.shape[1]
150
+ n_diff_input_output = (final_input_tensors != output_ids[:, :input_token_len]).sum().item()
151
+ if n_diff_input_output > 0:
152
+ print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
153
+ outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)
154
+ for k in range(0,len(final_input_list)):
155
+ output = outputs[k].strip()
156
+ if output.endswith(stop_str):
157
+ output = output[:-len(stop_str)]
158
+ output = output.strip()
159
+
160
+ ans_id = shortuuid.uuid()
161
+
162
+ ans_file.write(json.dumps({
163
+ "id": questions[count]["id"],
164
+ "image_id": questions[count]["image"],
165
+ "question": questions[count]['conversations'][0]['value'],
166
+ "predicted": output,
167
+ "ground_truth": questions[count]['conversations'][1]['value'],
168
+ "task": questions[count]['task'],
169
+ "linked_id": questions[count]['linked_id']
170
+ }) + "\n")
171
+ count=count+1
172
+ ans_file.flush()
173
+ ans_file.close()
174
+
175
+ output = [json.loads(q) for q in open((ans_file), "r")]
176
+ output = [{q['id']: q} for q in output]
177
+ with open(ans_file, 'r') as f:
178
+ json.dump(output, f)
179
+
180
+ agg_ans_file = ans_file.replace('.jsonl', '_agg.jsonl')
181
+ print("Raw Geochat output saved to ", ans_file)
182
+ print("Now parsing and aggregating votes for geovlm evaluation...")
183
+ aggregate_accuracy(ans_file, agg_ans_file)
184
+ print("Aggregated output saved to ", agg_ans_file)
185
+
186
+ accuracy_precision_recall(agg_ans_file, 'fmow')
187
+
188
+ if __name__ == "__main__":
189
+ parser = argparse.ArgumentParser()
190
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
191
+ parser.add_argument("--model-base", type=str, default=None)
192
+ parser.add_argument("--image-folder", type=str, default="")
193
+ parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
194
+ parser.add_argument("--answers-file", type=str, default="answer.jsonl")
195
+ parser.add_argument("--conv-mode", type=str, default="llava_v1")
196
+ parser.add_argument("--num-chunks", type=int, default=1)
197
+ parser.add_argument("--chunk-idx", type=int, default=0)
198
+ parser.add_argument("--temperature", type=float, default=0.2)
199
+ parser.add_argument("--top_p", type=float, default=None)
200
+ parser.add_argument("--num_beams", type=int, default=1)
201
+ parser.add_argument("--batch_size",type=int, default=1)
202
+ parser.add_argument("--cache-dir", type=str, default=None)
203
+ args = parser.parse_args()
204
+
205
+ eval_model(args)
videollava/eval/geochat_geovlm_infer.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+ import os
4
+ import json
5
+ from tqdm import tqdm
6
+ import shortuuid
7
+ import sys
8
+ import random
9
+
10
+ from geochat.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
11
+ from geochat.conversation import conv_templates, SeparatorStyle
12
+ from geochat.model.builder import load_pretrained_model
13
+ from geochat.utils import disable_torch_init
14
+ from geochat.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
15
+ from eval_classification import *
16
+ from datasets_into_geochat_format import s2looking_to_geochat_dataset_format, qfabric_semiconverted_to_geochat_dataset_format, xbd_to_geochat_dataset_format
17
+ from geochat_s2looking_utils import evaluate_geochat_s2looking
18
+
19
+ from PIL import Image
20
+ import math
21
+ import numpy as np
22
+
23
+ def aggregate_accuracy(answers_file, output_file):
24
+ """
25
+ Parses geochat inference output and aggregates votes on single images
26
+ across an image sequence into the format needed for geovlm-style evaluation.
27
+
28
+ params:
29
+ - answers_file: path to the file containing geochat inference output
30
+ - output_file: path to the file where the aggregated output will be saved
31
+ """
32
+ with open(answers_file, 'r') as f:
33
+ answers = [json.loads(line) for line in f]
34
+
35
+ # dictionary that will contain parsed output
36
+ votes = {}
37
+
38
+ # parse answers so that predictions with the same geovlm_id
39
+ # are aggregated into a single item with 'predictions' containing
40
+ # a list of values. All other keys should be the same
41
+ for answer in answers:
42
+ id = answer['geovlm_id']
43
+ if id not in votes:
44
+ item = {}
45
+ item['predicted'] = [answer['predicted']]
46
+ item['ground_truth'] = answer['ground_truth']
47
+ item['task'] = answer['task']
48
+ item['original_input_polygon'] = answer['original_input_polygon']
49
+ item['question'] = answer['question']
50
+ item['id'] = answer['id']
51
+ votes[id] = item
52
+ else:
53
+ votes[id]['predicted'].append(answer['predicted'])
54
+
55
+ # implement voting so that each list in 'predicted' attribute
56
+ # is reduced to the most common value
57
+ for linked_id, predicted_dict in votes.items():
58
+ predicted = predicted_dict['predicted']
59
+ unique, counts = np.unique(predicted, return_counts=True)
60
+ index = np.argmax(counts)
61
+ votes[linked_id]['predicted'] = unique[index]
62
+
63
+ with open(output_file, 'w') as f:
64
+ json.dump(votes, f)
65
+
66
+
67
+ def split_list(lst, n):
68
+ """Split a list into n (roughly) equal-sized chunks"""
69
+ chunk_size = math.ceil(len(lst) / n) # integer division
70
+ return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
71
+
72
+
73
+ def get_chunk(lst, n, k):
74
+ chunks = split_list(lst, n)
75
+ return chunks[k]
76
+
77
+
78
+ def eval_model(args):
79
+ print(args)
80
+ print()
81
+
82
+ answers_file = os.path.expanduser(args.answers_file)
83
+ os.makedirs(os.path.dirname(answers_file), exist_ok=True)
84
+
85
+ try:
86
+ with open(args.question_file, 'r') as f:
87
+ questions = json.load(f)
88
+ except:
89
+ questions = [json.loads(q) for q in open(os.path.expanduser(args.question_file), "r")]
90
+
91
+ if args.end_ind is not None:
92
+ questions = questions[args.start_ind:args.end_ind]
93
+ else:
94
+ questions = questions[args.start_ind:]
95
+ print("start ind: ", args.start_ind)
96
+ print("end ind: ", args.end_ind)
97
+
98
+ # check if the answers file alreay exists
99
+ if not os.path.exists(answers_file) or args.rerun==True:
100
+ print('Running inference...')
101
+ image = Image.open(image_file)
102
+
103
+ if args.dataset_size:
104
+ # randomly sample dataset_size number of questions
105
+ questions = random.sample(questions, args.dataset_size)
106
+
107
+ os.makedirs(os.path.dirname(answers_file), exist_ok=True)
108
+ ans_file = open(answers_file, "w")
109
+
110
+
111
+ # Model
112
+ disable_torch_init()
113
+ model_path = os.path.expanduser(args.model_path)
114
+ model_name = get_model_name_from_path(model_path)
115
+ tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, cache_dir=args.cache_dir)
116
+
117
+ for i in tqdm(range(0,len(questions),args.batch_size)):
118
+ input_batch=[]
119
+ input_image_batch=[]
120
+ count=i
121
+ image_folder=[]
122
+ batch_end = min(i + args.batch_size, len(questions))
123
+
124
+ for j in range(i,batch_end):
125
+ image_file=questions[j]['image']
126
+ qs=questions[j]['conversations'][0]['value']
127
+
128
+ # TODO do we keep that?
129
+
130
+ # if model.config.mm_use_im_start_end:
131
+ # qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
132
+ # print("start end token")
133
+ # else:
134
+ # qs = DEFAULT_IMAGE_TOKEN + '\n' + qs
135
+
136
+ conv = conv_templates[args.conv_mode].copy()
137
+ conv.append_message(conv.roles[0], qs)
138
+ conv.append_message(conv.roles[1], None)
139
+ prompt = conv.get_prompt()
140
+
141
+ print(prompt)
142
+
143
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
144
+ input_batch.append(input_ids)
145
+
146
+ image = Image.open(os.path.join(args.image_folder, image_file))
147
+
148
+ image_folder.append(image)
149
+
150
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
151
+ keywords = [stop_str]
152
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
153
+
154
+ max_length = max(tensor.size(1) for tensor in input_batch)
155
+
156
+ final_input_list = [torch.cat((torch.zeros((1,max_length - tensor.size(1)), dtype=tensor.dtype,device=tensor.get_device()), tensor),dim=1) for tensor in input_batch]
157
+ final_input_tensors=torch.cat(final_input_list,dim=0)
158
+ image_tensor_batch = image_processor.preprocess(image_folder,crop_size ={'height': 504, 'width': 504},size = {'shortest_edge': 504}, return_tensors='pt')['pixel_values']
159
+
160
+ with torch.inference_mode():
161
+ output_ids = model.generate( final_input_tensors, images=image_tensor_batch.half().cuda(), do_sample=False , temperature=args.temperature, top_p=args.top_p, num_beams=1, max_new_tokens=256,length_penalty=2.0, use_cache=True)
162
+
163
+ input_token_len = final_input_tensors.shape[1]
164
+ n_diff_input_output = (final_input_tensors != output_ids[:, :input_token_len]).sum().item()
165
+ if n_diff_input_output > 0:
166
+ print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
167
+ outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)
168
+ for k in range(0,len(final_input_list)):
169
+ output = outputs[k].strip()
170
+ if output.endswith(stop_str):
171
+ output = output[:-len(stop_str)]
172
+ output = output.strip()
173
+
174
+ ans_id = shortuuid.uuid()
175
+
176
+ if args.dataset == 'qfabric':
177
+ ans_file.write(json.dumps({
178
+ "id": questions[count]["id"],
179
+ "image_id": questions[count]["image"],
180
+ "question": questions[count]['conversations'][0]['value'],
181
+ "predicted": output,
182
+ "ground_truth": questions[count]['conversations'][1]['value'],
183
+ "task": questions[count]['task'],
184
+ "original_input_polygon": questions[count]['original_input_polygon'],
185
+ "geovlm_id": questions[count]['geovlm_id']
186
+ }) + "\n")
187
+ elif args.dataset == 's2looking':
188
+ ans_file.write(json.dumps({
189
+ questions[count]["id"] : {
190
+ "image_id": questions[count]["image"],
191
+ "question": questions[count]['conversations'][0]['value'],
192
+ "predicted": output,
193
+ "task": questions[count]['task'],
194
+ "original_input_polygon": questions[count]['original_input_polygon'],
195
+ "geovlm_id": questions[count]['geovlm_id'],
196
+ "original_question": questions[count]['conversations'][0]['value'],
197
+ "original_answer": questions[count]['conversations'][1]['value']
198
+ }}) + "\n")
199
+ elif args.dataset == 'xbd':
200
+ ans_file.write(json.dumps({
201
+ questions[count]["id"] : {
202
+ "image_id": questions[count]["image"],
203
+ "question": questions[count]['conversations'][0]['value'],
204
+ "predicted": output,
205
+ "task": questions[count]['task'],
206
+ "original_input_polygon": questions[count]['original_input_polygon'],
207
+ "original_question": questions[count]['conversations'][0]['value'],
208
+ "original_answer": questions[count]['conversations'][1]['value']
209
+ }}) + "\n")
210
+
211
+ count=count+1
212
+ ans_file.flush()
213
+ ans_file.close()
214
+
215
+ agg_ans_file = args.answers_file.replace('.json', '_agg.json')
216
+ print("Raw Geochat output saved to ", args.answers_file)
217
+
218
+ # determine the split from args.question_file
219
+ if 'test' in args.question_file:
220
+ split = 'test'
221
+ elif 'val' or 'valid' or 'validation' in args.question_file:
222
+ split = 'val'
223
+ elif 'train' in args.question_file:
224
+ split = 'train'
225
+ else:
226
+ raise ValueError("Split not found in question file name")
227
+
228
+ print("Now parsing and aggregating votes for geovlm evaluation...")
229
+ if args.dataset == 'qfabric':
230
+ aggregate_accuracy(args.answers_file, agg_ans_file)
231
+ print("Aggregated output saved to ", agg_ans_file)
232
+
233
+ classification_segmentation(agg_ans_file, 'qfabric')
234
+ elif args.dataset == 's2looking':
235
+ evaluate_geochat_s2looking(args.answers_file, args.question_file, split)
236
+ elif args.dataset == 'xbd':
237
+ classification_segmentation(agg_ans_file, 'xbd')
238
+
239
+
240
+ if __name__ == "__main__":
241
+ parser = argparse.ArgumentParser()
242
+ parser.add_argument("--model-path", type=str, default="facebook/opt-350m")
243
+ parser.add_argument("--model-base", type=str, default=None)
244
+ parser.add_argument("--image-folder", type=str, default="")
245
+ parser.add_argument("--question-file", type=str, default="tables/question.jsonl")
246
+ parser.add_argument("--answers-file", type=str, default="answer.jsonl")
247
+ parser.add_argument("--conv-mode", type=str, default="llava_v1")
248
+ parser.add_argument("--num-chunks", type=int, default=1)
249
+ parser.add_argument("--chunk-idx", type=int, default=0)
250
+ parser.add_argument("--temperature", type=float, default=0.2)
251
+ parser.add_argument("--top_p", type=float, default=None)
252
+ parser.add_argument("--num_beams", type=int, default=1)
253
+ parser.add_argument("--batch_size",type=int, default=1)
254
+ parser.add_argument("--start-ind", type=int, default=0)
255
+ parser.add_argument("--end-ind", type=int, default=None)
256
+ parser.add_argument("--cache-dir", type=str, default=None)
257
+ parser.add_argument("--dataset", type=str)
258
+ parser.add_argument("--rerun", type=bool, default=False)
259
+ parser.add_argument("--dataset_size", type=int, default=None)
260
+ args = parser.parse_args()
261
+
262
+ eval_model(args)
videollava/eval/geochat_referring_2.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code adapted from calculate_mean_ap.py
3
+ author: Timothy C. Arlen
4
+ date: 28 Feb 2018
5
+ """
6
+
7
+ import sys
8
+ from os.path import dirname, abspath
9
+ sys.path.append(dirname(dirname(dirname(dirname(abspath(__file__))))))
10
+
11
+ from collections import defaultdict
12
+ import numpy as np
13
+ import json
14
+ import ast
15
+ import re
16
+ import cv2
17
+ from shapely import wkt, Polygon, box
18
+ from infer_utils import create_mask
19
+ from matplotlib.path import Path
20
+ from tqdm import tqdm
21
+
22
+ from eval_referring import referring_expression
23
+ import matplotlib.pyplot as plt
24
+ import time
25
+ import math
26
+ from matplotlib.path import Path
27
+
28
+ def convert_geochat_string(build, img_size=256):
29
+ """
30
+ Convert the raw str geochat output {<40><89><56><100>|<57>}, {<0><89><56><100>|<57>}
31
+ to a list of rotated bboxes.
32
+ """
33
+ build = build.strip('{}')
34
+ bbox_segments = build.split("}{")
35
+ # Regular expression to find all numbers inside angle brackets
36
+ pattern = r"<(\d+)>"
37
+
38
+ # Extract numbers, convert them to integers, and collect into a list
39
+ bboxes = [
40
+ list(map(int, re.findall(pattern, segment)))
41
+ for segment in bbox_segments
42
+ ]
43
+
44
+ rotated_bboxes = []
45
+ for bbox in bboxes:
46
+ try:
47
+ xmin, ymin, xmax, ymax, angle = [float(v) for v in bbox]
48
+ except:
49
+ print("Warning - Malformed bbox: ", bbox)
50
+ print("Original string: ", build)
51
+ print()
52
+ continue
53
+
54
+ # Convert percentages to pixel coordinates
55
+ xmin = xmin * img_size / 100
56
+ ymin = ymin * img_size / 100
57
+ xmax = xmax * img_size / 100
58
+ ymax = ymax * img_size / 100
59
+
60
+ # Calculate rectangle dimensions
61
+ rect_width = xmax - xmin
62
+ rect_height = ymax - ymin
63
+ center_x = xmin + rect_width / 2
64
+ center_y = ymin + rect_height / 2
65
+
66
+ # Calculate corners before rotation
67
+ corners = np.array([
68
+ [xmin, ymin],
69
+ [xmax, ymin],
70
+ [xmax, ymax],
71
+ [xmin, ymax]
72
+ ])
73
+
74
+ # Rotate corners
75
+ angle_rad = math.radians(angle)
76
+ cos_angle = math.cos(angle_rad)
77
+ sin_angle = math.sin(angle_rad)
78
+ rotated_corners = []
79
+ for x, y in corners:
80
+ tx = x - center_x
81
+ ty = y - center_y
82
+ rotated_x = tx * cos_angle - ty * sin_angle + center_x
83
+ rotated_y = tx * sin_angle + ty * cos_angle + center_y
84
+ rotated_corners.append([rotated_x, rotated_y])
85
+
86
+ rotated_bboxes.append(np.array(rotated_corners))
87
+
88
+ return rotated_bboxes
89
+
90
+ def create_geochat_mask(buildings, img_size=(256, 256)):
91
+ """
92
+ Given a list of buildings in an image, this function
93
+ - creates an img_size * img_size numpy array for the image
94
+ - returns the mask for all buildings
95
+ Input:
96
+ - buildings: List of geochat strings representing buildings
97
+ - img_size: Tuple indicating the size of the image (height, width)
98
+ """
99
+ mask = np.zeros(img_size, np.uint8)
100
+
101
+ # Fill in with ones the pixels that are inside the buildings (rotated bboxes)
102
+ for bbox in buildings:
103
+ path = Path(bbox)
104
+ x, y = np.meshgrid(np.arange(img_size[1]), np.arange(img_size[0]))
105
+ points = np.vstack((x.flatten(), y.flatten())).T
106
+ mask[path.contains_points(points).reshape(img_size)] = 1
107
+
108
+ return mask
109
+
110
+ def calc_iou_individual(pred_box, gt_box):
111
+ """Calculate IoU of single predicted and ground truth box
112
+ Args:
113
+ pred_box (list of floats): location of predicted object as
114
+ [xmin, ymin, xmax, ymax]
115
+ gt_box (list of floats): location of ground truth object as
116
+ [xmin, ymin, xmax, ymax]
117
+ Returns:
118
+ float: value of the IoU for the two boxes.
119
+ Raises:
120
+ AssertionError: if the box is obviously malformed
121
+ """
122
+ x1_t, y1_t, x2_t, y2_t = gt_box
123
+ try:
124
+ x1_p, y1_p, x2_p, y2_p = pred_box
125
+ except:
126
+ return 0.0
127
+
128
+ if (x1_p > x2_p) or (y1_p > y2_p):
129
+ print("Prediction box is malformed? pred box: {}".format(pred_box))
130
+ if (x1_t > x2_t) or (y1_t > y2_t):
131
+ print("Ground Truth box is malformed? true box: {}".format(gt_box))
132
+
133
+ if (x2_t < x1_p or x2_p < x1_t or y2_t < y1_p or y2_p < y1_t):
134
+ return 0.0
135
+
136
+ far_x = np.min([x2_t, x2_p])
137
+ near_x = np.max([x1_t, x1_p])
138
+ far_y = np.min([y2_t, y2_p])
139
+ near_y = np.max([y1_t, y1_p])
140
+
141
+ inter_area = (far_x - near_x + 1) * (far_y - near_y + 1)
142
+ true_box_area = (x2_t - x1_t + 1) * (y2_t - y1_t + 1)
143
+ pred_box_area = (x2_p - x1_p + 1) * (y2_p - y1_p + 1)
144
+ iou = inter_area / (true_box_area + pred_box_area - inter_area)
145
+
146
+ return iou
147
+
148
+ def calc_iou_individual_rotated(pred_box, gt_box):
149
+ """Calculate IoU of single predicted and ground truth box
150
+ Args:
151
+ pred_box (list of floats): location of predicted object as
152
+ [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
153
+ gt_box (list of floats): location of ground truth object as
154
+ [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
155
+ Returns:
156
+ float: value of the IoU for the two boxes.
157
+ Raises:
158
+ AssertionError: if the box is obviously malformed
159
+ """
160
+ try:
161
+ pred_box = np.array(pred_box)
162
+ gt_box = np.array(gt_box)
163
+ except:
164
+ return 0.0
165
+ if len(pred_box) == 4:
166
+ pred_box = [[pred_box[0], pred_box[1]], [pred_box[2], pred_box[1]], [pred_box[2], pred_box[3]], [pred_box[0], pred_box[3]]]
167
+ if len(gt_box) == 4:
168
+ gt_box = [[gt_box[0], gt_box[1]], [gt_box[2], gt_box[1]], [gt_box[2], gt_box[3]], [gt_box[0], gt_box[3]]]
169
+ pred_box = np.array(pred_box)
170
+ gt_box = np.array(gt_box)
171
+ pred_box = pred_box.reshape(4, 2)
172
+ gt_box = gt_box.reshape(4, 2)
173
+ pred_polygon = Polygon(pred_box)
174
+ gt_polygon = Polygon(gt_box)
175
+ intersection = pred_polygon.intersection(gt_polygon).area
176
+ union = pred_polygon.union(gt_polygon).area
177
+ iou = intersection / union
178
+ return iou
179
+
180
+ # try:
181
+ # pred_box = np.array(pred_box)
182
+ # gt_box = np.array(gt_box)
183
+ # except:
184
+ # return 0.0
185
+
186
+ # pred_box = pred_box.reshape(4, 2)
187
+ # gt_box = gt_box.reshape(4, 2)
188
+
189
+ # pred_polygon = Polygon(pred_box)
190
+ # gt_polygon = Polygon(gt_box)
191
+
192
+ # intersection = pred_polygon.intersection(gt_polygon).area
193
+ # union = pred_polygon.union(gt_polygon).area
194
+
195
+ # iou = intersection / union
196
+
197
+ # plt.figure()
198
+ # plt.plot(*pred_polygon.exterior.xy, color='r', label='pred')
199
+ # plt.plot(*gt_polygon.exterior.xy, color='b', label='gt')
200
+ # plt.legend()
201
+ # plt.title(f"IoU: {iou}")
202
+ # plt.show()
203
+ # plt.savefig("iou.png")
204
+ # time.sleep(1)
205
+ # plt.close()
206
+
207
+ return iou
208
+
209
+
210
+ def get_single_image_bound_results(gt_wkts, pred_geochat_string, img_size=256):
211
+ """
212
+ Calculates upper bound and lower bound number of true_pos, false_pos, false_neg from single batch of boxes.
213
+ Args:
214
+ gt_wkts (list of strs): list of wkt strings of input polygons, scaled to raw pixel value
215
+ pred_boxes (list of lists): list of list of boxes, where each box is formatted
216
+ as [x_min, y_min, x_max, y_max] on scale from 0-100
217
+ img_size (int): dimensions of the image. defaults to 256.
218
+ Returns:
219
+ tuple of dicts: true positives (int), false positives (int), false negatives (int)
220
+ """
221
+ if isinstance(gt_wkts, str):
222
+ gt_polygons = [wkt.loads(gt_wkts)]
223
+ else:
224
+ gt_polygons = [wkt.loads(gt_wkt) for gt_wkt in gt_wkts]
225
+
226
+ # #Β Needs fixing for auxiliary
227
+ # if len(gt_polygons) == 0:
228
+ # false_neg = np.sum(gt_mask)
229
+ # ub_stats= {'true_pos': 0, 'false_pos': 0, 'false_neg': false_neg, 'intersection':0, 'union':false_neg}
230
+ # lb_stats = {'true_pos': 0, 'false_pos': 0, 'false_neg': false_neg, 'intersection':0, 'union':false_neg}
231
+ # return lb_stats, ub_stats
232
+
233
+ lb_preds = convert_geochat_string(pred_geochat_string, img_size)
234
+ # get mask of all gt_polygons and lb_preds
235
+ gt_mask = create_mask(gt_polygons, (img_size, img_size))
236
+ lb_preds_mask = create_geochat_mask(lb_preds, (img_size, img_size))
237
+
238
+ # get lower bound intersection and union masks
239
+ intersection = np.logical_and(gt_mask, lb_preds_mask)
240
+ union = np.logical_or(gt_mask, lb_preds_mask)
241
+
242
+ # compute lb metrics
243
+ # lower_bound_iou = np.sum(intersection) / np.sum(union)
244
+ fp = np.sum(np.logical_and(lb_preds_mask, np.logical_not(gt_mask)))
245
+ tp = np.sum(np.logical_and(lb_preds_mask, gt_mask))
246
+ fn = np.sum(np.logical_and(np.logical_not(lb_preds_mask), gt_mask))
247
+ lb_stats = {'true_pos': tp, 'false_pos': fp, 'false_neg': fn, 'intersection': np.sum(intersection), 'union': np.sum(union)}
248
+
249
+ # get upper bound intersection and union masks
250
+ ub_pred_mask = np.logical_and(gt_mask, lb_preds_mask)
251
+ intersection = np.logical_and(ub_pred_mask, gt_mask)
252
+ union = np.logical_or(gt_mask, ub_pred_mask)
253
+
254
+ # compute ub metrics
255
+ # upper_bound_iou = np.sum(intersection) / np.sum(union)
256
+ ub_fp = np.sum(np.logical_and(ub_pred_mask, np.logical_not(gt_mask)))
257
+ ub_tp = np.sum(np.logical_and(ub_pred_mask, gt_mask))
258
+ ub_fn = np.sum(np.logical_and(np.logical_not(ub_pred_mask), gt_mask))
259
+ ub_stats = {'true_pos': ub_tp, 'false_pos': ub_fp, 'false_neg': ub_fn, 'intersection': np.sum(intersection), 'union': np.sum(union)}
260
+
261
+ return lb_stats, ub_stats
262
+
263
+ def get_geochat_dataset(image_id):
264
+ if image_id.startswith("P"):
265
+ dataset = "SOTA"
266
+ elif image_id.startswith("train"):
267
+ dataset = "FAST"
268
+ else:
269
+ dataset = "SIOR"
270
+ return dataset
271
+
272
+ def get_single_image_results(gt_boxes, pred_boxes, iou_thr):
273
+ """Calculates number of true_pos, false_pos, false_neg from single batch of boxes.
274
+ Args:
275
+ gt_boxes (list of list of floats): list of locations of ground truth
276
+ objects as [[x1,y1], [x2,y2], ...]
277
+ pred_boxes (dict): dict of dicts of 'boxes'
278
+ [[x1,y1], [x2,y2], ...]
279
+ iou_thr (float): value of IoU to consider as threshold for a
280
+ true prediction.
281
+ Returns:
282
+ dict: true positives (int), false positives (int), false negatives (int)
283
+ """
284
+
285
+ all_pred_indices = range(len(pred_boxes))
286
+ all_gt_indices = range(len(gt_boxes))
287
+ if len(all_pred_indices) == 0:
288
+ tp = 0
289
+ fp = 0
290
+ fn = len(gt_boxes)
291
+ return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}
292
+ if len(all_gt_indices) == 0:
293
+ tp = 0
294
+ fp = len(pred_boxes)
295
+ fn = 0
296
+ return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}
297
+
298
+ gt_idx_thr = []
299
+ pred_idx_thr = []
300
+ ious = []
301
+ for ipb, pred_box in enumerate(pred_boxes):
302
+ for igb, gt_box in enumerate(gt_boxes):
303
+ iou = calc_iou_individual_rotated(pred_box, gt_box)
304
+ if iou > iou_thr:
305
+ gt_idx_thr.append(igb)
306
+ pred_idx_thr.append(ipb)
307
+ ious.append(iou)
308
+
309
+ args_desc = np.argsort(ious)[::-1]
310
+ if len(args_desc) == 0:
311
+ # No matches
312
+ tp = 0
313
+ fp = len(pred_boxes)
314
+ fn = len(gt_boxes)
315
+ else:
316
+ gt_match_idx = []
317
+ pred_match_idx = []
318
+ for idx in args_desc:
319
+ gt_idx = gt_idx_thr[idx]
320
+ pr_idx = pred_idx_thr[idx]
321
+ # If the boxes are unmatched, add them to matches
322
+ if (gt_idx not in gt_match_idx) and (pr_idx not in pred_match_idx):
323
+ gt_match_idx.append(gt_idx)
324
+ pred_match_idx.append(pr_idx)
325
+ tp = len(gt_match_idx)
326
+ fp = len(pred_boxes) - len(pred_match_idx)
327
+ fn = len(gt_boxes) - len(gt_match_idx)
328
+
329
+ return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}
330
+
331
+
332
+ def calc_precision_recall(img_results):
333
+ """Calculates precision and recall from the set of images
334
+ Args:
335
+ img_results (dict): dictionary formatted like:
336
+ {
337
+ 'img_id1': {'true_pos': int, 'false_pos': int, 'false_neg': int},
338
+ 'img_id2': ...
339
+ ...
340
+ }
341
+ Returns:
342
+ tuple: of floats of (precision, recall)
343
+ """
344
+ true_pos = 0; false_pos = 0; false_neg = 0
345
+ for _, res in img_results.items():
346
+ true_pos += res['true_pos']
347
+ false_pos += res['false_pos']
348
+ false_neg += res['false_neg']
349
+
350
+ try:
351
+ precision = true_pos/(true_pos + false_pos)
352
+ except ZeroDivisionError:
353
+ precision = 0.0
354
+ try:
355
+ recall = true_pos/(true_pos + false_neg)
356
+ except ZeroDivisionError:
357
+ recall = 0.0
358
+
359
+ return (precision, recall)
360
+
361
+
362
+ DIMENSIONS = {'FAST': 600,
363
+ 'SIOR': 800,
364
+ 'SOTA': 1024}
365
+
366
+
367
+ def referring_expression(answer_path, dataset, verbose=False, saving_path_root=None, img_size=256):
368
+ # Replace with the path to the answers file
369
+ if type(answer_path) == dict:
370
+ results = answer_path
371
+ else:
372
+ with open(answer_path) as json_data:
373
+ results = json.load(json_data)
374
+
375
+ img_results = {}
376
+ ub_results = {}
377
+ lb_results = {}
378
+ num_bboxes = 0
379
+ # Loop over results and get precision, recall overall
380
+ for id, result in tqdm(results.items()):
381
+
382
+ if dataset == "geochat_xbd":
383
+ pred = result['predicted']
384
+
385
+ dataset = get_geochat_dataset(id)
386
+ img_size = (DIMENSIONS[dataset])
387
+ pred = convert_geochat_string(pred, img_size)
388
+
389
+ ground_truth = result['ground_truth']
390
+ ground_truth = np.array(ground_truth)
391
+ num_bboxes += len(ground_truth)
392
+
393
+ img_results[id] = get_single_image_results(ground_truth, pred, iou_thr=0.5)
394
+
395
+ continue
396
+
397
+ try:
398
+ if 'referring_expression' not in result['task']:
399
+ continue # no bounding box outputs for temporal_referring_expression
400
+ except:
401
+ pass
402
+
403
+ # TODO: LOOP THROUGH IDENTIFY TASKS/QUESTIONS IN THE DATASET
404
+
405
+ # TODO: HANDLE WHEN THERE ARE NO BOUNDING BOXES IN GROUND TRUTH for auxiliary tasks
406
+ if not result['original_input_polygon']:
407
+ first_open_bracket_ind = result["predicted"].find("{")
408
+ last_close_bracket_ind = result["predicted"].rfind("}")
409
+ if last_close_bracket_ind != -1 and first_open_bracket_ind != -1:
410
+ parsed_predicted = result["predicted"][first_open_bracket_ind:last_close_bracket_ind+1]
411
+ else:
412
+ parsed_predicted = ""
413
+ predicted_boxes = convert_geochat_string(parsed_predicted)
414
+ # If ground truth contains no boxes: all predictions are false positives
415
+ false_pos = len(predicted_boxes)
416
+ false_pos_pixels = np.sum(create_geochat_mask(predicted_boxes))
417
+ img_results[id] = {'true_pos': 0, 'false_pos': false_pos, 'false_neg': 0, 'intersection':0, 'union':false_pos_pixels}
418
+ ub_results[id] = {'true_pos': 0, 'false_pos': false_pos_pixels, 'false_neg': 0, 'intersection':0, 'union':false_pos_pixels}
419
+ lb_results[id] = {'true_pos': 0, 'false_pos': false_pos_pixels, 'false_neg': 0, 'intersection':0, 'union':false_pos_pixels}
420
+ continue
421
+ else: #Β Ground truth contains boxes: find predicted Geochat boxes
422
+ first_open_bracket_ind = result["predicted"].find("{")
423
+ last_close_bracket_ind = result["predicted"].rfind("}")
424
+ if last_close_bracket_ind != -1 and first_open_bracket_ind != -1:
425
+ parsed_predicted = result["predicted"][first_open_bracket_ind:last_close_bracket_ind+1]
426
+ else:
427
+ parsed_predicted = ""
428
+ gt_wkts = result['original_input_polygon']
429
+ lb_results[id], ub_results[id] = get_single_image_bound_results(gt_wkts, parsed_predicted)
430
+
431
+ if len(ub_results) != 0:
432
+ ub_intersection = np.sum([res['intersection'] for res in ub_results.values()])
433
+ ub_union = np.sum([res['union'] for res in ub_results.values()])
434
+ lb_intersection = np.sum([res['intersection'] for res in lb_results.values()])
435
+ lb_union = np.sum([res['union'] for res in lb_results.values()])
436
+ print("Upper bound IOU: ", ub_intersection / ub_union if ub_union != 0 else 0)
437
+ print("Lower bound IOU: ", lb_intersection / lb_union if lb_union != 0 else 0)
438
+ ub_precision, ub_recall = calc_precision_recall(ub_results)
439
+ lb_precision, lb_recall = calc_precision_recall(lb_results)
440
+ print('Lower bound precision: ', lb_precision)
441
+ print('Lower bound recall: ', lb_recall)
442
+ print("Upper bound F1: ", 2 * (ub_precision * ub_recall) / (ub_precision + ub_recall) if (ub_precision + ub_recall) != 0 else 0)
443
+ print("Lower bound F1: ", 2 * (lb_precision * lb_recall) / (lb_precision + lb_recall) if (lb_precision + lb_recall) != 0 else 0)
444
+
445
+ print("[email protected]: ", np.sum([res['true_pos'] for res in img_results.values()]) / num_bboxes)
446
+
447
+ if type(answer_path) == dict:
448
+ return
449
+
450
+ if saving_path_root:
451
+ with open(f"{saving_path_root}/referring_expression_scores.json", 'w') as f:
452
+ json.dump(img_results, f)
453
+
454
+ if __name__ == '__main__':
455
+ answer_path = "scripts/geovlm/eval/xBD/answers/ckpt14000-geochat-bench_interleave_test.json"
456
+ referring_expression(answer_path, dataset="geochat_xbd")
457
+ #answer_path = "scripts/geochat/eval/xBD/geochat_xbd_test_auxiliary_dict.json"
458
+ # referring_expression(answer_path, dataset="xbd")
459
+
videollava/eval/geochat_s2looking_utils.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import json
3
+ import numpy as np
4
+ import cv2
5
+ import re
6
+ from eval_referring import referring_expression
7
+ import matplotlib.pyplot as plt
8
+ from shapely import wkt
9
+ import time
10
+ import math
11
+ from matplotlib.path import Path
12
+ from eval_classification import accuracy_precision_recall
13
+
14
+
15
+ def convert_geochat_string(build, img_size=256):
16
+ """
17
+ convert the raw str geochat output {<40><89><56><100>|<57>}, {<0><89><56><100>|<57>}
18
+ to a list of rotated bboxes
19
+ """
20
+ build = build.strip('{}')
21
+ bbox_segments = build.split("}{")
22
+
23
+ # Regular expression to find all numbers inside angle brackets
24
+ pattern = r"<(\d+)>"
25
+
26
+ # Extract numbers, convert them to integers, and collect into a list
27
+ bboxes = [
28
+ list(map(int, re.findall(pattern, segment)))
29
+ for segment in bbox_segments]
30
+
31
+ rotated_bboxes = []
32
+ for bbox in bboxes:
33
+ try:
34
+ xmin, ymin, xmax, ymax, angle = [float(v) for v in bbox]
35
+ except:
36
+ pass
37
+
38
+ # Convert percentages to pixel coordinates
39
+ xmin = xmin * img_size / 100
40
+ ymin = ymin * img_size / 100
41
+ xmax = xmax * img_size / 100
42
+ ymax = ymax * img_size / 100
43
+
44
+ # Calculate rectangle dimensions
45
+ rect_width = xmax - xmin
46
+ rect_height = ymax - ymin
47
+ center_x = xmin + rect_width / 2
48
+ center_y = ymin + rect_height / 2
49
+
50
+ # Calculate corners before rotation
51
+ corners = np.array([
52
+ [xmin, ymin],
53
+ [xmax, ymin],
54
+ [xmax, ymax],
55
+ [xmin, ymax]
56
+ ])
57
+
58
+ # Rotate corners
59
+ angle_rad = math.radians(angle)
60
+ cos_angle = math.cos(angle_rad)
61
+ sin_angle = math.sin(angle_rad)
62
+ rotated_corners = []
63
+ for x, y in corners:
64
+ tx = x - center_x
65
+ ty = y - center_y
66
+ rotated_x = tx * cos_angle - ty * sin_angle + center_x
67
+ rotated_y = tx * sin_angle + ty * cos_angle + center_y
68
+ rotated_corners.append([rotated_x, rotated_y])
69
+
70
+ rotated_bboxes.append(np.array(rotated_corners))
71
+
72
+ return rotated_bboxes
73
+
74
+
75
+ def get_changed_buildings(build1, build2, img_size=256, task=None):
76
+ """
77
+ Given a list of predicted buildings in image 1 and image 2, this function
78
+ - creates two img_size * img_size numpy arrays for both of the images
79
+ - gets the mask differences between the two numpy arrays
80
+ - returns a list of bounding boxes that reflect those differences, as well as the difference mask
81
+ Input:
82
+ - build1: [[x,y],[x,y],[x,y],[x,y]] array of four x,y coordinates of the bounding box of a building
83
+ - task can be either None, constructed or destructed
84
+ Note: those bboxes can be rotated
85
+ """
86
+ image1 = np.zeros((img_size, img_size), np.uint8)
87
+ image2 = np.zeros((img_size, img_size), np.uint8)
88
+
89
+ build1 = convert_geochat_string(build1)
90
+ build2 = convert_geochat_string(build2)
91
+
92
+ # fill in with ones the pixels that are inside the rotated bboxes
93
+ for b in build1:
94
+ path = Path(b)
95
+ x, y = np.meshgrid(np.arange(img_size), np.arange(img_size))
96
+ points = np.vstack((x.flatten(), y.flatten())).T
97
+ image1[path.contains_points(points).reshape(img_size, img_size)] = 1
98
+
99
+ for b in build2:
100
+ path = Path(b)
101
+ x, y = np.meshgrid(np.arange(img_size), np.arange(img_size))
102
+ points = np.vstack((x.flatten(), y.flatten())).T
103
+ image2[path.contains_points(points).reshape(img_size, img_size)] = 1
104
+
105
+ # xor between the two images
106
+ if task == None:
107
+ diff = cv2.bitwise_xor(image1, image2)
108
+ elif task == "constructed":
109
+ # if the task is constructed, we want to find the pixels that are in image2 but not in image1
110
+ diff = cv2.bitwise_and(image2, cv2.bitwise_not(image1))
111
+ elif task == "destructed":
112
+ # if the task is destructed, we want to find the pixels that are in image1 but not in image2
113
+ diff = cv2.bitwise_and(image1, cv2.bitwise_not(image2))
114
+
115
+ # get the bounding boxes of the difference pixels
116
+ contours, _ = cv2.findContours(diff, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
117
+ bboxes = []
118
+ for contour in contours:
119
+ x, y, w, h = cv2.boundingRect(contour)
120
+ x, y, w, h = y, x, h, w
121
+ bboxes.append([x, y, x+w, y+h])
122
+
123
+ return bboxes, diff
124
+
125
+ def get_canonical_answer_dataset(answers):
126
+ """
127
+ This function creates a new dataset with questions and answers for geochat, ready to parse into the evaluation metrics."""
128
+
129
+ new_dataset = {}
130
+
131
+ for key, answer in answers.items():
132
+ num, quadrant, geovlmid = key.split("_")
133
+ task = answer['task']
134
+ if geovlmid == "1" in task:
135
+ continue
136
+
137
+ # find the paired image
138
+ id2 = num + "_" + quadrant + "_" + "1"
139
+ answer1 = answers[key]
140
+ try:
141
+ answer2 = answers[id2]
142
+ except:
143
+ print(f"The associated image to {key} wasn't present in the dataset")
144
+ continue
145
+
146
+ # get the pixel diff boxes
147
+ change_bboxes, mask = get_changed_buildings(answer1['predicted'], answer2['predicted'])
148
+
149
+ # create the new dataset adapted for running metrics on it
150
+ new_line = {}
151
+
152
+ new_line['predicted'] = ""
153
+ if len(change_bboxes)>0:
154
+ for bbox in change_bboxes:
155
+ new_line['predicted'] += str(bbox) + ", "
156
+ new_line['predicted'] = new_line['predicted'][:-2]
157
+ new_line['predicted_mask'] = mask.tolist()
158
+
159
+ new_line['ground_truth'] = answer1['original_answer']
160
+ new_line['question'] = answer1['original_question']
161
+ new_line['task'] = answer1['task']
162
+ new_line['original_input_polygon'] = answer1['original_input_polygon']
163
+
164
+ new_key = num + "_" + quadrant
165
+ new_dataset[new_key] = new_line
166
+
167
+ return new_dataset
168
+
169
+ def postprocess_auxiliary_qa(key, answer, original_answers):
170
+ new_line = {}
171
+ new_line['ground_truth'] = answer['ground_truth']
172
+ new_line['question'] = answer['question']
173
+ new_line['task'] = answer['task']
174
+ new_line['original_input_polygon'] = answer['original_input_polygon']
175
+
176
+ # retrieve the original 2 anwers
177
+ answer1 = original_answers[key + '_0']['predicted']
178
+ answer2 = original_answers[key + '_1']['predicted']
179
+
180
+ # retrieve the task (construction or destruction)
181
+ setting = None
182
+ if "constructed" or "built" in answer['original_question']:
183
+ setting = "constructed"
184
+ elif "destructed" or "torn down" in answer['original_question']:
185
+ setting = "destructed"
186
+ else:
187
+ print("The task is not recognized")
188
+ print("Original question: ", answer['original_question'])
189
+ print()
190
+
191
+ # get the pixel diff boxes
192
+ change_bboxes, mask = get_changed_buildings(answer1, answer2, task=setting)
193
+
194
+ new_line['predicted_mask'] = mask.tolist()
195
+ contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
196
+
197
+ found_convex_polygon = False
198
+ for contour in contours:
199
+ # check if the contour is a bounding box (4 vertices, rectangle shape)
200
+ epsilon = 0.04 * cv2.arcLength(contour, True)
201
+ approx = cv2.approxPolyDP(contour, epsilon, True)
202
+ if len(approx) == 4:
203
+ found_convex_polygon = True
204
+ break
205
+
206
+ if found_convex_polygon:
207
+ new_line['predicted'] = "Yes"
208
+ else:
209
+ new_line['predicted'] = "No"
210
+
211
+ return new_line
212
+
213
+
214
+ def postprocess_auxiliary_region_qa(key, answer, original_answers, img_size=256):
215
+ """
216
+ There is a bbox in the input polygon, we need to find the changed buildings in the image
217
+ inside that bbox
218
+ """
219
+ new_line = {}
220
+ new_line['ground_truth'] = answer['ground_truth']
221
+ new_line['question'] = answer['question']
222
+ new_line['task'] = answer['task']
223
+ new_line['original_input_polygon'] = answer['original_input_polygon']
224
+
225
+ # retrieve the original 2 anwers
226
+ answer1 = original_answers[key + '_0']['predicted']
227
+ answer2 = original_answers[key + '_1']['predicted']
228
+
229
+ # get the pixel diff boxes
230
+ change_bboxes, mask = get_changed_buildings(answer1, answer2)
231
+
232
+ # get the input bbox
233
+ question = new_line['question']
234
+ # find the positions of '[' and ']'
235
+ start = question.find('[')
236
+ end = question.find(']')
237
+ bbox = question[start+1:end].split(',')
238
+ bbox = [int(b) * img_size // 100 for b in bbox]
239
+
240
+ # adapt the mask, put 0s outside the bbox
241
+ mask[:bbox[0], :] = 0
242
+ mask[bbox[2]:, :] = 0
243
+ mask[:, :bbox[1]] = 0
244
+ mask[:, bbox[3]:] = 0
245
+
246
+ # predict yes or no if there is a convex polygon in the mask
247
+ found_convex_polygon = False
248
+ contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
249
+ for contour in contours:
250
+ # check if the contour is a bounding box (4 vertices, rectangle shape)
251
+ epsilon = 0.04 * cv2.arcLength(contour, True)
252
+ approx = cv2.approxPolyDP(contour, epsilon, True)
253
+ if len(approx) == 4:
254
+ found_convex_polygon = True
255
+ break
256
+
257
+ new_line['predicted_mask'] = mask.tolist()
258
+
259
+ if found_convex_polygon:
260
+ new_line['predicted'] = "Yes"
261
+ else:
262
+ new_line['predicted'] = "No"
263
+
264
+ return new_line
265
+
266
+
267
+ def postprocess_auxiliary_referring(key, answer, original_answers):
268
+ new_line = {}
269
+ new_line['ground_truth'] = answer['ground_truth']
270
+ new_line['question'] = answer['question']
271
+ new_line['task'] = answer['task']
272
+ new_line['original_input_polygon'] = answer['original_input_polygon']
273
+
274
+ # retrieve the original 2 anwers
275
+ answer1 = original_answers[key + '_0']['predicted']
276
+ answer2 = original_answers[key + '_1']['predicted']
277
+
278
+ # retrieve the task (construction or destruction)
279
+ setting = None
280
+ if "constructed" or "built" in answer['original_question']:
281
+ setting = "constructed"
282
+ elif "destructed" or "torn down" in answer['original_question']:
283
+ setting = "destructed"
284
+ else:
285
+ print("The task is not recognized")
286
+ print("Original question: ", answer['original_question'])
287
+ print()
288
+
289
+ # get the pixel diff boxes
290
+ change_bboxes, mask = get_changed_buildings(answer1, answer2, task=setting)
291
+
292
+ new_line['predicted_mask'] = mask.tolist()
293
+ new_line['predicted'] = ""
294
+ if len(change_bboxes)>0:
295
+ for bbox in change_bboxes:
296
+ new_line['predicted'] += str(bbox) + ", "
297
+ new_line['predicted'] = new_line['predicted'][:-2]
298
+
299
+ return new_line
300
+
301
+
302
+ def postprocess_auxiliary_geochat_s2looking(canonical_answers, original_answers):
303
+ """
304
+ Postprocess the auxiliary file for geochat_s2looking
305
+ The present questions are
306
+ question1 = 'temporal_question_answering: Are there any buildings in the first image which were {destructed,torn down} in the second?'
307
+ question2 = 'temporal_referring_expression: Identify the buildings in the first image which were {built,constructed,destructed,torn down} as seen in the second image.'
308
+ question3 = 'localization_task: Identify all changed buildings.'
309
+ question4 = 'referring_expression: identify the {constructed, destructed} buildings in the image.'
310
+ question5 = 'question_answering: Have any buildings been task in the area? Please answer with Yes or No'
311
+
312
+ The goal is to update the 'predicted' field with the correct bounding boxes of the changed buildings.
313
+ - Localization can be kept as is.
314
+ - For question answering tasks, the 'predicted' field should be updated with 'Yes' or 'No' depending on the answer.
315
+ We output 'Yes' if there is a convex polygon in the 'predicted' field.
316
+ - For referring expression, we first need to identify if the task is 'constructed' or 'destructed' and then update the 'predicted' field with the correct mask of the changed buildings.
317
+ Input:
318
+ - answers: dictionary with the answers paired with the get_canonical_answer_dataset function
319
+ Output:
320
+ - postprocessed_answers: dictionary with 'predicted' and 'predicted_mask' fields updated
321
+ """
322
+ postprocessed_answers = {}
323
+
324
+ for key, answer in canonical_answers.items():
325
+ task = answer['task']
326
+
327
+ if 'localization' in task:
328
+ postprocessed_answers[key] = answer
329
+ continue
330
+ if 'region_based_question_answering' in task:
331
+ answer = postprocess_auxiliary_region_qa(key, answer, original_answers)
332
+ postprocessed_answers[key] = answer
333
+ continue
334
+ if 'question_answering' in task:
335
+ answer = postprocess_auxiliary_qa(key, answer, original_answers)
336
+ postprocessed_answers[key] = answer
337
+ continue
338
+ if 'referring_expression' in task:
339
+ answer = postprocess_auxiliary_referring(key, answer, original_answers)
340
+ postprocessed_answers[key] = answer
341
+ continue
342
+
343
+ return postprocessed_answers
344
+
345
+
346
+ def evaluate_geochat_s2looking(answer_file, dataset_file, split):
347
+ answers = {}
348
+ with open(answer_file, 'r') as f:
349
+ for line in f:
350
+ line = json.loads(line)
351
+ answers[list(line.keys())[0]] = line[list(line.keys())[0]]
352
+
353
+ dataset = dataset_file.split("/")[-1]
354
+ if dataset == "dataset_canonical.json":
355
+
356
+ # create a new dataset with questions and answers for geochat
357
+ postprocessed_answers = get_canonical_answer_dataset(answers)
358
+
359
+ referring_expression(postprocessed_answers, "geochat_s2looking", False, "s2looking/answers/geochat_canonical_test", split=split)
360
+
361
+ elif dataset == "dataset_v01_v02_canonical_filtered.json" or dataset == "dataset_RQA.json":
362
+
363
+ # create a new dataset with questions and answers for geochat
364
+ postprocessed_answers = get_canonical_answer_dataset(answers)
365
+ postprocessed_answers = postprocess_auxiliary_geochat_s2looking(postprocessed_answers, answers)
366
+
367
+ print("Referring expression")
368
+ referring_expression(postprocessed_answers, "geochat_s2looking", False, "s2looking/answers/geochat_v01_v02_canonical_filtered_test", split=split)
369
+ print()
370
+ print("Accuracy")
371
+ accuracy_precision_recall(postprocessed_answers, "s2looking", verbose=False)
372
+ print()
373
+
374
+
375
+ # also run per-question referring expression
376
+ question1 = 'temporal_question_answering: Are there any buildings in the first image which were {destructed,torn down} in the second?'
377
+ question2 = 'temporal_referring_expression: Identify the buildings in the first image which were {built,constructed,destructed,torn down} as seen in the second image.'
378
+ question3 = 'localization_task: Identify all changed buildings.'
379
+ question4 = 'referring_expression: identify the {constructed, destructed} buildings in the image.'
380
+ question5 = 'question_answering: Have any buildings been task in the area? Please answer with Yes or No'
381
+
382
+
383
+ for question in [question1, question2, question3, question4, question5]:
384
+ dataset_question = {}
385
+ for data in postprocessed_answers:
386
+ if postprocessed_answers[data]['task'] == question:
387
+ dataset_question[data] = postprocessed_answers[data]
388
+
389
+ if len(dataset_question) > 0:
390
+ print('Evaluating for question ', question)
391
+ print('Size of the dataset is ', len(dataset_question))
392
+ referring_expression(dataset_question, "geochat_s2looking", False, "s2looking/answers/geochat_v01_v02_canonical_filtered_test", split=split)
393
+ print()
394
+
395
+ else:
396
+ print("Evaluation is not suppored for this dataset. Please provide a valid dataset.")
397
+ print("The supported datasets are: dataset_canonical.json, dataset_v01_v02_canonical_filtered.json")
398
+
399
+
400
+
videollava/eval/geochat_utils.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from tqdm import tqdm
3
+ from pathlib import Path
4
+
5
+ from infer_utils import run_inference_single
6
+ import numpy as np
7
+
8
+
9
+ def run_geochat_inference(
10
+ model,
11
+ dataset_path,
12
+ processor,
13
+ tokenizer,
14
+ conv_mode,
15
+ answer_path,
16
+ use_video_data=False,
17
+ open_prompt=None,
18
+ repeat_frames=None,
19
+ prompt_strategy="interleave",
20
+ chronological_prefix=True,
21
+ data_frac=1,
22
+ data_size=None,
23
+ delete_system_prompt=False,
24
+ start_ind=0,
25
+ end_ind=None,
26
+ print_prompt=False
27
+ ):
28
+
29
+ with open(dataset_path) as f:
30
+ qfabric_data = json.load(f)
31
+
32
+ if data_size is not None:
33
+ data_size = min(data_size, len(qfabric_data))
34
+ idx = np.random.choice(len(qfabric_data), data_size, replace=False)
35
+ qfabric_data = [qfabric_data[i] for i in idx]
36
+ elif data_frac < 1:
37
+ idx = np.random.choice(len(qfabric_data), int(len(qfabric_data) * data_frac), replace=False)
38
+ qfabric_data = [qfabric_data[i] for i in idx]
39
+
40
+ answers = {}
41
+ answers_tmp = str(answer_path).replace(".json", "_tmp.json")
42
+ if end_ind is not None:
43
+ answers_tmp = str(answers_tmp).replace(".json", f"_{start_ind}_{end_ind}.json")
44
+ qfabric_data = qfabric_data[start_ind:end_ind]
45
+ else:
46
+ answers_tmp = str(answers_tmp).replace(".json", f"_{start_ind}_end.json")
47
+ qfabric_data = qfabric_data[start_ind:]
48
+
49
+ print("answers_tmp: ", answers_tmp)
50
+ print("start ind: ", start_ind)
51
+ print("end ind: ", end_ind)
52
+
53
+ for question in tqdm(qfabric_data):
54
+ question_id = question["id"]
55
+ inp = question["conversations"][0]['value']
56
+
57
+ answer_str = question["conversations"][1]['value']
58
+ metadata = question['metadata']
59
+ image_paths = question['video']
60
+ task = question['task']
61
+ original_input_polygon = question['original_input_polygon']
62
+ dataset = question['dataset']
63
+
64
+ outputs = run_inference_single(
65
+ model=model,
66
+ processor=processor,
67
+ tokenizer=tokenizer,
68
+ conv_mode=conv_mode,
69
+ inp=inp,
70
+ image_paths=image_paths,
71
+ metadata=metadata,
72
+ repeat_frames=repeat_frames,
73
+ use_video_data=use_video_data,
74
+ prompt_strategy=prompt_strategy,
75
+ chronological_prefix=chronological_prefix,
76
+ delete_system_prompt=delete_system_prompt,
77
+ print_prompt=print_prompt
78
+ )
79
+
80
+ entry = {
81
+ "id": question_id,
82
+ "question": inp,
83
+ "predicted": outputs,
84
+ "ground_truth": answer_str,
85
+ "task": task,
86
+ "original_input_polygon": original_input_polygon,
87
+ "dataset": dataset,
88
+ }
89
+ answers[question_id] = entry
90
+
91
+ with open(answers_tmp, "a") as f:
92
+ f.write(json.dumps(entry) + "\n")
93
+
94
+ return answers
videollava/eval/infer_eval.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fire
2
+ import json
3
+ from pathlib import Path
4
+
5
+ from videollava.model.builder import load_pretrained_model
6
+ from videollava.utils import disable_torch_init
7
+ from videollava.mm_utils import get_model_name_from_path
8
+ from videollava.model.multimodal_encoder.languagebind.video.processing_video import LanguageBindVideoProcessor
9
+
10
+ from eval_classification import accuracy_precision_recall
11
+ from eval_referring import referring_expression
12
+ from classification_segmentation import classification_segmentation
13
+
14
+ from ben_utils import run_ben_inference
15
+ from aid_fmow_ucmerced_utils import run_aid_fmow_ucmerced_inference
16
+ from qfabric_utils import run_qfabric_inference
17
+ from geochat_utils import run_geochat_inference
18
+ from s2looking_utils import run_s2looking_inference
19
+ from xbd_utils import run_xbd_inference
20
+ from cdvqa_utils import run_cdvqa_inference
21
+
22
+
23
+ def aggregated(answer_path, dataset=None, verbose=False, split=None):
24
+ """
25
+ Define an aggregated metric for our created instruction-following datasets.
26
+ It includes eval_description and eval_referring metrics.
27
+ """
28
+ saving_path_root = Path(answer_path).parent
29
+
30
+ with open(answer_path, 'r') as f:
31
+ answers = json.load(f)
32
+
33
+ print("Referring expression")
34
+ referring_expression(answer_path, dataset, False, saving_path_root, split=split)
35
+ print()
36
+ print("Accuracy")
37
+ accuracy_precision_recall(answer_path, dataset, verbose=False)
38
+ print()
39
+
40
+ # TODO per-task metrics for qfabric and xbd
41
+
42
+ if dataset == 'qfabric' or dataset == 'xbd':
43
+ classification_segmentation(answer_path, dataset)
44
+
45
+ if dataset == "s2looking":
46
+ # also run per-question referring expression
47
+ question1 = 'temporal_question_answering: Are there any buildings in the first image which were {destructed,torn down} in the second?'
48
+ question2 = 'temporal_referring_expression: Identify the buildings in the first image which were {built,constructed,destructed,torn down} as seen in the second image.'
49
+ question3 = 'localization_task: Identify all changed buildings.'
50
+ question4 = 'referring_expression: identify the {constructed, destructed} buildings in the image.'
51
+ question5 = 'question_answering: Have any buildings been task in the area? Please answer with Yes or No'
52
+
53
+
54
+ for question in [question1, question2, question3, question4, question5]:
55
+ dataset_question = {}
56
+ for data in answers:
57
+ if answers[data]['task'] == question:
58
+ dataset_question[data] = answers[data]
59
+ if len(dataset_question) > 0:
60
+ print('Evaluating for question ', question)
61
+ print('Size of the dataset is ', len(dataset_question))
62
+ referring_expression(dataset_question, dataset, False, saving_path_root, split=split)
63
+ print()
64
+
65
+
66
+ def load_model(model_path, model_base, cache_dir, device, vision_type=None, load_4bit=False, load_8bit=False):
67
+ model_name = get_model_name_from_path(model_path)
68
+
69
+ tokenizer, model, processor, _ = load_pretrained_model(
70
+ model_path,
71
+ model_base,
72
+ model_name,
73
+ load_4bit=load_4bit,
74
+ load_8bit=load_8bit,
75
+ device=device,
76
+ cache_dir=cache_dir,
77
+ vision_type=vision_type,
78
+ )
79
+
80
+ if vision_type is None:
81
+ # Automatically determine which to us
82
+ # For now assumes one of the processors is not None and one is None
83
+ vision_types = ['image', 'video']
84
+ if processor['image'] is None and processor['video'] is None:
85
+ raise ValueError("Both image and video processors are None")
86
+ elif processor['image'] is not None and processor['video'] is not None:
87
+ vision_processor = processor['image']
88
+ for vision_type in vision_types:
89
+ vision_processor = processor[vision_type]
90
+ if vision_processor is not None:
91
+ break
92
+ else:
93
+ vision_processor = processor[vision_type]
94
+ use_video_data = vision_type == 'video'
95
+ return tokenizer, model, vision_processor, use_video_data
96
+
97
+
98
+ def infer_eval(
99
+ dataset_path,
100
+ model_path,
101
+ model_base="LanguageBind/Video-LLaVA-7B",
102
+ cache_dir="/deep/group/aicc-bootcamp/geovlm/models/vllava_cache",
103
+ outname=None,
104
+ open_prompt=None,
105
+ repeat_frames=None,
106
+ prompt_strategy="interleave",
107
+ chronological_prefix=True,
108
+ load_8bit=False,
109
+ load_4bit=False,
110
+ verbose=False,
111
+ rerun=False,
112
+ vision_type=None,
113
+ data_frac=None,
114
+ data_size=None,
115
+ conv_mode="v1",
116
+ delete_system_prompt=False,
117
+ start_ind=None,
118
+ end_ind=None,
119
+ last_image=None,
120
+ print_prompt=False
121
+ ):
122
+ """
123
+ Args:
124
+ dataset_path: path to dataset
125
+ model_path: path to model
126
+ model_base: model base name
127
+ cache_dir: cache directory
128
+ outname: output file name (uses args if None)
129
+ open_prompt options: None, "open", "multi-open"
130
+ repeat_frames options: None, "uniform", "first", "last"
131
+ prompt_strategy options: None, "interleave"
132
+ chronological_prefix: whether to use chronological prefix "in chronological order"
133
+ load_8bit: whether to load 8-bit model
134
+ load_4bit: whether to load 4-bit model
135
+ verbose: whether to print verbose output
136
+ rerun: whether to rerun inference
137
+ vision_type: "image" or "video"
138
+ data_frac: fraction of data to use
139
+ data_size: number of data samples to use
140
+ conv_mode: conversation mode (should be v1 for our models, geochat, and videollava)
141
+ delete_system_prompt: whether to delete system prompt
142
+ start_ind: start index of data
143
+ end_ind: end index of data
144
+ last_image: whether to use last image in video
145
+ print_prompt: whether to print prompt
146
+ """
147
+ args = locals()
148
+ print(f"Arguments passed to infer_eval:")
149
+ for k, v in args.items():
150
+ print(f"{k} ({type(v).__name__}): {v}")
151
+
152
+ # check that data_size and data_frac are not both set
153
+ if data_size is not None and data_frac is not None:
154
+ raise ValueError("data_size and data_frac cannot both be set")
155
+ if data_size is None and data_frac is None:
156
+ data_frac = 1
157
+
158
+ dataset2metrics = {
159
+ "lrben": [accuracy_precision_recall],
160
+ "hrben": [accuracy_precision_recall],
161
+ "fmow": [accuracy_precision_recall],
162
+ "s2looking": [aggregated],
163
+ "xbd": [aggregated],
164
+ "qfabric": [aggregated],
165
+ "aid": [accuracy_precision_recall],
166
+ "ucmerced": [accuracy_precision_recall],
167
+ "cdvqa": [accuracy_precision_recall]
168
+ }
169
+
170
+ eval_outdir = Path('scripts/geovlm/eval/')
171
+
172
+ # Per dataset configurations
173
+ if "lrben" in dataset_path.lower():
174
+ dataset = "lrben"
175
+ run_inference = run_ben_inference
176
+ outdir = eval_outdir / "RSVQA-LRBEN/answers/"
177
+ if open_prompt is not None:
178
+ raise ValueError("LRBEN dataset does not support open prompt")
179
+ elif "hrben" in dataset_path.lower():
180
+ dataset = "hrben"
181
+ run_inference = run_ben_inference
182
+ outdir = eval_outdir / "RSVQA-HRBEN/answers/"
183
+ if open_prompt is not None:
184
+ raise ValueError("HRBEN dataset does not support open prompt")
185
+ elif "fmow" in dataset_path.lower():
186
+ dataset = "fmow"
187
+ run_inference = run_aid_fmow_ucmerced_inference
188
+ outdir = eval_outdir / "fmow-highres/answers/"
189
+ elif "s2looking" in dataset_path.lower():
190
+ dataset = "s2looking"
191
+ run_inference = run_s2looking_inference
192
+ outdir = eval_outdir / "s2looking/answers/"
193
+ elif "xbd" in dataset_path.lower():
194
+ dataset = "xbd"
195
+ run_inference = run_xbd_inference
196
+ outdir = eval_outdir / "xBD/answers/"
197
+ elif 'qfabric' in dataset_path.lower() or 'geochat' in dataset_path.lower():
198
+ dataset = "qfabric"
199
+ run_inference = run_qfabric_inference
200
+ outdir = eval_outdir / "QFabric/answers/"
201
+ elif 'geochat' in dataset_path.lower():
202
+ dataset = "geochat"
203
+ run_inference = run_geochat_inference
204
+ outdir = eval_outdir / "GeoChat/answers/"
205
+ elif 'aid' in dataset_path.lower():
206
+ dataset = "aid"
207
+ run_inference = run_aid_fmow_ucmerced_inference
208
+ outdir = eval_outdir / "AID/answers/"
209
+ elif 'ucmerced' in dataset_path.lower():
210
+ dataset = "ucmerced"
211
+ run_inference = run_aid_fmow_ucmerced_inference
212
+ outdir = eval_outdir / "UCMerced/answers/"
213
+ elif 'cdvqa' in dataset_path.lower():
214
+ dataset = "cdvqa"
215
+ run_inference = run_cdvqa_inference
216
+ outdir = eval_outdir / "CDVQA/answers/"
217
+ else:
218
+ raise ValueError(f"No supported dataset found in {dataset_path}, supported datasets: fmow, lrben, s2looking, xbd, qfabric, aic, ucmerced")
219
+
220
+ if (start_ind is not None or end_ind is not None) and dataset not in ['qfabric', 'hrben', 'lrben']:
221
+ raise ValueError("start_ind and end_ind can only be used with qfabric, hrben, or lrben datasets")
222
+
223
+ # Determine the split
224
+ if 'test' in dataset_path.lower():
225
+ split = 'test'
226
+ elif 'val' or 'valid' or 'validation' in dataset_path.lower():
227
+ split = 'val'
228
+ elif 'train' in dataset_path.lower():
229
+ split = 'train'
230
+ else:
231
+ print("Warning: Could not determine split from dataset path")
232
+
233
+ args_to_determine_path = [
234
+ 'open_prompt',
235
+ 'repeat_frames',
236
+ 'prompt_strategy',
237
+ 'chronological_prefix',
238
+ 'load_8bit',
239
+ 'load_4bit',
240
+ 'data_frac',
241
+ 'data_size',
242
+ 'delete_system_prompt'
243
+ ]
244
+
245
+ # Setup answer path
246
+ outdir.mkdir(parents=True, exist_ok=True)
247
+ model_name = Path(model_path).stem
248
+
249
+ if 'llava' not in model_name and 'llava' not in model_name.lower() and 'teochat' not in model_name.lower():
250
+ if model_base != None:
251
+ if model_path[-1] == "/":
252
+ model_path = model_path[:-1]
253
+ model_name = model_path.split("/")[-2] + "-" + model_path.split("/")[-1]
254
+ print("Model name used: ", model_name)
255
+ else:
256
+ raise ValueError(f"Model name {model_name} does not contain 'llava'")
257
+ if 'lora' not in model_name:
258
+ print("Warning: Model name does not contain 'lora'")
259
+
260
+ if outname is None:
261
+ dataset_path_name = Path(dataset_path).stem
262
+ outname = f"{model_name}_{dataset}_{dataset_path_name}_{split}.json"
263
+
264
+ if ".json" not in outname:
265
+ outname = f"{outname}.json"
266
+
267
+ args_to_determine_path = [
268
+ 'open_prompt',
269
+ 'repeat_frames',
270
+ 'prompt_strategy',
271
+ 'chronological_prefix',
272
+ 'load_8bit',
273
+ 'load_4bit',
274
+ 'data_frac',
275
+ 'data_size',
276
+ 'delete_system_prompt',
277
+ 'start_ind',
278
+ 'end_ind',
279
+ 'last_image'
280
+ ]
281
+ for arg in args_to_determine_path:
282
+ if args[arg] is not None:
283
+ outname = outname.replace(".json", f"_{arg}_{args[arg]}.json")
284
+
285
+ answer_path = outdir / outname
286
+
287
+ print(f'answer_path: {answer_path}')
288
+
289
+ # Save args to file
290
+ args_path = outdir / outname.replace(".json", "_args.json")
291
+
292
+ if len(str(args_path)) < 255:
293
+ with open(args_path, 'w') as f:
294
+ json.dump(args, f)
295
+ else:
296
+ # File name too long. Just use first letter of each arg
297
+ for arg in args_to_determine_path:
298
+ if args[arg] is not None:
299
+ first_letters = ''.join([word[0] for word in arg.split('_')])
300
+ #print("outname before replacing: ", outname)
301
+ outname = outname.replace(f"{arg}", first_letters)
302
+ #print("outname after replacing: ", outname)
303
+ answer_path = outdir / outname
304
+ args_path = outdir / outname.replace(".json", "_args.json")
305
+ with open(args_path, 'w') as f:
306
+ json.dump(args, f)
307
+ print(f'New answer_path: {answer_path}')
308
+
309
+ # If answer file exists, compute metrics
310
+ if answer_path.exists() and not rerun:
311
+ for metric in dataset2metrics[dataset]:
312
+ if dataset == "s2looking":
313
+ metric(answer_path, dataset=dataset, verbose=verbose, split=split)
314
+ else:
315
+ metric(answer_path, dataset=dataset, verbose=verbose)
316
+ return
317
+
318
+ # Load model
319
+ disable_torch_init()
320
+ device = 'cuda'
321
+ tokenizer, model, processor, use_video_data = load_model(
322
+ model_path,
323
+ model_base,
324
+ cache_dir,
325
+ device,
326
+ load_4bit=load_4bit,
327
+ load_8bit=load_8bit,
328
+ vision_type=vision_type
329
+ )
330
+
331
+ if use_video_data:
332
+ if dataset == "lrben":
333
+ raise ValueError("LRBEN dataset does not support video processing")
334
+ # Hack to set backend of video processor
335
+ # NOTE: If we change image size, we might need to change this in the config here too
336
+ # (better solution is to figure out where this config is set when saving the model)
337
+ processor.config.vision_config.video_decode_backend = "image_list"
338
+ processor = LanguageBindVideoProcessor(processor.config, tokenizer)
339
+
340
+ if rerun or not answer_path.exists():
341
+ # Run inference
342
+ answers = run_inference(
343
+ model,
344
+ dataset_path,
345
+ processor,
346
+ tokenizer,
347
+ conv_mode,
348
+ answer_path=answer_path,
349
+ open_prompt=open_prompt,
350
+ repeat_frames=repeat_frames,
351
+ use_video_data = use_video_data,
352
+ prompt_strategy=prompt_strategy,
353
+ chronological_prefix=chronological_prefix,
354
+ data_size=data_size,
355
+ data_frac=data_frac,
356
+ delete_system_prompt=delete_system_prompt,
357
+ start_ind=start_ind,
358
+ end_ind=end_ind,
359
+ last_image=last_image,
360
+ print_prompt=print_prompt
361
+ )
362
+
363
+ # Save answers
364
+ with open(answer_path, 'w') as f:
365
+ json.dump(answers, f, indent=4)
366
+ else:
367
+ answers = json.load(open(answer_path))
368
+
369
+
370
+ # Calculate metrics
371
+ for metric in dataset2metrics[dataset]:
372
+ if dataset == "s2looking":
373
+ metric(answer_path, dataset=dataset, verbose=verbose, split=split)
374
+ else:
375
+ metric(answer_path, dataset=dataset, verbose=verbose)
376
+
377
+
378
+ if __name__ == '__main__':
379
+ """Example usage:
380
+ export CUDA_VISIBLE_DEVICES=0;
381
+ export PYTHONPATH=/path/to/aicc-win24-geo-vlm/videollava/:$PYTHONPATH;
382
+ python videollava/eval/video/infer_eval.py infer_eval\
383
+ --dataset fmow\
384
+ --model_path /path/to/model\
385
+ """
386
+ fire.Fire()
videollava/eval/infer_utils.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import torch
3
+ import warnings
4
+ import numpy as np
5
+ from datetime import datetime
6
+ import cv2
7
+ import warnings
8
+ import time
9
+
10
+ from videollava.mm_utils import tokenizer_image_token, KeywordsStoppingCriteria
11
+ from videollava.conversation import conv_templates, SeparatorStyle
12
+ from videollava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_VIDEO_TOKEN
13
+
14
+
15
+ def replace_video_token(prompt, image_paths, prompt_strategy):
16
+ if prompt_strategy is None:
17
+ vid_replace_token = DEFAULT_IMAGE_TOKEN * len(image_paths)
18
+ elif prompt_strategy == 'interleave':
19
+ vid_replace_token = ''.join(f"Image {i+1}: {DEFAULT_IMAGE_TOKEN}" for i in range(len(image_paths)))
20
+ else:
21
+ raise ValueError(f"Unknown prompt strategy: {prompt_strategy}")
22
+ return prompt.replace(DEFAULT_VIDEO_TOKEN, vid_replace_token)
23
+
24
+
25
+ def run_inference_single(
26
+ model,
27
+ processor,
28
+ tokenizer,
29
+ conv_mode,
30
+ inp,
31
+ image_paths,
32
+ metadata=None,
33
+ use_video_data=False,
34
+ repeat_frames=None,
35
+ prompt_strategy=None,
36
+ chronological_prefix=True,
37
+ delete_system_prompt=False,
38
+ print_prompt=False,
39
+ return_prompt=False,
40
+ last_image=False,
41
+ prompt=None
42
+ ):
43
+ conv = conv_templates[conv_mode].copy()
44
+ if prompt is None:
45
+ conv.append_message(conv.roles[0], inp)
46
+ conv.append_message(conv.roles[1], None)
47
+ prompt = conv.get_prompt()
48
+
49
+ if chronological_prefix:
50
+ prompt = prompt.replace("times:", "times in chronological order:")
51
+
52
+ if metadata is not None:
53
+ # Sort by time
54
+ image_paths, metadata = zip(*sorted(
55
+ zip(image_paths, metadata),
56
+ key=lambda t: datetime.strptime(t[1]["timestamp"], "%Y-%m-%d")
57
+ ))
58
+
59
+ if delete_system_prompt:
60
+ if "This is" in prompt:
61
+ start_index = prompt.find("This is")
62
+ elif "These are" in prompt:
63
+ start_index = prompt.find("These are")
64
+ end_index = prompt.find(":", start_index)
65
+ if start_index != -1 and end_index != -1:
66
+ prompt = prompt[:start_index] + prompt[end_index+1:]
67
+ else:
68
+ warnings.warn("Impossible to remove the system message from the prompt.")
69
+
70
+ if use_video_data:
71
+ image_paths = list(image_paths)
72
+ if repeat_frames == "uniform":
73
+ # Repeat up to 8 for now
74
+ num_frames = 8
75
+ if len(image_paths) < num_frames:
76
+ num_repeats = num_frames // len(image_paths)
77
+ index = len(image_paths) - num_frames % len(image_paths)
78
+ image_paths = list(np.repeat(image_paths[:index], num_repeats)) + list(np.repeat(image_paths[index:], num_repeats+1))
79
+ elif repeat_frames == "first":
80
+ # Repeat the first frame
81
+ num_frames = 8
82
+ if len(image_paths) < num_frames:
83
+ repeat_frames = [image_paths[0]] * (num_frames - len(image_paths)) + image_paths
84
+ elif repeat_frames == "last":
85
+ # Repeat the last frame
86
+ num_frames = 8
87
+ if len(image_paths) < num_frames:
88
+ repeat_frames = image_paths + [image_paths[-1]] * (num_frames - len(image_paths))
89
+
90
+ video_tensor = processor.preprocess(image_paths, return_tensors='pt')['pixel_values']
91
+ tensor = [video_tensor.to(model.device, dtype=torch.float16)]
92
+
93
+ else:
94
+ image_tensors = [processor.preprocess(i, return_tensors='pt')['pixel_values'][0] for i in image_paths]
95
+ tensor = [image_tensor.to(model.device, dtype=torch.float16) for image_tensor in image_tensors]
96
+
97
+ if last_image:
98
+ tensor = [tensor[-1]]
99
+ image_paths = [image_paths[-1]]
100
+ if metadata is not None:
101
+ metadata = [metadata[-1]]
102
+
103
+ prompt = replace_video_token(prompt, image_paths, prompt_strategy)
104
+
105
+ if print_prompt:
106
+ print(prompt)
107
+
108
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
109
+ keywords = [stop_str]
110
+
111
+ input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device)
112
+ stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
113
+
114
+ with torch.inference_mode():
115
+ output_ids = model.generate(
116
+ input_ids=input_ids,
117
+ images=tensor,
118
+ do_sample=True,
119
+ temperature=0.2,
120
+ max_new_tokens=256,
121
+ use_cache=True,
122
+ stopping_criteria=[stopping_criteria],
123
+ )
124
+
125
+ # .replace removes the end sentence token "</s>" from the output
126
+ outputs = tokenizer.decode(output_ids[0, input_ids.shape[1]:]).replace('</s>', '').strip()
127
+
128
+ if return_prompt:
129
+ return prompt, outputs
130
+ else:
131
+ return outputs
132
+
133
+
134
+ def create_mask(poly, im_size):
135
+ """
136
+ Create mask of given height and width where entries
137
+ inside polygon are 1.
138
+ params:
139
+ - poly (shapely polygon object): polygon to create mask for
140
+ - im_size (tuple): size of image (height, width)
141
+ returns:
142
+ - img_mask (np.array): mask of polygon"""
143
+ img_mask = np.zeros(im_size, np.uint8)
144
+ def int_coords(x): return np.array(x).round().astype(np.int32)
145
+ try:
146
+ exteriors = [int_coords(pol.exterior.coords) for pol in poly]
147
+ except:
148
+ exteriors = [int_coords(poly.exterior.coords)]
149
+ cv2.fillPoly(img_mask, exteriors, 1)
150
+ try:
151
+ interiors = [int_coords(pol.interior.coords) for pol in poly]
152
+ cv2.fillPoly(img_mask, interiors, 0)
153
+ except:
154
+ pass
155
+ try:
156
+ interiors = [int_coords(poly.interior.coords)]
157
+ cv2.fillPoly(img_mask, interiors, 0)
158
+ except:
159
+ pass
160
+
161
+ return img_mask
162
+
163
+
164
+ def create_mask_s2looking(img_id, split=None, question=None):
165
+ if split == None:
166
+ raise ValueError("split must be provided for S2Looking evaluation")
167
+
168
+ if question == None:
169
+ raise ValueError("question must be provided for S2Looking evaluation")
170
+
171
+ im1_path = f'/scr/geovlm/S2Looking/{split}/label1' # built
172
+ img2_path = f'/scr/geovlm/S2Looking/{split}/label2' # destroyed
173
+ id, chunk = img_id.split('_')
174
+ # Load image as numpy array
175
+ im1 = cv2.imread(f'{im1_path}/{id}.png', cv2.IMREAD_GRAYSCALE)
176
+ im2 = cv2.imread(f'{img2_path}/{id}.png', cv2.IMREAD_GRAYSCALE)
177
+ # replace any value different from 0 with 1
178
+ im1[im1 != 0] = 1
179
+ im2[im2 != 0] = 1
180
+
181
+ # get the corresponding of the 16 chunks
182
+ # 1 is upper left, 16 is lower right
183
+ if chunk == '1':
184
+ mask1 = im1[:256, :256]
185
+ mask2 = im2[:256, :256]
186
+ elif chunk == '2':
187
+ mask1 = im1[:256, 256:2*256]
188
+ mask2 = im2[:256, 256:2*256]
189
+ elif chunk == '3':
190
+ mask1 = im1[:256, 2*256:3*256]
191
+ mask2 = im2[:256, 2*256:3*256]
192
+ elif chunk == '4':
193
+ mask1 = im1[:256, 3*256:]
194
+ mask2 = im2[:256, 3*256:]
195
+ elif chunk == '5':
196
+ mask1 = im1[256:2*256, :256]
197
+ mask2 = im2[256:2*256, :256]
198
+ elif chunk == '6':
199
+ mask1 = im1[256:2*256, 256:2*256]
200
+ mask2 = im2[256:2*256, 256:2*256]
201
+ elif chunk == '7':
202
+ mask1 = im1[256:2*256, 2*256:3*256]
203
+ mask2 = im2[256:2*256, 2*256:3*256]
204
+ elif chunk == '8':
205
+ mask1 = im1[256:2*256, 3*256:]
206
+ mask2 = im2[256:2*256, 3*256:]
207
+ elif chunk == '9':
208
+ mask1 = im1[2*256:3*256, :256]
209
+ mask2 = im2[2*256:3*256, :256]
210
+ elif chunk == '10':
211
+ mask1 = im1[2*256:3*256, 256:2*256]
212
+ mask2 = im2[2*256:3*256, 256:2*256]
213
+ elif chunk == '11':
214
+ mask1 = im1[2*256:3*256, 2*256:3*256]
215
+ mask2 = im2[2*256:3*256, 2*256:3*256]
216
+ elif chunk == '12':
217
+ mask1 = im1[2*256:3*256, 3*256:]
218
+ mask2 = im2[2*256:3*256, 3*256:]
219
+ elif chunk == '13':
220
+ mask1 = im1[3*256:, :256]
221
+ mask2 = im2[3*256:, :256]
222
+ elif chunk == '14':
223
+ mask1 = im1[3*256:, 256:2*256]
224
+ mask2 = im2[3*256:, 256:2*256]
225
+ elif chunk == '15':
226
+ mask1 = im1[3*256:, 2*256:3*256]
227
+ mask2 = im2[3*256:, 2*256:3*256]
228
+ elif chunk == '16':
229
+ mask1 = im1[3*256:, 3*256:]
230
+ mask2 = im2[3*256:, 3*256:]
231
+
232
+ task = None
233
+ if 'built' in question or 'constructed' in question:
234
+ task = 'constructing'
235
+ if 'destroyed' in question or 'torn down' in question or 'demolished' in question:
236
+ task = 'destroying'
237
+ if 'changed' in question:
238
+ task = 'changing'
239
+ if (('built' in question) or ('constructed' in question)) and (('destroyed' in question) or ('torn down' in question) or ('demolished' in question)):
240
+ print(question)
241
+ raise ValueError("Question cannot contain both 'built' and 'destroyed'")
242
+ if task is None:
243
+ print(question)
244
+ raise ValueError("Question must contain either 'built', 'destroyed', or 'changed'")
245
+
246
+ if task == 'constructing':
247
+ mask = mask1
248
+ elif task == 'destroying':
249
+ mask = mask2
250
+ elif task == 'changing':
251
+ mask = np.logical_or(mask1, mask2)
252
+
253
+ return mask
videollava/eval/qfabric_utils.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from tqdm import tqdm
3
+ from pathlib import Path
4
+
5
+ from infer_utils import run_inference_single
6
+ import numpy as np
7
+
8
+
9
+ def run_qfabric_inference(
10
+ model,
11
+ dataset_path,
12
+ processor,
13
+ tokenizer,
14
+ conv_mode,
15
+ answer_path,
16
+ use_video_data=False,
17
+ open_prompt=None,
18
+ repeat_frames=None,
19
+ prompt_strategy="interleave",
20
+ chronological_prefix=True,
21
+ data_frac=1,
22
+ data_size=None,
23
+ delete_system_prompt=False,
24
+ print_prompt=False,
25
+ start_ind=None,
26
+ end_ind=None,
27
+ last_image=False,
28
+ ):
29
+
30
+ with open(dataset_path) as f:
31
+ qfabric_data = json.load(f)
32
+
33
+ if data_size is not None:
34
+ data_size = min(data_size, len(qfabric_data))
35
+ idx = np.random.choice(len(qfabric_data), data_size, replace=False)
36
+ qfabric_data = [qfabric_data[i] for i in idx]
37
+ elif data_frac < 1:
38
+ idx = np.random.choice(len(qfabric_data), int(len(qfabric_data) * data_frac), replace=False)
39
+ qfabric_data = [qfabric_data[i] for i in idx]
40
+
41
+ answers = {}
42
+ answers_tmp = str(answer_path).replace(".json", "_tmp.json")
43
+ if start_ind is None:
44
+ start_ind = 0
45
+ if end_ind is not None:
46
+ # TODO: Don't append as it's already done previously
47
+ answers_tmp = str(answer_path).replace(".json", f"_{start_ind}_{end_ind}.json")
48
+ qfabric_data = qfabric_data[start_ind:end_ind]
49
+ else:
50
+ # TODO: Don't append as it's already done previously
51
+ answers_tmp = str(answer_path).replace(".json", f"_{start_ind}_end.json")
52
+ qfabric_data = qfabric_data[start_ind:]
53
+
54
+ print("answers_tmp: ", answers_tmp)
55
+ print("start ind: ", start_ind)
56
+ print("end ind: ", end_ind)
57
+
58
+ for question in tqdm(qfabric_data):
59
+ question_id = question["id"]
60
+ inp = question["conversations"][0]['value']
61
+
62
+ answer_str = question["conversations"][1]['value']
63
+ metadata = question['metadata']
64
+ image_paths = question['video']
65
+ task = question['task']
66
+ original_input_polygon = question['original_input_polygon']
67
+
68
+ outputs = run_inference_single(
69
+ model=model,
70
+ processor=processor,
71
+ tokenizer=tokenizer,
72
+ conv_mode=conv_mode,
73
+ inp=inp,
74
+ image_paths=image_paths,
75
+ metadata=metadata,
76
+ repeat_frames=repeat_frames,
77
+ use_video_data=use_video_data,
78
+ prompt_strategy=prompt_strategy,
79
+ chronological_prefix=chronological_prefix,
80
+ delete_system_prompt=delete_system_prompt,
81
+ last_image=last_image,
82
+ print_prompt=print_prompt
83
+ )
84
+
85
+ entry = {
86
+ "id": question_id,
87
+ "question": inp,
88
+ "predicted": outputs,
89
+ "ground_truth": answer_str,
90
+ "task": task,
91
+ "original_input_polygon": original_input_polygon
92
+ }
93
+ answers[question_id] = entry
94
+
95
+ with open(answers_tmp, "a") as f:
96
+ f.write(json.dumps(entry) + "\n")
97
+
98
+ return answers
videollava/eval/s2looking_utils.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import numpy as np
3
+ from tqdm import tqdm
4
+ from pathlib import Path
5
+
6
+ from infer_utils import run_inference_single, create_mask
7
+
8
+
9
+ def run_s2looking_inference(
10
+ model,
11
+ dataset_path,
12
+ processor,
13
+ tokenizer,
14
+ conv_mode,
15
+ use_video_data=False,
16
+ open_prompt=None,
17
+ repeat_frames=True,
18
+ prompt_strategy="interleave",
19
+ chronological_prefix=True,
20
+ data_frac=1,
21
+ data_size=None,
22
+ delete_system_prompt=False,
23
+ last_image=False,
24
+ print_prompt=False,
25
+ answer_path=None,
26
+ start_ind=None,
27
+ end_ind=None,
28
+ ):
29
+
30
+ dir = Path(dataset_path)
31
+
32
+ with open(dir) as f:
33
+ s2looking_data = json.load(f)
34
+
35
+ if data_size is not None:
36
+ data_size = min(data_size, len(s2looking_data))
37
+ idx = np.random.choice(len(s2looking_data), data_size, replace=False)
38
+ s2looking_data = [s2looking_data[i] for i in idx]
39
+ elif data_frac < 1:
40
+ idx = np.random.choice(len(s2looking_data), int(len(s2looking_data) * data_frac), replace=False)
41
+ s2looking_data = [s2looking_data[i] for i in idx]
42
+
43
+ answers = {}
44
+ for question in tqdm(s2looking_data):
45
+ question_id = question["id"]
46
+ inp = question["conversations"][0]['value']
47
+ answer_str = question["conversations"][1]['value']
48
+ metadata = question['metadata']
49
+ task = question['task']
50
+ image_paths = question['video']
51
+ original_input_polygon = question['original_input_polygon']
52
+
53
+ outputs = run_inference_single(
54
+ model=model,
55
+ processor=processor,
56
+ tokenizer=tokenizer,
57
+ conv_mode=conv_mode,
58
+ inp=inp,
59
+ image_paths=image_paths,
60
+ metadata=metadata,
61
+ repeat_frames=repeat_frames,
62
+ use_video_data=use_video_data,
63
+ prompt_strategy=prompt_strategy,
64
+ chronological_prefix=chronological_prefix,
65
+ delete_system_prompt=delete_system_prompt,
66
+ last_image=last_image,
67
+ print_prompt=print_prompt
68
+ )
69
+
70
+ answers[question_id] = {
71
+ "predicted": outputs,
72
+ "ground_truth": answer_str,
73
+ "question": inp,
74
+ "task": task,
75
+ "original_input_polygon": original_input_polygon
76
+ }
77
+
78
+ return answers
videollava/eval/xbd_utils.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from tqdm import tqdm
3
+ from pathlib import Path
4
+
5
+ from infer_utils import run_inference_single
6
+ import numpy as np
7
+
8
+
9
+
10
+ def run_xbd_inference(
11
+ model,
12
+ dataset_path,
13
+ processor,
14
+ tokenizer,
15
+ conv_mode,
16
+ use_video_data=False,
17
+ open_prompt=None,
18
+ repeat_frames=None,
19
+ prompt_strategy="interleave",
20
+ chronological_prefix=True,
21
+ data_frac=1,
22
+ data_size=None,
23
+ last_image=False,
24
+ delete_system_prompt=False,
25
+ print_prompt=False,
26
+ answer_path=None,
27
+ start_ind=None,
28
+ end_ind=None,
29
+ ):
30
+
31
+ with open(dataset_path) as f:
32
+ xbd_data = json.load(f)
33
+
34
+ if data_size is not None:
35
+ data_size = min(data_size, len(xbd_data))
36
+ idx = np.random.choice(len(xbd_data), data_size, replace=False)
37
+ xbd_data = [xbd_data[i] for i in idx]
38
+ elif data_frac < 1:
39
+ idx = np.random.choice(len(xbd_data), int(len(xbd_data) * data_frac), replace=False)
40
+ xbd_data = [xbd_data[i] for i in idx]
41
+
42
+ answers = {}
43
+ for question in tqdm(xbd_data):
44
+ question_id = question["id"]
45
+ inp = question["conversations"][0]['value']
46
+
47
+ answer_str = question["conversations"][1]['value']
48
+ metadata = question['metadata']
49
+ image_paths = question['video']
50
+ task = question['task']
51
+ original_input_polygon = question['original_input_polygon']
52
+
53
+ # TODO: check if you want to add closed framing for yes/no questions
54
+ outputs = run_inference_single(
55
+ model=model,
56
+ processor=processor,
57
+ tokenizer=tokenizer,
58
+ conv_mode=conv_mode,
59
+ inp=inp,
60
+ image_paths=image_paths,
61
+ metadata=metadata,
62
+ repeat_frames=repeat_frames,
63
+ use_video_data=use_video_data,
64
+ prompt_strategy=prompt_strategy,
65
+ chronological_prefix=chronological_prefix,
66
+ last_image=last_image,
67
+ print_prompt=print_prompt
68
+ )
69
+
70
+ answers[question_id] = {
71
+ "question": inp,
72
+ "predicted": outputs,
73
+ "ground_truth": answer_str,
74
+ "task": task,
75
+ "original_input_polygon": original_input_polygon
76
+ }
77
+ # For recording individual answers as inference runs
78
+ entry = {question_id: answers[question_id]}
79
+ with open('/deep/u/joycech/aicc-working/geovlm_xbd_localization.json', 'a') as f:
80
+ f.write(json.dumps(entry) + ',')
81
+
82
+ return answers
videollava/mm_utils.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from io import BytesIO
3
+ import base64
4
+
5
+ import torch
6
+ from transformers import StoppingCriteria
7
+ from videollava.constants import IMAGE_TOKEN_INDEX
8
+
9
+
10
+ def load_image_from_base64(image):
11
+ return Image.open(BytesIO(base64.b64decode(image)))
12
+
13
+
14
+ def expand2square(pil_img, background_color):
15
+ width, height = pil_img.size
16
+ if width == height:
17
+ return pil_img
18
+ elif width > height:
19
+ result = Image.new(pil_img.mode, (width, width), background_color)
20
+ result.paste(pil_img, (0, (width - height) // 2))
21
+ return result
22
+ else:
23
+ result = Image.new(pil_img.mode, (height, height), background_color)
24
+ result.paste(pil_img, ((height - width) // 2, 0))
25
+ return result
26
+
27
+
28
+ def process_images(images, image_processor, model_cfg):
29
+ image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
30
+ new_images = []
31
+ if image_aspect_ratio == 'pad':
32
+ for image in images:
33
+ image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean))
34
+ image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
35
+ new_images.append(image)
36
+ else:
37
+ return image_processor(images, return_tensors='pt')['pixel_values']
38
+ if all(x.shape == new_images[0].shape for x in new_images):
39
+ new_images = torch.stack(new_images, dim=0)
40
+ return new_images
41
+
42
+
43
+ def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
44
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split('<image>')]
45
+
46
+ def insert_separator(X, sep):
47
+ return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1]
48
+
49
+ input_ids = []
50
+ offset = 0
51
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
52
+ offset = 1
53
+ input_ids.append(prompt_chunks[0][0])
54
+
55
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
56
+ input_ids.extend(x[offset:])
57
+
58
+ if return_tensors is not None:
59
+ if return_tensors == 'pt':
60
+ return torch.tensor(input_ids, dtype=torch.long)
61
+ raise ValueError(f'Unsupported tensor type: {return_tensors}')
62
+ return input_ids
63
+
64
+
65
+ def get_model_name_from_path(model_path):
66
+ model_path = model_path.strip("/")
67
+ model_paths = model_path.split("/")
68
+ if model_paths[-1].startswith('checkpoint-'):
69
+ return model_paths[-2] + "_" + model_paths[-1]
70
+ else:
71
+ return model_paths[-1]
72
+
73
+ class KeywordsStoppingCriteria(StoppingCriteria):
74
+ def __init__(self, keywords, tokenizer, input_ids):
75
+ self.keywords = keywords
76
+ self.keyword_ids = []
77
+ self.max_keyword_len = 0
78
+ for keyword in keywords:
79
+ cur_keyword_ids = tokenizer(keyword).input_ids
80
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
81
+ cur_keyword_ids = cur_keyword_ids[1:]
82
+ if len(cur_keyword_ids) > self.max_keyword_len:
83
+ self.max_keyword_len = len(cur_keyword_ids)
84
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
85
+ self.tokenizer = tokenizer
86
+ self.start_len = input_ids.shape[1]
87
+
88
+ def call_for_batch(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
89
+ offset = min(output_ids.shape[1] - self.start_len, self.max_keyword_len)
90
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
91
+ for keyword_id in self.keyword_ids:
92
+ if (output_ids[0, -keyword_id.shape[0]:] == keyword_id).all():
93
+ return True
94
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
95
+ for keyword in self.keywords:
96
+ if keyword in outputs:
97
+ return True
98
+ return False
99
+
100
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
101
+ outputs = []
102
+ for i in range(output_ids.shape[0]):
103
+ outputs.append(self.call_for_batch(output_ids[i].unsqueeze(0), scores))
104
+ return all(outputs)
videollava/model/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .language_model.llava_llama import LlavaLlamaForCausalLM, LlavaConfig
2
+ from .language_model.llava_mpt import LlavaMPTForCausalLM, LlavaMPTConfig
videollava/model/apply_delta.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from tqdm import tqdm
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ from videollava import LlavaLlamaForCausalLM
11
+
12
+
13
+ def apply_delta(base_model_path, target_model_path, delta_path):
14
+ print("Loading base model")
15
+ base = AutoModelForCausalLM.from_pretrained(
16
+ base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+
18
+ print("Loading delta")
19
+ delta = LlavaLlamaForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
20
+ delta_tokenizer = AutoTokenizer.from_pretrained(delta_path)
21
+
22
+ print("Applying delta")
23
+ for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"):
24
+ if name not in base.state_dict():
25
+ assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model'
26
+ continue
27
+ if param.data.shape == base.state_dict()[name].shape:
28
+ param.data += base.state_dict()[name]
29
+ else:
30
+ assert name in ['model.embed_tokens.weight', 'lm_head.weight'], \
31
+ f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}'
32
+ bparam = base.state_dict()[name]
33
+ param.data[:bparam.shape[0], :bparam.shape[1]] += bparam
34
+
35
+ print("Saving target model")
36
+ delta.save_pretrained(target_model_path)
37
+ delta_tokenizer.save_pretrained(target_model_path)
38
+
39
+
40
+ if __name__ == "__main__":
41
+ parser = argparse.ArgumentParser()
42
+ parser.add_argument("--base-model-path", type=str, required=True)
43
+ parser.add_argument("--target-model-path", type=str, required=True)
44
+ parser.add_argument("--delta-path", type=str, required=True)
45
+
46
+ args = parser.parse_args()
47
+
48
+ apply_delta(args.base_model_path, args.target_model_path, args.delta_path)
videollava/model/builder.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import os
17
+ import warnings
18
+ import shutil
19
+
20
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
21
+ import torch
22
+ from videollava.model import *
23
+ from videollava.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, \
24
+ DEFAULT_VIDEO_PATCH_TOKEN, DEFAULT_VID_START_TOKEN, DEFAULT_VID_END_TOKEN
25
+
26
+
27
+ def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda", **kwargs):
28
+ kwargs = {"device_map": device_map, **kwargs}
29
+
30
+ if device != "cuda":
31
+ kwargs['device_map'] = {"": device}
32
+
33
+ if load_8bit:
34
+ kwargs['load_in_8bit'] = True
35
+ elif load_4bit:
36
+ kwargs['load_in_4bit'] = True
37
+ kwargs['quantization_config'] = BitsAndBytesConfig(
38
+ load_in_4bit=True,
39
+ bnb_4bit_compute_dtype=torch.float16,
40
+ bnb_4bit_use_double_quant=True,
41
+ bnb_4bit_quant_type='nf4'
42
+ )
43
+ else:
44
+ kwargs['torch_dtype'] = torch.float16
45
+
46
+ if 'llava' in model_name.lower() or "teochat" in model_name.lower():
47
+ # Load LLaVA model
48
+ if 'lora' in model_name.lower() and model_base is None:
49
+ warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.')
50
+ if 'lora' in model_name.lower() and model_base is not None:
51
+ lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
52
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
53
+ print('Loading LLaVA from base model...')
54
+ model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
55
+ token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
56
+ if model.lm_head.weight.shape[0] != token_num:
57
+ model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
58
+ model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
59
+
60
+ print('Loading additional LLaVA weights...')
61
+ if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
62
+ non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
63
+ else:
64
+ # this is probably from HF Hub
65
+ from huggingface_hub import hf_hub_download
66
+ def load_from_hf(repo_id, filename, subfolder=None):
67
+ cache_file = hf_hub_download(
68
+ repo_id=repo_id,
69
+ filename=filename,
70
+ subfolder=subfolder)
71
+ return torch.load(cache_file, map_location='cpu')
72
+ non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
73
+ non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
74
+ if any(k.startswith('model.model.') for k in non_lora_trainables):
75
+ non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
76
+ model.load_state_dict(non_lora_trainables, strict=False)
77
+
78
+ from peft import PeftModel
79
+ print('Loading LoRA weights...')
80
+ model = PeftModel.from_pretrained(model, model_path, **kwargs)
81
+ print('Merging LoRA weights...')
82
+ model = model.merge_and_unload()
83
+ print('Model is loaded...')
84
+ elif model_base is not None:
85
+ # this may be mm projector only
86
+ print('Loading LLaVA from base model...')
87
+ if 'mpt' in model_name.lower():
88
+ if not os.path.isfile(os.path.join(model_path, 'configuration_mpt.py')):
89
+ shutil.copyfile(os.path.join(model_base, 'configuration_mpt.py'), os.path.join(model_path, 'configuration_mpt.py'))
90
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)
91
+ cfg_pretrained = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
92
+ model = LlavaMPTForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
93
+ else:
94
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
95
+ cfg_pretrained = AutoConfig.from_pretrained(model_path)
96
+ model = LlavaLlamaForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
97
+
98
+ mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
99
+ mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
100
+ model.load_state_dict(mm_projector_weights, strict=False)
101
+ else:
102
+ if 'mpt' in model_name.lower():
103
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True, **kwargs)
104
+ model = LlavaMPTForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
105
+ else:
106
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False, **kwargs)
107
+ model = LlavaLlamaForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
108
+ else:
109
+ # Load language model
110
+ if model_base is not None:
111
+ # PEFT model
112
+ from peft import PeftModel
113
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False, **kwargs)
114
+ model = AutoModelForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, **kwargs)
115
+ print(f"Loading LoRA weights from {model_path}")
116
+ model = PeftModel.from_pretrained(model, model_path)
117
+ print(f"Merging weights")
118
+ model = model.merge_and_unload()
119
+ print('Convert to FP16...')
120
+ model.to(torch.float16)
121
+ else:
122
+ use_fast = False
123
+ if 'mpt' in model_name.lower():
124
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True, **kwargs)
125
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs)
126
+ else:
127
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False, **kwargs)
128
+ model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
129
+
130
+ # ==========================================================================================================
131
+ processor = {'image': None, 'video': None}
132
+
133
+ if 'llava' in model_name.lower() or "teochat" in model_name.lower():
134
+ mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
135
+ mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
136
+ if mm_use_im_patch_token:
137
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
138
+ tokenizer.add_tokens([DEFAULT_VIDEO_PATCH_TOKEN], special_tokens=True)
139
+ if mm_use_im_start_end:
140
+ tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
141
+ tokenizer.add_tokens([DEFAULT_VID_START_TOKEN, DEFAULT_VID_END_TOKEN], special_tokens=True)
142
+ model.resize_token_embeddings(len(tokenizer))
143
+
144
+ if model.config.mm_image_tower is not None:
145
+ image_tower = model.get_image_tower()
146
+ if not image_tower.is_loaded:
147
+ image_tower.load_model()
148
+ image_tower.to(device=device, dtype=torch.float16)
149
+ image_processor = image_tower.image_processor
150
+ processor['image'] = image_processor
151
+
152
+ if model.config.mm_video_tower is not None:
153
+ video_tower = model.get_video_tower()
154
+ if not video_tower.is_loaded:
155
+ video_tower.load_model()
156
+ video_tower.to(device=device, dtype=torch.float16)
157
+ video_processor = video_tower.video_processor
158
+ processor['video'] = video_processor
159
+ # ==========================================================================================================
160
+
161
+ if hasattr(model.config, "max_sequence_length"):
162
+ context_len = model.config.max_sequence_length
163
+ else:
164
+ context_len = 2048
165
+
166
+ return tokenizer, model, processor, context_len
videollava/model/consolidate.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM
9
+ from videollava.model import *
10
+ from videollava.model.utils import auto_upgrade
11
+
12
+
13
+ def consolidate_ckpt(src_path, dst_path):
14
+ print("Loading model")
15
+ auto_upgrade(src_path)
16
+ src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+ src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False)
18
+ src_model.save_pretrained(dst_path)
19
+ src_tokenizer.save_pretrained(dst_path)
20
+
21
+
22
+ if __name__ == "__main__":
23
+ parser = argparse.ArgumentParser()
24
+ parser.add_argument("--src", type=str, required=True)
25
+ parser.add_argument("--dst", type=str, required=True)
26
+
27
+ args = parser.parse_args()
28
+
29
+ consolidate_ckpt(args.src, args.dst)
videollava/model/language_model/llava_llama.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from transformers import AutoConfig, AutoModelForCausalLM, \
22
+ LlamaConfig, LlamaModel, LlamaForCausalLM
23
+
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+
26
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
27
+
28
+
29
+ class LlavaConfig(LlamaConfig):
30
+ model_type = "llava"
31
+
32
+
33
+ class LlavaLlamaModel(LlavaMetaModel, LlamaModel):
34
+ config_class = LlavaConfig
35
+
36
+ def __init__(self, config: LlamaConfig):
37
+ super(LlavaLlamaModel, self).__init__(config)
38
+
39
+
40
+ class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):
41
+ config_class = LlavaConfig
42
+
43
+ def __init__(self, config):
44
+ super(LlamaForCausalLM, self).__init__(config)
45
+ self.model = LlavaLlamaModel(config)
46
+ self.pretraining_tp = config.pretraining_tp
47
+ self.vocab_size = config.vocab_size
48
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
49
+
50
+ # Initialize weights and apply final processing
51
+ self.post_init()
52
+
53
+ def get_model(self):
54
+ return self.model
55
+
56
+ def forward(
57
+ self,
58
+ input_ids: torch.LongTensor = None,
59
+ attention_mask: Optional[torch.Tensor] = None,
60
+ position_ids: Optional[torch.LongTensor] = None,
61
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
62
+ inputs_embeds: Optional[torch.FloatTensor] = None,
63
+ labels: Optional[torch.LongTensor] = None,
64
+ use_cache: Optional[bool] = None,
65
+ output_attentions: Optional[bool] = None,
66
+ output_hidden_states: Optional[bool] = None,
67
+ images: Optional[torch.FloatTensor] = None,
68
+ return_dict: Optional[bool] = None,
69
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
70
+
71
+ if inputs_embeds is None:
72
+ (
73
+ input_ids,
74
+ position_ids,
75
+ attention_mask,
76
+ past_key_values,
77
+ inputs_embeds,
78
+ labels
79
+ ) = self.prepare_inputs_labels_for_multimodal(
80
+ input_ids,
81
+ position_ids,
82
+ attention_mask,
83
+ past_key_values,
84
+ labels,
85
+ images
86
+ )
87
+
88
+ return super().forward(
89
+ input_ids=input_ids,
90
+ attention_mask=attention_mask,
91
+ position_ids=position_ids,
92
+ past_key_values=past_key_values,
93
+ inputs_embeds=inputs_embeds,
94
+ labels=labels,
95
+ use_cache=use_cache,
96
+ output_attentions=output_attentions,
97
+ output_hidden_states=output_hidden_states,
98
+ return_dict=return_dict
99
+ )
100
+
101
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
102
+ images = kwargs.pop("images", None)
103
+ _inputs = super().prepare_inputs_for_generation(
104
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
105
+ )
106
+ if images is not None:
107
+ _inputs['images'] = images
108
+ return _inputs
109
+
110
+ AutoConfig.register("llava", LlavaConfig)
111
+ AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM)
videollava/model/language_model/llava_mpt.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import List, Optional, Tuple
17
+ import warnings
18
+
19
+ import torch
20
+ import torch.nn.functional as F
21
+ import math
22
+
23
+ from transformers import AutoConfig, AutoModelForCausalLM
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+
26
+ from .mpt.modeling_mpt import MPTConfig, MPTForCausalLM, MPTModel
27
+ from videollava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
28
+
29
+
30
+ class LlavaMPTConfig(MPTConfig):
31
+ model_type = "llava_mpt"
32
+
33
+
34
+ class LlavaMPTModel(LlavaMetaModel, MPTModel):
35
+ config_class = LlavaMPTConfig
36
+
37
+ def __init__(self, config: MPTConfig):
38
+ config.hidden_size = config.d_model
39
+ super(LlavaMPTModel, self).__init__(config)
40
+
41
+ def embed_tokens(self, x):
42
+ return self.wte(x)
43
+
44
+
45
+ class LlavaMPTForCausalLM(MPTForCausalLM, LlavaMetaForCausalLM):
46
+ config_class = LlavaMPTConfig
47
+ supports_gradient_checkpointing = True
48
+
49
+ def __init__(self, config):
50
+ super(MPTForCausalLM, self).__init__(config)
51
+
52
+ if not config.tie_word_embeddings:
53
+ raise ValueError('MPTForCausalLM only supports tied word embeddings')
54
+ self.transformer = LlavaMPTModel(config)
55
+ self.logit_scale = None
56
+ if config.logit_scale is not None:
57
+ logit_scale = config.logit_scale
58
+ if isinstance(logit_scale, str):
59
+ if logit_scale == 'inv_sqrt_d_model':
60
+ logit_scale = 1 / math.sqrt(config.d_model)
61
+ else:
62
+ raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
63
+ self.logit_scale = logit_scale
64
+
65
+ def get_model(self):
66
+ return self.transformer
67
+
68
+ def _set_gradient_checkpointing(self, module, value=False):
69
+ if isinstance(module, LlavaMPTModel):
70
+ module.gradient_checkpointing = value
71
+
72
+ def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, images=None):
73
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
74
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
75
+
76
+ input_ids, _, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, None, attention_mask, past_key_values, labels, images)
77
+ outputs = self.transformer(input_ids=input_ids, inputs_embeds=inputs_embeds, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache)
78
+ # FIXME: this is a hack to fix the multiple gpu inference issue in https://github.com/haotian-liu/LLaVA/issues/338
79
+ logits = F.linear(outputs.last_hidden_state.to(self.transformer.wte.weight.device), self.transformer.wte.weight)
80
+ if self.logit_scale is not None:
81
+ if self.logit_scale == 0:
82
+ warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
83
+ logits *= self.logit_scale
84
+ loss = None
85
+ if labels is not None:
86
+ labels = torch.roll(labels, shifts=-1)
87
+ labels[:, -1] = -100
88
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1))
89
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states)
90
+
91
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
92
+ if inputs_embeds is not None:
93
+ raise NotImplementedError('inputs_embeds is not implemented for MPT yet')
94
+ attention_mask = kwargs['attention_mask'].bool()
95
+ if attention_mask[:, -1].sum() != attention_mask.shape[0]:
96
+ raise NotImplementedError('MPT does not support generation with right padding.')
97
+ if self.transformer.attn_uses_sequence_id and self.training:
98
+ sequence_id = torch.zeros_like(input_ids[:1])
99
+ else:
100
+ sequence_id = None
101
+ if past_key_values is not None:
102
+ input_ids = input_ids[:, -1].unsqueeze(-1)
103
+ if self.transformer.prefix_lm:
104
+ prefix_mask = torch.ones_like(attention_mask)
105
+ if kwargs.get('use_cache') == False:
106
+ raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
107
+ else:
108
+ prefix_mask = None
109
+ return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True), "images": kwargs.get("images", None)}
110
+
111
+
112
+ AutoConfig.register("llava_mpt", LlavaMPTConfig)
113
+ AutoModelForCausalLM.register(LlavaMPTConfig, LlavaMPTForCausalLM)
videollava/model/language_model/mpt/adapt_tokenizer.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+ from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast
3
+ Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
4
+ NUM_SENTINEL_TOKENS: int = 100
5
+
6
+ def adapt_tokenizer_for_denoising(tokenizer: Tokenizer):
7
+ """Adds sentinel tokens and padding token (if missing).
8
+
9
+ Expands the tokenizer vocabulary to include sentinel tokens
10
+ used in mixture-of-denoiser tasks as well as a padding token.
11
+
12
+ All added tokens are added as special tokens. No tokens are
13
+ added if sentinel tokens and padding token already exist.
14
+ """
15
+ sentinels_to_add = [f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)]
16
+ tokenizer.add_tokens(sentinels_to_add, special_tokens=True)
17
+ if tokenizer.pad_token is None:
18
+ tokenizer.add_tokens('<pad>', special_tokens=True)
19
+ tokenizer.pad_token = '<pad>'
20
+ assert tokenizer.pad_token_id is not None
21
+ sentinels = ''.join([f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)])
22
+ _sentinel_token_ids = tokenizer(sentinels, add_special_tokens=False).input_ids
23
+ tokenizer.sentinel_token_ids = _sentinel_token_ids
24
+
25
+ class AutoTokenizerForMOD(AutoTokenizer):
26
+ """AutoTokenizer + Adaptation for MOD.
27
+
28
+ A simple wrapper around AutoTokenizer to make instantiating
29
+ an MOD-adapted tokenizer a bit easier.
30
+
31
+ MOD-adapted tokenizers have sentinel tokens (e.g., <extra_id_0>),
32
+ a padding token, and a property to get the token ids of the
33
+ sentinel tokens.
34
+ """
35
+
36
+ @classmethod
37
+ def from_pretrained(cls, *args, **kwargs):
38
+ """See `AutoTokenizer.from_pretrained` docstring."""
39
+ tokenizer = super().from_pretrained(*args, **kwargs)
40
+ adapt_tokenizer_for_denoising(tokenizer)
41
+ return tokenizer
videollava/model/language_model/mpt/attention.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Attention layers."""
2
+ import math
3
+ import warnings
4
+ from typing import Optional
5
+ import torch
6
+ import torch.nn as nn
7
+ from einops import rearrange
8
+ from packaging import version
9
+ from torch import nn
10
+ from .norm import LPLayerNorm
11
+
12
+ def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool):
13
+ if original_is_causal and num_query_tokens != num_key_tokens:
14
+ if num_query_tokens != 1:
15
+ raise NotImplementedError('MPT does not support query and key with different number of tokens, unless number of query tokens is 1.')
16
+ else:
17
+ return False
18
+ return original_is_causal
19
+
20
+ def scaled_multihead_dot_product_attention(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
21
+ q = rearrange(query, 'b s (h d) -> b h s d', h=n_heads)
22
+ kv_n_heads = 1 if multiquery else n_heads
23
+ k = rearrange(key, 'b s (h d) -> b h d s', h=kv_n_heads)
24
+ v = rearrange(value, 'b s (h d) -> b h s d', h=kv_n_heads)
25
+ if past_key_value is not None:
26
+ if len(past_key_value) != 0:
27
+ k = torch.cat([past_key_value[0], k], dim=3)
28
+ v = torch.cat([past_key_value[1], v], dim=2)
29
+ past_key_value = (k, v)
30
+ (b, _, s_q, d) = q.shape
31
+ s_k = k.size(-1)
32
+ if softmax_scale is None:
33
+ softmax_scale = 1 / math.sqrt(d)
34
+ attn_weight = q.matmul(k) * softmax_scale
35
+ if attn_bias is not None:
36
+ _s_q = max(0, attn_bias.size(2) - s_q)
37
+ _s_k = max(0, attn_bias.size(3) - s_k)
38
+ attn_bias = attn_bias[:, :, _s_q:, _s_k:]
39
+ if attn_bias.size(-1) != 1 and attn_bias.size(-1) != s_k or (attn_bias.size(-2) != 1 and attn_bias.size(-2) != s_q):
40
+ raise RuntimeError(f'attn_bias (shape: {attn_bias.shape}) is expected to broadcast to shape: {attn_weight.shape}.')
41
+ attn_weight = attn_weight + attn_bias
42
+ min_val = torch.finfo(q.dtype).min
43
+ if key_padding_mask is not None:
44
+ if attn_bias is not None:
45
+ warnings.warn('Propogating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unneccessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
46
+ attn_weight = attn_weight.masked_fill(~key_padding_mask.view((b, 1, 1, s_k)), min_val)
47
+ if is_causal and (not q.size(2) == 1):
48
+ s = max(s_q, s_k)
49
+ causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16)
50
+ causal_mask = causal_mask.tril()
51
+ causal_mask = causal_mask.to(torch.bool)
52
+ causal_mask = ~causal_mask
53
+ causal_mask = causal_mask[-s_q:, -s_k:]
54
+ attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k), min_val)
55
+ attn_weight = torch.softmax(attn_weight, dim=-1)
56
+ if dropout_p:
57
+ attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p, training=training, inplace=True)
58
+ out = attn_weight.to(v.dtype).matmul(v)
59
+ out = rearrange(out, 'b h s d -> b s (h d)')
60
+ if needs_weights:
61
+ return (out, attn_weight, past_key_value)
62
+ return (out, None, past_key_value)
63
+
64
+ def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
65
+ for tensor in tensors:
66
+ if tensor.dtype not in valid_dtypes:
67
+ raise TypeError(f'tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}.')
68
+ if not tensor.is_cuda:
69
+ raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
70
+
71
+ def flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
72
+ try:
73
+ from flash_attn import bert_padding, flash_attn_interface
74
+ except:
75
+ raise RuntimeError('Please install flash-attn==1.0.3.post0')
76
+ check_valid_inputs(query, key, value)
77
+ if past_key_value is not None:
78
+ if len(past_key_value) != 0:
79
+ key = torch.cat([past_key_value[0], key], dim=1)
80
+ value = torch.cat([past_key_value[1], value], dim=1)
81
+ past_key_value = (key, value)
82
+ if attn_bias is not None:
83
+ _s_q = max(0, attn_bias.size(2) - query.size(1))
84
+ _s_k = max(0, attn_bias.size(3) - key.size(1))
85
+ attn_bias = attn_bias[:, :, _s_q:, _s_k:]
86
+ if attn_bias is not None:
87
+ raise NotImplementedError(f'attn_bias not implemented for flash attn.')
88
+ (batch_size, seqlen) = query.shape[:2]
89
+ if key_padding_mask is None:
90
+ key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
91
+ query_padding_mask = key_padding_mask[:, -query.size(1):]
92
+ (query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(query, query_padding_mask)
93
+ query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
94
+ (key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(key, key_padding_mask)
95
+ key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
96
+ (value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask)
97
+ value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
98
+ if multiquery:
99
+ key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
100
+ value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1))
101
+ dropout_p = dropout_p if training else 0.0
102
+ reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
103
+ output_unpad = flash_attn_interface.flash_attn_unpadded_func(query_unpad, key_unpad, value_unpad, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights)
104
+ output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen)
105
+ return (output, None, past_key_value)
106
+
107
+ def triton_flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
108
+ try:
109
+ from .flash_attn_triton import flash_attn_func
110
+ except:
111
+ _installed = False
112
+ if version.parse(torch.__version__) < version.parse('2.0.0'):
113
+ _installed = True
114
+ try:
115
+ from flash_attn.flash_attn_triton import flash_attn_func
116
+ except:
117
+ _installed = False
118
+ if not _installed:
119
+ raise RuntimeError('Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU and `pip install .[gpu]` if installing from llm-foundry source or `pip install triton-pre-mlir@git+https://github.com/vchiley/triton.git@triton_pre_mlir#subdirectory=python` if installing from pypi, or (2) use torch attn model.attn_config.attn_impl=torch (torch attn_impl will be slow). Note: (1) requires you have CMake and PyTorch already installed.')
120
+ check_valid_inputs(query, key, value)
121
+ if past_key_value is not None:
122
+ if len(past_key_value) != 0:
123
+ key = torch.cat([past_key_value[0], key], dim=1)
124
+ value = torch.cat([past_key_value[1], value], dim=1)
125
+ past_key_value = (key, value)
126
+ if attn_bias is not None:
127
+ _s_q = max(0, attn_bias.size(2) - query.size(1))
128
+ _s_k = max(0, attn_bias.size(3) - key.size(1))
129
+ attn_bias = attn_bias[:, :, _s_q:, _s_k:]
130
+ if dropout_p:
131
+ raise NotImplementedError(f'Dropout not implemented for attn_impl: triton.')
132
+ if needs_weights:
133
+ raise NotImplementedError(f'attn_impl: triton cannot return attn weights.')
134
+ if key_padding_mask is not None:
135
+ warnings.warn('Propagating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unnecessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
136
+ (b_size, s_k) = key_padding_mask.shape[:2]
137
+ if attn_bias is None:
138
+ attn_bias = query.new_zeros(b_size, 1, 1, s_k)
139
+ attn_bias = attn_bias.masked_fill(~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min)
140
+ query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads)
141
+ key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
142
+ value = rearrange(value, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
143
+ if multiquery:
144
+ key = key.expand(*key.shape[:2], n_heads, key.size(-1))
145
+ value = value.expand(*value.shape[:2], n_heads, value.size(-1))
146
+ reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
147
+ attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale)
148
+ output = attn_output.view(*attn_output.shape[:2], -1)
149
+ return (output, None, past_key_value)
150
+
151
+ class MultiheadAttention(nn.Module):
152
+ """Multi-head self attention.
153
+
154
+ Using torch or triton attention implementation enables user to also use
155
+ additive bias.
156
+ """
157
+
158
+ def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
159
+ super().__init__()
160
+ self.attn_impl = attn_impl
161
+ self.clip_qkv = clip_qkv
162
+ self.qk_ln = qk_ln
163
+ self.d_model = d_model
164
+ self.n_heads = n_heads
165
+ self.softmax_scale = softmax_scale
166
+ if self.softmax_scale is None:
167
+ self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
168
+ self.attn_dropout_p = attn_pdrop
169
+ self.Wqkv = nn.Linear(self.d_model, 3 * self.d_model, device=device)
170
+ fuse_splits = (d_model, 2 * d_model)
171
+ self.Wqkv._fused = (0, fuse_splits)
172
+ if self.qk_ln:
173
+ layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
174
+ self.q_ln = layernorm_class(self.d_model, device=device)
175
+ self.k_ln = layernorm_class(self.d_model, device=device)
176
+ if self.attn_impl == 'flash':
177
+ self.attn_fn = flash_attn_fn
178
+ elif self.attn_impl == 'triton':
179
+ self.attn_fn = triton_flash_attn_fn
180
+ if verbose:
181
+ warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
182
+ elif self.attn_impl == 'torch':
183
+ self.attn_fn = scaled_multihead_dot_product_attention
184
+ if torch.cuda.is_available() and verbose:
185
+ warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
186
+ else:
187
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
188
+ self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
189
+ self.out_proj._is_residual = True
190
+
191
+ def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
192
+ qkv = self.Wqkv(x)
193
+ if self.clip_qkv:
194
+ qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
195
+ (query, key, value) = qkv.chunk(3, dim=2)
196
+ key_padding_mask = attention_mask
197
+ if self.qk_ln:
198
+ dtype = query.dtype
199
+ query = self.q_ln(query).to(dtype)
200
+ key = self.k_ln(key).to(dtype)
201
+ (context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights)
202
+ return (self.out_proj(context), attn_weights, past_key_value)
203
+
204
+ class MultiQueryAttention(nn.Module):
205
+ """Multi-Query self attention.
206
+
207
+ Using torch or triton attention implementation enables user to also use
208
+ additive bias.
209
+ """
210
+
211
+ def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
212
+ super().__init__()
213
+ self.attn_impl = attn_impl
214
+ self.clip_qkv = clip_qkv
215
+ self.qk_ln = qk_ln
216
+ self.d_model = d_model
217
+ self.n_heads = n_heads
218
+ self.head_dim = d_model // n_heads
219
+ self.softmax_scale = softmax_scale
220
+ if self.softmax_scale is None:
221
+ self.softmax_scale = 1 / math.sqrt(self.head_dim)
222
+ self.attn_dropout_p = attn_pdrop
223
+ self.Wqkv = nn.Linear(d_model, d_model + 2 * self.head_dim, device=device)
224
+ fuse_splits = (d_model, d_model + self.head_dim)
225
+ self.Wqkv._fused = (0, fuse_splits)
226
+ if self.qk_ln:
227
+ layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
228
+ self.q_ln = layernorm_class(d_model, device=device)
229
+ self.k_ln = layernorm_class(self.head_dim, device=device)
230
+ if self.attn_impl == 'flash':
231
+ self.attn_fn = flash_attn_fn
232
+ elif self.attn_impl == 'triton':
233
+ self.attn_fn = triton_flash_attn_fn
234
+ if verbose:
235
+ warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
236
+ elif self.attn_impl == 'torch':
237
+ self.attn_fn = scaled_multihead_dot_product_attention
238
+ if torch.cuda.is_available() and verbose:
239
+ warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
240
+ else:
241
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
242
+ self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
243
+ self.out_proj._is_residual = True
244
+
245
+ def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
246
+ qkv = self.Wqkv(x)
247
+ if self.clip_qkv:
248
+ qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
249
+ (query, key, value) = qkv.split([self.d_model, self.head_dim, self.head_dim], dim=2)
250
+ key_padding_mask = attention_mask
251
+ if self.qk_ln:
252
+ dtype = query.dtype
253
+ query = self.q_ln(query).to(dtype)
254
+ key = self.k_ln(key).to(dtype)
255
+ (context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, multiquery=True)
256
+ return (self.out_proj(context), attn_weights, past_key_value)
257
+
258
+ def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):
259
+ if attn_impl == 'flash':
260
+ return None
261
+ elif attn_impl in ['torch', 'triton']:
262
+ if alibi:
263
+ if (prefix_lm or not causal) or use_sequence_id:
264
+ return (1, n_heads, seq_len, seq_len)
265
+ return (1, n_heads, 1, seq_len)
266
+ elif prefix_lm or use_sequence_id:
267
+ return (1, 1, seq_len, seq_len)
268
+ return None
269
+ else:
270
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
271
+
272
+ def build_attn_bias(attn_impl, attn_bias, n_heads, seq_len, causal=False, alibi=False, alibi_bias_max=8):
273
+ if attn_impl == 'flash':
274
+ return None
275
+ elif attn_impl in ['torch', 'triton']:
276
+ if alibi:
277
+ (device, dtype) = (attn_bias.device, attn_bias.dtype)
278
+ attn_bias = attn_bias.add(build_alibi_bias(n_heads, seq_len, full=not causal, alibi_bias_max=alibi_bias_max, device=device, dtype=dtype))
279
+ return attn_bias
280
+ else:
281
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
282
+
283
+ def gen_slopes(n_heads, alibi_bias_max=8, device=None):
284
+ _n_heads = 2 ** math.ceil(math.log2(n_heads))
285
+ m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
286
+ m = m.mul(alibi_bias_max / _n_heads)
287
+ slopes = 1.0 / torch.pow(2, m)
288
+ if _n_heads != n_heads:
289
+ slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
290
+ return slopes.view(1, n_heads, 1, 1)
291
+
292
+ def build_alibi_bias(n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None):
293
+ alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, 1, seq_len)
294
+ if full:
295
+ alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, seq_len, 1)
296
+ alibi_bias = alibi_bias.abs().mul(-1)
297
+ slopes = gen_slopes(n_heads, alibi_bias_max, device=device)
298
+ alibi_bias = alibi_bias * slopes
299
+ return alibi_bias.to(dtype=dtype)
300
+ ATTN_CLASS_REGISTRY = {'multihead_attention': MultiheadAttention, 'multiquery_attention': MultiQueryAttention}
videollava/model/language_model/mpt/blocks.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GPT Blocks used for the GPT Model."""
2
+ from typing import Dict, Optional, Tuple
3
+ import torch
4
+ import torch.nn as nn
5
+ from .attention import ATTN_CLASS_REGISTRY
6
+ from .norm import NORM_CLASS_REGISTRY
7
+
8
+ class MPTMLP(nn.Module):
9
+
10
+ def __init__(self, d_model: int, expansion_ratio: int, device: Optional[str]=None):
11
+ super().__init__()
12
+ self.up_proj = nn.Linear(d_model, expansion_ratio * d_model, device=device)
13
+ self.act = nn.GELU(approximate='none')
14
+ self.down_proj = nn.Linear(expansion_ratio * d_model, d_model, device=device)
15
+ self.down_proj._is_residual = True
16
+
17
+ def forward(self, x):
18
+ return self.down_proj(self.act(self.up_proj(x)))
19
+
20
+ class MPTBlock(nn.Module):
21
+
22
+ def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config: Dict={'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}, resid_pdrop: float=0.0, norm_type: str='low_precision_layernorm', verbose: int=0, device: Optional[str]=None, **kwargs):
23
+ del kwargs
24
+ super().__init__()
25
+ norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
26
+ attn_class = ATTN_CLASS_REGISTRY[attn_config['attn_type']]
27
+ self.norm_1 = norm_class(d_model, device=device)
28
+ self.attn = attn_class(attn_impl=attn_config['attn_impl'], clip_qkv=attn_config['clip_qkv'], qk_ln=attn_config['qk_ln'], softmax_scale=attn_config['softmax_scale'], attn_pdrop=attn_config['attn_pdrop'], d_model=d_model, n_heads=n_heads, verbose=verbose, device=device)
29
+ self.norm_2 = norm_class(d_model, device=device)
30
+ self.ffn = MPTMLP(d_model=d_model, expansion_ratio=expansion_ratio, device=device)
31
+ self.resid_attn_dropout = nn.Dropout(resid_pdrop)
32
+ self.resid_ffn_dropout = nn.Dropout(resid_pdrop)
33
+
34
+ def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, attention_mask: Optional[torch.ByteTensor]=None, is_causal: bool=True) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor]]]:
35
+ a = self.norm_1(x)
36
+ (b, attn_weights, past_key_value) = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=is_causal)
37
+ x = x + self.resid_attn_dropout(b)
38
+ m = self.norm_2(x)
39
+ n = self.ffn(m)
40
+ x = x + self.resid_ffn_dropout(n)
41
+ return (x, attn_weights, past_key_value)
videollava/model/language_model/mpt/configuration_mpt.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A HuggingFace-style model configuration."""
2
+ from typing import Dict, Optional, Union
3
+ from transformers import PretrainedConfig
4
+ attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}
5
+ init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
6
+
7
+ class MPTConfig(PretrainedConfig):
8
+ model_type = 'mpt'
9
+
10
+ def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False, verbose: int=0, embedding_fraction: float=1.0, norm_type: str='low_precision_layernorm', use_cache: bool=False, init_config: Dict=init_config_defaults, **kwargs):
11
+ """The MPT configuration class.
12
+
13
+ Args:
14
+ d_model (int): The size of the embedding dimension of the model.
15
+ n_heads (int): The number of attention heads.
16
+ n_layers (int): The number of layers in the model.
17
+ expansion_ratio (int): The ratio of the up/down scale in the MLP.
18
+ max_seq_len (int): The maximum sequence length of the model.
19
+ vocab_size (int): The size of the vocabulary.
20
+ resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
21
+ emb_pdrop (float): The dropout probability for the embedding layer.
22
+ learned_pos_emb (bool): Whether to use learned positional embeddings
23
+ attn_config (Dict): A dictionary used to configure the model's attention module:
24
+ attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention
25
+ attn_pdrop (float): The dropout probability for the attention layers.
26
+ attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
27
+ qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
28
+ clip_qkv (Optional[float]): If not None, clip the queries, keys, and values in the attention layer to
29
+ this value.
30
+ softmax_scale (Optional[float]): If not None, scale the softmax in the attention layer by this value. If None,
31
+ use the default scale of ``1/sqrt(d_keys)``.
32
+ prefix_lm (Optional[bool]): Whether the model should operate as a Prefix LM. This requires passing an
33
+ extra `prefix_mask` argument which indicates which tokens belong to the prefix. Tokens in the prefix
34
+ can attend to one another bi-directionally. Tokens outside the prefix use causal attention.
35
+ attn_uses_sequence_id (Optional[bool]): Whether to restrict attention to tokens that have the same sequence_id.
36
+ When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
37
+ which sub-sequence each token belongs to.
38
+ Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
39
+ alibi (bool): Whether to use the alibi bias instead of position embeddings.
40
+ alibi_bias_max (int): The maximum value of the alibi bias.
41
+ init_device (str): The device to use for parameter initialization.
42
+ logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
43
+ no_bias (bool): Whether to use bias in all layers.
44
+ verbose (int): The verbosity level. 0 is silent.
45
+ embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
46
+ norm_type (str): choose type of norm to use
47
+ multiquery_attention (bool): Whether to use multiquery attention implementation.
48
+ use_cache (bool): Whether or not the model should return the last key/values attentions
49
+ init_config (Dict): A dictionary used to configure the model initialization:
50
+ init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
51
+ 'kaiming_uniform_', 'kaiming_normal_', 'neox_init_', 'small_init_', 'xavier_uniform_', or
52
+ 'xavier_normal_'. These mimic the parameter initialization methods in PyTorch.
53
+ init_div_is_residual (Union[int, float, str, bool]): Value to divide initial weights by if ``module._is_residual`` is True.
54
+ emb_init_std (Optional[float]): The standard deviation of the normal distribution used to initialize the embedding layer.
55
+ emb_init_uniform_lim (Optional[Union[Tuple[float, float], float]]): The lower and upper limits of the uniform distribution
56
+ used to initialize the embedding layer. Mutually exclusive with ``emb_init_std``.
57
+ init_std (float): The standard deviation of the normal distribution used to initialize the model,
58
+ if using the baseline_ parameter initialization scheme.
59
+ init_gain (float): The gain to use for parameter initialization with kaiming or xavier initialization schemes.
60
+ fan_mode (str): The fan mode to use for parameter initialization with kaiming initialization schemes.
61
+ init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
62
+ ---
63
+ See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
64
+ """
65
+ self.d_model = d_model
66
+ self.n_heads = n_heads
67
+ self.n_layers = n_layers
68
+ self.expansion_ratio = expansion_ratio
69
+ self.max_seq_len = max_seq_len
70
+ self.vocab_size = vocab_size
71
+ self.resid_pdrop = resid_pdrop
72
+ self.emb_pdrop = emb_pdrop
73
+ self.learned_pos_emb = learned_pos_emb
74
+ self.attn_config = attn_config
75
+ self.init_device = init_device
76
+ self.logit_scale = logit_scale
77
+ self.no_bias = no_bias
78
+ self.verbose = verbose
79
+ self.embedding_fraction = embedding_fraction
80
+ self.norm_type = norm_type
81
+ self.use_cache = use_cache
82
+ self.init_config = init_config
83
+ if 'name' in kwargs:
84
+ del kwargs['name']
85
+ if 'loss_fn' in kwargs:
86
+ del kwargs['loss_fn']
87
+ super().__init__(**kwargs)
88
+ self._validate_config()
89
+
90
+ def _set_config_defaults(self, config, config_defaults):
91
+ for (k, v) in config_defaults.items():
92
+ if k not in config:
93
+ config[k] = v
94
+ return config
95
+
96
+ def _validate_config(self):
97
+ self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults)
98
+ self.init_config = self._set_config_defaults(self.init_config, init_config_defaults)
99
+ if self.d_model % self.n_heads != 0:
100
+ raise ValueError('d_model must be divisible by n_heads')
101
+ if any((prob < 0 or prob > 1 for prob in [self.attn_config['attn_pdrop'], self.resid_pdrop, self.emb_pdrop])):
102
+ raise ValueError("self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop are probabilities and must be between 0 and 1")
103
+ if self.attn_config['attn_impl'] not in ['torch', 'flash', 'triton']:
104
+ raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
105
+ if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
106
+ raise NotImplementedError('prefix_lm only implemented with torch and triton attention.')
107
+ if self.attn_config['alibi'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
108
+ raise NotImplementedError('alibi only implemented with torch and triton attention.')
109
+ if self.attn_config['attn_uses_sequence_id'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
110
+ raise NotImplementedError('attn_uses_sequence_id only implemented with torch and triton attention.')
111
+ if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
112
+ raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!')
113
+ if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model':
114
+ raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
115
+ if self.init_config.get('name', None) is None:
116
+ raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
117
+ if not self.learned_pos_emb and (not self.attn_config['alibi']):
118
+ raise ValueError(f'Positional information must be provided to the model using either learned_pos_emb or alibi.')
videollava/model/language_model/mpt/custom_embedding.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torch import Tensor
5
+
6
+ class SharedEmbedding(nn.Embedding):
7
+
8
+ def forward(self, input: Tensor, unembed: bool=False) -> Tensor:
9
+ if unembed:
10
+ return F.linear(input, self.weight)
11
+ return super().forward(input)
videollava/model/language_model/mpt/flash_attn_triton.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py
3
+ update imports to use 'triton_pre_mlir'
4
+
5
+ *Experimental* implementation of FlashAttention in Triton.
6
+ Tested with triton==2.0.0.dev20221202.
7
+ Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions
8
+ other than 64:
9
+ https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207
10
+ We'll update this implementation with the new Triton backend once this is fixed.
11
+
12
+ We use the FlashAttention implementation from Phil Tillet a starting point.
13
+ https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
14
+
15
+ Changes:
16
+ - Implement both causal and non-causal attention.
17
+ - Implement both self-attention and cross-attention.
18
+ - Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
19
+ - Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
20
+ - Support attention bias.
21
+ - Speed up the forward pass a bit, and only store the LSE instead of m and l.
22
+ - Make the backward for d=128 much faster by reducing register spilling.
23
+ - Optionally parallelize the backward pass across seqlen_k, to deal with the case of
24
+ small batch size * nheads.
25
+
26
+ Caution:
27
+ - This is an *experimental* implementation. The forward pass should be quite robust but
28
+ I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler).
29
+ - This implementation has only been tested on A100.
30
+ - If you plan to use headdim other than 64 and 128, you should test for race conditions
31
+ (due to the Triton compiler), as done in tests/test_flash_attn.py
32
+ "test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
33
+ for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
34
+ that there are none left for other head dimensions.
35
+
36
+ Differences between this Triton version and the CUDA version:
37
+ - Triton version doesn't support dropout.
38
+ - Triton forward is generally faster than CUDA forward, while Triton backward is
39
+ generally slower than CUDA backward. Overall Triton forward + backward is slightly slower
40
+ than CUDA forward + backward.
41
+ - Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
42
+ - Triton version supports attention bias, while CUDA version doesn't.
43
+ """
44
+ import math
45
+ import torch
46
+ import triton_pre_mlir as triton
47
+ import triton_pre_mlir.language as tl
48
+
49
+ @triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
50
+ @triton.jit
51
+ def _fwd_kernel(Q, K, V, Bias, Out, Lse, TMP, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_ob, stride_oh, stride_om, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
52
+ start_m = tl.program_id(0)
53
+ off_hb = tl.program_id(1)
54
+ off_b = off_hb // nheads
55
+ off_h = off_hb % nheads
56
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
57
+ offs_n = tl.arange(0, BLOCK_N)
58
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
59
+ q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :])
60
+ k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :])
61
+ v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :])
62
+ if BIAS_TYPE == 'vector':
63
+ b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
64
+ elif BIAS_TYPE == 'matrix':
65
+ b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (offs_m[:, None] * stride_bm + offs_n[None, :])
66
+ t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
67
+ lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
68
+ m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
69
+ acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
70
+ if EVEN_M & EVEN_N:
71
+ if EVEN_HEADDIM:
72
+ q = tl.load(q_ptrs)
73
+ else:
74
+ q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
75
+ elif EVEN_HEADDIM:
76
+ q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
77
+ else:
78
+ q = tl.load(q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
79
+ end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k)
80
+ for start_n in range(0, end_n, BLOCK_N):
81
+ start_n = tl.multiple_of(start_n, BLOCK_N)
82
+ if EVEN_N & EVEN_M:
83
+ if EVEN_HEADDIM:
84
+ k = tl.load(k_ptrs + start_n * stride_kn)
85
+ else:
86
+ k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0)
87
+ elif EVEN_HEADDIM:
88
+ k = tl.load(k_ptrs + start_n * stride_kn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
89
+ else:
90
+ k = tl.load(k_ptrs + start_n * stride_kn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
91
+ qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
92
+ qk += tl.dot(q, k, trans_b=True)
93
+ if not EVEN_N:
94
+ qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float('-inf'))
95
+ if IS_CAUSAL:
96
+ qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float('-inf'))
97
+ if BIAS_TYPE != 'none':
98
+ if BIAS_TYPE == 'vector':
99
+ if EVEN_N:
100
+ bias = tl.load(b_ptrs + start_n).to(tl.float32)
101
+ else:
102
+ bias = tl.load(b_ptrs + start_n, mask=start_n + offs_n < seqlen_k, other=0.0).to(tl.float32)
103
+ bias = bias[None, :]
104
+ elif BIAS_TYPE == 'matrix':
105
+ if EVEN_M & EVEN_N:
106
+ bias = tl.load(b_ptrs + start_n).to(tl.float32)
107
+ else:
108
+ bias = tl.load(b_ptrs + start_n, mask=(offs_m[:, None] < seqlen_q) & ((start_n + offs_n)[None, :] < seqlen_k), other=0.0).to(tl.float32)
109
+ qk = qk * softmax_scale + bias
110
+ m_ij = tl.maximum(tl.max(qk, 1), lse_i)
111
+ p = tl.exp(qk - m_ij[:, None])
112
+ else:
113
+ m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
114
+ p = tl.exp(qk * softmax_scale - m_ij[:, None])
115
+ l_ij = tl.sum(p, 1)
116
+ acc_o_scale = tl.exp(m_i - m_ij)
117
+ tl.store(t_ptrs, acc_o_scale)
118
+ acc_o_scale = tl.load(t_ptrs)
119
+ acc_o = acc_o * acc_o_scale[:, None]
120
+ if EVEN_N & EVEN_M:
121
+ if EVEN_HEADDIM:
122
+ v = tl.load(v_ptrs + start_n * stride_vn)
123
+ else:
124
+ v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0)
125
+ elif EVEN_HEADDIM:
126
+ v = tl.load(v_ptrs + start_n * stride_vn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
127
+ else:
128
+ v = tl.load(v_ptrs + start_n * stride_vn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
129
+ p = p.to(v.dtype)
130
+ acc_o += tl.dot(p, v)
131
+ m_i = m_ij
132
+ l_i_new = tl.exp(lse_i - m_ij) + l_ij
133
+ lse_i = m_ij + tl.log(l_i_new)
134
+ o_scale = tl.exp(m_i - lse_i)
135
+ tl.store(t_ptrs, o_scale)
136
+ o_scale = tl.load(t_ptrs)
137
+ acc_o = acc_o * o_scale[:, None]
138
+ start_m = tl.program_id(0)
139
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
140
+ lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
141
+ tl.store(lse_ptrs, lse_i)
142
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
143
+ out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (offs_m[:, None] * stride_om + offs_d[None, :])
144
+ if EVEN_M:
145
+ if EVEN_HEADDIM:
146
+ tl.store(out_ptrs, acc_o)
147
+ else:
148
+ tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
149
+ elif EVEN_HEADDIM:
150
+ tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
151
+ else:
152
+ tl.store(out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
153
+
154
+ @triton.jit
155
+ def _bwd_preprocess_do_o_dot(Out, DO, Delta, stride_ob, stride_oh, stride_om, stride_dob, stride_doh, stride_dom, nheads, seqlen_q, seqlen_q_rounded, headdim, BLOCK_M: tl.constexpr, BLOCK_HEADDIM: tl.constexpr):
156
+ start_m = tl.program_id(0)
157
+ off_hb = tl.program_id(1)
158
+ off_b = off_hb // nheads
159
+ off_h = off_hb % nheads
160
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
161
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
162
+ o = tl.load(Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
163
+ do = tl.load(DO + off_b * stride_dob + off_h * stride_doh + offs_m[:, None] * stride_dom + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
164
+ delta = tl.sum(o * do, axis=1)
165
+ tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
166
+
167
+ @triton.jit
168
+ def _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr):
169
+ if EVEN_N & EVEN_M:
170
+ if EVEN_HEADDIM:
171
+ tl.store(dv_ptrs, dv)
172
+ tl.store(dk_ptrs, dk)
173
+ else:
174
+ tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
175
+ tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
176
+ elif EVEN_HEADDIM:
177
+ tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
178
+ tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
179
+ else:
180
+ tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
181
+ tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
182
+
183
+ @triton.jit
184
+ def _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD: tl.constexpr, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
185
+ begin_m = 0 if not IS_CAUSAL else start_n * BLOCK_N // BLOCK_M * BLOCK_M
186
+ offs_qm = begin_m + tl.arange(0, BLOCK_M)
187
+ offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
188
+ offs_m = tl.arange(0, BLOCK_M)
189
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
190
+ q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
191
+ k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
192
+ v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
193
+ do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
194
+ dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
195
+ if BIAS_TYPE == 'vector':
196
+ b_ptrs = Bias + offs_n
197
+ elif BIAS_TYPE == 'matrix':
198
+ b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
199
+ dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
200
+ dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
201
+ if begin_m >= seqlen_q:
202
+ dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
203
+ dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
204
+ _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
205
+ return
206
+ if EVEN_N & EVEN_M:
207
+ if EVEN_HEADDIM:
208
+ k = tl.load(k_ptrs)
209
+ v = tl.load(v_ptrs)
210
+ else:
211
+ k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
212
+ v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
213
+ elif EVEN_HEADDIM:
214
+ k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
215
+ v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
216
+ else:
217
+ k = tl.load(k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
218
+ v = tl.load(v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
219
+ num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
220
+ for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
221
+ start_m = tl.multiple_of(start_m, BLOCK_M)
222
+ offs_m_curr = start_m + offs_m
223
+ if EVEN_M & EVEN_HEADDIM:
224
+ q = tl.load(q_ptrs)
225
+ elif EVEN_HEADDIM:
226
+ q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
227
+ else:
228
+ q = tl.load(q_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
229
+ qk = tl.dot(q, k, trans_b=True)
230
+ if not EVEN_N:
231
+ qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf'))
232
+ if IS_CAUSAL:
233
+ qk = tl.where(offs_m_curr[:, None] >= offs_n[None, :], qk, float('-inf'))
234
+ if BIAS_TYPE != 'none':
235
+ tl.debug_barrier()
236
+ if BIAS_TYPE == 'vector':
237
+ if EVEN_N:
238
+ bias = tl.load(b_ptrs).to(tl.float32)
239
+ else:
240
+ bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32)
241
+ bias = bias[None, :]
242
+ elif BIAS_TYPE == 'matrix':
243
+ if EVEN_M & EVEN_N:
244
+ bias = tl.load(b_ptrs).to(tl.float32)
245
+ else:
246
+ bias = tl.load(b_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k), other=0.0).to(tl.float32)
247
+ qk = qk * softmax_scale + bias
248
+ if not EVEN_M & EVEN_HEADDIM:
249
+ tl.debug_barrier()
250
+ lse_i = tl.load(LSE + offs_m_curr)
251
+ if BIAS_TYPE == 'none':
252
+ p = tl.exp(qk * softmax_scale - lse_i[:, None])
253
+ else:
254
+ p = tl.exp(qk - lse_i[:, None])
255
+ if EVEN_M & EVEN_HEADDIM:
256
+ do = tl.load(do_ptrs)
257
+ else:
258
+ do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
259
+ dv += tl.dot(p.to(do.dtype), do, trans_a=True)
260
+ if not EVEN_M & EVEN_HEADDIM:
261
+ tl.debug_barrier()
262
+ dp = tl.dot(do, v, trans_b=True)
263
+ if not EVEN_HEADDIM:
264
+ tl.debug_barrier()
265
+ Di = tl.load(D + offs_m_curr)
266
+ ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
267
+ dk += tl.dot(ds, q, trans_a=True)
268
+ if not EVEN_M & EVEN_HEADDIM:
269
+ tl.debug_barrier()
270
+ if not ATOMIC_ADD:
271
+ if EVEN_M & EVEN_HEADDIM:
272
+ dq = tl.load(dq_ptrs, eviction_policy='evict_last')
273
+ dq += tl.dot(ds, k)
274
+ tl.store(dq_ptrs, dq, eviction_policy='evict_last')
275
+ elif EVEN_HEADDIM:
276
+ dq = tl.load(dq_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0, eviction_policy='evict_last')
277
+ dq += tl.dot(ds, k)
278
+ tl.store(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q, eviction_policy='evict_last')
279
+ else:
280
+ dq = tl.load(dq_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0, eviction_policy='evict_last')
281
+ dq += tl.dot(ds, k)
282
+ tl.store(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), eviction_policy='evict_last')
283
+ else:
284
+ dq = tl.dot(ds, k)
285
+ if EVEN_M & EVEN_HEADDIM:
286
+ tl.atomic_add(dq_ptrs, dq)
287
+ elif EVEN_HEADDIM:
288
+ tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q)
289
+ else:
290
+ tl.atomic_add(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
291
+ dq_ptrs += BLOCK_M * stride_dqm
292
+ q_ptrs += BLOCK_M * stride_qm
293
+ do_ptrs += BLOCK_M * stride_dom
294
+ if BIAS_TYPE == 'matrix':
295
+ b_ptrs += BLOCK_M * stride_bm
296
+ dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
297
+ dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
298
+ _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
299
+
300
+ def init_to_zero(name):
301
+ return lambda nargs: nargs[name].zero_()
302
+
303
+ @triton.autotune(configs=[triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ'))], key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM'])
304
+ @triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
305
+ @triton.jit
306
+ def _bwd_kernel(Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_dob, stride_doh, stride_dom, stride_dqb, stride_dqh, stride_dqm, stride_dkb, stride_dkh, stride_dkn, stride_dvb, stride_dvh, stride_dvn, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, SEQUENCE_PARALLEL: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
307
+ off_hb = tl.program_id(1)
308
+ off_b = off_hb // nheads
309
+ off_h = off_hb % nheads
310
+ Q += off_b * stride_qb + off_h * stride_qh
311
+ K += off_b * stride_kb + off_h * stride_kh
312
+ V += off_b * stride_vb + off_h * stride_vh
313
+ DO += off_b * stride_dob + off_h * stride_doh
314
+ DQ += off_b * stride_dqb + off_h * stride_dqh
315
+ DK += off_b * stride_dkb + off_h * stride_dkh
316
+ DV += off_b * stride_dvb + off_h * stride_dvh
317
+ if BIAS_TYPE != 'none':
318
+ Bias += off_b * stride_bb + off_h * stride_bh
319
+ D += off_hb * seqlen_q_rounded
320
+ LSE += off_hb * seqlen_q_rounded
321
+ if not SEQUENCE_PARALLEL:
322
+ num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
323
+ for start_n in range(0, num_block_n):
324
+ _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=False, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
325
+ else:
326
+ start_n = tl.program_id(0)
327
+ _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=True, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
328
+
329
+ def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
330
+ (batch, seqlen_q, nheads, d) = q.shape
331
+ (_, seqlen_k, _, _) = k.shape
332
+ assert k.shape == (batch, seqlen_k, nheads, d)
333
+ assert v.shape == (batch, seqlen_k, nheads, d)
334
+ assert d <= 128, 'FlashAttention only support head dimensions up to 128'
335
+ assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
336
+ assert q.dtype in [torch.float16, torch.bfloat16], 'Only support fp16 and bf16'
337
+ assert q.is_cuda and k.is_cuda and v.is_cuda
338
+ softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
339
+ has_bias = bias is not None
340
+ bias_type = 'none'
341
+ if has_bias:
342
+ assert bias.dtype in [q.dtype, torch.float]
343
+ assert bias.is_cuda
344
+ assert bias.dim() == 4
345
+ if bias.stride(-1) != 1:
346
+ bias = bias.contiguous()
347
+ if bias.shape[2:] == (1, seqlen_k):
348
+ bias_type = 'vector'
349
+ elif bias.shape[2:] == (seqlen_q, seqlen_k):
350
+ bias_type = 'matrix'
351
+ else:
352
+ raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
353
+ bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
354
+ bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
355
+ seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
356
+ lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
357
+ tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
358
+ o = torch.empty_like(q)
359
+ BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
360
+ BLOCK = 128
361
+ num_warps = 4 if d <= 64 else 8
362
+ grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
363
+ _fwd_kernel[grid](q, k, v, bias, o, lse, tmp, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, o.stride(0), o.stride(2), o.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM, BLOCK_M=BLOCK, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1)
364
+ return (o, lse, softmax_scale)
365
+
366
+ def _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None):
367
+ if do.stride(-1) != 1:
368
+ do = do.contiguous()
369
+ (batch, seqlen_q, nheads, d) = q.shape
370
+ (_, seqlen_k, _, _) = k.shape
371
+ assert d <= 128
372
+ seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
373
+ assert lse.shape == (batch, nheads, seqlen_q_rounded)
374
+ assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
375
+ assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
376
+ softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
377
+ dq_accum = torch.empty_like(q, dtype=torch.float32)
378
+ delta = torch.empty_like(lse)
379
+ BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
380
+ grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
381
+ _bwd_preprocess_do_o_dot[grid](o, do, delta, o.stride(0), o.stride(2), o.stride(1), do.stride(0), do.stride(2), do.stride(1), nheads, seqlen_q, seqlen_q_rounded, d, BLOCK_M=128, BLOCK_HEADDIM=BLOCK_HEADDIM)
382
+ has_bias = bias is not None
383
+ bias_type = 'none'
384
+ if has_bias:
385
+ assert bias.dtype in [q.dtype, torch.float]
386
+ assert bias.is_cuda
387
+ assert bias.dim() == 4
388
+ assert bias.stride(-1) == 1
389
+ if bias.shape[2:] == (1, seqlen_k):
390
+ bias_type = 'vector'
391
+ elif bias.shape[2:] == (seqlen_q, seqlen_k):
392
+ bias_type = 'matrix'
393
+ else:
394
+ raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
395
+ bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
396
+ bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
397
+ grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N']) if META['SEQUENCE_PARALLEL'] else 1, batch * nheads)
398
+ _bwd_kernel[grid](q, k, v, bias, do, dq_accum, dk, dv, lse, delta, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, do.stride(0), do.stride(2), do.stride(1), dq_accum.stride(0), dq_accum.stride(2), dq_accum.stride(1), dk.stride(0), dk.stride(2), dk.stride(1), dv.stride(0), dv.stride(2), dv.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM)
399
+ dq.copy_(dq_accum)
400
+
401
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
402
+
403
+ @staticmethod
404
+ def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
405
+ """
406
+ qkv: (batch, seqlen, 3, nheads, headdim)
407
+ bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
408
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
409
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
410
+ """
411
+ if qkv.stride(-1) != 1:
412
+ qkv = qkv.contiguous()
413
+ (o, lse, ctx.softmax_scale) = _flash_attn_forward(qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], bias=bias, causal=causal, softmax_scale=softmax_scale)
414
+ ctx.save_for_backward(qkv, o, lse, bias)
415
+ ctx.causal = causal
416
+ return o
417
+
418
+ @staticmethod
419
+ def backward(ctx, do):
420
+ (qkv, o, lse, bias) = ctx.saved_tensors
421
+ assert not ctx.needs_input_grad[1], 'FlashAttention does not support bias gradient yet'
422
+ with torch.inference_mode():
423
+ dqkv = torch.empty_like(qkv)
424
+ _flash_attn_backward(do, qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], o, lse, dqkv[:, :, 0], dqkv[:, :, 1], dqkv[:, :, 2], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
425
+ return (dqkv, None, None, None)
426
+ flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply
427
+
428
+ class FlashAttnKVPackedFunc(torch.autograd.Function):
429
+
430
+ @staticmethod
431
+ def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
432
+ """
433
+ q: (batch, seqlen_q, nheads, headdim)
434
+ kv: (batch, seqlen_k, 2, nheads, headdim)
435
+ bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
436
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
437
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
438
+ """
439
+ (q, kv) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]]
440
+ (o, lse, ctx.softmax_scale) = _flash_attn_forward(q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale)
441
+ ctx.save_for_backward(q, kv, o, lse, bias)
442
+ ctx.causal = causal
443
+ return o
444
+
445
+ @staticmethod
446
+ def backward(ctx, do):
447
+ (q, kv, o, lse, bias) = ctx.saved_tensors
448
+ if len(ctx.needs_input_grad) >= 3:
449
+ assert not ctx.needs_input_grad[2], 'FlashAttention does not support bias gradient yet'
450
+ with torch.inference_mode():
451
+ dq = torch.empty_like(q)
452
+ dkv = torch.empty_like(kv)
453
+ _flash_attn_backward(do, q, kv[:, :, 0], kv[:, :, 1], o, lse, dq, dkv[:, :, 0], dkv[:, :, 1], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
454
+ return (dq, dkv, None, None, None)
455
+ flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply
456
+
457
+ class FlashAttnFunc(torch.autograd.Function):
458
+
459
+ @staticmethod
460
+ def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
461
+ """
462
+ q: (batch_size, seqlen_q, nheads, headdim)
463
+ k, v: (batch_size, seqlen_k, nheads, headdim)
464
+ bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
465
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
466
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
467
+ """
468
+ (q, k, v) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]]
469
+ (o, lse, ctx.softmax_scale) = _flash_attn_forward(q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale)
470
+ ctx.save_for_backward(q, k, v, o, lse, bias)
471
+ ctx.causal = causal
472
+ return o
473
+
474
+ @staticmethod
475
+ def backward(ctx, do):
476
+ (q, k, v, o, lse, bias) = ctx.saved_tensors
477
+ assert not ctx.needs_input_grad[3], 'FlashAttention does not support bias gradient yet'
478
+ with torch.inference_mode():
479
+ dq = torch.empty_like(q)
480
+ dk = torch.empty_like(k)
481
+ dv = torch.empty_like(v)
482
+ _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
483
+ return (dq, dk, dv, None, None, None)
484
+ flash_attn_func = FlashAttnFunc.apply
videollava/model/language_model/mpt/hf_prefixlm_converter.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Converts Huggingface Causal LM to Prefix LM.
2
+
3
+ Conversion does lightweight surgery on a HuggingFace
4
+ Causal LM to convert it to a Prefix LM.
5
+
6
+ Prefix LMs accepts a `bidirectional_mask` input in `forward`
7
+ and treat the input prompt as the prefix in `generate`.
8
+ """
9
+ import math
10
+ import warnings
11
+ from types import MethodType
12
+ from typing import Any, Dict, List, Optional, Tuple, Union
13
+ import torch
14
+ from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss
15
+ from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom
16
+ from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom
17
+ from transformers.models.bloom.modeling_bloom import logging
18
+ from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
19
+ from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
20
+ from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
21
+ from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
22
+ from transformers.models.opt.modeling_opt import OPTForCausalLM
23
+ from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt
24
+ from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt
25
+ logger = logging.get_logger(__name__)
26
+ _SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
27
+ CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
28
+
29
+ def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_TYPES:
30
+ """Converts a GPT-style Causal LM to a Prefix LM.
31
+
32
+ Supported HuggingFace model classes:
33
+ - `GPT2LMHeadModel`
34
+ - `GPTNeoForCausalLM`
35
+ - `GPTNeoXForCausalLM`
36
+ - `GPTJForCausalLM`
37
+
38
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
39
+ """
40
+ if hasattr(model, '_prefix_lm_converted'):
41
+ return model
42
+ assert isinstance(model, _SUPPORTED_GPT_MODELS)
43
+ assert model.config.add_cross_attention == False, 'Only supports GPT-style decoder-only models'
44
+
45
+ def _get_attn_modules(model: CAUSAL_GPT_TYPES) -> List[torch.nn.Module]:
46
+ """Helper that gets a list of the model's attention modules.
47
+
48
+ Each module has a `bias` buffer used for causal masking. The Prefix LM
49
+ conversion adds logic to dynamically manipulate these biases to support
50
+ Prefix LM attention masking.
51
+ """
52
+ attn_modules = []
53
+ if isinstance(model, GPTNeoXForCausalLM):
54
+ blocks = model.gpt_neox.layers
55
+ else:
56
+ blocks = model.transformer.h
57
+ for block in blocks:
58
+ if isinstance(model, GPTNeoForCausalLM):
59
+ if block.attn.attention_type != 'global':
60
+ continue
61
+ attn_module = block.attn.attention
62
+ elif isinstance(model, GPTNeoXForCausalLM):
63
+ attn_module = block.attention
64
+ else:
65
+ attn_module = block.attn
66
+ attn_modules.append(attn_module)
67
+ return attn_modules
68
+ setattr(model, '_original_forward', getattr(model, 'forward'))
69
+ setattr(model, '_original_generate', getattr(model, 'generate'))
70
+
71
+ def forward(self: CAUSAL_GPT_TYPES, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, attention_mask: Optional[torch.FloatTensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.LongTensor]=None, position_ids: Optional[torch.LongTensor]=None, head_mask: Optional[torch.FloatTensor]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
72
+ """Wraps original forward to enable PrefixLM attention."""
73
+
74
+ def call_og_forward():
75
+ if isinstance(self, GPTNeoXForCausalLM):
76
+ return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
77
+ else:
78
+ return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
79
+ if bidirectional_mask is None:
80
+ return call_og_forward()
81
+ assert isinstance(bidirectional_mask, torch.Tensor)
82
+ attn_modules = _get_attn_modules(model)
83
+ (b, s) = bidirectional_mask.shape
84
+ max_length = attn_modules[0].bias.shape[-1]
85
+ if s > max_length:
86
+ raise ValueError(f'bidirectional_mask sequence length (={s}) exceeds the ' + f'max length allowed by the model ({max_length}).')
87
+ assert s <= max_length
88
+ if s < max_length:
89
+ pad = torch.zeros((int(b), int(max_length - s)), dtype=bidirectional_mask.dtype, device=bidirectional_mask.device)
90
+ bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)
91
+ bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)
92
+ for attn_module in attn_modules:
93
+ attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)
94
+ output = call_og_forward()
95
+ for attn_module in attn_modules:
96
+ attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
97
+ return output
98
+
99
+ def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):
100
+ """Wraps original generate to enable PrefixLM attention."""
101
+ attn_modules = _get_attn_modules(model)
102
+ for attn_module in attn_modules:
103
+ attn_module.bias.data[:] = 1
104
+ output = self._original_generate(*args, **kwargs)
105
+ for attn_module in attn_modules:
106
+ attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
107
+ return output
108
+ setattr(model, 'forward', MethodType(forward, model))
109
+ setattr(model, 'generate', MethodType(generate, model))
110
+ setattr(model, '_prefix_lm_converted', True)
111
+ return model
112
+
113
+ def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:
114
+ """Converts a BLOOM Causal LM to a Prefix LM.
115
+
116
+ Supported HuggingFace model classes:
117
+ - `BloomForCausalLM`
118
+
119
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
120
+ """
121
+ if hasattr(model, '_prefix_lm_converted'):
122
+ return model
123
+ assert isinstance(model, BloomForCausalLM)
124
+ assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models'
125
+
126
+ def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor:
127
+ combined_attention_mask = None
128
+ device = attention_mask.device
129
+ (_, src_length) = input_shape
130
+ if src_length > 1:
131
+ combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length)
132
+ if bidirectional_mask is not None:
133
+ assert attention_mask.shape == bidirectional_mask.shape
134
+ expanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length)
135
+ combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask)
136
+ expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)
137
+ combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
138
+ return combined_attention_mask
139
+
140
+ def _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
141
+ num_heads = self.config.n_head
142
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
143
+ base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32)
144
+ powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)
145
+ slopes = torch.pow(base, powers)
146
+ if closest_power_of_2 != num_heads:
147
+ extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32)
148
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
149
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)
150
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
151
+ qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)
152
+ ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)
153
+ diffs = qa - ka + key_length - query_length
154
+ diffs = -diffs.abs()
155
+ alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length)
156
+ alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length)
157
+ return alibi.to(dtype)
158
+ KeyValueT = Tuple[torch.Tensor, torch.Tensor]
159
+
160
+ def forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
161
+ if deprecated_arguments.pop('position_ids', False) is not False:
162
+ warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning)
163
+ if len(deprecated_arguments) > 0:
164
+ raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
165
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
166
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
167
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
168
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
169
+ if input_ids is not None and inputs_embeds is not None:
170
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
171
+ elif input_ids is not None:
172
+ (batch_size, seq_length) = input_ids.shape
173
+ elif inputs_embeds is not None:
174
+ (batch_size, seq_length, _) = inputs_embeds.shape
175
+ else:
176
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
177
+ if past_key_values is None:
178
+ past_key_values = tuple([None] * len(self.h))
179
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
180
+ if inputs_embeds is None:
181
+ inputs_embeds = self.word_embeddings(input_ids)
182
+ hidden_states = self.word_embeddings_layernorm(inputs_embeds)
183
+ presents = () if use_cache else None
184
+ all_self_attentions = () if output_attentions else None
185
+ all_hidden_states = () if output_hidden_states else None
186
+ seq_length_with_past = seq_length
187
+ past_key_values_length = 0
188
+ if past_key_values[0] is not None:
189
+ tmp = past_key_values[0][0]
190
+ past_key_values_length = tmp.shape[2]
191
+ seq_length_with_past = seq_length_with_past + past_key_values_length
192
+ if attention_mask is None:
193
+ attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
194
+ else:
195
+ attention_mask = attention_mask.to(hidden_states.device)
196
+ alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device)
197
+ causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length)
198
+ for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)):
199
+ if output_hidden_states:
200
+ hst = (hidden_states,)
201
+ all_hidden_states = all_hidden_states + hst
202
+ if self.gradient_checkpointing and self.training:
203
+ if use_cache:
204
+ logger.warning('`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')
205
+ use_cache = False
206
+
207
+ def create_custom_forward(module):
208
+
209
+ def custom_forward(*inputs):
210
+ return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
211
+ return custom_forward
212
+ outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i])
213
+ else:
214
+ outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi)
215
+ hidden_states = outputs[0]
216
+ if use_cache is True:
217
+ presents = presents + (outputs[1],)
218
+ if output_attentions:
219
+ oa = (outputs[2 if use_cache else 1],)
220
+ all_self_attentions = all_self_attentions + oa
221
+ hidden_states = self.ln_f(hidden_states)
222
+ if output_hidden_states:
223
+ hst = (hidden_states,)
224
+ all_hidden_states = all_hidden_states + hst
225
+ if not return_dict:
226
+ return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None))
227
+ return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions)
228
+ setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer))
229
+ setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer))
230
+ setattr(model.transformer, 'forward', MethodType(forward, model.transformer))
231
+ KeyValueT = Tuple[torch.Tensor, torch.Tensor]
232
+
233
+ def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
234
+ """Replacement forward method for BloomCausalLM."""
235
+ if deprecated_arguments.pop('position_ids', False) is not False:
236
+ warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning)
237
+ if len(deprecated_arguments) > 0:
238
+ raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
239
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
240
+ transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
241
+ hidden_states = transformer_outputs[0]
242
+ lm_logits = self.lm_head(hidden_states)
243
+ loss = None
244
+ if labels is not None:
245
+ shift_logits = lm_logits[..., :-1, :].contiguous()
246
+ shift_labels = labels[..., 1:].contiguous()
247
+ (batch_size, seq_length, vocab_size) = shift_logits.shape
248
+ loss_fct = CrossEntropyLoss()
249
+ loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length))
250
+ if not return_dict:
251
+ output = (lm_logits,) + transformer_outputs[1:]
252
+ return (loss,) + output if loss is not None else output
253
+ return CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)
254
+
255
+ def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs) -> dict:
256
+ if past:
257
+ input_ids = input_ids[:, -1].unsqueeze(-1)
258
+ bidirectional_mask = None
259
+ if past[0][0].shape[0] == input_ids.shape[0]:
260
+ past = self._convert_to_bloom_cache(past)
261
+ else:
262
+ bidirectional_mask = torch.ones_like(input_ids)
263
+ return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask}
264
+ setattr(model, 'forward', MethodType(forward, model))
265
+ setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model))
266
+ setattr(model, '_prefix_lm_converted', True)
267
+ return model
268
+
269
+ def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:
270
+ """Converts an OPT Causal LM to a Prefix LM.
271
+
272
+ Supported HuggingFace model classes:
273
+ - `OPTForCausalLM`
274
+
275
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
276
+ """
277
+ if hasattr(model, '_prefix_lm_converted'):
278
+ return model
279
+ assert isinstance(model, OPTForCausalLM)
280
+ assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models'
281
+ setattr(model, '_original_forward', getattr(model, 'forward'))
282
+ setattr(model, '_original_generate', getattr(model, 'generate'))
283
+ model.model.decoder.bidirectional_mask = None
284
+
285
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
286
+ combined_attention_mask = None
287
+ if input_shape[-1] > 1:
288
+ if self.bidirectional_mask == 'g':
289
+ (bsz, src_length) = input_shape
290
+ combined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
291
+ else:
292
+ combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device)
293
+ if self.bidirectional_mask is not None:
294
+ assert attention_mask.shape == self.bidirectional_mask.shape
295
+ expanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
296
+ combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask)
297
+ if attention_mask is not None:
298
+ expanded_attn_mask = _expand_mask_opt(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
299
+ combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
300
+ return combined_attention_mask
301
+ setattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder))
302
+
303
+ def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
304
+
305
+ def call_og_forward():
306
+ return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
307
+ if bidirectional_mask is None:
308
+ return call_og_forward()
309
+ self.model.decoder.bidirectional_mask = bidirectional_mask
310
+ try:
311
+ outputs = call_og_forward()
312
+ except:
313
+ self.model.decoder.bidirectional_mask = None
314
+ raise
315
+ self.model.decoder.bidirectional_mask = None
316
+ return outputs
317
+
318
+ def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]):
319
+ """Wraps original generate to enable PrefixLM-style attention."""
320
+ self.model.decoder.bidirectional_mask = 'g'
321
+ try:
322
+ output = self._original_generate(*args, **kwargs)
323
+ except:
324
+ self.model.decoder.bidirectional_mask = None
325
+ raise
326
+ self.model.decoder.bidirectional_mask = None
327
+ return output
328
+ setattr(model, 'forward', MethodType(forward, model))
329
+ setattr(model, 'generate', MethodType(generate, model))
330
+ setattr(model, '_prefix_lm_converted', True)
331
+ return model
332
+ _SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)
333
+ CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM]
334
+
335
+ def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
336
+ """Converts a HuggingFace Causal LM to a Prefix LM.
337
+
338
+ Supported HuggingFace model classes:
339
+ - `GPT2LMHeadModel`
340
+ - `GPTNeoForCausalLM`
341
+ - `GPTNeoXForCausalLM`
342
+ - `GPTJForCausalLM`
343
+ - `BloomForCausalLM`
344
+ - `OPTForCausalLM`
345
+
346
+ Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
347
+ `generate` method and/or select underlying methods depending on the model class.
348
+
349
+ These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask".
350
+
351
+ Notes on training:
352
+ To actually train the converted model as a Prefix LM, training batches will need to indicate
353
+ the prefix/target structure by including `bidirectional_mask` as part of the batch inputs.
354
+
355
+ **This is not a standard input and requires custom layers either within or after your dataloader.**
356
+
357
+ In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels`
358
+ such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`.
359
+ That is, the prefix portion of the sequence should not generate any loss. Loss should only be
360
+ generated by the target portion of the sequence.
361
+
362
+ Notes on `GPTNeoForCausalLM`:
363
+ To simplify the implementation, "global" and "local" attention layers are handled differently.
364
+ For "global" layers, we handle conversion as described above. For "local" layers, which use a
365
+ causal attention mask within a restricted local window, we do not alter the masking.
366
+
367
+ Notes on `forward` method conversion:
368
+ After conversion, the `forward` method will handle a new input, `bidirectional_mask`,
369
+ which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions
370
+ belonging to the prefix (prefix tokens can attend to one another bidirectionally), and
371
+ 0 indicates token positions belonging to the target.
372
+
373
+ The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing
374
+ causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset
375
+ the causal masks before returning the result.
376
+
377
+ Notes on `generate` method conversion:
378
+ After conversion, the `generate` method will have the same signature but will internally
379
+ convert all causal masks to be purely bidirectional, call the original `generate` method, and
380
+ (where appropriate) reset the causal masks before returning the result.
381
+
382
+ This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token
383
+ "prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates
384
+ each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one
385
+ another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and
386
+ previously-generated tokens (also as expected in a Prefix LM).
387
+
388
+ To preserve the API, the original methods are renamed to `_original_forward` and
389
+ `_original_generate`, and replaced with new `forward` and `generate` methods that wrap
390
+ them, respectively. Although implementation details vary by model class.
391
+ """
392
+ if isinstance(model, _SUPPORTED_GPT_MODELS):
393
+ return _convert_gpt_causal_lm_to_prefix_lm(model)
394
+ elif isinstance(model, BloomForCausalLM):
395
+ return _convert_bloom_causal_lm_to_prefix_lm(model)
396
+ elif isinstance(model, OPTForCausalLM):
397
+ return _convert_opt_causal_lm_to_prefix_lm(model)
398
+ else:
399
+ raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')
400
+
401
+ def add_bidirectional_mask_if_missing(batch: Dict[str, Any]):
402
+ """Attempts to add bidirectional_mask to batch if missing.
403
+
404
+ Raises:
405
+ KeyError if bidirectional_mask is missing and can't be inferred
406
+ """
407
+ if 'bidirectional_mask' not in batch:
408
+ if batch.get('mode', None) == 'icl_task':
409
+ batch['bidirectional_mask'] = batch['attention_mask'].clone()
410
+ for (i, continuation_indices) in enumerate(batch['continuation_indices']):
411
+ batch['bidirectional_mask'][i, continuation_indices] = 0
412
+ elif 'labels' in batch and 'attention_mask' in batch:
413
+ batch['bidirectional_mask'] = torch.logical_and(torch.eq(batch['attention_mask'], 1), torch.eq(batch['labels'], -100)).type_as(batch['attention_mask'])
414
+ else:
415
+ raise KeyError('No bidirectional_mask in batch and not sure how to construct one.')
videollava/model/language_model/mpt/meta_init_context.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import contextmanager
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+ @contextmanager
6
+ def init_empty_weights(include_buffers: bool=False):
7
+ """Meta initialization context manager.
8
+
9
+ A context manager under which models are initialized with all parameters
10
+ on the meta device, therefore creating an empty model. Useful when just
11
+ initializing the model would blow the available RAM.
12
+
13
+ Args:
14
+ include_buffers (`bool`, *optional*, defaults to `False`): Whether or
15
+ not to also put all buffers on the meta device while initializing.
16
+
17
+ Example:
18
+ ```python
19
+ import torch.nn as nn
20
+
21
+ # Initialize a model with 100 billions parameters in no time and without using any RAM.
22
+ with init_empty_weights():
23
+ tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
24
+ ```
25
+
26
+ <Tip warning={true}>
27
+
28
+ Any model created under this context manager has no weights. As such you can't do something like
29
+ `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
30
+
31
+ </Tip>
32
+ """
33
+ with init_on_device(torch.device('meta'), include_buffers=include_buffers) as f:
34
+ yield f
35
+
36
+ @contextmanager
37
+ def init_on_device(device: torch.device, include_buffers: bool=False):
38
+ """Device initialization context manager.
39
+
40
+ A context manager under which models are initialized with all parameters
41
+ on the specified device.
42
+
43
+ Args:
44
+ device (`torch.device`): Device to initialize all parameters on.
45
+ include_buffers (`bool`, *optional*, defaults to `False`): Whether or
46
+ not to also put all buffers on the meta device while initializing.
47
+
48
+ Example:
49
+ ```python
50
+ import torch.nn as nn
51
+
52
+ with init_on_device(device=torch.device("cuda")):
53
+ tst = nn.Liner(100, 100) # on `cuda` device
54
+ ```
55
+ """
56
+ old_register_parameter = nn.Module.register_parameter
57
+ if include_buffers:
58
+ old_register_buffer = nn.Module.register_buffer
59
+
60
+ def register_empty_parameter(module, name, param):
61
+ old_register_parameter(module, name, param)
62
+ if param is not None:
63
+ param_cls = type(module._parameters[name])
64
+ kwargs = module._parameters[name].__dict__
65
+ module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
66
+
67
+ def register_empty_buffer(module, name, buffer):
68
+ old_register_buffer(module, name, buffer)
69
+ if buffer is not None:
70
+ module._buffers[name] = module._buffers[name].to(device)
71
+ if include_buffers:
72
+ tensor_constructors_to_patch = {torch_function_name: getattr(torch, torch_function_name) for torch_function_name in ['empty', 'zeros', 'ones', 'full']}
73
+ else:
74
+ tensor_constructors_to_patch = {}
75
+
76
+ def patch_tensor_constructor(fn):
77
+
78
+ def wrapper(*args, **kwargs):
79
+ kwargs['device'] = device
80
+ return fn(*args, **kwargs)
81
+ return wrapper
82
+ try:
83
+ nn.Module.register_parameter = register_empty_parameter
84
+ if include_buffers:
85
+ nn.Module.register_buffer = register_empty_buffer
86
+ for torch_function_name in tensor_constructors_to_patch.keys():
87
+ setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
88
+ yield
89
+ finally:
90
+ nn.Module.register_parameter = old_register_parameter
91
+ if include_buffers:
92
+ nn.Module.register_buffer = old_register_buffer
93
+ for (torch_function_name, old_torch_function) in tensor_constructors_to_patch.items():
94
+ setattr(torch, torch_function_name, old_torch_function)
videollava/model/language_model/mpt/modeling_mpt.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A simple, flexible implementation of a GPT model.
2
+
3
+ Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
4
+ """
5
+ import math
6
+ import warnings
7
+ from typing import List, Optional, Tuple, Union
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
12
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
13
+ from .attention import attn_bias_shape, build_attn_bias
14
+ from .blocks import MPTBlock
15
+ from .custom_embedding import SharedEmbedding
16
+ from .norm import NORM_CLASS_REGISTRY
17
+ from .configuration_mpt import MPTConfig
18
+ from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising
19
+ from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm
20
+ from .meta_init_context import init_empty_weights
21
+ from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_
22
+ try:
23
+ from .flash_attn_triton import flash_attn_func
24
+ except:
25
+ pass
26
+ Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
27
+
28
+ class MPTPreTrainedModel(PreTrainedModel):
29
+ config_class = MPTConfig
30
+ base_model_prefix = 'model'
31
+ _no_split_modules = ['MPTBlock']
32
+
33
+ class MPTModel(MPTPreTrainedModel):
34
+
35
+ def __init__(self, config: MPTConfig):
36
+ config._validate_config()
37
+ super().__init__(config)
38
+ self.attn_impl = config.attn_config['attn_impl']
39
+ self.prefix_lm = config.attn_config['prefix_lm']
40
+ self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
41
+ self.alibi = config.attn_config['alibi']
42
+ self.alibi_bias_max = config.attn_config['alibi_bias_max']
43
+ if config.init_device == 'mixed':
44
+ if dist.get_local_rank() == 0:
45
+ config.init_device = 'cpu'
46
+ else:
47
+ config.init_device = 'meta'
48
+ if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():
49
+ norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys())
50
+ raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).')
51
+ norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]
52
+ self.embedding_fraction = config.embedding_fraction
53
+ self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device)
54
+ if not self.alibi:
55
+ self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device)
56
+ self.emb_drop = nn.Dropout(config.emb_pdrop)
57
+ self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
58
+ self.norm_f = norm_class(config.d_model, device=config.init_device)
59
+ if config.init_device != 'meta':
60
+ print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.')
61
+ self.apply(self.param_init_fn)
62
+ self.is_causal = not self.prefix_lm
63
+ self._attn_bias_initialized = False
64
+ self.attn_bias = None
65
+ self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id)
66
+ if config.no_bias:
67
+ for module in self.modules():
68
+ if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
69
+ if config.verbose:
70
+ warnings.warn(f'Removing bias ({module.bias}) from {module}.')
71
+ module.register_parameter('bias', None)
72
+ if config.verbose and config.verbose > 2:
73
+ print(self)
74
+ if 'verbose' not in self.config.init_config:
75
+ self.config.init_config['verbose'] = self.config.verbose
76
+ if self.config.init_config['verbose'] > 1:
77
+ init_fn_name = self.config.init_config['name']
78
+ warnings.warn(f'Using {init_fn_name} initialization.')
79
+ self.gradient_checkpointing = False
80
+
81
+ def get_input_embeddings(self):
82
+ return self.wte
83
+
84
+ def set_input_embeddings(self, value):
85
+ self.wte = value
86
+
87
+ @torch.no_grad()
88
+ def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None):
89
+ if not self._attn_bias_initialized:
90
+ if self.attn_bias_shape:
91
+ self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
92
+ self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max)
93
+ self._attn_bias_initialized = True
94
+ if self.attn_impl == 'flash':
95
+ return (self.attn_bias, attention_mask)
96
+ if self.attn_bias is not None:
97
+ self.attn_bias = self.attn_bias.to(dtype=dtype, device=device)
98
+ attn_bias = self.attn_bias
99
+ if self.prefix_lm:
100
+ assert isinstance(attn_bias, torch.Tensor)
101
+ assert isinstance(prefix_mask, torch.Tensor)
102
+ attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
103
+ if self.attn_uses_sequence_id and sequence_id is not None:
104
+ assert isinstance(attn_bias, torch.Tensor)
105
+ attn_bias = self._apply_sequence_id(attn_bias, sequence_id)
106
+ if attention_mask is not None:
107
+ s_k = attention_mask.shape[-1]
108
+ if attn_bias is None:
109
+ attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype)
110
+ else:
111
+ _s_k = max(0, attn_bias.size(-1) - s_k)
112
+ attn_bias = attn_bias[:, :, :, _s_k:]
113
+ if prefix_mask is not None and attention_mask.shape != prefix_mask.shape:
114
+ raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')
115
+ min_val = torch.finfo(attn_bias.dtype).min
116
+ attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)
117
+ return (attn_bias, None)
118
+
119
+ def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor):
120
+ (s_k, s_q) = attn_bias.shape[-2:]
121
+ if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len:
122
+ raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.')
123
+ seq_len = prefix_mask.shape[-1]
124
+ if seq_len > self.config.max_seq_len:
125
+ raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
126
+ attn_bias = attn_bias[..., :seq_len, :seq_len]
127
+ causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len)
128
+ prefix = prefix_mask.view(-1, 1, 1, seq_len)
129
+ cannot_attend = ~torch.logical_or(causal, prefix.bool())
130
+ min_val = torch.finfo(attn_bias.dtype).min
131
+ attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
132
+ return attn_bias
133
+
134
+ def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor):
135
+ seq_len = sequence_id.shape[-1]
136
+ if seq_len > self.config.max_seq_len:
137
+ raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
138
+ attn_bias = attn_bias[..., :seq_len, :seq_len]
139
+ cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)
140
+ min_val = torch.finfo(attn_bias.dtype).min
141
+ attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
142
+ return attn_bias
143
+
144
+ def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None):
145
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
146
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
147
+ if attention_mask is not None:
148
+ attention_mask = attention_mask.bool()
149
+ if prefix_mask is not None:
150
+ prefix_mask = prefix_mask.bool()
151
+ if not return_dict:
152
+ raise NotImplementedError('return_dict False is not implemented yet for MPT')
153
+ if output_attentions:
154
+ if self.attn_impl != 'torch':
155
+ raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.')
156
+ if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training:
157
+ raise NotImplementedError('MPT does not support training with left padding.')
158
+ if self.prefix_lm and prefix_mask is None:
159
+ raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
160
+ if self.training:
161
+ if self.attn_uses_sequence_id and sequence_id is None:
162
+ raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.')
163
+ elif self.attn_uses_sequence_id is False and sequence_id is not None:
164
+ warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.')
165
+ if input_ids is not None:
166
+ S = input_ids.size(1)
167
+ assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}'
168
+ tok_emb = self.wte(input_ids)
169
+ else:
170
+ assert inputs_embeds is not None
171
+ assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.'
172
+ S = inputs_embeds.size(1)
173
+ tok_emb = inputs_embeds
174
+ if self.alibi:
175
+ x = tok_emb
176
+ else:
177
+ past_position = 0
178
+ if past_key_values is not None:
179
+ if len(past_key_values) != self.config.n_layers:
180
+ raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).')
181
+ past_position = past_key_values[0][0].size(1)
182
+ if self.attn_impl == 'torch':
183
+ past_position = past_key_values[0][0].size(3)
184
+ if S + past_position > self.config.max_seq_len:
185
+ raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.')
186
+ pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0)
187
+ if attention_mask is not None:
188
+ pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)
189
+ pos_emb = self.wpe(pos)
190
+ x = tok_emb + pos_emb
191
+ if self.embedding_fraction == 1:
192
+ x = self.emb_drop(x)
193
+ else:
194
+ x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction)
195
+ assert isinstance(self.emb_drop, nn.Module)
196
+ x = self.emb_drop(x_shrunk)
197
+ (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)
198
+ if use_cache and past_key_values is None:
199
+ past_key_values = [() for _ in range(self.config.n_layers)]
200
+ all_hidden_states = () if output_hidden_states else None
201
+ all_self_attns = () if output_attentions else None
202
+ for (b_idx, block) in enumerate(self.blocks):
203
+ if output_hidden_states:
204
+ assert all_hidden_states is not None
205
+ all_hidden_states = all_hidden_states + (x,)
206
+ past_key_value = past_key_values[b_idx] if past_key_values is not None else None
207
+ if self.gradient_checkpointing and self.training:
208
+ (x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal)
209
+ else:
210
+ (x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal)
211
+ if past_key_values is not None:
212
+ past_key_values[b_idx] = past_key_value
213
+ if output_attentions:
214
+ assert all_self_attns is not None
215
+ all_self_attns = all_self_attns + (attn_weights,)
216
+ x = self.norm_f(x)
217
+ if output_hidden_states:
218
+ assert all_hidden_states is not None
219
+ all_hidden_states = all_hidden_states + (x,)
220
+ return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns)
221
+
222
+ def param_init_fn(self, module):
223
+ init_fn_name = self.config.init_config['name']
224
+ MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
225
+
226
+ def fsdp_wrap_fn(self, module):
227
+ return isinstance(module, MPTBlock)
228
+
229
+ def activation_checkpointing_fn(self, module):
230
+ return isinstance(module, MPTBlock)
231
+
232
+ class MPTForCausalLM(MPTPreTrainedModel):
233
+
234
+ def __init__(self, config: MPTConfig):
235
+ super().__init__(config)
236
+ if not config.tie_word_embeddings:
237
+ raise ValueError('MPTForCausalLM only supports tied word embeddings')
238
+ print(f'Instantiating an MPTForCausalLM model from {__file__}')
239
+ self.transformer = MPTModel(config)
240
+ for child in self.transformer.children():
241
+ if isinstance(child, torch.nn.ModuleList):
242
+ continue
243
+ if isinstance(child, torch.nn.Module):
244
+ child._fsdp_wrap = True
245
+ self.logit_scale = None
246
+ if config.logit_scale is not None:
247
+ logit_scale = config.logit_scale
248
+ if isinstance(logit_scale, str):
249
+ if logit_scale == 'inv_sqrt_d_model':
250
+ logit_scale = 1 / math.sqrt(config.d_model)
251
+ else:
252
+ raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
253
+ self.logit_scale = logit_scale
254
+
255
+ def get_input_embeddings(self):
256
+ return self.transformer.wte
257
+
258
+ def set_input_embeddings(self, value):
259
+ self.transformer.wte = value
260
+
261
+ def get_output_embeddings(self):
262
+ return self.transformer.wte
263
+
264
+ def set_output_embeddings(self, new_embeddings):
265
+ self.transformer.wte = new_embeddings
266
+
267
+ def set_decoder(self, decoder):
268
+ self.transformer = decoder
269
+
270
+ def get_decoder(self):
271
+ return self.transformer
272
+
273
+ def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.FloatTensor]=None):
274
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
275
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
276
+ if inputs_embeds is not None:
277
+ raise NotImplementedError('inputs_embeds has to be None (for hf/peft support).')
278
+ outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache)
279
+ logits = self.transformer.wte(outputs.last_hidden_state.to(self.transformer.wte.weight.device), True)
280
+ if self.logit_scale is not None:
281
+ if self.logit_scale == 0:
282
+ warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
283
+ logits *= self.logit_scale
284
+ loss = None
285
+ if labels is not None:
286
+ labels = torch.roll(labels, shifts=-1)
287
+ labels[:, -1] = -100
288
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1))
289
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
290
+
291
+ def param_init_fn(self, module):
292
+ init_fn_name = self.config.init_config['name']
293
+ MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
294
+
295
+ def fsdp_wrap_fn(self, module):
296
+ return isinstance(module, MPTBlock)
297
+
298
+ def activation_checkpointing_fn(self, module):
299
+ return isinstance(module, MPTBlock)
300
+
301
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
302
+ if inputs_embeds is not None:
303
+ raise NotImplementedError('inputs_embeds is not implemented for MPT yet')
304
+ attention_mask = kwargs['attention_mask'].bool()
305
+ if attention_mask[:, -1].sum() != attention_mask.shape[0]:
306
+ raise NotImplementedError('MPT does not support generation with right padding.')
307
+ if self.transformer.attn_uses_sequence_id and self.training:
308
+ sequence_id = torch.zeros_like(input_ids[:1])
309
+ else:
310
+ sequence_id = None
311
+ if past_key_values is not None:
312
+ input_ids = input_ids[:, -1].unsqueeze(-1)
313
+ if self.transformer.prefix_lm:
314
+ prefix_mask = torch.ones_like(attention_mask)
315
+ if kwargs.get('use_cache') == False:
316
+ raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
317
+ else:
318
+ prefix_mask = None
319
+ return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)}
320
+
321
+ @staticmethod
322
+ def _reorder_cache(past_key_values, beam_idx):
323
+ """Used by HuggingFace generate when using beam search with kv-caching.
324
+
325
+ See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133
326
+ for an example in transformers.
327
+ """
328
+ reordered_past = []
329
+ for layer_past in past_key_values:
330
+ reordered_past += [tuple((past_state.index_select(0, beam_idx) for past_state in layer_past))]
331
+ return reordered_past
videollava/model/language_model/mpt/norm.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ def _cast_if_autocast_enabled(tensor):
4
+ if torch.is_autocast_enabled():
5
+ if tensor.device.type == 'cuda':
6
+ dtype = torch.get_autocast_gpu_dtype()
7
+ elif tensor.device.type == 'cpu':
8
+ dtype = torch.get_autocast_cpu_dtype()
9
+ else:
10
+ raise NotImplementedError()
11
+ return tensor.to(dtype=dtype)
12
+ return tensor
13
+
14
+ class LPLayerNorm(torch.nn.LayerNorm):
15
+
16
+ def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True, device=None, dtype=None):
17
+ super().__init__(normalized_shape=normalized_shape, eps=eps, elementwise_affine=elementwise_affine, device=device, dtype=dtype)
18
+
19
+ def forward(self, x):
20
+ module_device = x.device
21
+ downcast_x = _cast_if_autocast_enabled(x)
22
+ downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
23
+ downcast_bias = _cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
24
+ with torch.autocast(enabled=False, device_type=module_device.type):
25
+ return torch.nn.functional.layer_norm(downcast_x, self.normalized_shape, downcast_weight, downcast_bias, self.eps)
26
+
27
+ def rms_norm(x, weight=None, eps=1e-05):
28
+ output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
29
+ if weight is not None:
30
+ return output * weight
31
+ return output
32
+
33
+ class RMSNorm(torch.nn.Module):
34
+
35
+ def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
36
+ super().__init__()
37
+ self.eps = eps
38
+ if weight:
39
+ self.weight = torch.nn.Parameter(torch.ones(normalized_shape, dtype=dtype, device=device))
40
+ else:
41
+ self.register_parameter('weight', None)
42
+
43
+ def forward(self, x):
44
+ return rms_norm(x.float(), self.weight, self.eps).to(dtype=x.dtype)
45
+
46
+ class LPRMSNorm(RMSNorm):
47
+
48
+ def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
49
+ super().__init__(normalized_shape=normalized_shape, eps=eps, weight=weight, dtype=dtype, device=device)
50
+
51
+ def forward(self, x):
52
+ downcast_x = _cast_if_autocast_enabled(x)
53
+ downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
54
+ with torch.autocast(enabled=False, device_type=x.device.type):
55
+ return rms_norm(downcast_x, downcast_weight, self.eps).to(dtype=x.dtype)
56
+ NORM_CLASS_REGISTRY = {'layernorm': torch.nn.LayerNorm, 'low_precision_layernorm': LPLayerNorm, 'rmsnorm': RMSNorm, 'low_precision_rmsnorm': LPRMSNorm}
videollava/model/language_model/mpt/param_init_fns.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import warnings
3
+ from collections.abc import Sequence
4
+ from functools import partial
5
+ from typing import Optional, Tuple, Union
6
+ import torch
7
+ from torch import nn
8
+ from .norm import NORM_CLASS_REGISTRY
9
+
10
+ def torch_default_param_init_fn_(module: nn.Module, verbose: int=0, **kwargs):
11
+ del kwargs
12
+ if verbose > 1:
13
+ warnings.warn(f"Initializing network using module's reset_parameters attribute")
14
+ if hasattr(module, 'reset_parameters'):
15
+ module.reset_parameters()
16
+
17
+ def fused_init_helper_(module: nn.Module, init_fn_):
18
+ _fused = getattr(module, '_fused', None)
19
+ if _fused is None:
20
+ raise RuntimeError(f'Internal logic error')
21
+ (dim, splits) = _fused
22
+ splits = (0, *splits, module.weight.size(dim))
23
+ for (s, e) in zip(splits[:-1], splits[1:]):
24
+ slice_indices = [slice(None)] * module.weight.ndim
25
+ slice_indices[dim] = slice(s, e)
26
+ init_fn_(module.weight[slice_indices])
27
+
28
+ def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
29
+ del kwargs
30
+ if verbose > 1:
31
+ warnings.warn(f'If model has bias parameters they are initialized to 0.')
32
+ init_div_is_residual = init_div_is_residual
33
+ if init_div_is_residual is False:
34
+ div_is_residual = 1.0
35
+ elif init_div_is_residual is True:
36
+ div_is_residual = math.sqrt(2 * n_layers)
37
+ elif isinstance(init_div_is_residual, float) or isinstance(init_div_is_residual, int):
38
+ div_is_residual = init_div_is_residual
39
+ elif isinstance(init_div_is_residual, str) and init_div_is_residual.isnumeric():
40
+ div_is_residual = float(init_div_is_residual)
41
+ else:
42
+ div_is_residual = 1.0
43
+ raise ValueError(f'Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}')
44
+ if init_div_is_residual is not False:
45
+ if verbose > 1:
46
+ warnings.warn(f'Initializing _is_residual layers then dividing them by {div_is_residual:.3f}. ' + f'Set `init_div_is_residual: false` in init config to disable this.')
47
+ if isinstance(module, nn.Linear):
48
+ if hasattr(module, '_fused'):
49
+ fused_init_helper_(module, init_fn_)
50
+ else:
51
+ init_fn_(module.weight)
52
+ if module.bias is not None:
53
+ torch.nn.init.zeros_(module.bias)
54
+ if init_div_is_residual is not False and getattr(module, '_is_residual', False):
55
+ with torch.no_grad():
56
+ module.weight.div_(div_is_residual)
57
+ elif isinstance(module, nn.Embedding):
58
+ if emb_init_std is not None:
59
+ std = emb_init_std
60
+ if std == 0:
61
+ warnings.warn(f'Embedding layer initialized to 0.')
62
+ emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std)
63
+ if verbose > 1:
64
+ warnings.warn(f'Embedding layer initialized using normal distribution with mean=0 and std={std!r}.')
65
+ elif emb_init_uniform_lim is not None:
66
+ lim = emb_init_uniform_lim
67
+ if isinstance(lim, Sequence):
68
+ if len(lim) > 2:
69
+ raise ValueError(f'Uniform init requires a min and a max limit. User input: {lim}.')
70
+ if lim[0] == lim[1]:
71
+ warnings.warn(f'Embedding layer initialized to {lim[0]}.')
72
+ else:
73
+ if lim == 0:
74
+ warnings.warn(f'Embedding layer initialized to 0.')
75
+ lim = [-lim, lim]
76
+ (a, b) = lim
77
+ emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b)
78
+ if verbose > 1:
79
+ warnings.warn(f'Embedding layer initialized using uniform distribution in range {lim}.')
80
+ else:
81
+ emb_init_fn_ = init_fn_
82
+ emb_init_fn_(module.weight)
83
+ elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))):
84
+ if verbose > 1:
85
+ warnings.warn(f'Norm weights are set to 1. If norm layer has a bias it is initialized to 0.')
86
+ if hasattr(module, 'weight') and module.weight is not None:
87
+ torch.nn.init.ones_(module.weight)
88
+ if hasattr(module, 'bias') and module.bias is not None:
89
+ torch.nn.init.zeros_(module.bias)
90
+ elif isinstance(module, nn.MultiheadAttention):
91
+ if module._qkv_same_embed_dim:
92
+ assert module.in_proj_weight is not None
93
+ assert module.q_proj_weight is None and module.k_proj_weight is None and (module.v_proj_weight is None)
94
+ assert d_model is not None
95
+ _d = d_model
96
+ splits = (0, _d, 2 * _d, 3 * _d)
97
+ for (s, e) in zip(splits[:-1], splits[1:]):
98
+ init_fn_(module.in_proj_weight[s:e])
99
+ else:
100
+ assert module.q_proj_weight is not None and module.k_proj_weight is not None and (module.v_proj_weight is not None)
101
+ assert module.in_proj_weight is None
102
+ init_fn_(module.q_proj_weight)
103
+ init_fn_(module.k_proj_weight)
104
+ init_fn_(module.v_proj_weight)
105
+ if module.in_proj_bias is not None:
106
+ torch.nn.init.zeros_(module.in_proj_bias)
107
+ if module.bias_k is not None:
108
+ torch.nn.init.zeros_(module.bias_k)
109
+ if module.bias_v is not None:
110
+ torch.nn.init.zeros_(module.bias_v)
111
+ init_fn_(module.out_proj.weight)
112
+ if init_div_is_residual is not False and getattr(module.out_proj, '_is_residual', False):
113
+ with torch.no_grad():
114
+ module.out_proj.weight.div_(div_is_residual)
115
+ if module.out_proj.bias is not None:
116
+ torch.nn.init.zeros_(module.out_proj.bias)
117
+ else:
118
+ for _ in module.parameters(recurse=False):
119
+ raise NotImplementedError(f'{module.__class__.__name__} parameters are not initialized by param_init_fn.')
120
+
121
+ def _normal_init_(std, mean=0.0):
122
+ return partial(torch.nn.init.normal_, mean=mean, std=std)
123
+
124
+ def _normal_param_init_fn_(module: nn.Module, std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
125
+ del kwargs
126
+ init_fn_ = _normal_init_(std=std)
127
+ if verbose > 1:
128
+ warnings.warn(f'Using torch.nn.init.normal_ init fn mean=0.0, std={std}')
129
+ generic_param_init_fn_(module=module, init_fn_=init_fn_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
130
+
131
+ def baseline_param_init_fn_(module: nn.Module, init_std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
132
+ del kwargs
133
+ if init_std is None:
134
+ raise ValueError("You must set model.init_config['init_std'] to a float value to use the default initialization scheme.")
135
+ _normal_param_init_fn_(module=module, std=init_std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
136
+
137
+ def small_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
138
+ del kwargs
139
+ std = math.sqrt(2 / (5 * d_model))
140
+ _normal_param_init_fn_(module=module, std=std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
141
+
142
+ def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
143
+ """From section 2.3.1 of GPT-NeoX-20B:
144
+
145
+ An Open-Source AutoregressiveLanguage Model β€” Black et. al. (2022)
146
+ see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151
147
+ and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py
148
+ """
149
+ del kwargs
150
+ residual_div = n_layers / math.sqrt(10)
151
+ if verbose > 1:
152
+ warnings.warn(f'setting init_div_is_residual to {residual_div}')
153
+ small_param_init_fn_(module=module, d_model=d_model, n_layers=n_layers, init_div_is_residual=residual_div, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
154
+
155
+ def kaiming_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
156
+ del kwargs
157
+ if verbose > 1:
158
+ warnings.warn(f'Using nn.init.kaiming_uniform_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
159
+ kaiming_uniform_ = partial(nn.init.kaiming_uniform_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
160
+ generic_param_init_fn_(module=module, init_fn_=kaiming_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
161
+
162
+ def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
163
+ del kwargs
164
+ if verbose > 1:
165
+ warnings.warn(f'Using nn.init.kaiming_normal_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
166
+ kaiming_normal_ = partial(torch.nn.init.kaiming_normal_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
167
+ generic_param_init_fn_(module=module, init_fn_=kaiming_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
168
+
169
+ def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
170
+ del kwargs
171
+ xavier_uniform_ = partial(torch.nn.init.xavier_uniform_, gain=init_gain)
172
+ if verbose > 1:
173
+ warnings.warn(f'Using torch.nn.init.xavier_uniform_ init fn with parameters: ' + f'gain={init_gain}')
174
+ generic_param_init_fn_(module=module, init_fn_=xavier_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
175
+
176
+ def xavier_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
177
+ xavier_normal_ = partial(torch.nn.init.xavier_normal_, gain=init_gain)
178
+ if verbose > 1:
179
+ warnings.warn(f'Using torch.nn.init.xavier_normal_ init fn with parameters: ' + f'gain={init_gain}')
180
+ generic_param_init_fn_(module=module, init_fn_=xavier_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
181
+ MODEL_INIT_REGISTRY = {'default_': torch_default_param_init_fn_, 'baseline_': baseline_param_init_fn_, 'kaiming_uniform_': kaiming_uniform_param_init_fn_, 'kaiming_normal_': kaiming_normal_param_init_fn_, 'neox_init_': neox_param_init_fn_, 'small_init_': small_param_init_fn_, 'xavier_uniform_': xavier_uniform_param_init_fn_, 'xavier_normal_': xavier_normal_param_init_fn_}
videollava/model/llava_arch.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from abc import ABC, abstractmethod
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from .multimodal_encoder.builder import build_image_tower, build_video_tower
22
+ from .multimodal_projector.builder import build_vision_projector
23
+
24
+ from videollava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
25
+
26
+
27
+ class LlavaMetaModel:
28
+
29
+ def __init__(self, config):
30
+ super(LlavaMetaModel, self).__init__(config)
31
+
32
+ if getattr(config, "mm_image_tower", None) is not None:
33
+ self.image_tower = build_image_tower(config, delay_load=True)
34
+ if getattr(config, "mm_video_tower", None) is not None:
35
+ self.video_tower = build_video_tower(config, delay_load=True)
36
+ if getattr(config, "mm_image_tower", None) is not None or getattr(config, "mm_video_tower", None) is not None:
37
+ self.mm_projector = build_vision_projector(config)
38
+
39
+ def get_image_tower(self):
40
+ image_tower = getattr(self, 'image_tower', None)
41
+ if type(image_tower) is list:
42
+ image_tower = image_tower[0]
43
+ return image_tower
44
+
45
+ def get_video_tower(self):
46
+ video_tower = getattr(self, 'video_tower', None)
47
+ if type(video_tower) is list:
48
+ video_tower = video_tower[0]
49
+ return video_tower
50
+
51
+ def initialize_vision_modules(self, model_args, fsdp=None):
52
+ # ==============================================
53
+ image_tower = model_args.image_tower
54
+ video_tower = model_args.video_tower
55
+ assert image_tower is not None or video_tower is not None
56
+ # ==============================================
57
+ mm_vision_select_layer = model_args.mm_vision_select_layer
58
+ mm_vision_select_feature = model_args.mm_vision_select_feature
59
+ pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
60
+
61
+ # ==========================================================================
62
+
63
+ self.config.mm_image_tower = image_tower
64
+ if image_tower is not None:
65
+ if self.get_image_tower() is None:
66
+ image_tower = build_image_tower(model_args)
67
+
68
+ if fsdp is not None and len(fsdp) > 0:
69
+ self.image_tower = [image_tower]
70
+ else:
71
+ self.image_tower = image_tower
72
+ else:
73
+ if fsdp is not None and len(fsdp) > 0:
74
+ image_tower = self.image_tower[0]
75
+ else:
76
+ image_tower = self.image_tower
77
+ image_tower.load_model()
78
+
79
+ self.config.mm_video_tower = video_tower
80
+ if video_tower is not None:
81
+ if self.get_video_tower() is None:
82
+ video_tower = build_video_tower(model_args)
83
+
84
+ if fsdp is not None and len(fsdp) > 0:
85
+ self.video_tower = [video_tower]
86
+ else:
87
+ self.video_tower = video_tower
88
+ else:
89
+ if fsdp is not None and len(fsdp) > 0:
90
+ video_tower = self.video_tower[0]
91
+ else:
92
+ video_tower = self.video_tower
93
+ video_tower.load_model()
94
+
95
+ # ==========================================================================
96
+
97
+ self.config.use_mm_proj = True
98
+ self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
99
+ self.config.mm_vision_select_layer = mm_vision_select_layer
100
+ self.config.mm_vision_select_feature = mm_vision_select_feature
101
+ # ==========================================================================
102
+ if image_tower is not None and video_tower is not None: # TODO: support different hidden_size
103
+ assert image_tower.hidden_size == video_tower.hidden_size
104
+ self.config.mm_hidden_size = image_tower.hidden_size
105
+ else:
106
+ self.config.mm_hidden_size = max(getattr(image_tower, 'hidden_size', -1),
107
+ getattr(video_tower, 'hidden_size', -1))
108
+ # ===================================================================================
109
+
110
+ if getattr(self, 'mm_projector', None) is None:
111
+ self.mm_projector = build_vision_projector(self.config)
112
+ else:
113
+ # In case it is frozen by LoRA
114
+ for p in self.mm_projector.parameters():
115
+ p.requires_grad = True
116
+
117
+ if pretrain_mm_mlp_adapter is not None:
118
+ mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
119
+ def get_w(weights, keyword):
120
+ return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
121
+
122
+ self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
123
+
124
+
125
+ class LlavaMetaForCausalLM(ABC):
126
+
127
+ @abstractmethod
128
+ def get_model(self):
129
+ pass
130
+
131
+ def get_image_tower(self):
132
+ return self.get_model().get_image_tower()
133
+
134
+ def get_video_tower(self):
135
+ return self.get_model().get_video_tower()
136
+
137
+ def encode_images(self, images):
138
+ image_features = self.get_model().get_image_tower()(images)
139
+ image_features = self.get_model().mm_projector(image_features)
140
+ return image_features
141
+
142
+ def encode_videos(self, videos): # [mini_b, c, t, h, w]
143
+ b, _, t, _, _ = videos.shape
144
+ video_features = self.get_model().get_video_tower()(videos) # [mini_b, t, n, c]
145
+ video_features = self.get_model().mm_projector(video_features)
146
+ return video_features
147
+
148
+ def prepare_inputs_labels_for_multimodal(
149
+ self, input_ids, position_ids, attention_mask, past_key_values, labels, images
150
+ ):
151
+ # ====================================================================================================
152
+ image_tower = self.get_image_tower()
153
+ video_tower = self.get_video_tower()
154
+ if (image_tower is None and video_tower is None) or images is None or input_ids.shape[1] == 1:
155
+ if past_key_values is not None and (image_tower is not None or video_tower is not None) and images is not None and input_ids.shape[1] == 1:
156
+ target_shape = past_key_values[-1][-1].shape[-2] + 1
157
+ attention_mask = torch.cat((attention_mask, torch.ones(
158
+ (attention_mask.shape[0], target_shape - attention_mask.shape[1]),
159
+ dtype=attention_mask.dtype,
160
+ device=attention_mask.device
161
+ )), dim=1)
162
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
163
+ return input_ids, position_ids, attention_mask, past_key_values, None, labels
164
+
165
+ '''
166
+ images is a list, if batch_size=6
167
+ [
168
+ image(3, 224, 224), # sample 1
169
+ image(3, 224, 224), # sample 2
170
+ video(t, 3, 224, 224), # sample 3
171
+ image(3, 224, 224), # sample 4
172
+ image(3, 224, 224), # sample 4
173
+ video(t, 3, 224, 224), # sample 5
174
+ video(t, 3, 224, 224), # sample 5
175
+ video(t, 3, 224, 224), # sample 6
176
+ image(3, 224, 224), # sample 6
177
+ ]
178
+ will be converted to image_features, all video_feature will be flatten as image
179
+ [
180
+ [n, c], # sample 1
181
+ [n, c), # sample 2
182
+ *(t * [new_n, c]), # sample 3
183
+ [n, c], # sample 4
184
+ [n, c], # sample 4
185
+ *(t * [new_n, c]), # sample 5
186
+ *(t * [new_n, c]), # sample 5
187
+ *(t * [new_n, c]), # sample 6
188
+ [n, c], # sample 6
189
+ ]
190
+ '''
191
+ image_idx = [idx for idx, img in enumerate(images) if img.ndim == 3]
192
+ is_all_image = len(image_idx) == len(images)
193
+ video_idx = [idx for idx, vid in enumerate(images) if vid.ndim == 4]
194
+ images_minibatch = torch.stack([images[idx] for idx in image_idx]) if len(image_idx) > 0 else [] # mini_b c h w
195
+ videos_minibatch = torch.stack([images[idx] for idx in video_idx]) if len(video_idx) > 0 else [] # mini_b c t h w
196
+
197
+ tmp_image_features = [None] * (len(image_idx) + len(video_idx))
198
+ if getattr(images_minibatch, 'ndim', 0) == 4: # batch consists of images, [mini_b, c, h, w]
199
+ if image_tower is not None:
200
+ image_features_minibatch = self.encode_images(images_minibatch) # [mini_b, l, c]
201
+ else:
202
+ image_features_minibatch = torch.randn(1).to(self.device) # dummy feature for video-only training under tuning
203
+ for i, pos in enumerate(image_idx):
204
+ tmp_image_features[pos] = image_features_minibatch[i]
205
+
206
+ if getattr(videos_minibatch, 'ndim', 0) == 5: # batch consists of videos, [mini_b, c, t, h, w]
207
+ video_features_minibatch = self.encode_videos(videos_minibatch) # fake list [mini_b, t, l, c]
208
+ for i, pos in enumerate(video_idx):
209
+ t = video_features_minibatch[i].shape[0]
210
+ tmp_image_features[pos] = [video_features_minibatch[i][j] for j in range(t)]
211
+
212
+ new_tmp = []
213
+ for image in tmp_image_features:
214
+ # print(len(new_tmp), len(image))
215
+ if isinstance(image, list):
216
+ t = len(image)
217
+ for i in range(t):
218
+ new_tmp.append(image[i])
219
+ # print('add video')
220
+ else:
221
+ new_tmp.append(image)
222
+ image_features = new_tmp
223
+ # print(len(image_features), *[i.shape for i in image_features])
224
+ # print(len(image_features), image_features[0].shape)
225
+ # ====================================================================================================
226
+
227
+ # TODO: image start / end is not implemented here to support pretraining.
228
+ if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
229
+ raise NotImplementedError
230
+
231
+ # Let's just add dummy tensors if they do not exist,
232
+ # it is a headache to deal with None all the time.
233
+ # But it is not ideal, and if you have a better idea,
234
+ # please open an issue / submit a PR, thanks.
235
+ _labels = labels
236
+ _position_ids = position_ids
237
+ _attention_mask = attention_mask
238
+ if attention_mask is None:
239
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
240
+ else:
241
+ attention_mask = attention_mask.bool()
242
+ if position_ids is None:
243
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
244
+ if labels is None:
245
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
246
+
247
+ # remove the padding using attention_mask -- TODO: double check
248
+ input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
249
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
250
+
251
+ new_input_embeds = []
252
+ new_labels = []
253
+ cur_image_idx = 0
254
+ for batch_idx, cur_input_ids in enumerate(input_ids):
255
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
256
+ # print(num_images, cur_input_ids)
257
+ if num_images == 0:
258
+ cur_image_features = image_features[cur_image_idx]
259
+ cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids)
260
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
261
+ new_input_embeds.append(cur_input_embeds)
262
+ new_labels.append(labels[batch_idx])
263
+ cur_image_idx += 1
264
+ continue
265
+
266
+ image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
267
+ cur_input_ids_noim = []
268
+ cur_labels = labels[batch_idx]
269
+ cur_labels_noim = []
270
+ for i in range(len(image_token_indices) - 1):
271
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]])
272
+ cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]])
273
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
274
+ cur_input_embeds = self.get_model().embed_tokens(torch.cat(cur_input_ids_noim))
275
+ cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
276
+ cur_new_input_embeds = []
277
+ cur_new_labels = []
278
+
279
+ for i in range(num_images + 1):
280
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
281
+ cur_new_labels.append(cur_labels_noim[i])
282
+ if i < num_images:
283
+ # print(cur_image_idx)
284
+ cur_image_features = image_features[cur_image_idx]
285
+ cur_image_idx += 1
286
+ cur_new_input_embeds.append(cur_image_features)
287
+ cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
288
+
289
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
290
+ cur_new_labels = torch.cat(cur_new_labels)
291
+
292
+ new_input_embeds.append(cur_new_input_embeds)
293
+ new_labels.append(cur_new_labels)
294
+
295
+ # Truncate sequences to max length as image embeddings can make the sequence longer
296
+ tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
297
+ if tokenizer_model_max_length is not None:
298
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
299
+ new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
300
+
301
+ # Combine them
302
+ max_len = max(x.shape[0] for x in new_input_embeds)
303
+ batch_size = len(new_input_embeds)
304
+
305
+ new_input_embeds_padded = []
306
+ new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
307
+ attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
308
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
309
+
310
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
311
+ cur_len = cur_new_embed.shape[0]
312
+ if getattr(self.config, 'tokenizer_padding_side', 'right') == "left":
313
+ new_input_embeds_padded.append(torch.cat((
314
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device),
315
+ cur_new_embed
316
+ ), dim=0))
317
+ if cur_len > 0:
318
+ new_labels_padded[i, -cur_len:] = cur_new_labels
319
+ attention_mask[i, -cur_len:] = True
320
+ position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
321
+ else:
322
+ new_input_embeds_padded.append(torch.cat((
323
+ cur_new_embed,
324
+ torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)
325
+ ), dim=0))
326
+ if cur_len > 0:
327
+ new_labels_padded[i, :cur_len] = cur_new_labels
328
+ attention_mask[i, :cur_len] = True
329
+ position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
330
+
331
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
332
+
333
+ if _labels is None:
334
+ new_labels = None
335
+ else:
336
+ new_labels = new_labels_padded
337
+
338
+ if _attention_mask is None:
339
+ attention_mask = None
340
+ else:
341
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
342
+
343
+ if _position_ids is None:
344
+ position_ids = None
345
+
346
+ return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
347
+
348
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
349
+ if model_args.mm_use_im_patch_token:
350
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
351
+ self.resize_token_embeddings(len(tokenizer))
352
+
353
+ if model_args.mm_use_im_start_end:
354
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
355
+ self.resize_token_embeddings(len(tokenizer))
356
+
357
+ if num_new_tokens > 0:
358
+ input_embeddings = self.get_input_embeddings().weight.data
359
+ output_embeddings = self.get_output_embeddings().weight.data
360
+
361
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
362
+ dim=0, keepdim=True)
363
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
364
+ dim=0, keepdim=True)
365
+
366
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
367
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
368
+
369
+ if model_args.tune_mm_mlp_adapter:
370
+ for p in self.get_input_embeddings().parameters():
371
+ p.requires_grad = True
372
+ for p in self.get_output_embeddings().parameters():
373
+ p.requires_grad = False
374
+
375
+ if model_args.pretrain_mm_mlp_adapter:
376
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
377
+ embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
378
+ assert num_new_tokens == 2
379
+ if input_embeddings.shape == embed_tokens_weight.shape:
380
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
381
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
382
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
383
+ else:
384
+ raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
385
+ elif model_args.mm_use_im_patch_token:
386
+ if model_args.tune_mm_mlp_adapter:
387
+ for p in self.get_input_embeddings().parameters():
388
+ p.requires_grad = False
389
+ for p in self.get_output_embeddings().parameters():
390
+ p.requires_grad = False
videollava/model/make_delta.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m llava.model.make_delta --base ~/model_weights/llama-7b --target ~/model_weights/llava-7b --delta ~/model_weights/llava-7b-delta --hub-repo-id liuhaotian/llava-7b-delta
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from tqdm import tqdm
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ from videollava.model.utils import auto_upgrade
11
+
12
+
13
+ def make_delta(base_model_path, target_model_path, delta_path, hub_repo_id):
14
+ print("Loading base model")
15
+ base = AutoModelForCausalLM.from_pretrained(
16
+ base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+
18
+ print("Loading target model")
19
+ auto_upgrade(target_model_path)
20
+ target = AutoModelForCausalLM.from_pretrained(target_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
21
+
22
+ print("Calculating delta")
23
+ for name, param in tqdm(target.state_dict().items(), desc="Calculating delta"):
24
+ if name not in base.state_dict():
25
+ assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model'
26
+ continue
27
+ if param.data.shape == base.state_dict()[name].shape:
28
+ param.data -= base.state_dict()[name]
29
+ else:
30
+ assert name in ['model.embed_tokens.weight', 'lm_head.weight'], f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}'
31
+ bparam = base.state_dict()[name]
32
+ param.data[:bparam.shape[0], :bparam.shape[1]] -= bparam
33
+
34
+ print("Saving delta")
35
+ if hub_repo_id:
36
+ kwargs = {"push_to_hub": True, "repo_id": hub_repo_id}
37
+ else:
38
+ kwargs = {}
39
+ target.save_pretrained(delta_path, **kwargs)
40
+ target_tokenizer = AutoTokenizer.from_pretrained(target_model_path)
41
+ target_tokenizer.save_pretrained(delta_path, **kwargs)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ parser = argparse.ArgumentParser()
46
+ parser.add_argument("--base-model-path", type=str, required=True)
47
+ parser.add_argument("--target-model-path", type=str, required=True)
48
+ parser.add_argument("--delta-path", type=str, required=True)
49
+ parser.add_argument("--hub-repo-id", type=str, default=None)
50
+ args = parser.parse_args()
51
+
52
+ make_delta(args.base_model_path, args.target_model_path, args.delta_path, args.hub_repo_id)
videollava/model/multimodal_encoder/builder.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .clip_encoder import CLIPVisionTower
3
+ from .languagebind import LanguageBindImageTower, LanguageBindVideoTower
4
+
5
+ # ============================================================================================================
6
+
7
+ def build_image_tower(image_tower_cfg, **kwargs):
8
+ image_tower = getattr(image_tower_cfg, 'mm_image_tower', getattr(image_tower_cfg, 'image_tower', None))
9
+ is_absolute_path_exists = os.path.exists(image_tower)
10
+ cache_dir = getattr(image_tower_cfg, 'cache_dir', './cache_dir')
11
+ if is_absolute_path_exists or image_tower.startswith("openai") or image_tower.startswith("laion"):
12
+ return CLIPVisionTower(image_tower, args=image_tower_cfg, **kwargs)
13
+ if image_tower.endswith('LanguageBind_Image'):
14
+ return LanguageBindImageTower(image_tower, args=image_tower_cfg, cache_dir=cache_dir, **kwargs)
15
+
16
+ raise ValueError(f'Unknown image tower: {image_tower}')
17
+
18
+ def build_video_tower(video_tower_cfg, **kwargs):
19
+ video_tower = getattr(video_tower_cfg, 'mm_video_tower', getattr(video_tower_cfg, 'video_tower', None))
20
+ cache_dir = getattr(video_tower_cfg, 'cache_dir', './cache_dir')
21
+ if video_tower.endswith('LanguageBind_Video_merge'):
22
+ return LanguageBindVideoTower(video_tower, args=video_tower_cfg, cache_dir=cache_dir, **kwargs)
23
+ raise ValueError(f'Unknown video tower: {video_tower}')
24
+ # ============================================================================================================
videollava/model/multimodal_encoder/clip_encoder.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
5
+
6
+
7
+ class CLIPVisionTower(nn.Module):
8
+ def __init__(self, vision_tower, args, delay_load=False):
9
+ super().__init__()
10
+
11
+ self.is_loaded = False
12
+
13
+ self.vision_tower_name = vision_tower
14
+ self.select_layer = args.mm_vision_select_layer
15
+ self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
16
+
17
+ if not delay_load:
18
+ self.load_model()
19
+ else:
20
+ self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
21
+
22
+ def load_model(self):
23
+ self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
24
+ self.vision_tower = CLIPVisionModel.from_pretrained(self.vision_tower_name)
25
+ self.vision_tower.requires_grad_(False)
26
+
27
+ self.is_loaded = True
28
+
29
+ def feature_select(self, image_forward_outs):
30
+ image_features = image_forward_outs.hidden_states[self.select_layer]
31
+ if self.select_feature == 'patch':
32
+ image_features = image_features[:, 1:]
33
+ elif self.select_feature == 'cls_patch':
34
+ image_features = image_features
35
+ else:
36
+ raise ValueError(f'Unexpected select feature: {self.select_feature}')
37
+ return image_features
38
+
39
+ @torch.no_grad()
40
+ def forward(self, images):
41
+ if type(images) is list:
42
+ image_features = []
43
+ for image in images:
44
+ image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
45
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
46
+ image_features.append(image_feature)
47
+ else:
48
+ image_forward_outs = self.vision_tower(images.to(device=self.device, dtype=self.dtype), output_hidden_states=True)
49
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
50
+
51
+ return image_features
52
+
53
+ @property
54
+ def dummy_feature(self):
55
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
56
+
57
+ @property
58
+ def dtype(self):
59
+ return self.vision_tower.dtype
60
+
61
+ @property
62
+ def device(self):
63
+ return self.vision_tower.device
64
+
65
+ @property
66
+ def config(self):
67
+ if self.is_loaded:
68
+ return self.vision_tower.config
69
+ else:
70
+ return self.cfg_only
71
+
72
+ @property
73
+ def hidden_size(self):
74
+ return self.config.hidden_size
75
+
76
+ @property
77
+ def num_patches(self):
78
+ return (self.config.image_size // self.config.patch_size) ** 2