mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 20:44:00 +00:00
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:
@@ -165,6 +165,49 @@ dataloader = torch.utils.data.DataLoader(permutation, collate_fn=lambda x: x)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Transforming rows with map {#transforming-rows-with-map}
|
||||
|
||||
To change rows in Python as they are read, call `map()` with a function that takes a row as a dict and returns a dict.
|
||||
Calls can be chained, and the functions run in order. Pass `batched=True` to receive the whole batch as a dict of
|
||||
column lists instead; the function must then return one value per input row for every column.
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
from lancedb.permutation import Permutation
|
||||
|
||||
db = lancedb.connect("memory://")
|
||||
reviews = db.create_table(
|
||||
"reviews",
|
||||
pa.table({"text": ["Great", "Awful", "Fine"], "stars": [5, 1, 3]}),
|
||||
)
|
||||
|
||||
|
||||
def lowercase(row):
|
||||
return {"text": row["text"].lower(), "stars": row["stars"]}
|
||||
|
||||
|
||||
def add_label(batch):
|
||||
return {**batch, "label": [int(stars >= 3) for stars in batch["stars"]]}
|
||||
|
||||
|
||||
permutation = Permutation.identity(reviews).map(lowercase).map(add_label, batched=True)
|
||||
|
||||
print(permutation.take_offsets([0, 1]))
|
||||
# [{'text': 'great', 'stars': 5, 'label': 1}, {'text': 'awful', 'stars': 1, 'label': 0}]
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
The dict a function returns replaces the row. A column the function does not return is dropped, so return every
|
||||
column you want to keep. A mapped `Permutation` always produces a list of dicts, like the default format, whether or
|
||||
not `batched` is set, so PyTorch's default collate function can batch it. `select_columns()` and `schema` still
|
||||
describe the columns read from the table, which are the input of the first function.
|
||||
|
||||
`map()` cannot be combined with `with_format()` or `with_transform()`. Calling one after the other, in either order,
|
||||
raises a `ValueError`. To build tensors from mapped rows, convert them in the DataLoader's `collate_fn`. When
|
||||
`num_workers > 0`, pass picklable top-level functions to `map()`, not lambdas.
|
||||
|
||||
## Selecting columns {#selecting-columns}
|
||||
|
||||
By default, the `Table` class will return all columns in the table when used as input to PyTorch. If you only need
|
||||
|
||||
Reference in New Issue
Block a user