diff --git a/docs/web/training/permutation.mdx b/docs/web/training/permutation.mdx index ebfcce0c6..0da10f947 100644 --- a/docs/web/training/permutation.mdx +++ b/docs/web/training/permutation.mdx @@ -50,32 +50,72 @@ LanceDB's `lancedb.util.tbl_to_tensor` helper as PyTorch's `collate_fn`; it conv column-major `torch.Tensor` with shape `(columns, rows)`. `Permutation` works differently: its default output is a list of Python dicts, which PyTorch's default collate function -can batch into a dict of tensors. This is usually more convenient when you are getting started. However, there is a -significant performance penalty converting from Arrow, Lance's internal representation, to this default format. If you -want the default PyTorch dict-of-tensors behavior, use a `Permutation` as-is; if you want direct Arrow-to-tensor -conversion, either pass `lancedb.util.tbl_to_tensor` as `collate_fn` with a direct `Table` or configure a `Permutation` -with one of the transform formats described below. +can batch into a dict of tensors. However, converting every value to a Python object has a significant performance +penalty. To convert the Arrow data in different ways, call `with_format()` with one of the formats below. Here `B` is +the batch size, `C` is the number of columns, and `*S` is the shape of one sample. -To address this, the `Permutation` class provides a set of builtin transform functions that can be applied to map -the Arrow data in different ways. The `arrow` and `polars` formats will always avoid data copies. However, `numpy`, -`pandas`, and `torch_col` formats will also avoid data copies in most cases. The `python`, `python_col`, and -`torch` formats will all require at least one full copy of the data and are the slowest options. +| Format | Output of `iter(batch_size=B)` | DataLoader collate | +|---|---|---| +| `"arrow"` | `pyarrow.RecordBatch` | Not accepted directly | +| `"torch_dict"` | `dict[str, Tensor]`, one `(B, *S)` tensor per column | Identity function | +| `"torch"` | `list[dict[str, Tensor]]`, one `(*S)` tensor per column per row | Default collate produces `dict[str, Tensor]` with `(B, *S)` | +| `"torch_col"` | One `(C, B, *S)` tensor | Identity function | +| `"torch_row"` | `list[Tensor]`, one `(C, *S)` tensor per row | Default collate produces `(B, C, *S)` | +| `"numpy"` | One NumPy ndarray | Not accepted directly | + +`torch_dict` is usually the best choice for training because it keeps column names, handles columns with different +sample shapes, and shares Arrow storage where the layout allows. `torch_col` and `torch_row` require every column to +have the same sample shape. `torch_row` combines numeric dtypes with `torch.promote_types`, and `torch_col` promotes +supported mixed numeric dtypes through `torch.stack`. If they see mixed scalar and vector columns, they name the +mismatched fields and shapes and point you to `torch_dict`. + +`torch_dict`, `torch`, and `torch_col` reject null values. `torch_row` preserves the previous NaN behavior for +nullable scalar integer and floating columns, but rejects nulls in nested fixed-size-list and tensor columns. Use the +`"python"` or `"arrow"` format for other nullable columns, or drop/fill the nulls first. `lance.bfloat16` values are +supported when the leaf field is `fixed_size_binary[2]` with the `ARROW:extension:name` metadata set to +`lance.bfloat16`; these become `torch.bfloat16` tensors. An unmarked binary column is rejected rather than guessed to +be bfloat16. + +The `numpy` format returns one ndarray built with `batch.to_pandas().to_numpy()`. The pandas conversion may copy data +and may promote mixed numeric columns to a common numeric dtype, for example int64 and float32 to float64. Nested, +list, or incompatible columns produce an object ndarray rather than a numeric array. + +### Using torch_dict with a torch data loader {#using-torch-dict-with-a-torch-data-loader} + +`torch_dict` produces a dictionary of per-column tensors for each batch. Pass an identity function as `collate_fn` so +PyTorch returns that dictionary unchanged. Scalar columns have shape `(B,)`, a `FixedSizeList` column has +shape `(B, D)`, and nested fixed-size lists contribute one dimension per level. Fixed-shape tensor columns use their +logical shape, with the Arrow axis permutation applied as a view. + + +```python Python icon="python" +import torch +from lancedb.permutation import Permutation + +permutation = Permutation.identity(table).with_format("torch_dict") +dataloader = torch.utils.data.DataLoader( + permutation, + batch_size=1024, + shuffle=True, + collate_fn=lambda batch: batch, +) + +for batch in dataloader: + print(batch["id"].shape) # (1024,) + print(batch["vector"].shape) # (1024, 128) +``` + + +When `num_workers > 0`, replace the lambda with a picklable top-level function that returns its argument. ### Using the torch column format with a torch data loader {#using-the-torch-column-format-with-a-torch-data-loader} -The `torch_col` format is the most efficient way to convert from Arrow to a `torch.Tensor`. It will convert the -entire Arrow batch to a _column-major_ `torch.Tensor`. In other words, given C columns and R rows, the resulting -Tensor will have shape `(C, R)`. However, this format generates an error if you are using a -`torch.utils.data.DataLoader` with the default collation function: +The `torch_col` format converts the entire Arrow batch to one tensor with shape `(C, B, *S)`. For a table of scalar +columns this is the familiar `(columns, rows)` tensor. For a single column it is an `unsqueeze(0)` view of the +per-column tensor, so no data is copied; stacking multiple columns does copy. -```text -TypeError: stack(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor -``` - -This error occurs because the default collation function does not currently expect a single two-dimensional tensor. -It expects a list of tensors which it will then stack. This is what is output by the `torch` format but that format -requires a data copy. To avoid this error, and avoid data copies, you will need to provide a custom collation function -in addition to specifying the `torch_col` format. +PyTorch's default collate does not accept a single multi-dimensional tensor. Pass an identity function as `collate_fn` +to receive the tensor directly from the data loader. ```python Python icon="python" @@ -86,8 +126,6 @@ dataloader = torch.utils.data.DataLoader(permutation, collate_fn=lambda x: x) ``` -This will now output a single two-dimensional tensor for each batch. - ## 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 diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index fcdbaa397..2a45f4cc4 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -11,7 +11,12 @@ import pyarrow as pa from ._lancedb import async_permutation_builder, PermutationReader from .table import LanceTable, Table from .background_loop import LOOP -from .util import batch_to_tensor, batch_to_tensor_dict, batch_to_tensor_rows +from .util import ( + batch_to_tensor, + batch_to_tensor_columns, + batch_to_tensor_dict, + batch_to_tensor_rows, +) from typing import Any, Callable, Iterator, Literal, Optional, TYPE_CHECKING, Union if TYPE_CHECKING: @@ -1031,6 +1036,7 @@ class Permutation: "pandas", "arrow", "torch", + "torch_dict", "torch_row", "torch_col", "polars", @@ -1042,28 +1048,54 @@ class Permutation: If this method is not called, the "python" format will be used. The format can be one of: - - "numpy" - the batch will be a dict of numpy arrays (one per column) + - "numpy" - a single NumPy ndarray built with + ``batch.to_pandas().to_numpy()``. This conversion may copy data and + may promote mixed numeric columns to a common numeric dtype, for + example int64 and float32 to float64. Nested or incompatible columns + produce an object array. - "python" - the batch will be a list of dicts (one per row) - "python_col" - the batch will be a dict of lists (one entry per column) - "pandas" - the batch will be a pandas DataFrame - "arrow" - the batch will be a pyarrow RecordBatch - - "torch" - the batch will be a list of per-row dicts mapping column - name to a 0-D torch tensor. Works with the default - ``torch.utils.data.DataLoader`` collate, which stacks the per-row - dicts back into a dict of batched tensors. - - "torch_row" - the batch will be a list of tensors, one per row - - "torch_col" - the batch will be a 2D torch tensor (first dim indexes columns) + - "torch" - a list of per-row dicts mapping column names to tensors with + shape ``(*S)``. The default DataLoader collate stacks these into a + dict of ``(B, *S)`` tensors. + - "torch_dict" - a dict mapping each column name to one tensor with + shape ``(B, *S)``. Columns may have different sample shapes ``S``. + Use an identity collate to consume the batch directly. Tensors share + Arrow storage where the layout allows. + - "torch_row" - a list of per-row tensors with shape ``(C, *S)``. All + columns must have the same sample shape ``S``. A single scalar column + produces ``(1,)`` tensors. Numeric dtypes are combined with + ``torch.promote_types``. + - "torch_col" - one tensor with shape ``(C, B, *S)``. All columns must + have the same sample shape ``S``. For one column this is an + ``unsqueeze(0)`` view of the column tensor. - "polars" - the batch will be a polars DataFrame - Conversion may or may not involve a data copy. Lance uses Arrow internally - and so it is able to zero-copy to the arrow and polars formats. + For torch formats, ``S`` is the shape of one sample. Scalar columns have + ``S = ()``. A fixed-size-list column of width ``D`` contributes a + dimension ``D``, and nested fixed-size lists contribute one dimension + per level. Fixed-shape tensors use their logical shape, including any + axis permutation. "torch_dict", "torch", and "torch_col" reject nulls; + use the "python" or "arrow" format for nullable columns. "torch_row" + preserves the previous NaN behavior for nullable scalar integer and + floating columns, but rejects nulls in nested fixed-size-list and tensor + columns. - Conversion to torch and torch_col will be zero-copy but will only support a - subset of data types (numeric types). + ``lance.bfloat16`` values become ``torch.bfloat16`` tensors when the + leaf field is ``fixed_size_binary[2]`` and carries the + ``ARROW:extension:name`` metadata value ``lance.bfloat16``. Unmarked + binary columns are rejected. - Conversion to numpy and/or pandas will typically be zero-copy for numeric - types. Conversion of strings, lists, and structs will require creating python - objects and this is not zero-copy. + Conversion may or may not involve a data copy. Lance uses Arrow + internally and can zero-copy to the arrow and polars formats. + "torch_dict", "torch", and a single-column "torch_col" produce + numeric and fixed-size-list tensors without copying where the Arrow + layout allows. Multi-column "torch_col" and "torch_row" stack columns + and therefore copy. Conversion to numpy and/or pandas can copy even + homogeneous numeric columns. Conversion of strings, lists, and structs + will require creating Python objects and this is not zero-copy. For custom formatting, use [with_transform][lancedb.permutation.Permutation.with_transform] which @@ -1082,6 +1114,8 @@ class Permutation: return self.with_transform(Transforms.arrow2arrow) elif format == "torch": return self.with_transform(batch_to_tensor_dict) + elif format == "torch_dict": + return self.with_transform(batch_to_tensor_columns) elif format == "torch_row": return self.with_transform(batch_to_tensor_rows) elif format == "torch_col": diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py index 67bffbc97..d8f846e24 100644 --- a/python/python/lancedb/util.py +++ b/python/python/lancedb/util.py @@ -8,6 +8,7 @@ import importlib import math import os import pathlib +import sys import warnings from datetime import date, datetime, time, timedelta from decimal import Decimal @@ -611,15 +612,253 @@ def tbl_to_tensor(tbl: pa.Table): return torch.stack([to_tensor(tbl.column(i)) for i in range(tbl.num_columns)]) +_BFLOAT16_EXTENSION_NAME = "lance.bfloat16" +_ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name" + + +def _field_metadata_value(field: pa.Field, key: str): + metadata = field.metadata or {} + value = metadata.get(key.encode()) or metadata.get(key) + if isinstance(value, bytes): + return value.decode() + return value + + +def _field_extension_name(field: pa.Field) -> Optional[str]: + extension_name = _field_metadata_value(field, _ARROW_EXTENSION_NAME_KEY) + if extension_name is not None: + return extension_name + if isinstance(field.type, pa.ExtensionType): + return field.type.extension_name + return None + + +def _field_storage_type(field: pa.Field) -> pa.DataType: + if isinstance(field.type, pa.ExtensionType): + return field.type.storage_type + return field.type + + +def _is_bfloat16_field(field: pa.Field) -> bool: + if _field_extension_name(field) != _BFLOAT16_EXTENSION_NAME: + return False + storage_type = _field_storage_type(field) + return pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2 + + +def _check_torch_nulls(array: pa.Array, column_name: str) -> None: + if array.null_count: + raise ValueError( + f"Cannot convert column `{column_name}` to a torch tensor because it " + f"contains {array.null_count} null value(s). Drop or fill nulls before " + "using a torch format." + ) + + +def _bfloat16_to_tensor(array: pa.Array, torch, column_name: str): + storage = array.storage if isinstance(array.type, pa.ExtensionType) else array + storage_type = storage.type + if not ( + pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2 + ): + raise ValueError( + f"Column `{column_name}` is marked as {_BFLOAT16_EXTENSION_NAME!r} but " + f"has storage type {storage_type}. The lance.bfloat16 extension requires " + "fixed_size_binary[2] storage." + ) + _check_torch_nulls(storage, column_name) + if len(storage) == 0: + return torch.empty((0,), dtype=torch.bfloat16) + + buffer = storage.buffers()[1] + if buffer is None: + return torch.empty((0,), dtype=torch.bfloat16) + offset = storage.offset * 2 + byte_length = len(storage) * 2 + if buffer.size < offset + byte_length: + raise ValueError( + f"Column `{column_name}` has a truncated bfloat16 value buffer." + ) + + # Arrow stores bfloat16 as two little-endian bytes. Copy only on big-endian + # hosts before viewing the same bits as torch.bfloat16. + values = np.frombuffer( + buffer, dtype=np.dtype(" bool: + data_type = array.type + if isinstance(data_type, pa.ExtensionType) or array.null_count == 0: + return False + return pa.types.is_integer(data_type) or pa.types.is_floating(data_type) + + +def _nullable_numeric_scalar_to_tensor(array: pa.Array, torch, column_name: str): + try: + numpy_values = array.to_numpy(zero_copy_only=False) + except pa.ArrowInvalid as err: + raise ValueError( + f"Cannot convert nullable column `{column_name}` of type {array.type} " + f"to a torch tensor: {err}" + ) from err + try: + return torch.from_numpy(numpy_values) + except (TypeError, RuntimeError) as err: + raise ValueError( + f"Cannot convert nullable column `{column_name}` of type {array.type} " + f"to a torch tensor: {err}" + ) from err + + +def _batch_column_tensors(batch: pa.RecordBatch, allow_scalar_nulls: bool = False): + torch = attempt_import_or_raise("torch", "torch") + columns = [] + for field, column in zip(batch.schema, batch.columns): + if allow_scalar_nulls and _is_nullable_numeric_scalar(column): + tensor = _nullable_numeric_scalar_to_tensor(column, torch, field.name) + else: + tensor = _arrow_column_to_tensor(column, field, torch, field.name) + columns.append((field.name, tensor)) + return torch, columns + + +def _uniform_column_tensors( + batch: pa.RecordBatch, format_name: str, allow_scalar_nulls: bool = False +): + torch, columns = _batch_column_tensors(batch, allow_scalar_nulls=allow_scalar_nulls) + if len(columns) <= 1: + return torch, columns + + first_name, first = columns[0] + first_shape = tuple(first.shape[1:]) + for name, tensor in columns[1:]: + shape = tuple(tensor.shape[1:]) + if shape != first_shape: + raise ValueError( + f"Cannot use the {format_name!r} format because column `{name}` " + f"has sample shape {shape} while column `{first_name}` has sample " + f'shape {first_shape}. Use with_format("torch_dict") for columns ' + 'with different shapes, or with_format("torch") for a list of ' + "per-row dicts." + ) + return torch, columns + + def batch_to_tensor(batch: pa.RecordBatch): """ Convert a PyArrow RecordBatch to a PyTorch Tensor. - Each column is converted to a tensor (using zero-copy via DLPack) - and the columns are then stacked into a single tensor. + Each column is converted to a tensor with shape ``(rows, *sample_shape)`` + and the columns are stacked along a new leading dimension. Scalar columns + have sample shape ``()`` and fixed-size-list columns contribute each list + dimension. All columns must have the same sample shape. Fails if torch is not installed. Fails if a column's data type is not supported by PyTorch. + Fails if a column contains nulls. Parameters ---------- @@ -628,43 +867,99 @@ def batch_to_tensor(batch: pa.RecordBatch): Returns ------- - torch.Tensor: The tensor containing the columns of the record batch. + torch.Tensor: A tensor with shape ``(columns, rows, *sample_shape)``. A + one-column batch returns an ``unsqueeze(0)`` view of that column. """ - torch = attempt_import_or_raise("torch", "torch") - return torch.stack([torch.from_dlpack(col) for col in batch.columns]) + torch, columns = _uniform_column_tensors(batch, "torch_col") + if not columns: + return torch.empty((0, batch.num_rows)) + if len(columns) == 1: + return columns[0][1].unsqueeze(0) + return torch.stack([tensor for _, tensor in columns], dim=0) def batch_to_tensor_rows(batch: pa.RecordBatch): """ - Convert a PyArrow RecordBatch to a list of PyTorch Tensor, one per row + Convert a PyArrow RecordBatch to a list of PyTorch Tensors, one per row. - Each column is converted to a tensor (using zero-copy via DLPack) - and the columns are then stacked into a single tensor. The 2D tensor - is then converted to a list of tensors, one per row + Each row tensor has shape ``(columns, *sample_shape)``. All columns must + have the same sample shape, so a table mixing scalar and vector columns + should use ``torch_dict`` or ``torch`` instead. Dtypes are combined with + ``torch.promote_types``, matching PyTorch's numeric promotion rules. - Fails if torch or numpy is not installed. + Fails if torch is not installed. Fails if a column's data type is not supported by PyTorch. + Nulls in ordinary integer or floating scalar columns become ``NaN``. + Nulls in nested fixed-size-list or tensor columns are rejected. + + Parameters + ---------- + batch : pa.RecordBatch + The record batch to convert. + + Returns + ------- + list[torch.Tensor] + One tensor per row, each with shape ``(columns, *sample_shape)``. A + one-column scalar batch produces ``(1,)`` tensors. """ - torch = attempt_import_or_raise("torch", "torch") - numpy = attempt_import_or_raise("numpy", "numpy") - columns = [col.to_numpy(zero_copy_only=False) for col in batch.columns] - stacked = torch.tensor(numpy.column_stack(columns)) - rows = list(stacked.unbind(dim=0)) - return rows + torch, columns = _uniform_column_tensors( + batch, "torch_row", allow_scalar_nulls=True + ) + if not columns: + return [torch.empty((0,)) for _ in range(batch.num_rows)] + + dtype = columns[0][1].dtype + for _, tensor in columns[1:]: + dtype = torch.promote_types(dtype, tensor.dtype) + tensors = [ + tensor if tensor.dtype == dtype else tensor.to(dtype) for _, tensor in columns + ] + stacked = torch.stack(tensors, dim=1) + return list(stacked.unbind(dim=0)) + + +def batch_to_tensor_columns(batch: pa.RecordBatch): + """ + Convert a PyArrow RecordBatch to a dict of per-column PyTorch Tensors. + + Each tensor has shape ``(rows, *sample_shape)`` and shares Arrow storage + where the layout allows it. Unlike ``torch_col`` and ``torch_row``, columns + may have different sample shapes. This is the transform behind + ``Permutation.with_format("torch_dict")`` and can be consumed directly by + a ``DataLoader`` with an identity ``collate_fn``. + + Fails if torch is not installed. + Fails if a column's data type is not supported by PyTorch. + Fails if a column contains nulls. + + Parameters + ---------- + batch : pa.RecordBatch + The record batch to convert. + + Returns + ------- + dict[str, torch.Tensor] + A tensor per column, each with shape ``(rows, *sample_shape)``. + """ + _, columns = _batch_column_tensors(batch) + return dict(columns) def batch_to_tensor_dict(batch: pa.RecordBatch): """ Convert a PyArrow RecordBatch to a list of per-row dicts of PyTorch Tensors. - Each column is first converted to a 1-D tensor (zero-copy via DLPack), then - sliced per row. The result is a list whose length is ``batch.num_rows`` and - whose items are dicts keyed by column name. This shape composes directly - with PyTorch's default ``DataLoader`` collate, which stacks the per-row - dicts back into a dict of batched tensors. + Each column is converted to a tensor with shape ``(rows, *sample_shape)``, + then sliced per row. The result is a list whose length is + ``batch.num_rows`` and whose items are dicts keyed by column name. This + shape composes directly with PyTorch's default ``DataLoader`` collate, + which stacks the per-row dicts back into a dict of batched tensors. Fails if torch is not installed. Fails if a column's data type is not supported by PyTorch. + Fails if a column contains nulls. Parameters ---------- @@ -675,14 +970,9 @@ def batch_to_tensor_dict(batch: pa.RecordBatch): ------- list[dict[str, torch.Tensor]] One per-row dict per row in the batch. Each dict maps column name to a - 0-D tensor view into the column. + tensor view into the column. """ - torch = attempt_import_or_raise("torch", "torch") - tensors = { - name: torch.from_dlpack(col) - for name, col in zip(batch.schema.names, batch.columns) - } + _, columns = _batch_column_tensors(batch) return [ - {name: tensor[i] for name, tensor in tensors.items()} - for i in range(batch.num_rows) + {name: tensor[i] for name, tensor in columns} for i in range(batch.num_rows) ] diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index a52aa420e..4a4c54a56 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -1224,6 +1224,31 @@ def test_transform_fn_pandas(mem_db): assert isinstance(result, pd.DataFrame) +def test_numpy_format_mixed_columns_is_object_ndarray(mem_db): + pytest.importorskip("pandas") + import numpy as np + + tbl = mem_db.create_table( + "test_table", + pa.table( + { + "id": range(3), + "vector": pa.array( + [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], + type=pa.list_(pa.float32(), 2), + ), + } + ), + ) + permutation = Permutation.identity(tbl).with_format("numpy") + result = next(permutation.iter(2, skip_last_batch=False)) + + assert isinstance(result, np.ndarray) + assert result.dtype == object + assert result.shape == (2, 2) + np.testing.assert_array_equal(result[0, 1], [1.0, 2.0]) + + def test_custom_transform(mem_db): tbl = mem_db.create_table( "test_table", pa.table({"id": range(10), "value": range(10)}) diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py index 1cc6500bd..e555bf7db 100644 --- a/python/python/tests/test_torch.py +++ b/python/python/tests/test_torch.py @@ -8,13 +8,15 @@ import json import multiprocessing as mp import pickle import re +import struct import sys import lancedb +import numpy as np import pyarrow as pa import pytest from lancedb.permutation import Permutation, Permutations, permutation_builder -from lancedb.util import tbl_to_tensor +from lancedb.util import batch_to_tensor, batch_to_tensor_columns, tbl_to_tensor from utils import start_server_thread torch = pytest.importorskip("torch") @@ -23,6 +25,43 @@ torch = pytest.importorskip("torch") REMOTE_ROWS = list(range(100)) +def _identity_collate(batch): + return batch + + +class _LanceBFloat16Type(pa.ExtensionType): + def __init__(self): + pa.ExtensionType.__init__(self, pa.binary(2), "lance.bfloat16") + + def __arrow_ext_serialize__(self): + return b"" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + return cls() + + +def _bf16_storage(values): + bits = torch.tensor(values, dtype=torch.bfloat16).view(torch.int16).tolist() + return [struct.pack("