Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DOC: Document that GIL must be grabbed (and Py_IsInitialized()) #140

Merged
merged 4 commits into from
Mar 22, 2024
Merged
Changes from 3 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
31 changes: 31 additions & 0 deletions docs/source/python_spec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,37 @@ C API which is called either when the refcount on the capsule named
Note: the capsule names ``"dltensor"`` and ``"used_dltensor"`` must be
statically allocated.

The ``DLManagedTensor`` deleter must ensure that sharing beyond Python
boundaries is possible, this means that the GIL must be acquired explicitly.
Copy link
Member

@tqchen tqchen Mar 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

aquired explicitly if the original memory comes from python runtime and deleter involves interacting with python runtime. If the original memory allocation comes from other languages(e.g. c++ and exposed to python) and de-allocation does not involve python runtime, then it is not necessary to grab the GIL.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair, added "[...] if it uses Python objects or API"

In Python, the deleter usually needs to ``Py_DECREF()`` the original owner
and free the ``DLManagedTensor`` allocation.
For example, NumPy uses the following code to ensure sharing with arbitrary
non-Python code is safe:

.. code-block:: C

static void array_dlpack_deleter(DLManagedTensor *self)
seberg marked this conversation as resolved.
Show resolved Hide resolved
{
/*
* Leak the Python object if the Python runtime is not available.
* This can happen if the DLPack consumer destroys the tensor late
* after Python runtime finalization (for example in case the tensor
* was indirectly kept alive by a C++ static variable).
*/
if (!Py_IsInitialized()) {
return;
}

PyGILState_STATE state = PyGILState_Ensure();

PyObject *array = (PyObject *)self->manager_ctx;
// This will also free the shape and strides as it's one allocation.
PyMem_Free(self);
Py_XDECREF(array);

PyGILState_Release(state);
}

When the ``strides`` field in the ``DLTensor`` struct is ``NULL``, it indicates a
row-major compact array. If the array is of size zero, the data pointer in
``DLTensor`` should be set to either ``NULL`` or ``0``.
Expand Down
Loading