From acbda1893c55c68b3afd6c4cde1ee11e6926bb75 Mon Sep 17 00:00:00 2001 From: Wes McKinney Date: Mon, 10 Apr 2017 08:11:25 -0400 Subject: [PATCH 1/3] ARROW-794: [C++/Python] Disallow strided tensors in ipc::WriteTensor Author: Wes McKinney Closes #519 from wesm/ARROW-794 and squashes the following commits: ab82ba7 [Wes McKinney] Typo 6f0a350 [Wes McKinney] Typo e945298 [Wes McKinney] Raise ValueError if writing strided ndarray with WriteTensor and pyarrow.write_tensor --- cpp/src/arrow/ipc/ipc-read-write-test.cc | 18 ++++++++++++++++++ cpp/src/arrow/ipc/writer.cc | 4 ++++ python/pyarrow/tests/test_tensor.py | 13 +++++++++++++ 3 files changed, 35 insertions(+) diff --git a/cpp/src/arrow/ipc/ipc-read-write-test.cc b/cpp/src/arrow/ipc/ipc-read-write-test.cc index 6807296b59a5..1a91ec39ca1f 100644 --- a/cpp/src/arrow/ipc/ipc-read-write-test.cc +++ b/cpp/src/arrow/ipc/ipc-read-write-test.cc @@ -642,5 +642,23 @@ TEST_F(TestTensorRoundTrip, BasicRoundtrip) { CheckTensorRoundTrip(tzero); } +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 values; + test::randint(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 } // namespace arrow diff --git a/cpp/src/arrow/ipc/writer.cc b/cpp/src/arrow/ipc/writer.cc index 9305567e74f6..d38a65c983d9 100644 --- a/cpp/src/arrow/ipc/writer.cc +++ b/cpp/src/arrow/ipc/writer.cc @@ -496,6 +496,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 metadata; RETURN_NOT_OK(WriteTensorMessage(tensor, 0, &metadata)); diff --git a/python/pyarrow/tests/test_tensor.py b/python/pyarrow/tests/test_tensor.py index a39064b49dfb..327b7f08a37f 100644 --- a/python/pyarrow/tests/test_tensor.py +++ b/python/pyarrow/tests/test_tensor.py @@ -98,3 +98,16 @@ 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) From 0d787ad673616059cf24e49ba36b6aba2a5155e4 Mon Sep 17 00:00:00 2001 From: Wes McKinney Date: Sun, 9 Apr 2017 22:11:08 -0400 Subject: [PATCH 2/3] Add GetTensorSize method, Python bindings Change-Id: Ida6a652624e7d59ae3579ebf9ff7e4d9c6a5bf94 --- cpp/src/arrow/ipc/ipc-read-write-test.cc | 4 +++ cpp/src/arrow/ipc/writer.cc | 29 ++++++++++++--------- cpp/src/arrow/ipc/writer.h | 4 +++ python/pyarrow/__init__.py | 3 ++- python/pyarrow/includes/libarrow.pxd | 3 +++ python/pyarrow/io.pyx | 20 ++++++++++++++ python/pyarrow/tests/test_convert_pandas.py | 4 +-- python/pyarrow/tests/test_ipc.py | 9 +++++++ python/pyarrow/tests/test_tensor.py | 9 ++++++- 9 files changed, 69 insertions(+), 16 deletions(-) diff --git a/cpp/src/arrow/ipc/ipc-read-write-test.cc b/cpp/src/arrow/ipc/ipc-read-write-test.cc index 1a91ec39ca1f..0422f1fbc89c 100644 --- a/cpp/src/arrow/ipc/ipc-read-write-test.cc +++ b/cpp/src/arrow/ipc/ipc-read-write-test.cc @@ -640,6 +640,10 @@ TEST_F(TestTensorRoundTrip, BasicRoundtrip) { CheckTensorRoundTrip(t0); CheckTensorRoundTrip(tzero); + + int64_t serialized_size; + ASSERT_OK(GetTensorSize(t0, &serialized_size)); + ASSERT_TRUE(serialized_size > (size * sizeof(int64_t))); } TEST_F(TestTensorRoundTrip, NonContiguous) { diff --git a/cpp/src/arrow/ipc/writer.cc b/cpp/src/arrow/ipc/writer.cc index d38a65c983d9..c96df3b35b34 100644 --- a/cpp/src/arrow/ipc/writer.cc +++ b/cpp/src/arrow/ipc/writer.cc @@ -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 Status VisitFixedWidth(const ArrayType& array) { @@ -522,8 +512,23 @@ Status WriteDictionary(int64_t dictionary_id, const std::shared_ptr& 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(); } diff --git a/cpp/src/arrow/ipc/writer.h b/cpp/src/arrow/ipc/writer.h index 0b7a6e1b56be..fa5d713372f5 100644 --- a/cpp/src/arrow/ipc/writer.h +++ b/cpp/src/arrow/ipc/writer.h @@ -81,6 +81,10 @@ Status WriteDictionary(int64_t dictionary_id, const std::shared_ptr& 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(); diff --git a/python/pyarrow/__init__.py b/python/pyarrow/__init__.py index 7b23cf66c6f7..df615b428c1c 100644 --- a/python/pyarrow/__init__.py +++ b/python/pyarrow/__init__.py @@ -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 diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index e719e185b7b1..19182897306b 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -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) diff --git a/python/pyarrow/io.pyx b/python/pyarrow/io.pyx index 98b5a62b372a..4eb0816ecbde 100644 --- a/python/pyarrow/io.pyx +++ b/python/pyarrow/io.pyx @@ -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 diff --git a/python/pyarrow/tests/test_convert_pandas.py b/python/pyarrow/tests/test_convert_pandas.py index d1bea0b3e32f..4a57e4ba1d4f 100644 --- a/python/pyarrow/tests/test_convert_pandas.py +++ b/python/pyarrow/tests/test_convert_pandas.py @@ -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) @@ -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) diff --git a/python/pyarrow/tests/test_ipc.py b/python/pyarrow/tests/test_ipc.py index 4c9dad1b840a..31d418d5150a 100644 --- a/python/pyarrow/tests/test_ipc.py +++ b/python/pyarrow/tests/test_ipc.py @@ -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) diff --git a/python/pyarrow/tests/test_tensor.py b/python/pyarrow/tests/test_tensor.py index 327b7f08a37f..ec71735b2a54 100644 --- a/python/pyarrow/tests/test_tensor.py +++ b/python/pyarrow/tests/test_tensor.py @@ -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 @@ -111,3 +112,9 @@ def test_tensor_ipc_strided(): 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) From 983177ec774b88099f04076a05d0484a02ed5521 Mon Sep 17 00:00:00 2001 From: Wes McKinney Date: Sun, 9 Apr 2017 22:18:17 -0400 Subject: [PATCH 3/3] Fix sign comparison warning Change-Id: If091a37420364234c8e219639ce95914366c93cb --- cpp/src/arrow/ipc/ipc-read-write-test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/arrow/ipc/ipc-read-write-test.cc b/cpp/src/arrow/ipc/ipc-read-write-test.cc index 0422f1fbc89c..f3a15236df0b 100644 --- a/cpp/src/arrow/ipc/ipc-read-write-test.cc +++ b/cpp/src/arrow/ipc/ipc-read-write-test.cc @@ -643,7 +643,7 @@ TEST_F(TestTensorRoundTrip, BasicRoundtrip) { int64_t serialized_size; ASSERT_OK(GetTensorSize(t0, &serialized_size)); - ASSERT_TRUE(serialized_size > (size * sizeof(int64_t))); + ASSERT_TRUE(serialized_size > static_cast(size * sizeof(int64_t))); } TEST_F(TestTensorRoundTrip, NonContiguous) {