aaron16 commited on
Commit
f06e369
·
verified ·
1 Parent(s): a1933bc

Upload mmneedle.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. mmneedle.py +199 -0
mmneedle.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import re
4
+ from typing import Dict, Iterable, Optional
5
+
6
+ import datasets
7
+
8
+ logger = datasets.logging.get_logger(__name__)
9
+
10
+ _HOMEPAGE = "https://mmneedle.github.io/"
11
+ _LICENSE = "CC-BY-4.0"
12
+
13
+ _DESCRIPTION = """\
14
+ MMNeedle stress-tests the long-context visual reasoning ability of multimodal LLMs.
15
+ Each example provides a sequence of stitched haystack images together with 1, 2, or 5
16
+ needle descriptions derived from MS COCO captions. Models must return the index and
17
+ spatial location (row, column) of the matching sub-image or indicate that the
18
+ needle is absent. This script exposes the complete benchmark as a Hugging Face
19
+ `datasets` builder so researchers can load it with `load_dataset` without
20
+ reconstructing the data from scratch or pulling it from Google Drive.
21
+ """
22
+
23
+ _BASE_URL = "https://huggingface.co/datasets/Wang-ML-Lab/MMNeedle/resolve/main"
24
+ _URLS = {
25
+ "images": f"{_BASE_URL}/data/images_stitched.zip",
26
+ "metadata": f"{_BASE_URL}/data/metadata_stitched.zip",
27
+ "captions": f"{_BASE_URL}/data/file_to_caption.json",
28
+ }
29
+
30
+ _SINGLE_PATTERN = re.compile(r"^annotations_(?P<seq>\\d+)_(?P<rows>\\d+)_(?P<cols>\\d+)\\.json$")
31
+ _MULTI_PATTERN = re.compile(r"^(?P<needles>\\d+)_annotations_(?P<seq>\\d+)_(?P<rows>\\d+)_(?P<cols>\\d+)\\.json$")
32
+
33
+
34
+ class MMNeedleConfig(datasets.BuilderConfig):
35
+ """Builder config (single config for now)."""
36
+
37
+ def __init__(self, **kwargs):
38
+ super().__init__(version=datasets.Version("1.0.0"), **kwargs)
39
+
40
+
41
+ class MMNeedle(datasets.GeneratorBasedBuilder):
42
+ BUILDER_CONFIGS = [
43
+ MMNeedleConfig(name="default", description="Full MMNeedle benchmark"),
44
+ ]
45
+ DEFAULT_CONFIG_NAME = "default"
46
+
47
+ def _info(self) -> datasets.DatasetInfo:
48
+ features = datasets.Features(
49
+ {
50
+ "id": datasets.Value("string"),
51
+ "sequence_length": datasets.Value("int32"),
52
+ "grid_rows": datasets.Value("int32"),
53
+ "grid_cols": datasets.Value("int32"),
54
+ "needles_per_query": datasets.Value("int32"),
55
+ "haystack_images": datasets.Sequence(datasets.Image()),
56
+ "needle_locations": datasets.Sequence(
57
+ {
58
+ "image_index": datasets.Value("int32"),
59
+ "row": datasets.Value("int32"),
60
+ "col": datasets.Value("int32"),
61
+ }
62
+ ),
63
+ "needle_image_ids": datasets.Sequence(datasets.Value("string")),
64
+ "needle_captions": datasets.Sequence(datasets.Value("string")),
65
+ "has_needle": datasets.Value("bool"),
66
+ }
67
+ )
68
+
69
+ return datasets.DatasetInfo(
70
+ description=_DESCRIPTION,
71
+ features=features,
72
+ homepage=_HOMEPAGE,
73
+ license=_LICENSE,
74
+ )
75
+
76
+ def _split_generators(self, dl_manager: datasets.DownloadManager):
77
+ archives = dl_manager.download_and_extract({k: v for k, v in _URLS.items() if k != "captions"})
78
+ captions_path = dl_manager.download(_URLS["captions"])
79
+ images_root = _resolve_subdir(archives["images"], "images_stitched")
80
+ metadata_root = _resolve_subdir(archives["metadata"], "metadata_stitched")
81
+
82
+ return [
83
+ datasets.SplitGenerator(
84
+ name=datasets.Split.TEST,
85
+ gen_kwargs={
86
+ "images_root": images_root,
87
+ "metadata_root": metadata_root,
88
+ "captions_path": captions_path,
89
+ },
90
+ )
91
+ ]
92
+
93
+ def _generate_examples(
94
+ self,
95
+ images_root: str,
96
+ metadata_root: str,
97
+ captions_path: str,
98
+ ) -> Iterable:
99
+ with open(captions_path, "r", encoding="utf-8") as f:
100
+ captions: Dict[str, str] = json.load(f)
101
+
102
+ metadata_files = sorted(
103
+ fname for fname in os.listdir(metadata_root) if fname.endswith(".json")
104
+ )
105
+
106
+ logger.info("Found %d metadata files", len(metadata_files))
107
+
108
+ for fname in metadata_files:
109
+ spec = _parse_metadata_name(fname)
110
+ if spec is None:
111
+ logger.warning("Skipping unrecognized metadata file: %s", fname)
112
+ continue
113
+
114
+ path = os.path.join(metadata_root, fname)
115
+ with open(path, "r", encoding="utf-8") as f:
116
+ entries = json.load(f)
117
+
118
+ for entry in entries:
119
+ example_id = f"{spec['needles']}n_{spec['seq']}seq_{spec['rows']}x{spec['cols']}_{entry['id']}"
120
+ image_paths = [
121
+ os.path.join(images_root, rel_path)
122
+ for rel_path in entry.get("image_ids", [])
123
+ ]
124
+
125
+ targets = entry.get("target", [])
126
+ if isinstance(targets, str):
127
+ target_list = [targets]
128
+ else:
129
+ target_list = list(targets)
130
+
131
+ index_field = entry.get("index", [])
132
+ if isinstance(index_field, int):
133
+ index_list = [index_field]
134
+ else:
135
+ index_list = list(index_field)
136
+
137
+ row_field = entry.get("row", [])
138
+ if isinstance(row_field, int):
139
+ row_list = [row_field]
140
+ else:
141
+ row_list = list(row_field)
142
+
143
+ col_field = entry.get("col", [])
144
+ if isinstance(col_field, int):
145
+ col_list = [col_field]
146
+ else:
147
+ col_list = list(col_field)
148
+
149
+ needle_locations = []
150
+ has_needle = False
151
+ for idx, row, col in zip(index_list, row_list, col_list):
152
+ has_needle = has_needle or idx != -1
153
+ needle_locations.append(
154
+ {
155
+ "image_index": int(idx),
156
+ "row": int(row),
157
+ "col": int(col),
158
+ }
159
+ )
160
+
161
+ needle_captions = [captions.get(t, "") for t in target_list]
162
+
163
+ yield example_id, {
164
+ "id": example_id,
165
+ "sequence_length": len(image_paths),
166
+ "grid_rows": spec["rows"],
167
+ "grid_cols": spec["cols"],
168
+ "needles_per_query": spec["needles"],
169
+ "haystack_images": image_paths,
170
+ "needle_locations": needle_locations,
171
+ "needle_image_ids": target_list,
172
+ "needle_captions": needle_captions,
173
+ "has_needle": has_needle,
174
+ }
175
+
176
+
177
+ def _resolve_subdir(root: str, expected: str) -> str:
178
+ candidate = os.path.join(root, expected)
179
+ return candidate if os.path.isdir(candidate) else root
180
+
181
+
182
+ def _parse_metadata_name(fname: str) -> Optional[Dict[str, int]]:
183
+ match = _SINGLE_PATTERN.match(fname)
184
+ if match:
185
+ return {
186
+ "needles": 1,
187
+ "seq": int(match.group("seq")),
188
+ "rows": int(match.group("rows")),
189
+ "cols": int(match.group("cols")),
190
+ }
191
+ match = _MULTI_PATTERN.match(fname)
192
+ if match:
193
+ return {
194
+ "needles": int(match.group("needles")),
195
+ "seq": int(match.group("seq")),
196
+ "rows": int(match.group("rows")),
197
+ "cols": int(match.group("cols")),
198
+ }
199
+ return None