From e435593602385c102f9f87fe5033e09b899fec31 Mon Sep 17 00:00:00 2001 From: Divyam Talwar Date: Mon, 30 Nov 2026 17:42:36 +0530 Subject: [PATCH] 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> --- python/python/lancedb/util.py | 16 ++++++++++------ python/python/tests/test_torch.py | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) 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(