diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py index d8f846e24..1f5b527e7 100644 --- a/python/python/lancedb/util.py +++ b/python/python/lancedb/util.py @@ -582,9 +582,9 @@ def add_note(base_exception: BaseException, note: str): raise ValueError("Cannot add note to exception") -def tbl_to_tensor(tbl: pa.Table): +def tbl_to_tensor(tbl: Union[pa.Table, pa.RecordBatch]): """ - Convert a PyArrow Table to a PyTorch Tensor. + Convert a PyArrow Table or 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. @@ -604,10 +604,14 @@ def tbl_to_tensor(tbl: pa.Table): """ torch = attempt_import_or_raise("torch", "torch") - def to_tensor(col: pa.ChunkedArray): - if col.num_chunks > 1: - raise Exception("Single batch was too large to fit into a one-chunk table") - return torch.from_dlpack(col.chunk(0)) + def to_tensor(col: Union[pa.Array, pa.ChunkedArray]): + if isinstance(col, pa.ChunkedArray): + if col.num_chunks > 1: + raise Exception( + "Single batch was too large to fit into a one-chunk table" + ) + col = col.chunk(0) if col.num_chunks else pa.array([], type=col.type) + return torch.from_dlpack(col) return torch.stack([to_tensor(tbl.column(i)) for i in range(tbl.num_columns)]) diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py index afbba92d1..899c3c142 100644 --- a/python/python/tests/test_torch.py +++ b/python/python/tests/test_torch.py @@ -191,6 +191,31 @@ class _DatasetHoldingConnectionAndTable(torch.utils.data.Dataset): return row +def test_tbl_to_tensor_record_batch(): + batch = pa.record_batch({"id": [1, 2], "label": [3, 4]}).slice(1) + expected = torch.tensor([[2], [4]]) + + assert torch.equal(tbl_to_tensor(batch), expected) + assert torch.equal(tbl_to_tensor(pa.Table.from_batches([batch])), expected) + + +def test_tbl_to_tensor_empty_table(): + schema = pa.schema([("x", pa.float32()), ("y", pa.float32())]) + table = pa.Table.from_batches([], schema=schema) + + tensor = tbl_to_tensor(table) + + assert tensor.shape == (2, 0) + assert tensor.dtype == torch.float32 + + +def test_tbl_to_tensor_rejects_multiple_chunks(): + table = pa.table({"id": pa.chunked_array([[1], [2]])}) + + with pytest.raises(Exception, match="one-chunk table"): + tbl_to_tensor(table) + + def test_table_dataloader(mem_db): table = mem_db.create_table("test_table", pa.table({"a": range(1000)})) dataloader = torch.utils.data.DataLoader(