feat(python): add map() method to Permutation for dict-based transforms (#3264)

### Summary

Adds `Permutation.map(fn, *, batched=False)`, a dict-based alternative
to `with_transform` so users can write `fn(dict) -> dict` without
touching `pyarrow.RecordBatch`.

- `batched=False` (default): `fn` receives one row as a dict and returns
a dict.
- `batched=True`: `fn` receives the batch as `dict[str, list]` and
returns the same shape, with one value per input row.
- `map` calls can be chained. Callbacks run in order and the returned
dict replaces the row, so the next callback only sees what the previous
one returned. Unlike HuggingFace's `Dataset.map`, the output is not
merged into the row.
- A mapped permutation always yields `list[dict]`, whatever `batched`
is, so it works with the default `DataLoader` collate. Rows keep their
position, including duplicate offsets, and `take_offsets([])` returns
`[]`.
- `map` cannot be combined with an explicit `with_format` or
`with_transform`, in either order. Doing so raises `ValueError` when the
chain is built, whether or not the format's optional dependency is
installed.
- `select_columns`, `remove_columns` and `schema` describe the columns
read from the base table, which are the input of the first callback.
- The chain is stored in a module-level callable, so a mapped
permutation can be pickled into `spawn` `DataLoader` workers as long as
the callbacks themselves are picklable.
- `with_transform` remains available for direct Arrow access.

### Documentation

- Docstrings for `map`, `with_format` and `with_transform` cover the
mixing rule, with a `DataLoader` + `collate_fn` example on `map`.
- Adds a "Transforming rows with map" section to the Permutation guide.

### Testing

- `test_permutation.py`: chaining, mixing errors in both orders, output
validation, duplicate and empty offsets, projection and schema, and a
pickle round-trip for both `batched` modes.
- `test_permutation.py`: the mixing check with `polars` unimportable,
with pickles written before the `explicit_transform` flag, and with a
transform passed to the constructor.
- `test_torch.py`: a map chain read through `DataLoader(...,
multiprocessing_context="spawn", num_workers=1)`.

Closes [#3246](https://github.com/lancedb/lancedb/issues/3246)
This commit is contained in:
Tanay
2026-11-25 06:35:28 +08:00
committed by GitHub
parent b3dd2b0392
commit fc6dfca11a
4 changed files with 516 additions and 2 deletions
+200 -2
View File
@@ -512,6 +512,88 @@ class Transforms:
# HuggingFace uses 10 which is pretty small
DEFAULT_BATCH_SIZE = 100
_MAP_FORMAT_ERROR = (
"map cannot be combined with with_format or with_transform; convert the "
"output inside the map callback or in the DataLoader collate_fn instead"
)
def _map_rows(data: Any, num_rows: int) -> list[dict[str, Any]]:
"""Return the data flowing through a map chain as a list of row dicts."""
if isinstance(data, pa.RecordBatch):
return data.to_pylist()
if isinstance(data, dict):
return [
{name: values[i] for name, values in data.items()} for i in range(num_rows)
]
return data
def _map_columns(data: Any) -> dict[str, Any]:
"""Return the data flowing through a map chain as a dict of columns."""
if isinstance(data, pa.RecordBatch):
return data.to_pydict()
if isinstance(data, list):
names = data[0].keys()
if any(row.keys() != names for row in data):
raise ValueError(
"Cannot pass rows to a batched map callback because the previous "
"callback did not return the same keys for every row"
)
return {name: [row[name] for row in data] for name in names}
return data
class _MapTransform:
"""
The transform installed by [map][lancedb.permutation.Permutation.map]
Each step is a ``(fn, batched)`` pair. This is a module-level class, and not a
closure, so that a mapped permutation pickles whenever its callbacks do.
"""
def __init__(self, steps: tuple[tuple[Callable, bool], ...]):
self.steps = steps
def __call__(self, batch: pa.RecordBatch) -> list[dict[str, Any]]:
num_rows = batch.num_rows
if num_rows == 0:
return []
# The layout is only converted when a callback needs the other one
data = batch
for fn, batched in self.steps:
if batched:
data = fn(_map_columns(data))
if not isinstance(data, dict):
raise TypeError(
"A batched map callback must return a dict of columns, "
f"got {type(data).__name__}"
)
for name, values in data.items():
# A str or dict can be indexed but is not a column of values
if isinstance(values, (str, bytes, dict)) or not hasattr(
values, "__getitem__"
):
raise TypeError(
"A batched map callback must return a list of values "
f"for column `{name}`, got {type(values).__name__}"
)
if len(values) != num_rows:
raise ValueError(
f"A batched map callback returned {len(values)} values "
f"for column `{name}` but the batch has {num_rows} rows"
)
else:
data = [fn(row) for row in _map_rows(data, num_rows)]
for row in data:
if not isinstance(row, dict):
raise TypeError(
"A map callback must return a dict for each row, "
f"got {type(row).__name__}"
)
return _map_rows(data, num_rows)
def _is_persisted_plan(table: Table) -> bool:
"""Whether a permutation table lives in reopenable storage rather than memory."""
@@ -619,6 +701,9 @@ class Permutation:
self.split = split
self.selection = selection
self.transform_fn = transform_fn
# Whether the default transform was replaced, by with_format, by
# with_transform, or by a caller passing its own transform here
self._explicit_transform = transform_fn is not Transforms.arrow2python
self.batch_size = batch_size
self.offset = offset
self.limit = limit
@@ -881,6 +966,7 @@ class Permutation:
"selection": self.selection,
"batch_size": self.batch_size,
"transform_fn": self.transform_fn,
"explicit_transform": self._explicit_transform,
"offset": self.offset,
"limit": self.limit,
"connection_factory": self.connection_factory,
@@ -953,6 +1039,11 @@ class Permutation:
self.selection = state["selection"]
self.batch_size = state["batch_size"]
self.transform_fn = state["transform_fn"]
# Pickles written before this flag existed still carry their transform.
# Anything but the default must have been set explicitly.
self._explicit_transform = state.get(
"explicit_transform", self.transform_fn is not Transforms.arrow2python
)
self.offset = state["offset"]
self.limit = state["limit"]
self.connection_factory = connection_factory
@@ -1304,8 +1395,16 @@ class Permutation:
For custom formatting, use
[with_transform][lancedb.permutation.Permutation.with_transform] which
overrides this method.
A format cannot be combined with
[map][lancedb.permutation.Permutation.map], which always yields a list
of dicts. Doing so raises a ValueError.
"""
assert format is not None, "format is required"
# Checked before with_transform does, so that a format with an optional
# dependency cannot fail on its import first
if isinstance(self.transform_fn, _MapTransform):
raise ValueError(_MAP_FORMAT_ERROR)
if format == "python":
return self.with_transform(Transforms.arrow2python)
if format == "python_col":
@@ -1338,10 +1437,109 @@ class Permutation:
Note: transforms are not invoked in parallel. This method is not a good place
for expensive operations such as image decoding.
For a higher-level API that works with Python dicts, see
[map][lancedb.permutation.Permutation.map]. A transform cannot be combined
with ``map``. Doing so raises a ValueError.
"""
assert transform is not None, "transform is required"
if isinstance(self.transform_fn, _MapTransform):
raise ValueError(_MAP_FORMAT_ERROR)
new = copy.copy(self)
new.transform_fn = transform
new._explicit_transform = True
return new
def map(
self,
fn: Callable[[dict[str, Any]], dict[str, Any]],
*,
batched: bool = False,
) -> "Permutation":
"""
Apply a function to the rows of the permutation
This is a dict-based alternative to
[with_transform][lancedb.permutation.Permutation.with_transform], loosely
modeled after the huggingface ``Dataset.map``. It is lazy: ``fn`` is not
called until data is read.
Calls to ``map`` can be chained. The callbacks run in order and the dict
returned by a callback replaces the row entirely, so the next callback only
sees what the previous one returned. Unlike the huggingface method, the
returned dict is not merged into the row: return every column to keep.
A mapped permutation always yields a list of dicts (one per row) for each
batch, which is the same shape as the default "python" format. ``batched``
only controls what ``fn`` receives. Rows keep their position, so a callback
cannot add, drop, or reorder rows.
Since ``map`` decides the output format it cannot be combined with
[with_format][lancedb.permutation.Permutation.with_format] or
[with_transform][lancedb.permutation.Permutation.with_transform]. Calling
one after the other, in either order, raises a ValueError. Convert the
mapped rows to tensors in the DataLoader ``collate_fn`` instead.
[select_columns][lancedb.permutation.Permutation.select_columns],
[remove_columns][lancedb.permutation.Permutation.remove_columns],
[rename_column][lancedb.permutation.Permutation.rename_column] and
[schema][lancedb.permutation.Permutation.schema] describe the columns read
from the base table, which are the input of the first callback. They do
not describe the output of ``map``, whether they are used before or after it.
Parameters
----------
fn: Callable
The function to apply. It receives and returns a single row as a dict
mapping column names to values. If ``batched`` is True it instead
receives and returns a whole batch as a dict mapping column names to
lists of values, and every returned column must have one value per
input row.
DataLoader workers started with ``spawn`` or ``forkserver`` receive a
pickled copy of the permutation, so ``fn`` must then be picklable.
Use a top-level function; lambdas and local functions do not pickle.
batched: bool, default False
Whether ``fn`` is called once per batch instead of once per row.
Examples
--------
>>> import lancedb
>>> db = lancedb.connect("memory:///")
>>> tbl = db.create_table("tbl", data=[{"x": x} for x in range(3)])
>>> def add_y(row):
... return {**row, "y": row["x"] * 2}
>>> def add_z(batch):
... return {**batch, "z": [x + y for x, y in zip(batch["x"], batch["y"])]}
>>> permutation = Permutation.identity(tbl).map(add_y).map(add_z, batched=True)
>>> permutation.take_offsets([0, 1])
[{'x': 0, 'y': 0, 'z': 0}, {'x': 1, 'y': 2, 'z': 3}]
With a PyTorch DataLoader, a ``collate_fn`` turns the mapped rows of each
batch into tensors::
import torch
def collate(rows):
return {
"x": torch.tensor([row["x"] for row in rows]),
"z": torch.tensor([row["z"] for row in rows]),
}
dataloader = torch.utils.data.DataLoader(
permutation, batch_size=32, shuffle=True, collate_fn=collate
)
"""
if not callable(fn):
raise TypeError("fn must be callable")
if self._explicit_transform:
raise ValueError(_MAP_FORMAT_ERROR)
steps = ((fn, batched),)
if isinstance(self.transform_fn, _MapTransform):
steps = self.transform_fn.steps + steps
new = copy.copy(self)
new.transform_fn = _MapTransform(steps)
return new
def take_offsets(self, offsets: list[int]) -> Any:
@@ -1349,8 +1547,8 @@ class Permutation:
Take rows from the permutation by offset
The returned value is passed through the permutation's current transform,
so `with_format` and `with_transform` affect this method in the same way
they affect iteration.
so `with_format`, `with_transform`, and `map` affect this method in the
same way they affect iteration.
"""
self._ensure_open()
+241
View File
@@ -1856,3 +1856,244 @@ def test_from_tables_split_without_permutation_table(mem_db):
with pytest.raises(ValueError, match="permutation on split `train` because no"):
Permutation.from_tables(tbl, split="train")
def _double_value_row(row):
return {"id": row["id"], "value": row["value"] * 2}
def _double_value_batch(batch):
return {"id": batch["id"], "value": [value * 2 for value in batch["value"]]}
def test_map_row_by_row(some_permutation: Permutation):
"""Test .map() applies fn to each row individually."""
mapped = some_permutation.map(_double_value_row)
batches = list(mapped.iter(10, skip_last_batch=False))
first_batch = batches[0]
assert len(first_batch) == 10
assert isinstance(first_batch[0], dict)
for row in first_batch:
assert row["value"] == row["id"] * 2
def test_map_batched(some_permutation: Permutation):
"""Test batched only changes what fn receives, not what is yielded."""
seen = []
def double_value(batch):
seen.append(batch)
return _double_value_batch(batch)
mapped = some_permutation.map(double_value, batched=True)
first_batch = next(mapped.iter(10, skip_last_batch=False))
assert isinstance(seen[0], dict)
assert len(seen[0]["id"]) == 10
assert first_batch == next(
some_permutation.map(_double_value_row).iter(10, skip_last_batch=False)
)
def test_map_chain(some_permutation: Permutation):
"""Test chained maps run in order and each one replaces the whole row."""
def add_doubled(row):
return {**row, "doubled": row["value"] * 2}
def to_total(batch):
return {
"total": [a + b for a, b in zip(batch["value"], batch["doubled"])],
}
def add_label(row):
return {**row, "label": str(row["total"])}
first = some_permutation.map(add_doubled)
mapped = first.map(to_total, batched=True).map(add_label)
expected = [
{"total": row["value"] * 3, "label": str(row["value"] * 3)}
for row in some_permutation.take_offsets([0, 1, 2])
]
assert mapped.take_offsets([0, 1, 2]) == expected
assert next(mapped.iter(3, skip_last_batch=False)) == expected
# Extending a chain does not change the permutation it was derived from
assert set(first.take_offsets([0])[0]) == {"id", "value", "doubled"}
@pytest.mark.parametrize(
"explicit",
[
lambda permutation: permutation.with_format("python"),
lambda permutation: permutation.with_format("arrow"),
lambda permutation: permutation.with_transform(Transforms.arrow2arrow),
],
)
def test_map_rejects_format_and_transform(some_permutation: Permutation, explicit):
"""Test .map() cannot be mixed with with_format or with_transform."""
with pytest.raises(ValueError, match="map cannot be combined"):
explicit(some_permutation).map(_double_value_row)
with pytest.raises(ValueError, match="map cannot be combined"):
explicit(some_permutation.map(_double_value_row))
def test_map_rejects_format_without_optional_dependency(
some_permutation: Permutation, monkeypatch
):
"""Test the map check runs before a format imports an optional dependency."""
import sys
# Make polars fail to import, as it does on an install without extras
monkeypatch.setitem(sys.modules, "polars", None)
with pytest.raises(ValueError, match="map cannot be combined"):
some_permutation.map(_double_value_row).with_format("polars")
def test_map_rejects_explicit_transform_from_old_pickle(
some_permutation: Permutation,
):
"""Test pickles written before explicit_transform existed keep the guard."""
def restore_without_flag(permutation):
state = permutation.__getstate__()
del state["explicit_transform"]
restored = Permutation.__new__(Permutation)
restored.__setstate__(state)
return restored
with pytest.raises(ValueError, match="map cannot be combined"):
restore_without_flag(some_permutation.with_format("arrow")).map(
_double_value_row
)
# The default transform is indistinguishable from an explicit "python" format
mapped = restore_without_flag(some_permutation).map(_double_value_row)
assert mapped.take_offsets([0]) == [
_double_value_row(row) for row in some_permutation.take_offsets([0])
]
def test_map_rejects_transform_passed_to_constructor(some_table: Table):
"""Test a transform given to the constructor counts as explicit too."""
permutation = Permutation(
some_table,
None,
0,
{"id": "id"},
DEFAULT_BATCH_SIZE,
Transforms.arrow2arrow,
)
with pytest.raises(ValueError, match="map cannot be combined"):
permutation.map(_double_value_row)
def test_map_take_offsets(some_permutation: Permutation):
"""Test .map() keeps the positions and duplicates of the requested offsets."""
calls = []
def record(batch):
calls.append(batch)
return batch
mapped = some_permutation.map(_double_value_row).map(record, batched=True)
offsets = [5, 0, 5, 2]
expected = [
_double_value_row(row) for row in some_permutation.take_offsets(offsets)
]
assert mapped.take_offsets(offsets) == expected
assert mapped.__getitems__(offsets) == expected
calls.clear()
assert mapped.take_offsets([]) == []
assert calls == []
def test_map_validates_output(some_permutation: Permutation):
"""Test .map() rejects callback output that would break the batch shape."""
with pytest.raises(ValueError, match="returned 1 values for column `id`"):
some_permutation.map(
lambda batch: {"id": batch["id"][:1]}, batched=True
).take_offsets([0, 1])
with pytest.raises(TypeError, match="must return a dict of columns, got list"):
some_permutation.map(
lambda batch: list(batch.values()), batched=True
).take_offsets([0, 1])
# A str has the right length here but is still not a column of values
for value in (2, "ab"):
with pytest.raises(TypeError, match="list of values for column `n`, got"):
some_permutation.map(lambda batch: {"n": value}, batched=True).take_offsets(
[0, 1]
)
with pytest.raises(
TypeError, match="must return a dict for each row, got NoneType"
):
some_permutation.map(lambda row: None).take_offsets([0, 1])
with pytest.raises(ValueError, match="did not return the same keys for every row"):
some_permutation.map(
lambda row: row if row["id"] % 2 else {"id": row["id"]}
).map(lambda batch: batch, batched=True).take_offsets(list(range(10)))
def test_map_projection_and_schema(some_permutation: Permutation):
"""Test the selection and schema describe the read that feeds the callbacks."""
def to_str(row):
return {name: str(value) for name, value in row.items()}
mapped = some_permutation.map(to_str)
assert mapped.schema == some_permutation.schema
assert mapped.column_names == ["id", "value"]
for projected in (
some_permutation.select_columns(["id"]).map(to_str),
mapped.select_columns(["id"]),
mapped.remove_columns(["value"]),
):
assert projected.schema == some_permutation.select_columns(["id"]).schema
assert list(projected.take_offsets([0])[0]) == ["id"]
renamed = mapped.rename_column("value", "data")
assert renamed.column_names == ["id", "data"]
assert list(renamed.take_offsets([0])[0]) == ["id", "data"]
def test_map_is_lazy(some_permutation: Permutation):
"""Test .map() does not call fn until iteration."""
call_count = [0]
def counting_fn(row):
call_count[0] += 1
return row
mapped = some_permutation.map(counting_fn)
assert call_count[0] == 0
mapped.__getitems__([0])
assert call_count[0] == 1
def test_map_non_callable(some_permutation: Permutation):
"""Test .map() raises TypeError for non-callable fn."""
with pytest.raises(TypeError, match="fn must be callable"):
some_permutation.map("not a function")
@pytest.mark.parametrize(
"fn, batched", [(_double_value_row, False), (_double_value_batch, True)]
)
def test_map_pickle_round_trip(some_permutation: Permutation, fn, batched):
"""Test a mapped permutation reads the same data after a pickle round trip."""
import pickle
mapped = some_permutation.map(fn, batched=batched)
restored = pickle.loads(pickle.dumps(mapped))
offsets = [3, 1, 3]
assert restored.take_offsets(offsets) == mapped.take_offsets(offsets)
assert restored.take_offsets(offsets)[0]["value"] == (
some_permutation.take_offsets(offsets)[0]["value"] * 2
)
# The restored permutation keeps enforcing the map / format constraint
with pytest.raises(ValueError, match="map cannot be combined"):
restored.with_format("arrow")
explicit = pickle.loads(pickle.dumps(some_permutation.with_format("arrow")))
with pytest.raises(ValueError, match="map cannot be combined"):
explicit.map(fn, batched=batched)
+32
View File
@@ -631,6 +631,38 @@ def test_permutation_torch_dict_dataloader_spawn(tmp_db):
assert sorted(seen) == list(range(11))
def _map_add_scaled(row):
return {**row, "scaled": row["a"] * 2}
def _map_add_total(batch):
total = [a + scaled for a, scaled in zip(batch["a"], batch["scaled"])]
return {**batch, "total": total}
def test_permutation_map_dataloader_spawn(tmp_db):
"""A map chain must be picklable so spawned DataLoader workers can run it."""
table = tmp_db.create_table("test_table", pa.table({"a": range(100)}))
permutation = (
Permutation.identity(table)
.map(_map_add_scaled)
.map(_map_add_total, batched=True)
)
dataloader = torch.utils.data.DataLoader(
permutation,
batch_size=10,
num_workers=1,
multiprocessing_context="spawn",
)
seen = []
for batch in dataloader:
assert set(batch) == {"a", "scaled", "total"}
assert torch.equal(batch["total"], batch["a"] * 3)
seen.extend(batch["a"].tolist())
assert seen == list(range(100))
def test_batch_to_tensor_columns_zero_copy_and_slice_offsets():
vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
nested_values = np.arange(5 * 3 * 2, dtype=np.float32).reshape(5, 3, 2)