Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions python/python/lance/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,13 +120,18 @@ def load_batch() -> pa.RecordBatch:
def _filtered_efficient_sample(
dataset: lance.LanceDataset,
n: int,
columns: List[str],
columns: Union[List[str], Dict[str, str]],
batch_size: int,
target_takes: int,
filter: str,
with_row_id: bool,
) -> Generator[pa.RecordBatch, None, None]:
if n == 0:
return
if isinstance(columns, dict):
raise NotImplementedError(
f"Partial filtered sampling requires column names, got {columns!r}"
)

total_records = len(dataset)
shard_size = math.ceil(n / target_takes)
Expand All @@ -146,6 +151,7 @@ def _filtered_efficient_sample(
offset=start,
limit=(end - start),
batch_size=shard_size,
**({"with_row_id": True} if with_row_id else {}),
)
if len(columns) == 1 and filter.lower() == f"{columns[0]} is not null".lower():
table = pc.drop_null(table)
Expand Down Expand Up @@ -179,10 +185,12 @@ def _filtered_efficient_sample(
def maybe_sample(
dataset: Union[str, Path, lance.LanceDataset],
n: int,
columns: Union[list[str], str],
columns: Union[list[str], dict[str, str], str],
batch_size: int = 10240,
max_takes: int = 2048,
filt: Optional[str] = None,
*,
with_row_id: bool = False,
) -> Generator[pa.RecordBatch, None, None]:
"""Sample n records from the dataset.

Expand All @@ -206,6 +214,10 @@ def maybe_sample(
The filter to apply to the dataset, by default None. If a filter is provided,
then we will first load all row ids in memory and then batch through the ids
in random order until enough matches have been found.
with_row_id : bool, optional
Include the dataset row ID. For example,
``maybe_sample(dataset, 10, "value", with_row_id=True)`` yields
batches with ``value`` and ``_rowid`` columns.

Returns
-------
Expand All @@ -231,13 +243,24 @@ def maybe_sample(
if n >= len(dataset):
# Dont have enough data in the dataset. Just do a full scan
yield from dataset.to_batches(
columns=columns, batch_size=batch_size, filter=filt
columns=columns,
batch_size=batch_size,
filter=filt,
**({"with_row_id": True} if with_row_id else {}),
)
elif filt is not None:
return
if filt is not None:
yield from _filtered_efficient_sample(
dataset, n, columns, batch_size, max_takes, filt
dataset, n, columns, batch_size, max_takes, filt, with_row_id
)
elif n > max_takes:
return

if with_row_id and "_rowid" not in columns:
if isinstance(columns, dict):
columns = {**columns, "_rowid": "_rowid"}
else:
columns = [*columns, "_rowid"]
if n > max_takes:
yield from _efficient_sample(dataset, n, columns, batch_size, max_takes)
else:
# Floyd's algorithm samples without allocating a population-sized permutation.
Expand Down
1 change: 1 addition & 0 deletions python/python/lance/torch/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,7 @@ def __iter__(self):
columns=projected_columns,
batch_size=self.batch_size,
filt=self.filter,
with_row_id=self.with_row_id,
)
else:
raw_stream = sampler(
Expand Down
11 changes: 2 additions & 9 deletions python/python/lance/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,17 +517,10 @@ def compute_partitions(
progress.set_description("Assigning partitions")

def _partition_assignment() -> Iterable[pa.RecordBatch]:
id_offset = 0
with torch.no_grad():
for batch in loader:
if sample_size is None:
vecs = batch[column]
ids = batch["_rowid"].reshape(-1)
else:
# No row ids with sampling
vecs = batch
ids = torch.arange(id_offset, id_offset + vecs.size(0))
id_offset += vecs.size(0)
vecs = batch[column]
ids = batch["_rowid"].reshape(-1)

vecs = _to_device(vecs, kmeans.device).reshape(
-1, kmeans.centroids.shape[1]
Expand Down
97 changes: 95 additions & 2 deletions python/python/tests/test_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,9 +623,15 @@ def test_maybe_sample_filtered(
def _patch_small_torch_sampler(monkeypatch, max_takes):
import lance.torch.data as torch_data

def sample(dataset, n, columns, batch_size=128, filt=None):
def sample(dataset, n, columns, batch_size=128, filt=None, with_row_id=False):
return maybe_sample(
dataset, n, columns, batch_size=batch_size, max_takes=max_takes, filt=filt
dataset,
n,
columns,
batch_size=batch_size,
max_takes=max_takes,
filt=filt,
with_row_id=with_row_id,
)

monkeypatch.setattr(torch_data, "maybe_sample", sample)
Expand Down Expand Up @@ -761,6 +767,93 @@ def test_maybe_sample_coalesces_multiple_strata_per_output_batch(
assert dataset.take_sizes == [6, 7, 4]


@pytest.mark.parametrize("stable_ids", [False, True])
@pytest.mark.parametrize(
"n,columns,filt",
[
(2, ["id"], None),
(4, {"id": "id + 10"}, None),
(7, ["id"], None),
(3, ["id"], "id is not null"),
],
ids=["uniform", "stratified", "full", "filtered"],
)
def test_torch_sampled_row_ids(
tmp_path,
monkeypatch,
preserve_numpy_state,
preserve_random_state,
stable_ids,
n,
columns,
filt,
):
pytest.importorskip("torch")
from lance.torch.data import LanceDataset as TorchDataset

ds = lance.write_dataset(
pa.table({"id": [0, 1, None, 3, 4, 5, 6, 7]}),
tmp_path,
max_rows_per_file=4,
enable_stable_row_ids=stable_ids,
)
ds.delete("id = 1")
_patch_small_torch_sampler(monkeypatch, max_takes=3)
projection = columns.copy()
reference = ds.to_table(columns=projection, filter=filt, with_row_id=True)
sample = TorchDataset(
ds,
batch_size=2,
columns=columns,
filter=filt,
samples=n,
with_row_id=True,
to_tensor_fn=None,
auto_detect_rank=False,
)
rows = pa.Table.from_batches(list(sample))
assert rows.column_names == ["id", "_rowid"]
assert rows.num_rows == n
assert columns == projection
expected_ids = {r["id"]: r["_rowid"] for r in reference.to_pylist()}
assert rows["_rowid"].to_pylist() == [
expected_ids[v] for v in rows["id"].to_pylist()
]


@pytest.mark.parametrize("with_row_id", [False, True])
def test_filtered_sample_preserves_implicit_row_ids(
tmp_path, preserve_random_state, with_row_id
):
ds = lance.write_dataset(
pa.table({"value": [0, 1, None, 3, None, 5]}), tmp_path, max_rows_per_file=3
)
ds.delete("value = 0")
ds = lance.dataset(
tmp_path,
default_scan_options={"include_deleted_rows": True, "with_row_id": True},
)
batches = maybe_sample(
ds, 4, ["value"], filt="value is not null", with_row_id=with_row_id
)
rows = pa.Table.from_batches(list(batches)).to_pylist()
assert rows
assert all(row["value"] is not None and row["_rowid"] is not None for row in rows)


def test_filtered_sample_with_expression_projection(tmp_path):
ds = lance.write_dataset(
pa.table({"id": [None, None, 7]}), tmp_path, max_rows_per_file=2
)
columns = {"id": "coalesce(id, 0)"}
filt = "id is not null"
assert list(maybe_sample(ds, 0, columns, filt=filt)) == []
with pytest.raises(NotImplementedError, match="requires column names"):
list(maybe_sample(ds, 2, columns, filt=filt))
full = pa.Table.from_batches(list(maybe_sample(ds, 3, columns, filt=filt)))
assert full["id"].to_pylist() == [7]


def test_torch_dataset_preserves_prefetch_rows_and_rng(
write_multifragment_dataset, preserve_numpy_state, monkeypatch
):
Expand Down
26 changes: 25 additions & 1 deletion python/python/tests/torch_tests/test_torch_kmeans.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
from lance.torch.distance import dot_distance, l2_distance # noqa: E402
from lance.torch.kmeans import KMeans # noqa: E402
from lance.util import validate_vector_index # noqa: E402
from lance.vector import train_ivf_centroids_on_accelerator # noqa: E402
from lance.vector import ( # noqa: E402
compute_partitions,
train_ivf_centroids_on_accelerator,
)


def test_kmeans():
Expand Down Expand Up @@ -72,6 +75,27 @@ def test_torch_kmeans_accept_torch_device(tmp_path: Path):
)


def test_sampled_partitions_keep_source_row_ids(tmp_path):
centroids = torch.arange(6, dtype=torch.float32).reshape(-1, 1)
vectors = pa.FixedSizeListArray.from_arrays(centroids.flatten().numpy(), 1)
ds = lance.write_dataset(
pa.table({"vector": vectors}), tmp_path / "source", max_rows_per_file=2
)
# Each source vector is its own centroid, so its partition identifies the row.
row_ids = ds.to_table(columns=[], with_row_id=True)["_rowid"]
partitions = compute_partitions(
ds,
"vector",
KMeans(6, centroids=centroids, device="cpu"),
batch_size=2,
dst_dataset_uri=tmp_path / "partitions",
sample_size=4,
)
rows = lance.dataset(partitions).to_table()
assert rows.num_rows == 4
assert rows["row_id"].equals(row_ids.take(rows["partition"]))


def test_torch_kmeans_nans(tmp_path: Path):
kmeans = KMeans(4, centroids=torch.rand(4, 8), device="cpu")
values = np.arange(64).astype(np.float32)
Expand Down
Loading