prrao87 commited on
Commit
f35ee6f
·
verified ·
1 Parent(s): e663404

Update README with LanceDB examples

Browse files
Files changed (1) hide show
  1. README.md +184 -67
README.md CHANGED
@@ -3,6 +3,7 @@ license: cc-by-sa-4.0
3
  task_categories:
4
  - question-answering
5
  - text-retrieval
 
6
  language:
7
  - en
8
  tags:
@@ -17,14 +18,14 @@ size_categories:
17
  ---
18
  # SQuAD v2 (Lance Format)
19
 
20
- Lance-formatted version of [SQuAD v2](https://huggingface.co/datasets/rajpurkar/squad_v2) — Stanford Question Answering Dataset, version 2 — with **MiniLM sentence embeddings** stored inline alongside the questions, contexts, and answers.
21
 
22
- ## Why this version?
23
 
24
- - **One self-contained Lance dataset** with 130k+ Wikipedia-grounded questions and reference answers.
25
- - **Pre-computed text embeddings** (`sentence-transformers/all-MiniLM-L6-v2`, 384-dim, L2-normalized) on the question column with an `IVF_PQ` index instant semantic question retrieval.
26
- - **Full-text inverted indices** on both `question` and `context` for keyword search.
27
- - **BITMAP** on `is_impossible` for fast filtering between answerable and unanswerable questions.
28
 
29
  ## Splits
30
 
@@ -37,7 +38,7 @@ Lance-formatted version of [SQuAD v2](https://huggingface.co/datasets/rajpurkar/
37
 
38
  | Column | Type | Notes |
39
  |---|---|---|
40
- | `id` | `string` | SQuAD question id |
41
  | `title` | `string` | Wikipedia article title |
42
  | `context` | `string` | Paragraph the question was generated from |
43
  | `question` | `string` | The question text |
@@ -48,85 +49,113 @@ Lance-formatted version of [SQuAD v2](https://huggingface.co/datasets/rajpurkar/
48
 
49
  ## Pre-built indices
50
 
51
- - `IVF_PQ` on `question_emb` — `metric=cosine`
52
- - `INVERTED` on `question` and `context`
53
- - `BTREE` on `id` and `title`
54
- - `BITMAP` on `is_impossible`
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- ## Quick start
57
 
58
  ```python
59
- import lance
60
 
61
- ds = lance.dataset("hf://datasets/lance-format/squad-v2-lance/data/validation.lance")
62
- print(ds.count_rows(), ds.schema.names, ds.list_indices())
 
63
  ```
64
 
65
  ## Load with LanceDB
66
 
67
- 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.
68
 
69
  ```python
70
  import lancedb
71
 
72
  db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data")
73
- tbl = db.open_table("validation")
74
- print(f"LanceDB table opened with {len(tbl)} questions")
75
  ```
76
 
77
- ## Semantic question retrieval
 
 
78
 
79
  ```python
80
  import lance
81
- import pyarrow as pa
82
- from sentence_transformers import SentenceTransformer
83
-
84
- encoder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", device="cuda")
85
- q_vec = encoder.encode(["what year was the eiffel tower built?"], normalize_embeddings=True)[0]
86
 
87
  ds = lance.dataset("hf://datasets/lance-format/squad-v2-lance/data/train.lance")
88
- emb_field = ds.schema.field("question_emb")
89
- query = pa.array([q_vec.tolist()], type=emb_field.type)
90
-
91
- hits = ds.scanner(
92
- nearest={"column": "question_emb", "q": query[0], "k": 10, "nprobes": 16, "refine_factor": 30},
93
- columns=["id", "title", "question", "answers"],
94
- ).to_table().to_pylist()
95
  ```
96
 
97
- ### LanceDB semantic question retrieval
 
 
 
 
 
 
 
 
98
 
99
  ```python
100
  import lancedb
101
- from sentence_transformers import SentenceTransformer
102
-
103
- encoder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", device="cuda")
104
- q_vec = encoder.encode(["what year was the eiffel tower built?"], normalize_embeddings=True)[0]
105
 
106
  db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data")
107
  tbl = db.open_table("train")
108
 
109
- results = (
110
- tbl.search(q_vec.tolist(), vector_column_name="question_emb")
 
 
 
 
 
 
 
 
111
  .metric("cosine")
 
112
  .select(["id", "title", "question", "answers"])
113
  .limit(10)
114
  .to_list()
115
  )
 
 
116
  ```
117
 
118
- ## Full-text search on contexts
119
 
120
  ```python
121
- ds = lance.dataset("hf://datasets/lance-format/squad-v2-lance/data/train.lance")
122
- hits = ds.scanner(
123
- full_text_query="great pyramid of giza",
124
- columns=["title", "question", "context"],
125
- limit=5,
126
- ).to_table().to_pylist()
 
 
 
 
 
127
  ```
128
 
129
- ### LanceDB full-text search
 
 
 
 
130
 
131
  ```python
132
  import lancedb
@@ -134,46 +163,134 @@ import lancedb
134
  db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data")
135
  tbl = db.open_table("train")
136
 
137
- results = (
138
- tbl.search("great pyramid of giza")
139
- .select(["title", "question", "context"])
140
- .limit(5)
 
141
  .to_list()
142
  )
 
143
  ```
144
 
145
- ## Filter answerable vs impossible questions
 
 
 
 
 
 
146
 
147
  ```python
148
- ds = lance.dataset("hf://datasets/lance-format/squad-v2-lance/data/validation.lance")
149
- impossible = ds.scanner(filter="is_impossible = true", columns=["question"], limit=5).to_table()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  ```
151
 
152
- ### Filter with LanceDB
 
 
 
 
153
 
154
  ```python
155
  import lancedb
 
 
156
 
157
  db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data")
158
- tbl = db.open_table("validation")
159
- impossible = (
160
- tbl.search()
161
- .where("is_impossible = true")
162
- .select(["question"])
163
- .limit(5)
164
- .to_list()
165
  )
 
 
 
 
 
 
166
  ```
167
 
168
- ## Why Lance?
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
- - One dataset carries questions + contexts + answers + embeddings + indices no sidecar files.
171
- - On-disk vector and full-text indices live next to the data, so search works on local copies and on the Hub.
172
- - Schema evolution: add columns (alternate embeddings, model predictions, task labels) without rewriting the data.
173
 
174
  ## Source & license
175
 
176
- Converted from [`rajpurkar/squad_v2`](https://huggingface.co/datasets/rajpurkar/squad_v2). SQuAD v2 is released under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/).
177
 
178
  ## Citation
179
 
@@ -182,6 +299,6 @@ Converted from [`rajpurkar/squad_v2`](https://huggingface.co/datasets/rajpurkar/
182
  title={Know What You Don't Know: Unanswerable Questions for SQuAD},
183
  author={Rajpurkar, Pranav and Jia, Robin and Liang, Percy},
184
  journal={Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Short Papers)},
185
- year={2018},
186
  }
187
  ```
 
3
  task_categories:
4
  - question-answering
5
  - text-retrieval
6
+ - lance
7
  language:
8
  - en
9
  tags:
 
18
  ---
19
  # SQuAD v2 (Lance Format)
20
 
21
+ A Lance-formatted version of [SQuAD v2](https://huggingface.co/datasets/rajpurkar/squad_v2) — the Stanford Question Answering Dataset with both answerable and deliberately unanswerable questions over Wikipedia passages — with MiniLM question embeddings stored inline and ready for retrieval at `hf://datasets/lance-format/squad-v2-lance/data`.
22
 
23
+ ## Key features
24
 
25
+ - **Span-extraction QA over Wikipedia** with 130k+ training questions and an `is_impossible` flag that cleanly separates answerable from unanswerable items.
26
+ - **Pre-computed 384-dim question embeddings** (`question_emb`, `sentence-transformers/all-MiniLM-L6-v2`, cosine-normalized) with a bundled `IVF_PQ` index for semantic question retrieval.
27
+ - **Full-text inverted indices** on both `question` and `context` for keyword search alongside dense retrieval.
28
+ - **One columnar dataset** carrying questions, contexts, answer spans, and embeddings together project only the columns each query needs.
29
 
30
  ## Splits
31
 
 
38
 
39
  | Column | Type | Notes |
40
  |---|---|---|
41
+ | `id` | `string` | SQuAD question id (natural join key for merges) |
42
  | `title` | `string` | Wikipedia article title |
43
  | `context` | `string` | Paragraph the question was generated from |
44
  | `question` | `string` | The question text |
 
49
 
50
  ## Pre-built indices
51
 
52
+ - `IVF_PQ` on `question_emb` — `metric=cosine`, vector similarity search
53
+ - `INVERTED` on `question` and `context` — full-text search
54
+ - `BTREE` on `id` and `title` — point lookups and prefix scans
55
+ - `BITMAP` on `is_impossible` — fast filtering between answerable and unanswerable
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/squad-v2-lance", split="validation", streaming=True)
74
+ for row in hf_ds.take(3):
75
+ print(row["question"], "->", row["answers"])
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, Versioning, and Materialize-a-subset sections below.
81
 
82
  ```python
83
  import lancedb
84
 
85
  db = lancedb.connect("hf://datasets/lance-format/squad-v2-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, the list of pre-built indices.
93
 
94
  ```python
95
  import lance
 
 
 
 
 
96
 
97
  ds = lance.dataset("hf://datasets/lance-format/squad-v2-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/squad-v2-lance --repo-type dataset --local-dir ./squad-v2-lance
105
+ > ```
106
+ > Then point Lance or LanceDB at `./squad-v2-lance/data`.
107
+
108
+ ## Search
109
+
110
+ The bundled `IVF_PQ` index on `question_emb` turns semantic question retrieval into a single call. In production you would encode an incoming question through the same MiniLM encoder used at ingest and pass the resulting 384-dim vector to `tbl.search(...)`. The example below uses the embedding from row 42 as a runnable stand-in, then restricts the result to answerable items so the response always carries a usable span.
111
 
112
  ```python
113
  import lancedb
 
 
 
 
114
 
115
  db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data")
116
  tbl = db.open_table("train")
117
 
118
+ seed = (
119
+ tbl.search()
120
+ .select(["question_emb", "question"])
121
+ .limit(1)
122
+ .offset(42)
123
+ .to_list()[0]
124
+ )
125
+
126
+ hits = (
127
+ tbl.search(seed["question_emb"], vector_column_name="question_emb")
128
  .metric("cosine")
129
+ .where("is_impossible = false", prefilter=True)
130
  .select(["id", "title", "question", "answers"])
131
  .limit(10)
132
  .to_list()
133
  )
134
+ for r in hits:
135
+ print(f"{r['title']:30s} | {r['question'][:80]}")
136
  ```
137
 
138
+ Because the recommended setup also builds an `INVERTED` index on both `question` and `context`, the same query can be issued as a hybrid search that combines the dense vector with a keyword query. LanceDB merges and reranks the two result lists in a single call, which is useful when a literal phrase must appear in the passage but the dense side should still drive ranking.
139
 
140
  ```python
141
+ hybrid_hits = (
142
+ tbl.search(query_type="hybrid")
143
+ .vector(seed["question_emb"])
144
+ .text("eiffel tower")
145
+ .where("is_impossible = false", prefilter=True)
146
+ .select(["id", "title", "question", "context", "answers"])
147
+ .limit(10)
148
+ .to_list()
149
+ )
150
+ for r in hybrid_hits:
151
+ print(f"{r['title']:30s} | {r['question'][:80]}")
152
  ```
153
 
154
+ Tune `metric`, `nprobes`, and `refine_factor` on the vector side to trade recall against latency.
155
+
156
+ ## Curate
157
+
158
+ SQuAD v2 has a natural split between answerable and unanswerable questions, and the `is_impossible` boolean — backed by a `BITMAP` index — makes either subset cheap to extract. Stacking predicates inside a single filtered scan keeps the result small and explicit, and the bounded `.limit(1000)` makes it easy to inspect or hand off.
159
 
160
  ```python
161
  import lancedb
 
163
  db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data")
164
  tbl = db.open_table("train")
165
 
166
+ impossible = (
167
+ tbl.search()
168
+ .where("is_impossible = true AND length(question) >= 40", prefilter=True)
169
+ .select(["id", "title", "question", "context"])
170
+ .limit(1000)
171
  .to_list()
172
  )
173
+ print(f"{len(impossible)} hard unanswerable questions; first title: {impossible[0]['title']}")
174
  ```
175
 
176
+ The mirror query long, well-grounded answerable questions — looks identical with the boolean flipped, and the `question_emb` vector is never read by either scan. The result is a plain list of dictionaries, ready to inspect, persist as a manifest of question ids, or hand to the Materialize-a-subset section below for export to a writable local copy.
177
+
178
+ ## Evolve
179
+
180
+ 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 a `question_length`, a `num_answers` count, and a `has_answer` flag — any of which can then be used directly in `where` clauses without recomputing the predicate on every query.
181
+
182
+ > **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.
183
 
184
  ```python
185
+ import lancedb
186
+
187
+ db = lancedb.connect("./squad-v2-lance/data") # local copy required for writes
188
+ tbl = db.open_table("train")
189
+
190
+ tbl.add_columns({
191
+ "question_length": "length(question)",
192
+ "num_answers": "array_length(answers)",
193
+ "has_answer": "NOT is_impossible",
194
+ })
195
+ ```
196
+
197
+ If the values you want to attach already live in another table (offline reader-model predictions, alternate embeddings, span-level labels), merge them in by joining on `id`:
198
+
199
+ ```python
200
+ import pyarrow as pa
201
+
202
+ scores = pa.table({
203
+ "id": pa.array(["56be4db0acb8001400a502ec", "56be4db0acb8001400a502ed"]),
204
+ "reader_score": pa.array([0.91, 0.42]),
205
+ })
206
+ tbl.merge(scores, on="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 different embedding model over the questions), 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 reading-comprehension model the natural projection is the question, the context, and the answer spans together; for a retriever or reranker on top of frozen features, project the precomputed embedding 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/squad-v2-lance/data")
221
+ tbl = db.open_table("train")
222
+
223
+ train_ds = Permutation.identity(tbl).select_columns(
224
+ ["question", "context", "answers", "answer_starts", "is_impossible"]
 
 
 
225
  )
226
+ loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4)
227
+
228
+ for batch in loader:
229
+ # batch carries only the projected columns; question_emb stays on disk.
230
+ # tokenize question+context, build span labels from answer_starts, forward, backward...
231
+ ...
232
  ```
233
 
234
+ Switching feature sets is a configuration change: passing `["question_emb"]` (optionally with `["answers"]` for hard-negative mining) to `select_columns(...)` on the next run reads only the 384-d vectors and skips the bulky `context` strings entirely, which is the right shape for training a retrieval head or reranker on cached embeddings. Columns added in Evolve cost nothing per batch until they are explicitly projected.
235
+
236
+ ## Versioning
237
+
238
+ 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.
239
+
240
+ ```python
241
+ import lancedb
242
+
243
+ db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data")
244
+ tbl = db.open_table("train")
245
+
246
+ print("Current version:", tbl.version)
247
+ print("History:", tbl.list_versions())
248
+ print("Tags:", tbl.tags.list())
249
+ ```
250
+
251
+ Once you have a local copy, tag a version for reproducibility:
252
+
253
+ ```python
254
+ local_db = lancedb.connect("./squad-v2-lance/data")
255
+ local_tbl = local_db.open_table("train")
256
+ local_tbl.tags.create("baseline-v1", local_tbl.version)
257
+ ```
258
+
259
+ A tagged version can be opened by name, or any version reopened by its number, against either the Hub copy or a local one:
260
+
261
+ ```python
262
+ tbl_v1 = db.open_table("train", version="baseline-v1")
263
+ tbl_v5 = db.open_table("train", version=5)
264
+ ```
265
+
266
+ Pinning supports two workflows. A retrieval system locked to `baseline-v1` keeps returning stable results while the dataset evolves in parallel — newly added reader scores 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 questions and contexts, so changes in metrics reflect model changes rather than data drift. Neither workflow needs shadow copies or external manifest tracking.
267
+
268
+ ## Materialize a subset
269
+
270
+ 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 corpus. 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.
271
+
272
+ ```python
273
+ import lancedb
274
+
275
+ remote_db = lancedb.connect("hf://datasets/lance-format/squad-v2-lance/data")
276
+ remote_tbl = remote_db.open_table("train")
277
+
278
+ batches = (
279
+ remote_tbl.search()
280
+ .where("is_impossible = false AND length(question) >= 30")
281
+ .select(["id", "title", "context", "question", "answers", "answer_starts", "question_emb"])
282
+ .to_batches()
283
+ )
284
+
285
+ local_db = lancedb.connect("./squad-v2-answerable")
286
+ local_db.create_table("train", batches)
287
+ ```
288
 
289
+ The resulting `./squad-v2-answerable` is a first-class LanceDB database. Every snippet in the Search, Evolve, Train, and Versioning sections above works against it by swapping `hf://datasets/lance-format/squad-v2-lance/data` for `./squad-v2-answerable`.
 
 
290
 
291
  ## Source & license
292
 
293
+ Converted from [`rajpurkar/squad_v2`](https://huggingface.co/datasets/rajpurkar/squad_v2). SQuAD v2 is distributed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/).
294
 
295
  ## Citation
296
 
 
299
  title={Know What You Don't Know: Unanswerable Questions for SQuAD},
300
  author={Rajpurkar, Pranav and Jia, Robin and Liang, Percy},
301
  journal={Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Short Papers)},
302
+ year={2018}
303
  }
304
  ```