feat(python)!: support vector columns in permutation torch formats (#5131)

BREAKING CHANGE: `Permutation.with_format("torch_row")` now uses PyTorch
dtype promotion instead of NumPy promotion. Mixed numeric columns can
change dtype, for example int64 and float32 now produce float32 instead
of float64. Cast columns before formatting when the old dtype matters.
Nullable scalar integer and floating columns still produce NaN; nulls in
nested fixed-size-list or tensor columns, and in bfloat16 columns, are
rejected.

## Problem

`Permutation.with_format("torch")`, `"torch_col"`, and `"torch_row"`
fail when the selected columns include a vector (`FixedSizeList`)
column, which is the column training workloads need. The conversion also
has to preserve Arrow slice offsets, logical `FixedShapeTensor` axes,
and visible nested nulls instead of flattening over them.

## Behavior

- Add `with_format("torch_dict")`: a dict of per-column `(B, *S)`
tensors, usable directly with a `DataLoader` identity collate. Tensors
share Arrow storage where the layout allows.
- Extend `torch` per-row dicts to nested `FixedSizeList` and
`FixedShapeTensor`; PyTorch's default collate stacks them back into `(B,
*S)` tensors.
- Preserve `torch_col` as `(C, B, *S)`, including a zero-copy
`unsqueeze(0)` view for one column.
- Preserve `torch_row` as per-row `(C, *S)` tensors, including `(1,)`
for one scalar column, with `torch.promote_types` for mixed numeric
dtypes. Nullable scalar integer and floating columns keep their previous
NaN behavior; nested fixed-size-list and tensor nulls are rejected.
- `torch_col` and `torch_row` reject heterogeneous sample shapes with
the field names, shapes, and guidance to `torch_dict`.
- Support nested fixed-size lists, `FixedShapeTensor` logical axis
permutations, boolean/integer/floating leaves, empty batches, and
nonzero slice offsets. `torch_dict`, `torch`, and `torch_col` reject
visible nulls.
- NumPy still returns one ndarray. Its pandas conversion may copy, may
promote mixed numeric columns to a common numeric dtype (for example
int64 and float32 to float64), and produces an object array for nested
or incompatible columns.
- `lance.bfloat16` is accepted only for a `FixedSizeBinary(2)` leaf
carrying the `ARROW:extension:name` metadata; offsets/length and byte
order are handled before viewing as `torch.bfloat16`. Unmarked binary
columns are rejected.

This is Python-only and does not change persistence, pickling, or public
method signatures.

## Validation

- `pyarrow 26.0.1`, `torch 2.15.0+cu132`, Python 3.12: `test_torch.py`
23 passed; `test_permutation.py` 84 passed.
- Minimum `pyarrow 16.0.0`, `torch 2.0.1+cpu`, Python 3.11: the nullable
scalar, mixed-dtype, null-rejection, and NumPy tests passed (4 focused
tests). The new NumPy test skips without pandas via
`pytest.importorskip`.
- The pre-existing fork DataLoader tests are flaky only when the full
`test_torch.py` file runs on the minimum stack; each passes when run
alone. Their failure is on the default Python format path and does not
exercise the changed format conversions.
- `ruff format`, `ruff check`, and `git diff --check` pass.
This commit is contained in:
Xuanwo
2026-11-21 02:21:51 +08:00
committed by GitHub
parent 7eb40118ac
commit 1658c8d762
5 changed files with 963 additions and 68 deletions
+49 -15
View File
@@ -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":
+319 -29
View File
@@ -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("<u2"), count=len(storage), offset=offset
)
if sys.byteorder != "little":
values = values.astype(np.uint16)
# Older torch releases cannot create a tensor from np.uint16, so view the
# same bits as signed 16-bit values before interpreting them as bfloat16.
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message="The given NumPy array is not writable",
category=UserWarning,
)
return torch.from_numpy(values.view(np.int16)).view(torch.bfloat16)
def _leaf_to_tensor(array: pa.Array, field: pa.Field, torch, column_name: str):
_check_torch_nulls(array, column_name)
if _is_bfloat16_field(field):
return _bfloat16_to_tensor(array, torch, column_name)
data_type = array.type
if isinstance(data_type, pa.ExtensionType):
raise ValueError(
f"Unsupported PyTorch column type {data_type} for column "
f"`{column_name}`. Supported extension types are "
f"{_BFLOAT16_EXTENSION_NAME!r} and arrow.fixed_shape_tensor."
)
if (
pa.types.is_boolean(data_type)
or pa.types.is_integer(data_type)
or pa.types.is_floating(data_type)
):
# Arrow packs booleans as bits while torch uses one byte per value, so
# boolean columns always need a copy. Other numeric columns share the
# Arrow buffer.
zero_copy_only = not pa.types.is_boolean(data_type)
try:
numpy_values = array.to_numpy(zero_copy_only=zero_copy_only)
except pa.ArrowInvalid as err:
raise ValueError(
f"Cannot convert column `{column_name}` of type {data_type} to a "
f"torch tensor without copying: {err}"
) from err
try:
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message="The given NumPy array is not writable",
category=UserWarning,
)
return torch.from_numpy(numpy_values)
except (TypeError, RuntimeError) as err:
raise ValueError(
f"Cannot convert column `{column_name}` of type {data_type} to a "
f"torch tensor: {err}"
) from err
if pa.types.is_fixed_size_binary(data_type) and data_type.byte_width == 2:
raise ValueError(
f"Column `{column_name}` has type fixed_size_binary[2] but is not "
f"marked with {_ARROW_EXTENSION_NAME_KEY!r} = "
f"{_BFLOAT16_EXTENSION_NAME!r}. An unmarked binary column is not "
"treated as bfloat16."
)
raise ValueError(
f"Unsupported PyTorch column type {data_type} for column `{column_name}`. "
"Supported leaf types are boolean, integer, floating point, and "
f"{_BFLOAT16_EXTENSION_NAME!r} fixed_size_binary[2] values."
)
def _fixed_size_list_to_tensor(array: pa.FixedSizeListArray, torch, column_name: str):
_check_torch_nulls(array, column_name)
width = array.type.list_size
values = array.values.slice(array.offset * width, len(array) * width)
child_tensor = _arrow_column_to_tensor(
values, array.type.value_field, torch, column_name
)
return child_tensor.reshape((len(array), width, *child_tensor.shape[1:]))
def _fixed_shape_tensor_to_tensor(array: pa.Array, torch, column_name: str):
_check_torch_nulls(array, column_name)
tensor_type = array.type
storage = array.storage
physical_shape = list(tensor_type.shape)
permutation = list(getattr(tensor_type, "permutation", None) or [])
storage_tensor = _arrow_column_to_tensor(
storage, storage.type.value_field, torch, column_name
)
tensor = storage_tensor.reshape((len(array), *physical_shape))
if permutation:
# Arrow's ``shape`` is the physical row-major shape, and
# ``permutation`` maps a logical axis to its physical axis. Transposing
# by it restores the logical shape as a view.
tensor = tensor.permute([0] + [axis + 1 for axis in permutation])
return tensor
def _arrow_column_to_tensor(array: pa.Array, field: pa.Field, torch, column_name: str):
if isinstance(array.type, pa.FixedShapeTensorType):
return _fixed_shape_tensor_to_tensor(array, torch, column_name)
if pa.types.is_fixed_size_list(array.type):
return _fixed_size_list_to_tensor(array, torch, column_name)
return _leaf_to_tensor(array, field, torch, column_name).reshape((len(array),))
def _is_nullable_numeric_scalar(array: pa.Array) -> 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)
]
+25
View File
@@ -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)})
+509 -1
View File
@@ -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("<H", bit & 0xFFFF) for bit in bits]
def _bf16_array(values):
storage = pa.array(_bf16_storage(values), type=pa.binary(2))
return pa.ExtensionArray.from_storage(_LanceBFloat16Type(), storage)
def _fixed_shape_tensor_array(physical_values, shape, permutation=None):
tensor_type = pa.fixed_shape_tensor(
pa.float32(), shape, permutation=permutation or []
)
flat_values = np.asarray(physical_values, dtype=np.float32).reshape(-1)
storage = pa.FixedSizeListArray.from_arrays(
pa.array(flat_values), int(np.prod(shape))
)
return pa.ExtensionArray.from_storage(tensor_type, storage)
def _make_mock_http_handler(handler):
class MockLanceDBHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
@@ -496,3 +535,472 @@ def test_remote_permutation_dataloader_fork_workers():
finally:
server.shutdown()
handle.join()
def test_permutation_torch_dict_mixed_columns(mem_db):
vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
grids = [
[[float(row), float(row) + 1.0], [float(row) + 2.0, float(row) + 3.0]]
for row in range(5)
]
table = mem_db.create_table(
"mixed",
pa.table(
{
"id": pa.array(range(5), type=pa.int32()),
"score": pa.array([i / 2 for i in range(5)], type=pa.float32()),
"vector": pa.array(vectors, type=pa.list_(pa.float32(), 3)),
"grid": pa.array(grids, type=pa.list_(pa.list_(pa.float32(), 2), 2)),
}
),
)
permutation = Permutation.identity(table).with_format("torch_dict")
batch = next(permutation.iter(5, skip_last_batch=False))
assert set(batch) == {"id", "score", "vector", "grid"}
assert batch["id"].shape == (5,)
assert batch["id"].dtype == torch.int32
assert batch["score"].dtype == torch.float32
assert batch["vector"].shape == (5, 3)
assert batch["grid"].shape == (5, 2, 2)
assert torch.equal(batch["vector"], torch.tensor(vectors))
assert torch.equal(batch["grid"], torch.tensor(grids))
items = permutation.__getitems__([0, 2, 4])
assert items["id"].shape == (3,)
assert items["score"].shape == (3,)
assert items["vector"].shape == (3, 3)
assert items["grid"].shape == (3, 2, 2)
dataloader = torch.utils.data.DataLoader(
permutation,
batch_size=2,
shuffle=False,
collate_fn=_identity_collate,
)
batches = list(dataloader)
assert [batch["id"].shape[0] for batch in batches] == [2, 2, 1]
assert batches[0]["vector"].shape == (2, 3)
assert batches[-1]["grid"].shape == (1, 2, 2)
empty = permutation.take_offsets([])
assert empty["id"].shape == (0,)
assert empty["vector"].shape == (0, 3)
assert empty["grid"].shape == (0, 2, 2)
torch_permutation = Permutation.identity(table).with_format("torch")
per_row = next(torch_permutation.iter(2, skip_last_batch=False))
assert isinstance(per_row, list)
assert per_row[0]["vector"].shape == (3,)
assert per_row[0]["grid"].shape == (2, 2)
torch_loader = torch.utils.data.DataLoader(
torch_permutation, batch_size=2, shuffle=False
)
collated = next(iter(torch_loader))
assert collated["vector"].shape == (2, 3)
assert collated["grid"].shape == (2, 2, 2)
def test_permutation_torch_dict_dataloader_spawn(tmp_db):
vectors = [[float(i), float(i) + 0.5] for i in range(11)]
table = tmp_db.create_table(
"spawn",
pa.table(
{
"id": range(11),
"vector": pa.array(vectors, type=pa.list_(pa.float32(), 2)),
}
),
)
permutation = Permutation.identity(table).with_format("torch_dict")
dataloader = torch.utils.data.DataLoader(
permutation,
batch_size=4,
shuffle=False,
num_workers=2,
multiprocessing_context="spawn",
collate_fn=_identity_collate,
)
seen = []
for batch in dataloader:
assert isinstance(batch, dict)
assert batch["id"].shape == (batch["id"].shape[0],)
assert batch["vector"].shape == (batch["id"].shape[0], 2)
seen.extend(batch["id"].tolist())
assert sorted(seen) == list(range(11))
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)
batch = pa.record_batch(
[
pa.array(range(5), type=pa.int64()),
pa.array(vectors, type=pa.list_(pa.float32(), 3)),
pa.array(
nested_values.tolist(),
type=pa.list_(pa.list_(pa.float32(), 2), 3),
),
pa.array([True, False, True, False, True]),
],
names=["id", "vector", "nested", "active"],
).slice(2, 2)
tensors = batch_to_tensor_columns(batch)
assert tensors["id"].tolist() == [2, 3]
assert torch.equal(tensors["vector"], torch.tensor(vectors[2:4]))
assert torch.equal(tensors["nested"], torch.from_numpy(nested_values[2:4].copy()))
assert tensors["active"].dtype == torch.bool
assert tensors["active"].tolist() == [True, False]
id_array = batch.column("id")
assert tensors["id"].data_ptr() == (
id_array.buffers()[1].address + id_array.offset * 8
)
vector_array = batch.column("vector")
vector_values = vector_array.values
expected_vector_offset = (vector_array.offset * 3 + vector_values.offset) * 4
assert tensors["vector"].data_ptr() == (
vector_values.buffers()[1].address + expected_vector_offset
)
single_column = pa.record_batch([batch.column("vector")], names=["vector"])
column_tensor = batch_to_tensor(single_column)
assert column_tensor.shape == (1, 2, 3)
assert column_tensor.data_ptr() == tensors["vector"].data_ptr()
def test_permutation_torch_col_and_row_vector_layouts(mem_db):
left = [[float(i), float(i) + 0.5] for i in range(4)]
right = [[float(i) + 1.0, float(i) + 1.5] for i in range(4)]
table = mem_db.create_table(
"uniform",
pa.table(
{
"left": pa.array(left, type=pa.list_(pa.float32(), 2)),
"right": pa.array(right, type=pa.list_(pa.float32(), 2)),
}
),
)
permutation = Permutation.identity(table)
column_batch = next(
permutation.with_format("torch_col").iter(4, skip_last_batch=False)
)
assert column_batch.shape == (2, 4, 2)
assert column_batch.dtype == torch.float32
assert torch.equal(column_batch[0], torch.tensor(left))
row_batch = next(
permutation.with_format("torch_row").iter(4, skip_last_batch=False)
)
assert len(row_batch) == 4
assert row_batch[0].shape == (2, 2)
assert torch.equal(
row_batch[0], torch.stack([torch.tensor(left[0]), torch.tensor(right[0])])
)
dataloader = torch.utils.data.DataLoader(
permutation.with_format("torch_row"), batch_size=4, shuffle=False
)
stacked = next(iter(dataloader))
assert stacked.shape == (4, 2, 2)
scalar_table = mem_db.create_table(
"single_scalar", pa.table({"x": pa.array(range(4), type=pa.int64())})
)
scalar_rows = next(
Permutation.identity(scalar_table)
.with_format("torch_row")
.iter(4, skip_last_batch=False)
)
assert scalar_rows[0].shape == (1,)
assert scalar_rows[0].dtype == torch.int64
vector_table = mem_db.create_table(
"single_vector",
pa.table({"v": pa.array(left, type=pa.list_(pa.float32(), 2))}),
)
vector_rows = next(
Permutation.identity(vector_table)
.with_format("torch_row")
.iter(4, skip_last_batch=False)
)
assert vector_rows[0].shape == (1, 2)
vector_column = next(
Permutation.identity(vector_table)
.with_format("torch_col")
.iter(4, skip_last_batch=False)
)
assert vector_column.shape == (1, 4, 2)
def test_torch_col_and_row_reject_heterogeneous_shapes(mem_db):
table = mem_db.create_table(
"heterogeneous",
pa.table(
{
"id": pa.array(range(4), type=pa.int64()),
"vector": pa.array(
[[float(i), float(i) + 1.0, float(i) + 2.0] for i in range(4)],
type=pa.list_(pa.float32(), 3),
),
}
),
)
permutation = Permutation.identity(table)
for format_name in ("torch_col", "torch_row"):
with pytest.raises(ValueError, match="torch_dict") as exc_info:
next(permutation.with_format(format_name).iter(2, skip_last_batch=False))
message = str(exc_info.value)
assert "`vector`" in message
assert "(3,)" in message
assert "`id`" in message
assert "()" in message
different_dims = mem_db.create_table(
"different_dims",
pa.table(
{
"left": pa.array(
[[1.0, 2.0] for _ in range(4)],
type=pa.list_(pa.float32(), 2),
),
"right": pa.array(
[[1.0, 2.0, 3.0] for _ in range(4)],
type=pa.list_(pa.float32(), 3),
),
}
),
)
with pytest.raises(ValueError, match="torch_dict") as exc_info:
next(
Permutation.identity(different_dims)
.with_format("torch_row")
.iter(2, skip_last_batch=False)
)
message = str(exc_info.value)
assert "`right`" in message and "(3,)" in message
assert "`left`" in message and "(2,)" in message
def test_torch_row_uses_pytorch_numeric_promotion(mem_db):
table = mem_db.create_table(
"promotion",
pa.table(
{
"id": pa.array(range(4), type=pa.int64()),
"score": pa.array([i / 2 for i in range(4)], type=pa.float32()),
"count": pa.array(range(4), type=pa.int32()),
}
),
)
rows = next(
Permutation.identity(table)
.with_format("torch_row")
.iter(4, skip_last_batch=False)
)
assert rows[0].shape == (3,)
assert rows[0].dtype == torch.float32
assert rows[0].tolist() == [0.0, 0.0, 0.0]
assert rows[2].tolist() == [2.0, 1.0, 2.0]
def test_torch_row_preserves_nullable_numeric_scalar_nan(mem_db):
nullable_int = mem_db.create_table(
"nullable_int",
pa.table({"value": pa.array([1, None, 3], type=pa.int64())}),
)
rows = next(
Permutation.identity(nullable_int)
.with_format("torch_row")
.iter(3, skip_last_batch=False)
)
assert rows[0].shape == (1,)
assert rows[0].dtype == torch.float64
assert rows[0].tolist() == [1.0]
assert torch.isnan(rows[1]).all()
assert rows[2].tolist() == [3.0]
nullable_float = mem_db.create_table(
"nullable_float",
pa.table({"value": pa.array([0.5, None, 2.5], type=pa.float32())}),
)
rows = next(
Permutation.identity(nullable_float)
.with_format("torch_row")
.iter(3, skip_last_batch=False)
)
assert rows[0].dtype == torch.float32
assert rows[0].tolist() == [0.5]
assert torch.isnan(rows[1]).all()
assert rows[2].tolist() == [2.5]
nullable_mixed = mem_db.create_table(
"nullable_mixed",
pa.table(
{
"id": pa.array([1, None, 3], type=pa.int64()),
"score": pa.array([0.5, 1.5, 2.5], type=pa.float32()),
}
),
)
rows = next(
Permutation.identity(nullable_mixed)
.with_format("torch_row")
.iter(3, skip_last_batch=False)
)
assert rows[0].dtype == torch.float64
assert rows[0].tolist() == [1.0, 0.5]
assert torch.isnan(rows[1][0])
assert rows[1][1].item() == 1.5
assert rows[2].tolist() == [3.0, 2.5]
def test_permutation_torch_formats_fixed_shape_tensor_permutation(mem_db):
physical_values = np.arange(2 * 2 * 3 * 4, dtype=np.float32).reshape(2, 2, 3, 4)
tensor_array = _fixed_shape_tensor_array(
physical_values, shape=(2, 3, 4), permutation=[0, 2, 1]
)
table = mem_db.create_table(
"tensor_permutation",
pa.table({"id": range(2), "tensor": tensor_array}),
)
permutation = Permutation.identity(table)
expected = np.transpose(physical_values, (0, 1, 3, 2))
batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
assert batch["tensor"].shape == (2, 2, 4, 3)
assert torch.equal(batch["tensor"], torch.from_numpy(expected.copy()))
tensor_only = permutation.select_columns(["tensor"])
rows = next(tensor_only.with_format("torch_row").iter(2, skip_last_batch=False))
assert rows[0].shape == (1, 2, 4, 3)
assert torch.equal(rows[0][0], torch.from_numpy(expected[0].copy()))
dataloader = torch.utils.data.DataLoader(
tensor_only.with_format("torch"), batch_size=2, shuffle=False
)
default_collated = next(iter(dataloader))
assert default_collated["tensor"].shape == (2, 2, 4, 3)
def test_permutation_torch_formats_bfloat16(mem_db):
values = [1.0, -1.5, 2.5, 0.0]
scalar_values = _bf16_array(values)
vector_values = pa.FixedSizeListArray.from_arrays(
_bf16_array([value for value in values for _ in range(2)]), 2
)
table = mem_db.create_table(
"bfloat16",
pa.table(
{
"id": range(4),
"scalar": scalar_values,
"vector": vector_values,
}
),
)
permutation = Permutation.identity(table)
batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
assert batch["scalar"].dtype == torch.bfloat16
assert batch["vector"].dtype == torch.bfloat16
assert torch.equal(batch["scalar"], torch.tensor(values[:2], dtype=torch.bfloat16))
assert torch.equal(
batch["vector"],
torch.tensor([[value, value] for value in values[:2]], dtype=torch.bfloat16),
)
arrow_batch = next(permutation.with_format("arrow").iter(2, skip_last_batch=False))
arrow_tensors = batch_to_tensor_columns(arrow_batch)
scalar_array = arrow_batch.column("scalar")
assert arrow_tensors["scalar"].data_ptr() == (
scalar_array.buffers()[1].address + scalar_array.offset * 2
)
sliced = arrow_batch.slice(1, 1)
sliced_tensors = batch_to_tensor_columns(sliced)
assert torch.equal(
sliced_tensors["scalar"],
torch.tensor([values[1]], dtype=torch.bfloat16),
)
assert torch.equal(
sliced_tensors["vector"],
torch.tensor([[values[1], values[1]]], dtype=torch.bfloat16),
)
skipped = next(
permutation.with_skip(1)
.with_format("torch_dict")
.iter(2, skip_last_batch=False)
)
assert torch.equal(
skipped["scalar"], torch.tensor(values[1:3], dtype=torch.bfloat16)
)
empty = permutation.with_format("torch_dict").take_offsets([])
assert empty["scalar"].shape == (0,)
assert empty["scalar"].dtype == torch.bfloat16
assert empty["vector"].shape == (0, 2)
assert empty["vector"].dtype == torch.bfloat16
unmarked = mem_db.create_table(
"unmarked_bfloat16",
pa.table(
{
"vector": pa.FixedSizeListArray.from_arrays(
pa.array(_bf16_storage(values), type=pa.binary(2)), 2
)
}
),
)
with pytest.raises(ValueError, match="not marked.*lance.bfloat16"):
next(
Permutation.identity(unmarked)
.with_format("torch_dict")
.iter(2, skip_last_batch=False)
)
def test_torch_formats_reject_nulls(mem_db):
parent_nulls = mem_db.create_table(
"parent_nulls",
pa.table(
{
"id": range(3),
"values": pa.array(
[[1.0, 2.0], None, [5.0, 6.0]],
type=pa.list_(pa.float32(), 2),
),
}
),
)
with pytest.raises(ValueError, match="contains 1 null"):
next(
Permutation.identity(parent_nulls)
.with_format("torch_dict")
.iter(2, skip_last_batch=False)
)
leaf_nulls = mem_db.create_table(
"leaf_nulls",
pa.table(
{
"id": range(2),
"values": pa.FixedSizeListArray.from_arrays(
pa.array([1.0, None, 5.0, 6.0], type=pa.float32()), 2
),
}
),
)
with pytest.raises(ValueError, match="contains 1 null"):
next(
Permutation.identity(leaf_nulls)
.with_format("torch_dict")
.iter(2, skip_last_batch=False)
)
leaf_only = Permutation.identity(leaf_nulls).select_columns(["values"])
with pytest.raises(ValueError, match="contains 1 null"):
next(leaf_only.with_format("torch_row").iter(2, skip_last_batch=False))