jorisvandenbossche commented on code in PR #38472:
URL: https://github.com/apache/arrow/pull/38472#discussion_r1402089809


##########
cpp/src/arrow/dlpack.cc:
##########
@@ -0,0 +1,97 @@
+// Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   @pitrou any advice on where to put this in the C++ codebase? Just as 
top-level files in /arrow, or does it fit better somewhere else?



##########
cpp/src/arrow/dlpack_structure.h:
##########


Review Comment:
   Small suggestion to rename this to `dlpack_abi.h`



##########
cpp/src/arrow/dlpack.cc:
##########
@@ -0,0 +1,97 @@
+// 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/dlpack.h"
+
+#include "arrow/array/array_base.h"
+#include "arrow/dlpack_structure.h"
+#include "arrow/type.h"
+
+namespace arrow {
+
+DLDataType getDLDataType(const Array& arr) {
+  DLDataType dtype;
+  dtype.lanes = 1;
+  dtype.bits = arr.type()->bit_width();
+  switch (arr.type()->id()) {
+    case Type::INT8:
+    case Type::INT16:
+    case Type::INT32:
+    case Type::INT64:
+      dtype.code = DLDataTypeCode::kDLInt;
+      break;
+    case Type::UINT8:
+    case Type::UINT16:
+    case Type::UINT32:
+    case Type::UINT64:
+      dtype.code = DLDataTypeCode::kDLUInt;
+      break;
+    case Type::HALF_FLOAT:
+    case Type::FLOAT:
+    case Type::DOUBLE:
+      dtype.code = DLDataTypeCode::kDLFloat;
+      break;
+    case Type::BOOL:
+      dtype.code = DLDataTypeCode::kDLBool;
+      break;
+    default:
+      // TODO
+      break;
+  }
+  return dtype;
+}
+
+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);
+}
+
+DLManagedTensor* toDLPack(const Array& arr) {

Review Comment:
   If we want to have this usable from C++ as well, I think we should add some 
validation of the input Array here? (i.e. checking it has no nulls; that it is 
a primitive type will implicitly be done by getDLDataType)



##########
cpp/src/arrow/dlpack.cc:
##########
@@ -0,0 +1,97 @@
+// 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/dlpack.h"
+
+#include "arrow/array/array_base.h"
+#include "arrow/dlpack_structure.h"
+#include "arrow/type.h"
+
+namespace arrow {
+
+DLDataType getDLDataType(const Array& arr) {

Review Comment:
   You can probably pass the type directory here, since that's the only thing 
needed



##########
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:
   I think this can be removed now (or at least part of it) now the bulk of the 
implementation doesn't live in cython?



##########
python/pyarrow/tests/test_array.py:
##########
@@ -3546,3 +3548,59 @@ 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',
+    [pa.uint8(), pa.uint32(), pa.int16(), pa.float32()]
+)
+def test_dlpack(value_type):
+    if Version(np.__version__) < Version("1.22.0"):
+        pytest.skip("No dlpack support in numpy versions older than 1.22.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])
+    result = np.from_dlpack(arr)
+    np.testing.assert_array_equal(result, expected)

Review Comment:
   `assert_array_equal` doesn't require the dtypes to be the same? We should 
also assert that part



##########
python/pyarrow/_dlpack.pxi:
##########
@@ -0,0 +1,48 @@
+# 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.
+
+from libc.stdlib cimport malloc, free
+
+cimport cpython
+from cpython.pycapsule cimport PyCapsule_New
+from cython import sizeof
+
+
+cdef void pycapsule_deleter(object dltensor) noexcept:
+    cdef DLManagedTensor* dlm_tensor
+    cdef PyObject* err_type
+    cdef PyObject* err_value
+    cdef PyObject* err_traceback
+
+    if cpython.PyCapsule_IsValid(dltensor, "used_dltensor"):
+        return
+
+    cpython.PyErr_Fetch(&err_type, &err_value, &err_traceback)

Review Comment:
   Can you add some comments about why this fetch/restore is done? (I see in 
the example on https://dmlc.github.io/dlpack/latest/python_spec.html there are 
some comments)



##########
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

Review Comment:
   Can you expand this doc note? (parameter section, maybe point to the DLPack 
webpage, restrictions about what the Array can be, ..)



##########
cpp/src/arrow/dlpack_structure.h:
##########


Review Comment:
   Can you also add to the comment the exact commit from which you copied it 
from the repo? (eg see 
https://github.com/numpy/numpy/blob/main/numpy/_core/src/common/dlpack/dlpack.h)



##########
python/pyarrow/array.pxi:
##########
@@ -21,6 +21,8 @@ import os
 import warnings
 from cython import sizeof
 
+include "_dlpack.pxi"

Review Comment:
   You can move this to lib.pyx where the other includes live



##########
python/pyarrow/tests/test_array.py:
##########
@@ -3546,3 +3548,59 @@ 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',
+    [pa.uint8(), pa.uint32(), pa.int16(), pa.float32()]

Review Comment:
   I suppose you can expand this parametrization to every single supported dtype



##########
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* toDLPack(const Array& arr);

Review Comment:
   Small nit, but following the namin scheme from the C Data bridge, we can 
maybe call this "ExportToDLPack"?



-- 
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]

Reply via email to