prrao87 commited on
Commit
a7ce06f
·
verified ·
1 Parent(s): 7ec2d56

Update README with LanceDB examples

Browse files
Files changed (1) hide show
  1. README.md +180 -96
README.md CHANGED
@@ -4,6 +4,7 @@ task_categories:
4
  - image-to-text
5
  - image-text-to-text
6
  - image-feature-extraction
 
7
  language:
8
  - en
9
  tags:
@@ -18,127 +19,144 @@ size_categories:
18
  ---
19
  # Flickr30k (Lance Format)
20
 
21
- Lance-formatted version of [Flickr30k](https://shannon.cs.illinois.edu/DenotationGraph/) (re-distributed via [`lmms-lab/flickr30k`](https://huggingface.co/datasets/lmms-lab/flickr30k)) **31,783 images, each paired with 5 human-written captions**, with CLIP image **and** text embeddings stored inline and pre-built ANN indices on both.
22
 
23
  ## Key features
24
 
25
- - **Inline images** — full JPEG bytes per row.
26
- - **Pre-computed CLIP embeddings** for both image and caption text — `IVF_PQ` indices on both columns let you do cross-modal retrieval (image→caption or caption→image) without any model at query time.
27
- - **Full-text inverted index** on the canonical caption.
28
- - Self-contained: no sidecar files or external image downloads.
 
 
 
 
 
 
29
 
30
  ## Schema
31
 
32
  | Column | Type | Notes |
33
  |---|---|---|
34
- | `id` | `int64` | Row index |
35
  | `image` | `large_binary` | Inline JPEG bytes |
36
  | `image_id` | `string` | Original Flickr image id |
37
- | `filename` | `string` | Original filename (e.g. `1000092795.jpg`) |
38
  | `captions` | `list<string>` | All 5 captions for the image |
39
- | `caption` | `string` | First caption — used as canonical text for FTS / quick browsing |
40
  | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) |
41
  | `text_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the canonical caption |
42
 
43
  ## Pre-built indices
44
 
45
- - `IVF_PQ` on `image_emb` — `metric=cosine`
46
- - `IVF_PQ` on `text_emb` — `metric=cosine` (cross-modal retrieval works out of the box)
47
- - `INVERTED` on `caption`
48
- - `BTREE` on `image_id`
49
 
50
- ## Splits
51
 
52
- A single `train.lance` table containing all 31,783 rows (the `lmms-lab/flickr30k` redistribution exposes them as a single split). The original train/val/test labels are not preserved in the source parquet.
 
 
 
 
 
53
 
54
- ## Load with Lance
 
 
55
 
56
  ```python
57
- import lance
58
 
59
- ds = lance.dataset("hf://datasets/lance-format/flickr30k-lance/data/train.lance")
60
- print(ds.count_rows(), ds.schema.names, ds.list_indices())
 
61
  ```
62
 
63
  ## Load with LanceDB
64
 
65
- 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.
66
 
67
  ```python
68
  import lancedb
69
 
70
  db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data")
71
  tbl = db.open_table("train")
72
- print(f"LanceDB table opened with {len(tbl)} image-caption pairs")
73
  ```
74
 
75
- ## Cross-modal text→image search
 
 
76
 
77
  ```python
78
  import lance
79
- import pyarrow as pa
80
- import open_clip
81
- import torch
82
-
83
- # 1. Encode the query text once with the same CLIP model used at conversion.
84
- model, _, _ = open_clip.create_model_and_transforms("ViT-B-32", pretrained="laion2b_s34b_b79k")
85
- tokenizer = open_clip.get_tokenizer("ViT-B-32")
86
- model = model.eval().cuda().half()
87
- with torch.no_grad():
88
- q = model.encode_text(tokenizer(["a man surfing at sunset"]).cuda())
89
- q = (q / q.norm(dim=-1, keepdim=True)).float().cpu().numpy()[0]
90
 
91
  ds = lance.dataset("hf://datasets/lance-format/flickr30k-lance/data/train.lance")
92
- emb_field = ds.schema.field("image_emb")
93
- query = pa.array([q.tolist()], type=emb_field.type)
94
-
95
- # 2. Nearest-neighbour search against the image embedding index.
96
- hits = ds.scanner(
97
- nearest={"column": "image_emb", "q": query[0], "k": 10, "nprobes": 16, "refine_factor": 30},
98
- columns=["image_id", "caption"],
99
- ).to_table().to_pylist()
100
- for h in hits:
101
- print(h)
102
  ```
103
 
104
- ### LanceDB cross-modal text→image search
 
 
 
 
105
 
106
- ```python
107
- import lancedb, open_clip, torch
 
108
 
109
- model, _, _ = open_clip.create_model_and_transforms("ViT-B-32", pretrained="laion2b_s34b_b79k")
110
- tokenizer = open_clip.get_tokenizer("ViT-B-32")
111
- model = model.eval().cuda().half()
112
- with torch.no_grad():
113
- q = model.encode_text(tokenizer(["a man surfing at sunset"]).cuda())
114
- q = (q / q.norm(dim=-1, keepdim=True)).float().cpu().numpy()[0]
115
 
116
  db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data")
117
  tbl = db.open_table("train")
118
 
119
- results = (
120
- tbl.search(q.tolist(), vector_column_name="image_emb")
 
 
 
 
 
 
 
 
121
  .metric("cosine")
122
  .select(["image_id", "caption"])
123
  .limit(10)
124
  .to_list()
125
  )
 
 
 
126
  ```
127
 
128
- ## Image→caption (image-to-text retrieval)
 
 
129
 
130
  ```python
131
- ds = lance.dataset("hf://datasets/lance-format/flickr30k-lance/data/train.lance")
132
- ref = ds.take([0], columns=["image_emb", "caption"]).to_pylist()[0]
133
- emb_field = ds.schema.field("text_emb")
134
- query = pa.array([ref["image_emb"]], type=emb_field.type)
135
- neighbors = ds.scanner(
136
- nearest={"column": "text_emb", "q": query[0], "k": 10},
137
- columns=["caption"],
138
- ).to_table().to_pylist()
 
 
139
  ```
140
 
141
- ### LanceDB image→caption search
 
 
 
 
142
 
143
  ```python
144
  import lancedb
@@ -146,61 +164,127 @@ import lancedb
146
  db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data")
147
  tbl = db.open_table("train")
148
 
149
- ref = tbl.search().limit(1).select(["image_emb", "caption"]).to_list()[0]
150
- query_embedding = ref["image_emb"]
151
-
152
- results = (
153
- tbl.search(query_embedding, vector_column_name="text_emb")
154
- .metric("cosine")
155
- .select(["caption"])
156
- .limit(10)
157
  .to_list()
158
  )
 
159
  ```
160
 
161
- ## Full-text search on captions
 
 
 
 
 
 
162
 
163
  ```python
164
- import lance
165
- ds = lance.dataset("hf://datasets/lance-format/flickr30k-lance/data/train.lance")
166
- hits = ds.scanner(
167
- full_text_query="dog playing in the snow",
168
- columns=["image_id", "caption"],
169
- limit=10,
170
- ).to_table().to_pylist()
 
 
171
  ```
172
 
173
- ### LanceDB full-text search
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
  ```python
176
  import lancedb
 
 
177
 
178
  db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data")
179
  tbl = db.open_table("train")
180
 
181
- results = (
182
- tbl.search("dog playing in the snow")
183
- .select(["image_id", "caption"])
184
- .limit(10)
185
- .to_list()
186
- )
 
187
  ```
188
 
189
- ## Working with images
 
 
 
 
190
 
191
  ```python
192
- from pathlib import Path
193
- import lance
194
- ds = lance.dataset("hf://datasets/lance-format/flickr30k-lance/data/train.lance")
195
- row = ds.take([0], columns=["image", "filename"]).to_pylist()[0]
196
- Path(row["filename"]).write_bytes(row["image"])
 
 
 
197
  ```
198
 
199
- ## Why Lance?
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
- - One dataset carries images + image embeddings + text embeddings + indices no sidecar files.
202
- - On-disk vector and full-text indices live next to the data, so search works on local copies and on the Hub.
203
- - Schema evolution: add columns (new captions, alternate embeddings, moderation labels) without rewriting the data.
204
 
205
  ## Source & license
206
 
 
4
  - image-to-text
5
  - image-text-to-text
6
  - image-feature-extraction
7
+ - lance
8
  language:
9
  - en
10
  tags:
 
19
  ---
20
  # Flickr30k (Lance Format)
21
 
22
+ A Lance-formatted version of [Flickr30k](https://shannon.cs.illinois.edu/DenotationGraph/), redistributed via [`lmms-lab/flickr30k`](https://huggingface.co/datasets/lmms-lab/flickr30k). Each row is one image with **5 human-written captions**, a cosine-normalized CLIP image embedding, and a cosine-normalized CLIP text embedding of the canonical caption — all stored inline and available directly from the Hub at `hf://datasets/lance-format/flickr30k-lance/data`.
23
 
24
  ## Key features
25
 
26
+ - **Inline JPEG bytes** in the `image` column no sidecar files, no image folders.
27
+ - **Paired CLIP embeddings in the same row** — `image_emb` and `text_emb` (ViT-B/32, 512-dim, cosine-normalized) so cross-modal retrieval is one indexed lookup.
28
+ - **All 5 raw captions kept in `captions`** alongside a `caption` canonical string used for full-text search.
29
+ - **Pre-built ANN, FTS, and scalar indices** covering both embedding columns, the canonical caption, and `image_id`.
30
+
31
+ ## Splits
32
+
33
+ | Split | Rows | Notes |
34
+ |-------|------|-------|
35
+ | `train.lance` | 31,783 | All Flickr30k images; the `lmms-lab/flickr30k` redistribution merges the original train/val/test labels into a single split |
36
 
37
  ## Schema
38
 
39
  | Column | Type | Notes |
40
  |---|---|---|
41
+ | `id` | `int64` | Row index within split (natural join key) |
42
  | `image` | `large_binary` | Inline JPEG bytes |
43
  | `image_id` | `string` | Original Flickr image id |
44
+ | `filename` | `string?` | Original filename (e.g. `1000092795.jpg`) |
45
  | `captions` | `list<string>` | All 5 captions for the image |
46
+ | `caption` | `string` | First caption — canonical text used for FTS |
47
  | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) |
48
  | `text_emb` | `fixed_size_list<float32, 512>` | CLIP text embedding of the canonical caption |
49
 
50
  ## Pre-built indices
51
 
52
+ - `IVF_PQ` on `image_emb` — image-side vector search (cosine)
53
+ - `IVF_PQ` on `text_emb` — text-side vector search (cosine)
54
+ - `INVERTED` (FTS) on `caption` — keyword and hybrid search
55
+ - `BTREE` on `image_id` — fast lookup by Flickr image id
56
 
57
+ ## Why Lance?
58
 
59
+ 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.
60
+ 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.
61
+ 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.
62
+ 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.
63
+ 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes.
64
+ 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.
65
 
66
+ ## Load with `datasets.load_dataset`
67
+
68
+ 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.
69
 
70
  ```python
71
+ import datasets
72
 
73
+ hf_ds = datasets.load_dataset("lance-format/flickr30k-lance", split="train", streaming=True)
74
+ for row in hf_ds.take(3):
75
+ print(row["caption"])
76
  ```
77
 
78
  ## Load with LanceDB
79
 
80
+ 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, Train, Versioning, and Materialize-a-subset sections below.
81
 
82
  ```python
83
  import lancedb
84
 
85
  db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data")
86
  tbl = db.open_table("train")
87
+ print(len(tbl))
88
  ```
89
 
90
+ ## Load with Lance
91
+
92
+ `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.
93
 
94
  ```python
95
  import lance
 
 
 
 
 
 
 
 
 
 
 
96
 
97
  ds = lance.dataset("hf://datasets/lance-format/flickr30k-lance/data/train.lance")
98
+ print(ds.count_rows(), ds.schema.names)
99
+ print(ds.list_indices())
 
 
 
 
 
 
 
 
100
  ```
101
 
102
+ > **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:
103
+ > ```bash
104
+ > hf download lance-format/flickr30k-lance --repo-type dataset --local-dir ./flickr30k-lance
105
+ > ```
106
+ > Then point Lance or LanceDB at `./flickr30k-lance/data`.
107
 
108
+ ## Search
109
+
110
+ The bundled `IVF_PQ` index on `image_emb` makes cross-modal text→image retrieval a single call: encode a text query 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 `text_emb` already stored in row 42 as a runnable stand-in for "the CLIP encoding of a caption", so the snippet works without any model loaded.
111
 
112
+ ```python
113
+ import lancedb
 
 
 
 
114
 
115
  db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data")
116
  tbl = db.open_table("train")
117
 
118
+ seed = (
119
+ tbl.search()
120
+ .select(["text_emb", "caption"])
121
+ .limit(1)
122
+ .offset(42)
123
+ .to_list()[0]
124
+ )
125
+
126
+ hits = (
127
+ tbl.search(seed["text_emb"], vector_column_name="image_emb")
128
  .metric("cosine")
129
  .select(["image_id", "caption"])
130
  .limit(10)
131
  .to_list()
132
  )
133
+ print("query caption:", seed["caption"])
134
+ for r in hits:
135
+ print(f" {r['image_id']:>12} {r['caption'][:70]}")
136
  ```
137
 
138
+ Because OpenAI-style CLIP embeddings are normalized, cosine is the right metric and the first hit will typically be the source image itself — a useful sanity check. Swap `vector_column_name="image_emb"` for `text_emb` to do text→text retrieval against the canonical captions instead.
139
+
140
+ Because the dataset also ships an `INVERTED` index on `caption`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges the two result lists and reranks them in a single call, which is useful when a phrase like "dog playing in the snow" must literally appear in the caption but you still want CLIP to do the heavy lifting on visual similarity.
141
 
142
  ```python
143
+ hybrid_hits = (
144
+ tbl.search(query_type="hybrid", vector_column_name="image_emb")
145
+ .vector(seed["text_emb"])
146
+ .text("dog playing in the snow")
147
+ .select(["image_id", "caption"])
148
+ .limit(10)
149
+ .to_list()
150
+ )
151
+ for r in hybrid_hits:
152
+ print(f" {r['image_id']:>12} {r['caption'][:70]}")
153
  ```
154
 
155
+ Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency.
156
+
157
+ ## Curate
158
+
159
+ A typical curation pass for a captioning or contrastive-training workflow combines a content filter on the captions with a structural filter on the row. 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.
160
 
161
  ```python
162
  import lancedb
 
164
  db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data")
165
  tbl = db.open_table("train")
166
 
167
+ candidates = (
168
+ tbl.search("surfer OR surfboard OR wave")
169
+ .where("array_length(captions) = 5", prefilter=True)
170
+ .select(["image_id", "caption", "captions"])
171
+ .limit(500)
 
 
 
172
  .to_list()
173
  )
174
+ print(f"{len(candidates)} candidates; first caption: {candidates[0]['caption'][:80]}")
175
  ```
176
 
177
+ The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `image_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 caption text rather than JPEG bytes.
178
+
179
+ ## Evolve
180
+
181
+ 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 `num_captions` and a `long_caption` flag, either of which can then be used directly in `where` clauses without recomputing the predicate on every query.
182
+
183
+ > **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.
184
 
185
  ```python
186
+ import lancedb
187
+
188
+ db = lancedb.connect("./flickr30k-lance/data") # local copy required for writes
189
+ tbl = db.open_table("train")
190
+
191
+ tbl.add_columns({
192
+ "num_captions": "array_length(captions)",
193
+ "long_caption": "length(caption) >= 80",
194
+ })
195
  ```
196
 
197
+ If the values you want to attach already live in another table (offline labels, classifier predictions, an aesthetic or NSFW score, a second-pass caption from a different model), merge them in by joining on `image_id`:
198
+
199
+ ```python
200
+ import pyarrow as pa
201
+
202
+ labels = pa.table({
203
+ "image_id": pa.array(["1000092795", "10002456"]),
204
+ "scene_label": pa.array(["outdoor", "indoor"]),
205
+ })
206
+ tbl.merge(labels, on="image_id")
207
+ ```
208
+
209
+ 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 a second CLIP variant over the image bytes), Lance provides a batch-UDF API — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/).
210
+
211
+ ## Train
212
+
213
+ 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 CLIP-style contrastive run, project the JPEG bytes and a sampled caption; for a reranker or probe on top of frozen features, project the precomputed embeddings instead.
214
 
215
  ```python
216
  import lancedb
217
+ from lancedb.permutation import Permutation
218
+ from torch.utils.data import DataLoader
219
 
220
  db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data")
221
  tbl = db.open_table("train")
222
 
223
+ train_ds = Permutation.identity(tbl).select_columns(["image", "caption"])
224
+ loader = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=4)
225
+
226
+ for batch in loader:
227
+ # batch carries only the projected columns; decode the JPEG bytes,
228
+ # tokenize the captions, encode, contrastive loss...
229
+ ...
230
  ```
231
 
232
+ Switching feature sets is a configuration change: passing `["image_emb", "text_emb"]` 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.
233
+
234
+ ## Versioning
235
+
236
+ 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.
237
 
238
  ```python
239
+ import lancedb
240
+
241
+ db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data")
242
+ tbl = db.open_table("train")
243
+
244
+ print("Current version:", tbl.version)
245
+ print("History:", tbl.list_versions())
246
+ print("Tags:", tbl.tags.list())
247
  ```
248
 
249
+ Once you have a local copy, tag a version for reproducibility:
250
+
251
+ ```python
252
+ local_db = lancedb.connect("./flickr30k-lance/data")
253
+ local_tbl = local_db.open_table("train")
254
+ local_tbl.tags.create("clip-vitb32-v1", local_tbl.version)
255
+ ```
256
+
257
+ A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one:
258
+
259
+ ```python
260
+ tbl_v1 = db.open_table("train", version="clip-vitb32-v1")
261
+ tbl_v5 = db.open_table("train", version=5)
262
+ ```
263
+
264
+ Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel — newly added embeddings or labels 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 captions, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking.
265
+
266
+ ## Materialize a subset
267
+
268
+ 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.
269
+
270
+ ```python
271
+ import lancedb
272
+
273
+ remote_db = lancedb.connect("hf://datasets/lance-format/flickr30k-lance/data")
274
+ remote_tbl = remote_db.open_table("train")
275
+
276
+ batches = (
277
+ remote_tbl.search("surfer OR surfboard OR wave")
278
+ .where("array_length(captions) = 5")
279
+ .select(["image_id", "image", "caption", "captions", "image_emb", "text_emb"])
280
+ .to_batches()
281
+ )
282
+
283
+ local_db = lancedb.connect("./flickr30k-surf-subset")
284
+ local_db.create_table("train", batches)
285
+ ```
286
 
287
+ The resulting `./flickr30k-surf-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/flickr30k-lance/data` for `./flickr30k-surf-subset`.
 
 
288
 
289
  ## Source & license
290