diff --git a/docs/web-tests/py/test_curation_sampling.py b/docs/web-tests/py/test_curation_sampling.py index dd1053fd1..73971a435 100644 --- a/docs/web-tests/py/test_curation_sampling.py +++ b/docs/web-tests/py/test_curation_sampling.py @@ -1,6 +1,8 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +import pytest + def test_sample_dataset(): from tempfile import TemporaryDirectory @@ -25,3 +27,66 @@ def test_sample_dataset(): assert len(selected_ids) == 3 assert len(set(selected_ids)) == 3 assert all(0 <= value < 10 for value in selected_ids) + + +# --8<-- [start:grouped_training_takes] +def take_training_batches(table, version, offset_batches, columns): + from itertools import islice + + table.checkout(version) + offset_batches = iter(offset_batches) + while group := list(islice(offset_batches, 4)): + batch_sizes = [len(batch) for batch in group] + if sum(batch_sizes) > 1024: + raise ValueError("A grouped take can request at most 1,024 rows") + + offsets = [offset for batch in group for offset in batch] + rows = ( + table.take_offsets(offsets, preserve_order=True).select(columns).to_arrow() + ) + if rows.num_rows != len(offsets): + raise ValueError("Some training offsets are missing from the snapshot") + + start = 0 + for size in batch_sizes: + yield rows.slice(start, size) + start += size + + +# --8<-- [end:grouped_training_takes] + + +def test_grouped_training_takes(tmp_db): + writer = tmp_db.create_table( + "training", [{"id": i, "label": i % 2} for i in range(6)] + ) + version = writer.version + writer.delete("id = 0") + table = tmp_db.open_table("training") + offset_batches = iter([[5, 1, 5], [2, 5], [0], [3, 1], [4]]) + + batches = take_training_batches(table, version, offset_batches, ["id"]) + + assert [batch.to_pydict() for batch in batches] == [ + {"id": [5, 1, 5]}, + {"id": [2, 5]}, + {"id": [0]}, + {"id": [3, 1]}, + {"id": [4]}, + ] + + +@pytest.mark.parametrize( + ("offset_batches", "message"), + [ + ([[1], [99, 0]], "Some training offsets are missing"), + ([[0] * 1025], "A grouped take can request at most 1,024 rows"), + ], +) +def test_grouped_training_takes_reject_invalid_group(tmp_db, offset_batches, message): + table = tmp_db.create_table("training", [{"id": 0}, {"id": 1}]) + + batches = take_training_batches(table, table.version, offset_batches, ["id"]) + + with pytest.raises(ValueError, match=message): + next(batches) diff --git a/docs/web/curation/selective-sampling.mdx b/docs/web/curation/selective-sampling.mdx index 89da453b6..6505bddf4 100644 --- a/docs/web/curation/selective-sampling.mdx +++ b/docs/web/curation/selective-sampling.mdx @@ -9,6 +9,8 @@ availability: enterprise: available --- +import { PyGroupedTrainingTakes } from '/snippets/curation_sampling.mdx'; + Selective sampling fetches specific, already-known rows -- by row ID, row address or offset -- rather than drawing a random fraction of the table. Use it to re-fetch rows a previous query identified, resume from a saved @@ -113,6 +115,30 @@ earlier query's `_rowid` column -- but unlike offsets, a row ID keeps addressing the same logical row even after compaction, as long as the table has stable row IDs enabled. +### Group training batches {#group-training-batches} + +If your Python training sampler produces batches of offsets, combine several +batches into one `take_offsets` call to reduce LanceDB Enterprise requests. +Use a dedicated table handle and the version your sampler used to generate the +offsets. Keep that version checked out for the entire read. + +With 256 offsets per training batch, the example reads up to four batches per +call. It rejects groups larger than 1,024 offsets. Larger groups use fewer +requests and increase the memory the SDK needs to buffer and reorder results. +Select only the columns your model needs and size each group for the width of +those columns. + + +{PyGroupedTrainingTakes} + + +Call `take_training_batches(table, version, offset_batches, ['image', 'label'])` +with your sampler's batches and the columns you need. The function yields one +Arrow table per original training batch, with repeats at their original +positions. A missing offset shortens the result and raises `ValueError` before +the function yields any batch from that group. Apply the same length check +when grouping inputs to `take_row_ids`, which omits missing or deleted IDs. + ## From SQL {#sql} The same three identifiers are available as diff --git a/docs/web/snippets/curation_sampling.mdx b/docs/web/snippets/curation_sampling.mdx index 62af48e18..a630eca42 100644 --- a/docs/web/snippets/curation_sampling.mdx +++ b/docs/web/snippets/curation_sampling.mdx @@ -1,4 +1,6 @@ {/* Auto-generated by scripts/mdx_snippets_gen.py. Do not edit manually. */} +export const PyGroupedTrainingTakes = "def take_training_batches(table, version, offset_batches, columns):\n from itertools import islice\n\n table.checkout(version)\n offset_batches = iter(offset_batches)\n while group := list(islice(offset_batches, 4)):\n batch_sizes = [len(batch) for batch in group]\n if sum(batch_sizes) > 1024:\n raise ValueError(\"A grouped take can request at most 1,024 rows\")\n\n offsets = [offset for batch in group for offset in batch]\n rows = (\n table.take_offsets(offsets, preserve_order=True).select(columns).to_arrow()\n )\n if rows.num_rows != len(offsets):\n raise ValueError(\"Some training offsets are missing from the snapshot\")\n\n start = 0\n for size in batch_sizes:\n yield rows.slice(start, size)\n start += size\n"; + export const PySampleDataset = "table = db.create_table(\"records\", [{\"id\": i} for i in range(10)])\nsplits = (\n permutation_builder(table).split_random(counts=[3, 7], seed=42).execute()\n)\nsample = Permutation.from_tables(table, splits, split=0).with_format(\"arrow\")\nselected_ids = []\nfor batch in sample.iter(batch_size=3):\n selected_ids.extend(batch.column(\"id\").to_pylist())\nprint(f\"Selected {len(selected_ids)} rows: {selected_ids}\")\n"; diff --git a/docs/web/training/data-loading.mdx b/docs/web/training/data-loading.mdx index 19b9066a9..4060fdda1 100644 --- a/docs/web/training/data-loading.mdx +++ b/docs/web/training/data-loading.mdx @@ -155,6 +155,10 @@ ds = StreamingDataset( ``` +If you already have a sampler that produces batches of offsets, you can +[group several training batches into one take](/curation/selective-sampling#group-training-batches) +against a fixed table version. + ## Transforming {#transforming} Many model training workloads require performing a transformation to the data after it is loaded from object storage and before it is passed to the GPU. For example, we may need to decode images, tokenize text, or normalize vectors. A transformation function can be provided using the `transform` parameter.