prrao87 commited on
Commit
a23dc97
·
verified ·
1 Parent(s): 2a672b4

Update README with LanceDB examples

Browse files
Files changed (1) hide show
  1. README.md +204 -45
README.md CHANGED
@@ -3,6 +3,7 @@ license: cc-by-4.0
3
  task_categories:
4
  - visual-question-answering
5
  - image-text-to-text
 
6
  language:
7
  - en
8
  tags:
@@ -18,9 +19,14 @@ size_categories:
18
  ---
19
  # GQA testdev-balanced (Lance Format)
20
 
21
- Lance-formatted version of the canonical GQA `testdev_balanced` slice — 12,578 compositional VQA questions joined with the matching 398 images — sourced from [`lmms-lab/GQA`](https://huggingface.co/datasets/lmms-lab/GQA).
 
 
22
 
23
- `lmms-lab/GQA` exposes instructions and images as **separate parquet configs**; this Lance dataset joins them on `imageId`, so each row has the question, the answer, the GQA reasoning-program tags, *and* the image bytes inline.
 
 
 
24
 
25
  ## Splits
26
 
@@ -28,57 +34,91 @@ Lance-formatted version of the canonical GQA `testdev_balanced` slice — 12,578
28
  |-------|------|----------------|
29
  | `testdev.lance` | 12,578 | 398 |
30
 
31
- > Train (`train_balanced_instructions` × `train_balanced_images`, ~943k Q's × 72k images, ~10 GB images) and val splits are not bundled by default pass `--instr-config`/`--images-config` to `gqa/dataprep.py` to extend.
32
 
33
  ## Schema
34
 
35
  | Column | Type | Notes |
36
  |---|---|---|
37
- | `id` | `int64` | Row index |
38
- | `image` | `large_binary` | Inline JPEG bytes (image is duplicated across rows that share an `image_id`) |
39
  | `image_id` | `string` | GQA scene-graph image id |
40
  | `question_id` | `string` | GQA question id |
41
  | `question` | `string` | Compositional natural-language question |
42
  | `answers` | `list<string>` | One-element list (the GQA short answer) |
43
- | `answer` | `string` | Same short answer (canonical / FTS target) |
44
- | `full_answer` | `string?` | Full sentence answer |
45
  | `structural` | `string?` | One of `verify`, `query`, `compare`, `choose`, `logical` |
46
  | `semantic` | `string?` | One of `attr`, `cat`, `global`, `obj`, `rel` |
47
  | `detailed` | `string?` | Fine-grained type (e.g. `weatherVerifyC`) |
48
  | `is_balanced` | `bool` | GQA balanced subset flag |
49
- | `group_global` / `group_local` | `string?` | GQA reasoning-group ids |
50
  | `semantic_str` | `string?` | Compact description of the reasoning program |
51
  | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) |
52
  | `question_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the question |
53
 
54
  ## Pre-built indices
55
 
56
- - `IVF_PQ` on `image_emb` and `question_emb` `metric=cosine`
57
- - `INVERTED` (FTS) on `question` and `answer`
58
- - `BITMAP` on `structural`, `semantic`, `detailed`
59
- - `BTREE` on `image_id`, `question_id`
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
- ## Quick start
62
 
63
  ```python
64
- import lance
65
- ds = lance.dataset("hf://datasets/lance-format/gqa-testdev-balanced-lance/data/testdev.lance")
66
- print(ds.count_rows(), ds.schema.names, ds.list_indices())
 
 
67
  ```
68
 
69
  ## Load with LanceDB
70
 
71
- These tables can also be consumed by [LanceDB](https://lancedb.github.io/lancedb/), the multimodal lakehouse and embedded search library built on top of Lance, for simplified vector search and other queries.
72
 
73
  ```python
74
  import lancedb
75
 
76
  db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data")
77
  tbl = db.open_table("testdev")
78
- print(f"LanceDB table opened with {len(tbl)} image-question pairs")
79
  ```
80
 
81
- ### LanceDB vector search
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  ```python
84
  import lancedb
@@ -86,19 +126,48 @@ import lancedb
86
  db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data")
87
  tbl = db.open_table("testdev")
88
 
89
- ref = tbl.search().limit(1).select(["question_emb", "question"]).to_list()[0]
90
- query_embedding = ref["question_emb"]
 
 
 
 
 
91
 
92
- results = (
93
- tbl.search(query_embedding, vector_column_name="question_emb")
94
  .metric("cosine")
95
- .select(["question", "answer"])
96
- .limit(5)
97
  .to_list()
98
  )
 
 
 
99
  ```
100
 
101
- ### LanceDB full-text search
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  ```python
104
  import lancedb
@@ -106,42 +175,132 @@ import lancedb
106
  db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data")
107
  tbl = db.open_table("testdev")
108
 
109
- results = (
110
- tbl.search("color of the car")
111
- .select(["question", "answer"])
112
- .limit(10)
 
 
 
 
113
  .to_list()
114
  )
 
115
  ```
116
 
117
- ## Filter by reasoning type
 
 
 
 
 
 
118
 
119
  ```python
120
- import lance
121
- ds = lance.dataset("hf://datasets/lance-format/gqa-testdev-balanced-lance/data/testdev.lance")
122
- verify_qs = ds.scanner(filter="structural = 'verify'", columns=["question", "answer"], limit=5).to_table()
 
 
 
 
 
 
 
123
  ```
124
 
125
- ### Filter with LanceDB
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
  ```python
128
  import lancedb
 
 
129
 
130
  db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data")
131
  tbl = db.open_table("testdev")
132
- verify_qs = (
133
- tbl.search()
134
- .where("structural = 'verify'")
135
- .select(["question", "answer"])
136
- .limit(5)
137
- .to_list()
138
- )
 
139
  ```
140
 
141
- ## Why Lance?
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
- - One dataset for the joined image + question + answer + reasoning-program metadata + dual embeddings + indices no instructions/images parquet split to keep in sync.
144
- - Schema evolution: add columns (alternate scene graphs, model predictions) without rewriting the data.
145
 
146
  ## Source & license
147
 
 
3
  task_categories:
4
  - visual-question-answering
5
  - image-text-to-text
6
+ - lance
7
  language:
8
  - en
9
  tags:
 
19
  ---
20
  # GQA testdev-balanced (Lance Format)
21
 
22
+ A Lance-formatted version of the canonical GQA `testdev_balanced` slice — 12,578 compositional VQA questions joined against the matching 398 images — sourced from [`lmms-lab/GQA`](https://huggingface.co/datasets/lmms-lab/GQA). The original redistribution ships instructions and images as separate parquet configs; here they are pre-joined on `image_id`, so each row carries the question text, the short answer, the GQA reasoning-program tags, paired CLIP image and question embeddings, and the inline JPEG bytes — all available directly from the Hub at `hf://datasets/lance-format/gqa-testdev-balanced-lance/data`.
23
+
24
+ ## Key features
25
 
26
+ - **Inline JPEG bytes** in the `image` column, duplicated across rows that share an `image_id` so each Q/A row is self-contained.
27
+ - **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (512-dim, cosine-normalized) — for cross-modal retrieval as one indexed lookup.
28
+ - **Compositional reasoning metadata** — `structural`, `semantic`, and `detailed` question-type tags plus the `semantic_str` reasoning program.
29
+ - **Pre-built ANN, FTS, scalar, and bitmap indices** covering both embeddings, the question and short answer, the reasoning-type tags, and the image/question ids.
30
 
31
  ## Splits
32
 
 
34
  |-------|------|----------------|
35
  | `testdev.lance` | 12,578 | 398 |
36
 
37
+ The train_balanced (~943 k Q's × 72 k images) and val_balanced splits are not bundled by default; pass `--instr-config` / `--images-config` to `gqa/dataprep.py` to extend.
38
 
39
  ## Schema
40
 
41
  | Column | Type | Notes |
42
  |---|---|---|
43
+ | `id` | `int64` | Row index within split |
44
+ | `image` | `large_binary` | Inline JPEG bytes (duplicated across rows that share an `image_id`) |
45
  | `image_id` | `string` | GQA scene-graph image id |
46
  | `question_id` | `string` | GQA question id |
47
  | `question` | `string` | Compositional natural-language question |
48
  | `answers` | `list<string>` | One-element list (the GQA short answer) |
49
+ | `answer` | `string` | Canonical short answer (used for FTS) |
50
+ | `full_answer` | `string?` | Full-sentence answer |
51
  | `structural` | `string?` | One of `verify`, `query`, `compare`, `choose`, `logical` |
52
  | `semantic` | `string?` | One of `attr`, `cat`, `global`, `obj`, `rel` |
53
  | `detailed` | `string?` | Fine-grained type (e.g. `weatherVerifyC`) |
54
  | `is_balanced` | `bool` | GQA balanced subset flag |
55
+ | `group_global`, `group_local` | `string?` | GQA reasoning-group ids |
56
  | `semantic_str` | `string?` | Compact description of the reasoning program |
57
  | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) |
58
  | `question_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the question |
59
 
60
  ## Pre-built indices
61
 
62
+ - `IVF_PQ` on `image_emb` image-side vector search (cosine)
63
+ - `IVF_PQ` on `question_emb` question-side vector search (cosine)
64
+ - `INVERTED` (FTS) on `question` and `answer` — keyword and hybrid search
65
+ - `BITMAP` on `structural`, `semantic`, `detailed` — fast categorical filters on the reasoning program
66
+ - `BTREE` on `image_id`, `question_id` — fast lookup by GQA id
67
+
68
+ ## Why Lance?
69
+
70
+ 1. **Blazing Fast Random Access**: Optimized for fetching scattered rows, making it ideal for random sampling, real-time ML serving, and interactive applications without performance degradation.
71
+ 2. **Native Multimodal Support**: Store text, embeddings, and other data types together in a single file. Large binary objects are loaded lazily, and vectors are optimized for fast similarity search.
72
+ 3. **Native Index Support**: Lance comes with fast, on-disk, scalable vector and FTS indexes that sit right alongside the dataset on the Hub, so you can share not only your data but also your embeddings and indexes without your users needing to recompute them.
73
+ 4. **Efficient Data Evolution**: Add new columns and backfill data without rewriting the entire dataset. This is perfect for evolving ML features, adding new embeddings, or introducing moderation tags over time.
74
+ 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes.
75
+ 6. **Data Versioning**: Every mutation commits a new version; previous versions remain intact on disk. Tags pin a snapshot by name, so retrieval systems and training runs can reproduce against an exact slice of history.
76
+
77
+ ## Load with `datasets.load_dataset`
78
 
79
+ You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable when your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample.
80
 
81
  ```python
82
+ import datasets
83
+
84
+ hf_ds = datasets.load_dataset("lance-format/gqa-testdev-balanced-lance", split="testdev", streaming=True)
85
+ for row in hf_ds.take(3):
86
+ print(row["question"], "->", row["answer"])
87
  ```
88
 
89
  ## Load with LanceDB
90
 
91
+ LanceDB is the embedded retrieval library built on top of the Lance format ([docs](https://lancedb.com/docs)), and is the interface most users interact with. It wraps the dataset as a queryable table with search and filter builders, and is the entry point used by the Search, Curate, Evolve, Versioning, and Materialize-a-subset sections below.
92
 
93
  ```python
94
  import lancedb
95
 
96
  db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data")
97
  tbl = db.open_table("testdev")
98
+ print(len(tbl))
99
  ```
100
 
101
+ ## Load with Lance
102
+
103
+ `pylance` is the Python binding for the Lance format and works directly with the format's lower-level APIs. Reach for it when you want to inspect dataset internals — schema, scanner, fragments, and the list of pre-built indices.
104
+
105
+ ```python
106
+ import lance
107
+
108
+ ds = lance.dataset("hf://datasets/lance-format/gqa-testdev-balanced-lance/data/testdev.lance")
109
+ print(ds.count_rows(), ds.schema.names)
110
+ print(ds.list_indices())
111
+ ```
112
+
113
+ > **Tip — for production use, download locally first.** Streaming from the Hub works for exploration, but heavy random access and ANN search are far faster against a local copy:
114
+ > ```bash
115
+ > hf download lance-format/gqa-testdev-balanced-lance --repo-type dataset --local-dir ./gqa-testdev-balanced-lance
116
+ > ```
117
+ > Then point Lance or LanceDB at `./gqa-testdev-balanced-lance/data`.
118
+
119
+ ## Search
120
+
121
+ The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a question with the same CLIP model used at ingest (ViT-B/32, cosine-normalized), then pass the resulting 512-d vector to `tbl.search(...)` and target `image_emb`. The example below uses the `question_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a question", so the snippet works without any model loaded.
122
 
123
  ```python
124
  import lancedb
 
126
  db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data")
127
  tbl = db.open_table("testdev")
128
 
129
+ seed = (
130
+ tbl.search()
131
+ .select(["question_emb", "question", "answer"])
132
+ .limit(1)
133
+ .offset(42)
134
+ .to_list()[0]
135
+ )
136
 
137
+ hits = (
138
+ tbl.search(seed["question_emb"], vector_column_name="image_emb")
139
  .metric("cosine")
140
+ .select(["image_id", "question", "answer", "structural"])
141
+ .limit(10)
142
  .to_list()
143
  )
144
+ print("query question:", seed["question"], "->", seed["answer"])
145
+ for r in hits:
146
+ print(f" {r['image_id']:>12} [{r['structural']}] {r['question'][:70]}")
147
  ```
148
 
149
+ Because the CLIP embeddings are cosine-normalized, cosine is the right metric and the first hit will often be the source row itself — a useful sanity check. Swap `vector_column_name="image_emb"` for `question_emb` to find paraphrased or topically related questions instead.
150
+
151
+ The dataset also ships an `INVERTED` index on `question` and `answer`, so the same query can be issued as a hybrid search that combines the dense vector with a literal keyword match. This is useful when a noun like "umbrella" must appear in the question text but you still want CLIP to handle visual similarity over the candidate set.
152
+
153
+ ```python
154
+ hybrid_hits = (
155
+ tbl.search(query_type="hybrid", vector_column_name="image_emb")
156
+ .vector(seed["question_emb"])
157
+ .text("umbrella")
158
+ .select(["image_id", "question", "answer"])
159
+ .limit(10)
160
+ .to_list()
161
+ )
162
+ for r in hybrid_hits:
163
+ print(f" {r['image_id']:>12} {r['question'][:70]} -> {r['answer']}")
164
+ ```
165
+
166
+ Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency.
167
+
168
+ ## Curate
169
+
170
+ A typical curation pass for a compositional-reasoning study combines a predicate on the question text (or the GQA short answer) with a structural filter on the reasoning program, so the candidate set is both topically and structurally consistent. Stacking both inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(500)` makes it cheap to inspect before committing the subset to anything downstream.
171
 
172
  ```python
173
  import lancedb
 
175
  db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data")
176
  tbl = db.open_table("testdev")
177
 
178
+ candidates = (
179
+ tbl.search()
180
+ .where(
181
+ "structural = 'verify' AND answer IN ('yes', 'no') AND question LIKE 'Is %'",
182
+ prefilter=True,
183
+ )
184
+ .select(["question_id", "image_id", "question", "answer", "semantic"])
185
+ .limit(500)
186
  .to_list()
187
  )
188
+ print(f"{len(candidates)} verify-style yes/no candidates; first: {candidates[0]['question']}")
189
  ```
190
 
191
+ The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `question_id`s, or feed into the Evolve and Train workflows below. The `image` column is never read, so the network traffic for a 500-row candidate scan is dominated by the question and answer strings rather than JPEG bytes.
192
+
193
+ ## Evolve
194
+
195
+ Lance stores each column independently, so a new column can be appended without rewriting the existing data. The lightest form is a SQL expression: derive the new column from columns that already exist, and Lance computes it once and persists it. The example below adds an `is_binary_answer` flag and a `question_length` integer, either of which can then be used directly in `where` clauses without recomputing the predicate on every query.
196
+
197
+ > **Note:** Mutations require a local copy of the dataset, since the Hub mount is read-only. See the Materialize-a-subset section at the end of this card for a streaming pattern that downloads only the rows and columns you need, or use `hf download` to pull the full split first.
198
 
199
  ```python
200
+ import lancedb
201
+
202
+ db = lancedb.connect("./gqa-testdev-balanced-lance/data") # local copy required for writes
203
+ tbl = db.open_table("testdev")
204
+
205
+ tbl.add_columns({
206
+ "is_binary_answer": "answer IN ('yes', 'no')",
207
+ "question_length": "length(question)",
208
+ "answer_length": "length(answer)",
209
+ })
210
  ```
211
 
212
+ If the values you want to attach already live in another table (offline labels, scene-graph features, or per-question predictions from an external model), merge them in by joining on `question_id`:
213
+
214
+ ```python
215
+ import pyarrow as pa
216
+
217
+ predictions = pa.table({
218
+ "question_id": pa.array(["20240268", "20240269"]),
219
+ "model_answer": pa.array(["yes", "left"]),
220
+ "model_confidence": pa.array([0.91, 0.62]),
221
+ })
222
+ tbl.merge(predictions, on="question_id")
223
+ ```
224
+
225
+ The original columns and indices are untouched, so existing code that does not reference the new columns continues to work unchanged. New columns become visible to every reader as soon as the operation commits. For column values that require a Python computation, Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/).
226
+
227
+ ## Train
228
+
229
+ Projection lets a training loop read only the columns each step actually needs. LanceDB tables expose this through `Permutation.identity(tbl).select_columns([...])`, which plugs straight into the standard `torch.utils.data.DataLoader` so prefetching, shuffling, and batching behave as in any PyTorch pipeline. For a VQA fine-tune, project the JPEG bytes, the question, and the short answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected.
230
 
231
  ```python
232
  import lancedb
233
+ from lancedb.permutation import Permutation
234
+ from torch.utils.data import DataLoader
235
 
236
  db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data")
237
  tbl = db.open_table("testdev")
238
+
239
+ train_ds = Permutation.identity(tbl).select_columns(["image", "question", "answer"])
240
+ loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4)
241
+
242
+ for batch in loader:
243
+ # batch carries only the projected columns; decode the JPEG bytes,
244
+ # tokenize the question, forward through the VLM, compute the loss...
245
+ ...
246
  ```
247
 
248
+ Switching feature sets is a configuration change: passing `["image_emb", "question_emb", "answer"]` to `select_columns(...)` on the next run skips JPEG decoding entirely and reads only the cached 512-d vectors, which is the right shape for a lightweight reasoning probe over frozen CLIP features.
249
+
250
+ ## Versioning
251
+
252
+ Every mutation to a Lance dataset, whether it adds a column, merges labels, or builds an index, commits a new version. Previous versions remain intact on disk. You can list versions and inspect the history directly from the Hub copy; creating new tags requires a local copy since tags are writes.
253
+
254
+ ```python
255
+ import lancedb
256
+
257
+ db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data")
258
+ tbl = db.open_table("testdev")
259
+
260
+ print("Current version:", tbl.version)
261
+ print("History:", tbl.list_versions())
262
+ print("Tags:", tbl.tags.list())
263
+ ```
264
+
265
+ Once you have a local copy, tag a version for reproducibility:
266
+
267
+ ```python
268
+ local_db = lancedb.connect("./gqa-testdev-balanced-lance/data")
269
+ local_tbl = local_db.open_table("testdev")
270
+ local_tbl.tags.create("clip-vitb32-v1", local_tbl.version)
271
+ ```
272
+
273
+ A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one:
274
+
275
+ ```python
276
+ tbl_v1 = db.open_table("testdev", version="clip-vitb32-v1")
277
+ tbl_v5 = db.open_table("testdev", version=5)
278
+ ```
279
+
280
+ Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added model predictions or reasoning annotations do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same images and questions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking.
281
+
282
+ ## Materialize a subset
283
+
284
+ Reads from the Hub are lazy, so exploratory queries only transfer the columns and row groups they touch. Mutating operations (Evolve, tag creation) need a writable backing store, and a training loop benefits from a local copy with fast random access. Both can be served by a subset of the dataset rather than the full split. The pattern is to stream a filtered query through `.to_batches()` into a new local table; only the projected columns and matching row groups cross the wire, and the bytes never fully materialize in Python memory.
285
+
286
+ ```python
287
+ import lancedb
288
+
289
+ remote_db = lancedb.connect("hf://datasets/lance-format/gqa-testdev-balanced-lance/data")
290
+ remote_tbl = remote_db.open_table("testdev")
291
+
292
+ batches = (
293
+ remote_tbl.search()
294
+ .where("structural = 'verify' AND answer IN ('yes', 'no')")
295
+ .select(["question_id", "image_id", "image", "question", "answer", "image_emb", "question_emb"])
296
+ .to_batches()
297
+ )
298
+
299
+ local_db = lancedb.connect("./gqa-yesno-subset")
300
+ local_db.create_table("testdev", batches)
301
+ ```
302
 
303
+ The resulting `./gqa-yesno-subset` is a first-class LanceDB database. Every snippet in the Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/gqa-testdev-balanced-lance/data` for `./gqa-yesno-subset`.
 
304
 
305
  ## Source & license
306