prrao87 commited on
Commit
d4145c2
·
verified ·
1 Parent(s): 61ca508

Update README with LanceDB examples

Browse files
Files changed (1) hide show
  1. README.md +167 -71
README.md CHANGED
@@ -3,6 +3,7 @@ license: mit
3
  task_categories:
4
  - image-classification
5
  - image-feature-extraction
 
6
  language:
7
  - en
8
  tags:
@@ -16,40 +17,51 @@ size_categories:
16
  ---
17
  # MNIST (Lance Format)
18
 
19
- A Lance-formatted version of the classic [MNIST handwritten-digit dataset](https://huggingface.co/datasets/ylecun/mnist) with **70,000 28×28 grayscale digits** stored inline alongside CLIP image embeddings and a pre-built ANN index.
20
 
21
  ## Key features
22
 
23
- - All multimodal data (image bytes + embeddings) stored **inline** in the same Lance dataset — no sidecar files, no external image folders.
24
- - **Pre-computed CLIP embeddings** (OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k`, 512-dim, L2-normalized) shipped with an `IVF_PQ` index for instant similarity search.
25
- - **BTREE index on `label`** and **BITMAP index on `label_name`** for sub-millisecond filtering.
26
- - Standard train/test splits, ready to use with `lance.dataset(...)` or `datasets.load_dataset(...)`.
27
 
28
  ## Splits
29
 
30
  | Split | Rows |
31
  |-------|------|
32
- | `train` | 60,000 |
33
- | `test` | 10,000 |
34
 
35
  ## Schema
36
 
37
  | Column | Type | Notes |
38
  |---|---|---|
39
- | `id` | `int64` | Row index within the split |
40
  | `image` | `large_binary` | Inline PNG bytes (28×28 grayscale) |
41
- | `label` | `int32` | Digit class id (0-9) |
42
- | `label_name` | `string` | Human-readable class (`"0".."9"`) |
43
  | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) |
44
 
45
  ## Pre-built indices
46
 
47
- - `IVF_PQ` on `image_emb` — vector similarity search (`metric=cosine`)
48
- - `BTREE` on `label` — fast equality / range filters
49
- - `BITMAP` on `label_name` — fast filters on the 10 class names
 
 
 
 
 
 
 
 
 
50
 
51
  ## Load with `datasets.load_dataset`
52
 
 
 
53
  ```python
54
  import datasets
55
 
@@ -58,18 +70,10 @@ for row in hf_ds.take(3):
58
  print(row["label"], row["label_name"])
59
  ```
60
 
61
- ## Load directly with Lance (recommended)
62
-
63
- ```python
64
- import lance
65
-
66
- ds = lance.dataset("hf://datasets/lance-format/mnist-lance/data/train.lance")
67
- print(ds.count_rows(), ds.schema.names)
68
- print(ds.list_indices())
69
- ```
70
-
71
  ## Load with LanceDB
72
 
 
 
73
  ```python
74
  import lancedb
75
 
@@ -78,31 +82,27 @@ tbl = db.open_table("train")
78
  print(len(tbl))
79
  ```
80
 
81
- > **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:
82
- > ```bash
83
- > hf download lance-format/mnist-lance --repo-type dataset --local-dir ./mnist-lance
84
- > ```
85
- > Then `lance.dataset("./mnist-lance/data/train.lance")`.
86
 
87
- ## Vector search example
88
 
89
  ```python
90
  import lance
91
- import pyarrow as pa
92
 
93
  ds = lance.dataset("hf://datasets/lance-format/mnist-lance/data/train.lance")
94
- emb_field = ds.schema.field("image_emb")
95
- ref = ds.take([0], columns=["image_emb"]).to_pylist()[0]["image_emb"]
96
- query = pa.array([ref], type=emb_field.type)
97
-
98
- neighbors = ds.scanner(
99
- nearest={"column": "image_emb", "q": query[0], "k": 5, "nprobes": 16, "refine_factor": 30},
100
- columns=["id", "label", "label_name"],
101
- ).to_table().to_pylist()
102
- print(neighbors)
103
  ```
104
 
105
- ### LanceDB vector search
 
 
 
 
 
 
 
 
106
 
107
  ```python
108
  import lancedb
@@ -110,64 +110,160 @@ import lancedb
110
  db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data")
111
  tbl = db.open_table("train")
112
 
113
- ref = tbl.search().limit(1).select(["image_emb"]).to_list()[0]
114
- query_embedding = ref["image_emb"]
 
 
 
 
 
115
 
116
- results = (
117
- tbl.search(query_embedding)
118
  .metric("cosine")
119
  .select(["id", "label", "label_name"])
120
- .limit(5)
121
  .to_list()
122
  )
123
- for row in results:
124
- print(row["id"], row["label"], row["label_name"])
 
125
  ```
126
 
127
- ## Filter by class
128
 
129
- ```python
130
- ds = lance.dataset("hf://datasets/lance-format/mnist-lance/data/train.lance")
131
- sevens = ds.scanner(filter="label = 7", columns=["id"], limit=10).to_table()
132
- print(sevens)
133
- ```
134
 
135
- ### Filter by class with LanceDB
136
 
137
  ```python
138
  import lancedb
139
 
140
  db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data")
141
  tbl = db.open_table("train")
142
- sevens = (
 
143
  tbl.search()
144
- .where("label = 7")
145
- .select(["id"])
146
- .limit(10)
147
  .to_list()
148
  )
149
- print(sevens)
150
  ```
151
 
152
- ## Working with images
 
 
 
 
 
 
153
 
154
  ```python
155
- from pathlib import Path
156
- import lance
157
 
158
- ds = lance.dataset("hf://datasets/lance-format/mnist-lance/data/train.lance")
159
- row = ds.take([0], columns=["image", "label"]).to_pylist()[0]
160
- Path("digit_0.png").write_bytes(row["image"])
161
- print("label =", row["label"])
 
 
 
162
  ```
163
 
164
- Images are stored inline as PNG bytes; scanning columns like `label` does not pay the I/O cost of loading image bytes.
165
 
166
- ## Why Lance?
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
- - One dataset for images + embeddings + indices + metadata no sidecar files to manage.
169
- - On-disk vector and full-text indices live next to the data, so search works on both local copies and the Hub.
170
- - Schema evolution lets you add new columns (fresh embeddings, augmentations, model predictions) without rewriting the data ([docs](https://lance.org/guide/data_evolution/)).
171
 
172
  ## Source & license
173
 
 
3
  task_categories:
4
  - image-classification
5
  - image-feature-extraction
6
+ - lance
7
  language:
8
  - en
9
  tags:
 
17
  ---
18
  # MNIST (Lance Format)
19
 
20
+ A Lance-formatted version of the classic [MNIST handwritten-digit dataset](https://huggingface.co/datasets/ylecun/mnist) covering 70,000 28×28 grayscale digits across ten balanced classes. Each row carries inline PNG bytes, the digit label, the human-readable class name, and a cosine-normalized CLIP image embedding, all backed by a bundled `IVF_PQ` vector index plus scalar indices on the label columns and available directly from the Hub at `hf://datasets/lance-format/mnist-lance/data`.
21
 
22
  ## Key features
23
 
24
+ - **Inline PNG bytes** in the `image` column — no sidecar files, no image folders.
25
+ - **Pre-computed CLIP image embeddings** (OpenCLIP `ViT-B-32` / `laion2b_s34b_b79k`, 512-dim, cosine-normalized) with a bundled `IVF_PQ` index.
26
+ - **Scalar indices on both label columns** — `BTREE` on `label` and `BITMAP` on `label_name` so digit filters and digit-conditioned search are constant-time lookups.
27
+ - **One columnar dataset** — scan labels cheaply, then fetch image bytes only for the rows you want.
28
 
29
  ## Splits
30
 
31
  | Split | Rows |
32
  |-------|------|
33
+ | `train.lance` | 60,000 |
34
+ | `test.lance` | 10,000 |
35
 
36
  ## Schema
37
 
38
  | Column | Type | Notes |
39
  |---|---|---|
40
+ | `id` | `int64` | Row index within the split (natural join key for merges) |
41
  | `image` | `large_binary` | Inline PNG bytes (28×28 grayscale) |
42
+ | `label` | `int32` | Digit class id (09) |
43
+ | `label_name` | `string` | Human-readable class (`"0"`..`"9"`) |
44
  | `image_emb` | `fixed_size_list<float32, 512>` | CLIP image embedding (cosine-normalized) |
45
 
46
  ## Pre-built indices
47
 
48
+ - `IVF_PQ` on `image_emb` — vector similarity search (cosine)
49
+ - `BTREE` on `label` — fast equality and range filters on the digit id
50
+ - `BITMAP` on `label_name` — fast filters across the ten class names
51
+
52
+ ## Why Lance?
53
+
54
+ 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.
55
+ 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.
56
+ 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.
57
+ 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.
58
+ 5. **Versatile Querying**: Supports combining vector similarity search, full-text search, and SQL-style filtering in a single query, accelerated by on-disk indexes.
59
+ 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.
60
 
61
  ## Load with `datasets.load_dataset`
62
 
63
+ You can load Lance datasets via the standard HuggingFace `datasets` interface, suitable if your pipeline already speaks `Dataset` / `IterableDataset` or you want a quick streaming sample without installing anything Lance-specific.
64
+
65
  ```python
66
  import datasets
67
 
 
70
  print(row["label"], row["label_name"])
71
  ```
72
 
 
 
 
 
 
 
 
 
 
 
73
  ## Load with LanceDB
74
 
75
+ 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.
76
+
77
  ```python
78
  import lancedb
79
 
 
82
  print(len(tbl))
83
  ```
84
 
85
+ ## Load with Lance
 
 
 
 
86
 
87
+ `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 or operate on dataset internals — schema, scanner, fragments, and the list of pre-built indices.
88
 
89
  ```python
90
  import lance
 
91
 
92
  ds = lance.dataset("hf://datasets/lance-format/mnist-lance/data/train.lance")
93
+ print(ds.count_rows(), ds.schema.names)
94
+ print(ds.list_indices())
 
 
 
 
 
 
 
95
  ```
96
 
97
+ > **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:
98
+ > ```bash
99
+ > hf download lance-format/mnist-lance --repo-type dataset --local-dir ./mnist-lance
100
+ > ```
101
+ > Then point Lance or LanceDB at `./mnist-lance/data`.
102
+
103
+ ## Search
104
+
105
+ The bundled `IVF_PQ` index on `image_emb` turns nearest-neighbor lookup on the 512-d CLIP space into a single call. In production you would encode a query digit through OpenCLIP `ViT-B-32` at runtime and pass the resulting vector to `tbl.search(...)`. The example below uses the embedding already stored in row 42 as a runnable stand-in so the snippet works without any model loaded.
106
 
107
  ```python
108
  import lancedb
 
110
  db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data")
111
  tbl = db.open_table("train")
112
 
113
+ seed = (
114
+ tbl.search()
115
+ .select(["image_emb", "label"])
116
+ .limit(1)
117
+ .offset(42)
118
+ .to_list()[0]
119
+ )
120
 
121
+ hits = (
122
+ tbl.search(seed["image_emb"])
123
  .metric("cosine")
124
  .select(["id", "label", "label_name"])
125
+ .limit(10)
126
  .to_list()
127
  )
128
+ print("query digit:", seed["label"])
129
+ for r in hits:
130
+ print(f" id={r['id']:>5} label={r['label']}")
131
  ```
132
 
133
+ Because the embeddings are cosine-normalized and MNIST digits cluster tightly in CLIP space, near-neighbors of a seed image are dominated by the seed's own digit class — a useful sanity check before swapping in a real query encoder. Tune `metric`, `nprobes`, and `refine_factor` to trade recall against latency.
134
 
135
+ ## Curate
 
 
 
 
136
 
137
+ A typical curation pass for a digit-classification workflow narrows the table to a single digit (or a small set of confusable digits like 4/9 or 3/8) before sampling. Because both label columns are indexed, the filter resolves without scanning the embedding or image bytes; the bounded `.limit(500)` keeps the output small enough to inspect or hand off as a manifest of row ids.
138
 
139
  ```python
140
  import lancedb
141
 
142
  db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data")
143
  tbl = db.open_table("train")
144
+
145
+ candidates = (
146
  tbl.search()
147
+ .where("label IN (4, 9)", prefilter=True)
148
+ .select(["id", "label", "label_name"])
149
+ .limit(500)
150
  .to_list()
151
  )
152
+ print(f"{len(candidates)} 4/9 candidates")
153
  ```
154
 
155
+ The result is a plain list of dictionaries, ready to inspect, persist as a manifest of `id`s, or feed into the Evolve and Train workflows below. The `image` and `image_emb` columns are never read, so the network traffic for a 500-row candidate scan is dominated by the tiny label payload.
156
+
157
+ ## Evolve
158
+
159
+ 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_target_class` flag for binary one-vs-rest experiments and an `is_curvy_digit` flag that groups digits with curved strokes, either of which can then be used directly in `where` clauses without recomputing the predicate on every query.
160
+
161
+ > **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 corpus first.
162
 
163
  ```python
164
+ import lancedb
 
165
 
166
+ db = lancedb.connect("./mnist-lance/data") # local copy required for writes
167
+ tbl = db.open_table("train")
168
+
169
+ tbl.add_columns({
170
+ "is_target_class": "label = 7",
171
+ "is_curvy_digit": "label IN (0, 3, 6, 8, 9)",
172
+ })
173
  ```
174
 
175
+ If the values you want to attach already live in another table (offline labels from a stronger model, classifier predictions, per-row confidence scores), merge them in by joining on the `id` column:
176
 
177
+ ```python
178
+ import pyarrow as pa
179
+
180
+ predictions = pa.table({
181
+ "id": pa.array([0, 1, 2], type=pa.int64()),
182
+ "pred_label": pa.array([5, 0, 4], type=pa.int32()),
183
+ "pred_conf": pa.array([0.97, 0.88, 0.82]),
184
+ })
185
+ tbl.merge(predictions, on="id")
186
+ ```
187
+
188
+ 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 image encoder over the inline PNG bytes), Lance provides a batch-UDF API in the underlying library — see the [Lance data evolution docs](https://lance.org/guide/data_evolution/) for that pattern.
189
+
190
+ ## Train
191
+
192
+ 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 prefetch, shuffling, and batching behave as in any PyTorch pipeline. Columns added in the Evolve section above cost nothing per batch until they are explicitly projected.
193
+
194
+ ```python
195
+ import lancedb
196
+ from lancedb.permutation import Permutation
197
+ from torch.utils.data import DataLoader
198
+
199
+ db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data")
200
+ tbl = db.open_table("train")
201
+
202
+ train_ds = Permutation.identity(tbl).select_columns(["image", "label"])
203
+ loader = DataLoader(train_ds, batch_size=256, shuffle=True, num_workers=4)
204
+
205
+ for batch in loader:
206
+ # batch carries only the projected columns; image_emb stays on disk.
207
+ # decode the PNG bytes, normalize to [0, 1], forward, backward...
208
+ ...
209
+ ```
210
+
211
+ Switching feature sets is a configuration change: passing `["image_emb", "label"]` to `select_columns(...)` on the next run skips PNG decoding entirely and reads only the cached 512-d vectors, which is the right shape for training a linear probe or a lightweight reranker on top of frozen CLIP features.
212
+
213
+ ## Versioning
214
+
215
+ 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.
216
+
217
+ ```python
218
+ import lancedb
219
+
220
+ db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data")
221
+ tbl = db.open_table("train")
222
+
223
+ print("Current version:", tbl.version)
224
+ print("History:", tbl.list_versions())
225
+ print("Tags:", tbl.tags.list())
226
+ ```
227
+
228
+ Once you have a local copy, tag a version for reproducibility:
229
+
230
+ ```python
231
+ local_db = lancedb.connect("./mnist-lance/data")
232
+ local_tbl = local_db.open_table("train")
233
+ local_tbl.tags.create("clip-vitb32-v1", local_tbl.version)
234
+ ```
235
+
236
+ A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one:
237
+
238
+ ```python
239
+ tbl_v1 = db.open_table("train", version="clip-vitb32-v1")
240
+ tbl_v5 = db.open_table("train", version=5)
241
+ ```
242
+
243
+ Pinning supports two workflows. A retrieval system locked to `clip-vitb32-v1` keeps returning stable results while the dataset evolves in parallel; newly added prediction columns or relabelings do not change what the tag resolves to. A training experiment pinned to the same tag can be rerun later against the exact same digits and labels, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking.
244
+
245
+ ## Materialize a subset
246
+
247
+ 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.
248
+
249
+ ```python
250
+ import lancedb
251
+
252
+ remote_db = lancedb.connect("hf://datasets/lance-format/mnist-lance/data")
253
+ remote_tbl = remote_db.open_table("train")
254
+
255
+ batches = (
256
+ remote_tbl.search()
257
+ .where("label IN (4, 9)")
258
+ .select(["id", "image", "label", "label_name", "image_emb"])
259
+ .to_batches()
260
+ )
261
+
262
+ local_db = lancedb.connect("./mnist-4-vs-9")
263
+ local_db.create_table("train", batches)
264
+ ```
265
 
266
+ The resulting `./mnist-4-vs-9` 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/mnist-lance/data` for `./mnist-4-vs-9`.
 
 
267
 
268
  ## Source & license
269