Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions cpp/src/arrow/ipc/ipc-read-write-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,28 @@ TEST_F(TestTensorRoundTrip, BasicRoundtrip) {

CheckTensorRoundTrip(t0);
CheckTensorRoundTrip(tzero);

int64_t serialized_size;
ASSERT_OK(GetTensorSize(t0, &serialized_size));
ASSERT_TRUE(serialized_size > static_cast<int64_t>(size * sizeof(int64_t)));
}

TEST_F(TestTensorRoundTrip, NonContiguous) {
std::string path = "test-write-tensor-strided";
constexpr int64_t kBufferSize = 1 << 20;
ASSERT_OK(io::MemoryMapFixture::InitMemoryMap(kBufferSize, path, &mmap_));

std::vector<int64_t> values;
test::randint<int64_t>(24, 0, 100, &values);

auto data = test::GetBufferFromVector(values);
Int64Tensor tensor(data, {4, 3}, {48, 16});

int32_t metadata_length;
int64_t body_length;
ASSERT_OK(mmap_->Seek(0));
ASSERT_RAISES(
Invalid, WriteTensor(tensor, mmap_.get(), &metadata_length, &body_length));
}

} // namespace ipc
Expand Down
33 changes: 21 additions & 12 deletions cpp/src/arrow/ipc/writer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -192,16 +192,6 @@ class RecordBatchWriter : public ArrayVisitor {
return Status::OK();
}

Status GetTotalSize(const RecordBatch& batch, int64_t* size) {
// emulates the behavior of Write without actually writing
int32_t metadata_length = 0;
int64_t body_length = 0;
MockOutputStream dst;
RETURN_NOT_OK(Write(batch, &dst, &metadata_length, &body_length));
*size = dst.GetExtentBytesWritten();
return Status::OK();
}

protected:
template <typename ArrayType>
Status VisitFixedWidth(const ArrayType& array) {
Expand Down Expand Up @@ -496,6 +486,10 @@ Status WriteLargeRecordBatch(const RecordBatch& batch, int64_t buffer_start_offs

Status WriteTensor(const Tensor& tensor, io::OutputStream* dst, int32_t* metadata_length,
int64_t* body_length) {
if (!tensor.is_contiguous()) {
return Status::Invalid("No support yet for writing non-contiguous tensors");
}

RETURN_NOT_OK(AlignStreamPosition(dst));
std::shared_ptr<Buffer> metadata;
RETURN_NOT_OK(WriteTensorMessage(tensor, 0, &metadata));
Expand All @@ -518,8 +512,23 @@ Status WriteDictionary(int64_t dictionary_id, const std::shared_ptr<Array>& dict
}

Status GetRecordBatchSize(const RecordBatch& batch, int64_t* size) {
RecordBatchWriter writer(default_memory_pool(), 0, kMaxNestingDepth, true);
RETURN_NOT_OK(writer.GetTotalSize(batch, size));
// emulates the behavior of Write without actually writing
int32_t metadata_length = 0;
int64_t body_length = 0;
MockOutputStream dst;
RETURN_NOT_OK(WriteRecordBatch(batch, 0, &dst, &metadata_length, &body_length,
default_memory_pool(), kMaxNestingDepth, true));
*size = dst.GetExtentBytesWritten();
return Status::OK();
}

Status GetTensorSize(const Tensor& tensor, int64_t* size) {
// emulates the behavior of Write without actually writing
int32_t metadata_length = 0;
int64_t body_length = 0;
MockOutputStream dst;
RETURN_NOT_OK(WriteTensor(tensor, &dst, &metadata_length, &body_length));
*size = dst.GetExtentBytesWritten();
return Status::OK();
}

Expand Down
4 changes: 4 additions & 0 deletions cpp/src/arrow/ipc/writer.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ Status WriteDictionary(int64_t dictionary_id, const std::shared_ptr<Array>& dict
// Flatbuffers metadata.
Status ARROW_EXPORT GetRecordBatchSize(const RecordBatch& batch, int64_t* size);

// Compute the precise number of bytes needed in a contiguous memory segment to
// write the tensor including metadata, padding, and data
Status ARROW_EXPORT GetTensorSize(const Tensor& tensor, int64_t* size);

class ARROW_EXPORT StreamWriter {
public:
virtual ~StreamWriter();
Expand Down
3 changes: 2 additions & 1 deletion python/pyarrow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
Buffer, BufferReader, InMemoryOutputStream,
MemoryMappedFile, memory_map,
frombuffer, read_tensor, write_tensor,
memory_map, create_memory_map)
memory_map, create_memory_map,
get_record_batch_size, get_tensor_size)

from pyarrow.ipc import FileReader, FileWriter, StreamReader, StreamWriter

Expand Down
3 changes: 3 additions & 0 deletions python/pyarrow/includes/libarrow.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,9 @@ cdef extern from "arrow/ipc/api.h" namespace "arrow::ipc" nogil:

CStatus GetRecordBatch(int i, shared_ptr[CRecordBatch]* batch)

CStatus GetRecordBatchSize(const CRecordBatch& batch, int64_t* size)
CStatus GetTensorSize(const CTensor& tensor, int64_t* size)

CStatus WriteTensor(const CTensor& tensor, OutputStream* dst,
int32_t* metadata_length,
int64_t* body_length)
Expand Down
20 changes: 20 additions & 0 deletions python/pyarrow/io.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1202,6 +1202,26 @@ cdef class FeatherReader:
return col


def get_tensor_size(Tensor tensor):
"""
Return total size of serialized Tensor including metadata and padding
"""
cdef int64_t size
with nogil:
check_status(GetTensorSize(deref(tensor.tp), &size))
return size


def get_record_batch_size(RecordBatch batch):
"""
Return total size of serialized RecordBatch including metadata and padding
"""
cdef int64_t size
with nogil:
check_status(GetRecordBatchSize(deref(batch.batch), &size))
return size


def write_tensor(Tensor tensor, NativeFile dest):
"""
Write pyarrow.Tensor to pyarrow.NativeFile object its current position
Expand Down
4 changes: 2 additions & 2 deletions python/pyarrow/tests/test_convert_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def _check_pandas_roundtrip(self, df, expected=None, nthreads=1,
timestamps_to_ms=False, expected_schema=None,
check_dtype=True, schema=None):
table = pa.Table.from_pandas(df, timestamps_to_ms=timestamps_to_ms,
schema=schema)
schema=schema)
result = table.to_pandas(nthreads=nthreads)
if expected_schema:
assert table.schema.equals(expected_schema)
Expand All @@ -79,7 +79,7 @@ def _check_pandas_roundtrip(self, df, expected=None, nthreads=1,
def _check_array_roundtrip(self, values, expected=None, mask=None,
timestamps_to_ms=False, type=None):
arr = pa.Array.from_numpy(values, timestamps_to_ms=timestamps_to_ms,
mask=mask, type=type)
mask=mask, type=type)
result = arr.to_pandas()

values_nulls = pd.isnull(values)
Expand Down
9 changes: 9 additions & 0 deletions python/pyarrow/tests/test_ipc.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ def test_ipc_zero_copy_numpy():
assert_frame_equal(df, rdf)


def test_get_record_batch_size():
N = 10
itemsize = 8
df = pd.DataFrame({'foo': np.random.randn(N)})

batch = pa.RecordBatch.from_pandas(df)
assert pa.get_record_batch_size(batch) > (N * itemsize)


def write_file(batch, sink):
writer = pa.FileWriter(sink, batch.schema)
writer.write_batch(batch)
Expand Down
22 changes: 21 additions & 1 deletion python/pyarrow/tests/test_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,11 @@ def test_tensor_attrs():
tensor = pa.Tensor.from_numpy(data2)
assert not tensor.is_mutable


def test_tensor_base_object():
tensor = pa.Tensor.from_numpy(np.random.randn(10, 4))
n = sys.getrefcount(tensor)
array = tensor.to_numpy()
array = tensor.to_numpy() # noqa
assert sys.getrefcount(tensor) == n + 1


Expand Down Expand Up @@ -98,3 +99,22 @@ def test_tensor_ipc_roundtrip():
assert result.equals(tensor)
finally:
_try_delete(path)


def test_tensor_ipc_strided():
data = np.random.randn(10, 4)
tensor = pa.Tensor.from_numpy(data[::2])

path = 'pyarrow-tensor-ipc-strided'
try:
with pytest.raises(ValueError):
mmap = pa.create_memory_map(path, 1024)
pa.write_tensor(tensor, mmap)
finally:
_try_delete(path)


def test_tensor_size():
data = np.random.randn(10, 4)
tensor = pa.Tensor.from_numpy(data)
assert pa.get_tensor_size(tensor) > (data.size * 8)