jorisvandenbossche commented on code in PR #38472:
URL: https://github.com/apache/arrow/pull/38472#discussion_r1408870138
##########
python/pyarrow/tests/test_array.py:
##########
@@ -3546,3 +3548,122 @@ def test_run_end_encoded_from_buffers():
with pytest.raises(ValueError):
pa.RunEndEncodedArray.from_buffers(ree_type, length, buffers,
1, offset, children)
+
+
+def PyCapsule_IsValid(capsule, name):
+ return ctypes.pythonapi.PyCapsule_IsValid(ctypes.py_object(capsule), name)
== 1
+
+
[email protected](
+ ('value_type', 'np_type'),
+ [
+ (pa.uint8(), np.uint8),
+ (pa.uint16(), np.uint16),
+ (pa.uint32(), np.uint32),
+ (pa.uint64(), np.uint64),
+ (pa.int8(), np.int8),
+ (pa.int16(), np.int16),
+ (pa.int32(), np.int32),
+ (pa.int64(), np.int64),
+ (pa.float32(), np.float32),
+ (pa.float64(), np.float64),
+ ]
+)
+def test_dlpack(value_type, np_type):
+ if Version(np.__version__) < Version("1.24.0"):
+ pytest.skip("No dlpack support in numpy versions older than 1.22.0, "
+ "strict keyward in assert_array_equal added in numpy
version "
+ "1.24.0")
+
+ arr = pa.array([1, 2, 3], type=value_type)
+ DLTensor = arr.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ expected = np.array([1, 2, 3], dtype=np_type)
+ result = np.from_dlpack(arr)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+ arr_sliced = arr.slice(1, 1)
+ DLTensor = arr_sliced.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ expected = np.array([2], dtype=np_type)
+ result = np.from_dlpack(arr_sliced)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+ arr_sliced = arr.slice(0, 1)
+ DLTensor = arr_sliced.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ expected = np.array([1], dtype=np_type)
+ result = np.from_dlpack(arr_sliced)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+ arr_sliced = arr.slice(1)
+ DLTensor = arr_sliced.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ expected = np.array([2, 3], dtype=np_type)
+ result = np.from_dlpack(arr_sliced)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+ arr_zero = pa.array([], type=value_type)
+ DLTensor = arr_zero.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ expected = np.array([], dtype=np_type)
+ result = np.from_dlpack(arr_zero)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+
+def test_dlpack_float_16():
+ if Version(np.__version__) < Version("1.24.0"):
+ pytest.skip("No dlpack support in numpy versions older than 1.22.0, "
+ "strict keyward in assert_array_equal added in numpy
version "
+ "1.24.0")
+
+ expected = np.array([1, 2, 3], dtype=np.float16)
+ arr = pa.array(expected, type=pa.float16())
+ DLTensor = arr.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ result = np.from_dlpack(arr)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+
+def test_dlpack_not_supported():
+ if Version(np.__version__) < Version("1.22.0"):
+ pytest.skip("No dlpack support in numpy versions older than 1.22.0.")
+
+ with pytest.raises(TypeError, match="Can only use __dlpack__ "
+ "on arrays with no validity buffer."):
+ arr = pa.array([1, None, 3])
Review Comment:
Can you put the array creation before the `with` context? The message match
will ensure we are not testing a wrong error, but ideally we only put in the
context the part that raises the error we want to test
##########
cpp/src/arrow/c/dlpack.cc:
##########
@@ -0,0 +1,139 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "arrow/c/dlpack.h"
+
+#include "arrow/array/array_base.h"
+#include "arrow/c/dlpack_abi.h"
+#include "arrow/device.h"
+#include "arrow/type.h"
+
+namespace arrow {
+
+namespace dlpack {
+
+Status getDLDataType(const std::shared_ptr<DataType>& type, DLDataType* out) {
+ DLDataType dtype;
+ dtype.lanes = 1;
+ dtype.bits = type->bit_width();
+ switch (type->id()) {
+ case Type::INT8:
+ case Type::INT16:
+ case Type::INT32:
+ case Type::INT64:
+ dtype.code = DLDataTypeCode::kDLInt;
+ *out = dtype;
+ return Status::OK();
+ case Type::UINT8:
+ case Type::UINT16:
+ case Type::UINT32:
+ case Type::UINT64:
+ dtype.code = DLDataTypeCode::kDLUInt;
+ *out = dtype;
+ return Status::OK();
+ case Type::HALF_FLOAT:
+ case Type::FLOAT:
+ case Type::DOUBLE:
+ dtype.code = DLDataTypeCode::kDLFloat;
+ *out = dtype;
+ return Status::OK();
+ case Type::BOOL:
+ // DLPack supports byte-packed boolean values
+ return Status::TypeError("Bit-packed boolean data type not supported by
DLPack.");
+ default:
+ return Status::TypeError(
+ "Can only use __dlpack__ on primitive arrays without NullType and
Decimal "
+ "types.");
+ }
+}
+
+struct DLMTensorCtx {
+ std::shared_ptr<ArrayData> ref;
+ std::vector<int64_t> shape;
+ DLManagedTensor tensor;
+};
+
+static void deleter(DLManagedTensor* arg) {
+ delete static_cast<DLMTensorCtx*>(arg->manager_ctx);
+}
+
+Status ExportArray(const std::shared_ptr<Array>& arr, DLManagedTensor** out) {
+ if (arr->null_count() > 0) {
+ return Status::TypeError(
+ "Can only use __dlpack__ on arrays with no validity buffer.");
Review Comment:
```suggestion
"Can only use __dlpack__ on arrays with no nulls.");
```
##########
cpp/src/arrow/dlpack.h:
##########
@@ -0,0 +1,32 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include "arrow/array/array_base.h"
+#include "arrow/dlpack_structure.h"
+
+namespace arrow {
+
+/// \brief DLPack protocol for producing DLManagedTensor
+///
+/// Returns pointer to the DLManagedTensor class defined by
+// the DLPack protocol
+ARROW_EXPORT
+DLManagedTensor* ExportToDLPack(const std::shared_ptr<Array>& arr);
Review Comment:
So in what you implemented now, it's still the ExportArray function that
allocates the struct (so the memory is not owned by the consumer or the capsule
itself on the python side of the interface), right? But the struct is stored in
`DLMTensorCtx` (the private data), and this gets deallocated by the deleter,
which gets called by the consumer at the end (or at destruction of the capsule
if not consumed), so that ensures it gets cleaned up?
##########
python/pyarrow/tests/test_array.py:
##########
@@ -3546,3 +3548,122 @@ def test_run_end_encoded_from_buffers():
with pytest.raises(ValueError):
pa.RunEndEncodedArray.from_buffers(ree_type, length, buffers,
1, offset, children)
+
+
+def PyCapsule_IsValid(capsule, name):
+ return ctypes.pythonapi.PyCapsule_IsValid(ctypes.py_object(capsule), name)
== 1
+
+
[email protected](
+ ('value_type', 'np_type'),
+ [
+ (pa.uint8(), np.uint8),
+ (pa.uint16(), np.uint16),
+ (pa.uint32(), np.uint32),
+ (pa.uint64(), np.uint64),
+ (pa.int8(), np.int8),
+ (pa.int16(), np.int16),
+ (pa.int32(), np.int32),
+ (pa.int64(), np.int64),
+ (pa.float32(), np.float32),
+ (pa.float64(), np.float64),
+ ]
+)
+def test_dlpack(value_type, np_type):
+ if Version(np.__version__) < Version("1.24.0"):
+ pytest.skip("No dlpack support in numpy versions older than 1.22.0, "
+ "strict keyward in assert_array_equal added in numpy
version "
+ "1.24.0")
+
+ arr = pa.array([1, 2, 3], type=value_type)
+ DLTensor = arr.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ expected = np.array([1, 2, 3], dtype=np_type)
+ result = np.from_dlpack(arr)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+ arr_sliced = arr.slice(1, 1)
+ DLTensor = arr_sliced.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ expected = np.array([2], dtype=np_type)
+ result = np.from_dlpack(arr_sliced)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+ arr_sliced = arr.slice(0, 1)
+ DLTensor = arr_sliced.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ expected = np.array([1], dtype=np_type)
+ result = np.from_dlpack(arr_sliced)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+ arr_sliced = arr.slice(1)
+ DLTensor = arr_sliced.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ expected = np.array([2, 3], dtype=np_type)
+ result = np.from_dlpack(arr_sliced)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+ arr_zero = pa.array([], type=value_type)
+ DLTensor = arr_zero.__dlpack__()
+ assert PyCapsule_IsValid(DLTensor, b"dltensor") is True
+ expected = np.array([], dtype=np_type)
+ result = np.from_dlpack(arr_zero)
+ np.testing.assert_array_equal(result, expected, strict=True)
+
+
+def test_dlpack_float_16():
Review Comment:
Is there a reason this one is not included in the parametrized test above?
(slicing isn't tested this way)
##########
python/pyarrow/includes/libarrow.pxd:
##########
@@ -1199,6 +1199,60 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil:
shared_ptr[CScalar] MakeNullScalar(shared_ptr[CDataType] type)
+cdef extern from "arrow/dlpack_structure.h" nogil:
+ cdef enum DLDeviceType:
Review Comment:
FWIW this isn't yet pushed?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]