prrao87 commited on
Commit
1feb507
·
verified ·
1 Parent(s): 2919ce1

Update README with LanceDB examples

Browse files
Files changed (1) hide show
  1. README.md +208 -48
README.md CHANGED
@@ -4,6 +4,7 @@ task_categories:
4
  - visual-question-answering
5
  - image-text-to-text
6
  - image-feature-extraction
 
7
  language:
8
  - en
9
  tags:
@@ -19,16 +20,21 @@ size_categories:
19
  ---
20
  # TextVQA (Lance Format)
21
 
22
- Lance-formatted version of [TextVQA](https://textvqa.org/) — VQA where the question requires *reading* text in the image — sourced from [`lmms-lab/textvqa`](https://huggingface.co/datasets/lmms-lab/textvqa).
 
 
23
 
24
- Each row carries the image bytes, the question, the 10 reference answers, the OCR tokens detected by the dataset's pre-processing, and CLIP image + question embeddings.
 
 
 
25
 
26
  ## Splits
27
 
28
  | Split | Rows |
29
  |-------|------|
30
  | `validation.lance` | 5,000 |
31
- | `train.lance` | 34,602 |
32
 
33
  ## Schema
34
 
@@ -40,7 +46,7 @@ Each row carries the image bytes, the question, the 10 reference answers, the OC
40
  | `question_id` | `string?` | TextVQA question id |
41
  | `question` | `string` | The question text |
42
  | `answers` | `list<string>` | 10 annotator answers |
43
- | `answer` | `string` | First answer — used as canonical / FTS target |
44
  | `ocr_tokens` | `list<string>` | OCR tokens detected on the image |
45
  | `image_classes` | `list<string>` | OpenImages-style scene tags from the source |
46
  | `set_name` | `string?` | Source partition (`train`, `val`) |
@@ -49,75 +55,114 @@ Each row carries the image bytes, the question, the 10 reference answers, the OC
49
 
50
  ## Pre-built indices
51
 
52
- - `IVF_PQ` on `image_emb` and `question_emb` — `metric=cosine`
53
- - `INVERTED` (FTS) on `question` and `answer`
54
- - `BTREE` on `image_id`, `question_id`, `set_name`
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- ## Quick start
57
 
58
  ```python
59
- import lance
60
- ds = lance.dataset("hf://datasets/lance-format/textvqa-lance/data/validation.lance")
61
- print(ds.count_rows(), ds.schema.names, ds.list_indices())
 
 
62
  ```
63
 
64
  ## Load with LanceDB
65
 
66
- 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.
67
 
68
  ```python
69
  import lancedb
70
 
71
  db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data")
72
  tbl = db.open_table("validation")
73
- print(f"LanceDB table opened with {len(tbl)} image-question pairs")
74
  ```
75
 
76
- ## Cross-modal text→image search
77
 
78
- ```python
79
- import lance, pyarrow as pa, open_clip, torch
80
 
81
- model, _, _ = open_clip.create_model_and_transforms("ViT-B-32", pretrained="laion2b_s34b_b79k")
82
- tokenizer = open_clip.get_tokenizer("ViT-B-32")
83
- model = model.eval().cuda().half()
84
- with torch.no_grad():
85
- q = model.encode_text(tokenizer(["what brand is on this billboard?"]).cuda())
86
- q = (q / q.norm(dim=-1, keepdim=True)).float().cpu().numpy()[0]
87
 
88
  ds = lance.dataset("hf://datasets/lance-format/textvqa-lance/data/validation.lance")
89
- emb_field = ds.schema.field("image_emb")
90
- hits = ds.scanner(
91
- nearest={"column": "image_emb", "q": pa.array([q.tolist()], type=emb_field.type)[0], "k": 10},
92
- columns=["question", "answer", "ocr_tokens"],
93
- ).to_table().to_pylist()
94
  ```
95
 
96
- ### LanceDB cross-modal text→image search
 
 
 
 
97
 
98
- ```python
99
- import lancedb, open_clip, torch
 
100
 
101
- model, _, _ = open_clip.create_model_and_transforms("ViT-B-32", pretrained="laion2b_s34b_b79k")
102
- tokenizer = open_clip.get_tokenizer("ViT-B-32")
103
- model = model.eval().cuda().half()
104
- with torch.no_grad():
105
- q = model.encode_text(tokenizer(["what brand is on this billboard?"]).cuda())
106
- q = (q / q.norm(dim=-1, keepdim=True)).float().cpu().numpy()[0]
107
 
108
  db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data")
109
  tbl = db.open_table("validation")
110
 
111
- results = (
112
- tbl.search(q.tolist(), vector_column_name="image_emb")
 
 
 
 
 
 
 
 
113
  .metric("cosine")
114
- .select(["question", "answer", "ocr_tokens"])
115
  .limit(10)
116
  .to_list()
117
  )
 
 
 
118
  ```
119
 
120
- ### LanceDB full-text search
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
  ```python
123
  import lancedb
@@ -125,19 +170,134 @@ import lancedb
125
  db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data")
126
  tbl = db.open_table("validation")
127
 
128
- results = (
129
- tbl.search("brand name")
130
- .select(["question", "answer"])
131
- .limit(10)
 
 
 
 
132
  .to_list()
133
  )
 
134
  ```
135
 
136
- ## Why Lance?
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
- - One dataset for images + questions + answers + OCR + dual embeddings + indices — no JSON/feature folders.
139
- - Cross-modal search and OCR-text filtering work on the same dataset on the Hub.
140
- - Schema evolution: add columns (alternate OCR systems, model predictions) without rewriting the data.
141
 
142
  ## Source & license
143
 
 
4
  - visual-question-answering
5
  - image-text-to-text
6
  - image-feature-extraction
7
+ - lance
8
  language:
9
  - en
10
  tags:
 
20
  ---
21
  # TextVQA (Lance Format)
22
 
23
+ A Lance-formatted version of [TextVQA](https://textvqa.org/) — visual question answering where the question requires *reading* text in the image (street signs, product labels, screen captures) — sourced from [`lmms-lab/textvqa`](https://huggingface.co/datasets/lmms-lab/textvqa). Each row carries the image bytes, the question, the 10 reference annotator answers, the OCR tokens detected by the source pre-processing, OpenImages-style scene tags, and paired CLIP image and question embeddings — all available directly from the Hub at `hf://datasets/lance-format/textvqa-lance/data`.
24
+
25
+ ## Key features
26
 
27
+ - **Inline JPEG bytes** in the `image` column — no sidecar files or image folders.
28
+ - **Paired CLIP embeddings in the same row** — `image_emb` and `question_emb` (OpenCLIP ViT-B/32, 512-dim, cosine-normalized) — so cross-modal text→image retrieval is one indexed lookup.
29
+ - **OCR tokens travel with the row** in `ocr_tokens`, which makes OCR-aware filtering and reranking a single SQL predicate alongside the visual and textual features.
30
+ - **Pre-built ANN, FTS, and scalar indices** covering both embeddings, the question and canonical answer, and the source partition.
31
 
32
  ## Splits
33
 
34
  | Split | Rows |
35
  |-------|------|
36
  | `validation.lance` | 5,000 |
37
+ | `train.lance` | 34,602 |
38
 
39
  ## Schema
40
 
 
46
  | `question_id` | `string?` | TextVQA question id |
47
  | `question` | `string` | The question text |
48
  | `answers` | `list<string>` | 10 annotator answers |
49
+ | `answer` | `string` | First annotator answer (used as canonical / FTS target) |
50
  | `ocr_tokens` | `list<string>` | OCR tokens detected on the image |
51
  | `image_classes` | `list<string>` | OpenImages-style scene tags from the source |
52
  | `set_name` | `string?` | Source partition (`train`, `val`) |
 
55
 
56
  ## Pre-built indices
57
 
58
+ - `IVF_PQ` on `image_emb` — image-side vector search (cosine)
59
+ - `IVF_PQ` on `question_emb` — question-side vector search (cosine)
60
+ - `INVERTED` (FTS) on `question` and `answer` — keyword and hybrid search
61
+ - `BTREE` on `image_id`, `question_id`, `set_name` — fast lookup by id and partition
62
+
63
+ ## Why Lance?
64
+
65
+ 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.
66
+ 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.
67
+ 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.
68
+ 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.
69
+ 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes.
70
+ 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.
71
+
72
+ ## Load with `datasets.load_dataset`
73
 
74
+ 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.
75
 
76
  ```python
77
+ import datasets
78
+
79
+ hf_ds = datasets.load_dataset("lance-format/textvqa-lance", split="validation", streaming=True)
80
+ for row in hf_ds.take(3):
81
+ print(row["question"], "->", row["answer"])
82
  ```
83
 
84
  ## Load with LanceDB
85
 
86
+ 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.
87
 
88
  ```python
89
  import lancedb
90
 
91
  db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data")
92
  tbl = db.open_table("validation")
93
+ print(len(tbl))
94
  ```
95
 
96
+ ## Load with Lance
97
 
98
+ `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.
 
99
 
100
+ ```python
101
+ import lance
 
 
 
 
102
 
103
  ds = lance.dataset("hf://datasets/lance-format/textvqa-lance/data/validation.lance")
104
+ print(ds.count_rows(), ds.schema.names)
105
+ print(ds.list_indices())
 
 
 
106
  ```
107
 
108
+ > **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:
109
+ > ```bash
110
+ > hf download lance-format/textvqa-lance --repo-type dataset --local-dir ./textvqa-lance
111
+ > ```
112
+ > Then point Lance or LanceDB at `./textvqa-lance/data`.
113
 
114
+ ## Search
115
+
116
+ The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a question with the same OpenCLIP model used at ingest (ViT-B/32 `laion2b_s34b_b79k`, 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.
117
 
118
+ ```python
119
+ import lancedb
 
 
 
 
120
 
121
  db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data")
122
  tbl = db.open_table("validation")
123
 
124
+ seed = (
125
+ tbl.search()
126
+ .select(["question_emb", "question", "answer"])
127
+ .limit(1)
128
+ .offset(42)
129
+ .to_list()[0]
130
+ )
131
+
132
+ hits = (
133
+ tbl.search(seed["question_emb"], vector_column_name="image_emb")
134
  .metric("cosine")
135
+ .select(["image_id", "question", "answer", "ocr_tokens"])
136
  .limit(10)
137
  .to_list()
138
  )
139
+ print("query question:", seed["question"], "->", seed["answer"])
140
+ for r in hits:
141
+ print(f" {r['image_id']:>14} {r['question'][:60]} ocr={r['ocr_tokens'][:5]}")
142
  ```
143
 
144
+ Because the CLIP embeddings are cosine-normalized, cosine is the right metric and the first hit will often be the source row itself. Swap `vector_column_name="image_emb"` for `question_emb` to find paraphrased questions instead of visually similar images.
145
+
146
+ Because the dataset also ships an `INVERTED` index on `question` and `answer`, the same query can be issued as a hybrid search that combines the dense vector with a literal keyword match. This is particularly useful for TextVQA, where a brand name or sign content like "stop" must literally appear in the question (or eventually, the answer) while CLIP handles the visual side.
147
+
148
+ ```python
149
+ hybrid_hits = (
150
+ tbl.search(query_type="hybrid", vector_column_name="image_emb")
151
+ .vector(seed["question_emb"])
152
+ .text("brand name")
153
+ .select(["image_id", "question", "answer", "ocr_tokens"])
154
+ .limit(10)
155
+ .to_list()
156
+ )
157
+ for r in hybrid_hits:
158
+ print(f" {r['image_id']:>14} {r['question'][:60]} -> {r['answer']}")
159
+ ```
160
+
161
+ Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency.
162
+
163
+ ## Curate
164
+
165
+ Curation passes for TextVQA usually combine an OCR-driven structural filter (does this image actually contain a meaningful amount of detected text?) with a content predicate on the question or the canonical answer, so the candidate set is both visually interesting and topically focused. 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.
166
 
167
  ```python
168
  import lancedb
 
170
  db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data")
171
  tbl = db.open_table("validation")
172
 
173
+ candidates = (
174
+ tbl.search()
175
+ .where(
176
+ "array_length(ocr_tokens) >= 5 AND question LIKE '%brand%' AND length(answer) > 0",
177
+ prefilter=True,
178
+ )
179
+ .select(["question_id", "image_id", "question", "answer", "ocr_tokens"])
180
+ .limit(500)
181
  .to_list()
182
  )
183
+ print(f"{len(candidates)} candidates; first: {candidates[0]['question']} -> {candidates[0]['answer']}")
184
  ```
185
 
186
+ 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 question, answer, and OCR-token strings rather than JPEG bytes.
187
+
188
+ ## Evolve
189
+
190
+ 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 `ocr_token_count`, an `is_yes_no_question` flag, and an `answer_length` integer, any of which can then be used directly in `where` clauses without recomputing the predicate on every query.
191
+
192
+ > **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.
193
+
194
+ ```python
195
+ import lancedb
196
+
197
+ db = lancedb.connect("./textvqa-lance/data") # local copy required for writes
198
+ tbl = db.open_table("validation")
199
+
200
+ tbl.add_columns({
201
+ "ocr_token_count": "array_length(ocr_tokens)",
202
+ "is_yes_no_question": "lower(answer) IN ('yes', 'no')",
203
+ "answer_length": "length(answer)",
204
+ "question_length": "length(question)",
205
+ })
206
+ ```
207
+
208
+ If the values you want to attach already live in another table (a stronger OCR system's tokens, a model's predicted answer, an annotator-disagreement score), merge them in by joining on `question_id`:
209
+
210
+ ```python
211
+ import pyarrow as pa
212
+
213
+ predictions = pa.table({
214
+ "question_id": pa.array(["34602", "34603"]),
215
+ "model_answer": pa.array(["pepsi", "exit"]),
216
+ "model_confidence": pa.array([0.88, 0.72]),
217
+ })
218
+ tbl.merge(predictions, on="question_id")
219
+ ```
220
+
221
+ 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 (e.g., running an alternate OCR engine over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/).
222
+
223
+ ## Train
224
+
225
+ 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 TextVQA fine-tune that needs OCR conditioning, project the JPEG bytes, the question, the OCR tokens, and the canonical answer; columns added in the Evolve section above cost nothing per batch until they are explicitly projected.
226
+
227
+ ```python
228
+ import lancedb
229
+ from lancedb.permutation import Permutation
230
+ from torch.utils.data import DataLoader
231
+
232
+ db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data")
233
+ tbl = db.open_table("train")
234
+
235
+ train_ds = Permutation.identity(tbl).select_columns(["image", "question", "ocr_tokens", "answer"])
236
+ loader = DataLoader(train_ds, batch_size=64, shuffle=True, num_workers=4)
237
+
238
+ for batch in loader:
239
+ # batch carries only the projected columns; decode the JPEG bytes,
240
+ # tokenize the question and OCR tokens, forward through the VLM,
241
+ # compute the loss against `answer`...
242
+ ...
243
+ ```
244
+
245
+ 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 training a lightweight reranker or a linear probe on top of frozen CLIP features.
246
+
247
+ ## Versioning
248
+
249
+ 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.
250
+
251
+ ```python
252
+ import lancedb
253
+
254
+ db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data")
255
+ tbl = db.open_table("validation")
256
+
257
+ print("Current version:", tbl.version)
258
+ print("History:", tbl.list_versions())
259
+ print("Tags:", tbl.tags.list())
260
+ ```
261
+
262
+ Once you have a local copy, tag a version for reproducibility:
263
+
264
+ ```python
265
+ local_db = lancedb.connect("./textvqa-lance/data")
266
+ local_tbl = local_db.open_table("validation")
267
+ local_tbl.tags.create("openclip-vitb32-v1", local_tbl.version)
268
+ ```
269
+
270
+ A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one:
271
+
272
+ ```python
273
+ tbl_v1 = db.open_table("validation", version="openclip-vitb32-v1")
274
+ tbl_v5 = db.open_table("validation", version=5)
275
+ ```
276
+
277
+ Pinning supports two workflows. A retrieval system locked to `openclip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added OCR systems or model predictions 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, questions, and OCR tokens, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking.
278
+
279
+ ## Materialize a subset
280
+
281
+ 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.
282
+
283
+ ```python
284
+ import lancedb
285
+
286
+ remote_db = lancedb.connect("hf://datasets/lance-format/textvqa-lance/data")
287
+ remote_tbl = remote_db.open_table("train")
288
+
289
+ batches = (
290
+ remote_tbl.search()
291
+ .where("array_length(ocr_tokens) >= 5")
292
+ .select(["question_id", "image_id", "image", "question", "answer", "ocr_tokens", "image_emb", "question_emb"])
293
+ .to_batches()
294
+ )
295
+
296
+ local_db = lancedb.connect("./textvqa-ocr-rich")
297
+ local_db.create_table("train", batches)
298
+ ```
299
 
300
+ The resulting `./textvqa-ocr-rich` 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/textvqa-lance/data` for `./textvqa-ocr-rich`.
 
 
301
 
302
  ## Source & license
303