mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
fix(python): convert Arrow record batches to Torch tensors (#5264)
Fixes #5263 ## Summary - Send an Arrow record batch's array columns directly through DLPack. - For table columns, keep the existing one-chunk conversion and multiple-chunk error. Use a typed empty array for a column with zero chunks. - Cover sliced record batches, equivalent one-chunk tables, empty table shape and dtype, and the multiple-chunk guard. ## Validation - Verified the record-batch and empty-table tests fail on `main`. All three `tbl_to_tensor` tests pass with PyArrow 26.0.1 and CPU Torch 2.10.0. - Ruff check, Ruff format check, and `git diff --check` pass. Co-authored-by: Divyam Talwar <237515611+DivyamTalwar@users.noreply.github.com>
This commit is contained in:
co-authored by
Divyam Talwar
parent
fd745ac4f3
commit
e435593602
@@ -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)])
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user