Skip to content
185 changes: 152 additions & 33 deletions suitesparse_graphblas/api/io/serialize.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import operator
import warnings

import numpy as np

from suitesparse_graphblas import check_status, ffi, lib
from suitesparse_graphblas.api.global_options import global_get_int32
from suitesparse_graphblas.exceptions import InvalidValue
from suitesparse_graphblas.utils import claim_buffer


Expand All @@ -11,11 +15,85 @@ def _free_desc(desc):
lib.GrB_Descriptor_free(desc_ptr)


def _call_with_nthreads(nthreads, func, *args):
"""Return ``func(*args)``, called under a new GxB_Context with `nthreads` threads.

GraphBLAS 10 takes the number of threads from the Context engaged on the calling thread,
not from a descriptor. If `nthreads` is None, 0 or negative, `func` is just called.
`nthreads` must be an integer, and not a bool.

Apart from the number of threads, the new Context is a copy of GxB_CONTEXT_WORLD:
GxB_Context_new copies its chunk and GPUs, and the arenas are copied here, since they
would otherwise be arena 0. WORLD is the Context the call would use without `nthreads`,
because a Context engaged on this thread makes this raise.

It all happens in this one frame, in try and finally blocks, rather than in a generator
context manager. A KeyboardInterrupt can come as the context manager's ``__exit__``
begins, before the generator resumes, and that leaves disengaging and freeing the Context
to garbage collection: later, and on PyPy perhaps in another thread.
"""
if nthreads is not None:
# NumPy 2.2 still lets `operator.index` take its bool, with a DeprecationWarning
if isinstance(nthreads, (bool, np.bool_)):
raise TypeError("nthreads must be an integer, not a bool")
nthreads = operator.index(nthreads) # TypeError if it isn't an integer
if nthreads is None or nthreads <= 0:
return func(*args)
ctx = ffi.new("GxB_Context*")
# A KeyboardInterrupt between here and `try` leaks the Context, which isn't engaged yet
check_status(ctx, lib.GxB_Context_new(ctx))
try:
# A Context engaged on this thread would be lost: GraphBLAS can't say which one it
# is, so it can't be engaged again afterwards. But it can say whether there is one:
# disengaging a Context that isn't engaged fails with GrB_INVALID_VALUE if another
# one is, and changes nothing.
info = lib.GxB_Context_disengage(ctx[0])
if info == lib.GrB_INVALID_VALUE:
raise InvalidValue(
"nthreads can't be given while a GxB_Context is engaged on this thread; "
"set GxB_CONTEXT_NTHREADS of that Context instead"
)
check_status(ctx, info)
# OverflowError if `nthreads` doesn't fit in int32_t
check_status(ctx, lib.GxB_Context_set_INT(ctx[0], nthreads, lib.GxB_CONTEXT_NTHREADS))
header_arena = global_get_int32(lib.GxB_ARENA_HEADER)
check_status(ctx, lib.GxB_Context_set_INT(ctx[0], header_arena, lib.GxB_ARENA_HEADER))
data_arena = global_get_int32(lib.GxB_ARENA_DATA)
check_status(ctx, lib.GxB_Context_set_INT(ctx[0], data_arena, lib.GxB_ARENA_DATA))
try:
check_status(ctx, lib.GxB_Context_engage(ctx[0]))
return func(*args)
finally:
lib.GxB_Context_disengage(ctx[0])
finally:
# Disengaging a Context that isn't engaged changes nothing, so disengage it again, in
# case a KeyboardInterrupt stopped the `finally` above before it could (PyPy may stop
# it at its first bytecode). Freeing it while engaged would leave the thread with a
# dangling Context.
lib.GxB_Context_disengage(ctx[0])
lib.GxB_Context_free(ctx)


def get_serialize_desc(compression=lib.GxB_COMPRESSION_DEFAULT, level=None, nthreads=None):
"""Create a descriptor for serializing or deserializing.

This returns None (for NULL descriptor) or a GrB_Descriptor.

.. deprecated:: 10.5.3.0
The `nthreads` argument. The number of threads isn't a descriptor setting in
GraphBLAS 10, which raises InvalidValue if `nthreads` is given. Use the `nthreads`
argument of serialize_matrix, serialize_vector, deserialize_matrix or
deserialize_vector instead, which sets it in a GxB_Context.
"""
if nthreads is not None:
warnings.warn(
"The `nthreads` argument of get_serialize_desc is deprecated: GraphBLAS 10 "
"rejects the number of threads in a descriptor. Use the `nthreads` argument "
"of serialize_matrix, serialize_vector, deserialize_matrix or "
"deserialize_vector instead.",
DeprecationWarning,
stacklevel=2,
)
if nthreads is None and (compression is None or compression == lib.GxB_COMPRESSION_DEFAULT):
return None
desc_ptr = ffi.new("GrB_Descriptor*")
Expand Down Expand Up @@ -50,18 +128,26 @@ def serialize_matrix(A, compression=lib.GxB_COMPRESSION_DEFAULT, level=None, *,
level : int, optional
For GxB_COMPRESSION_LZ4HC, should be between 1 and 9, where 9 is most compressed.
For GxB_COMPRESSION_ZSTD, should be between 1 and 19, where 19 is most compressed.

nthreads : int, optional
The maximum number of OpenMP threads to use.
The maximum number of OpenMP threads to use. None (the default), 0 or any negative
integer, however large, means the number of threads of the GxB_Context engaged on
this thread, if any, or else of GxB_CONTEXT_WORLD. A positive integer makes the
call run under a new Context with that many threads. It raises OverflowError if
that is more than int32_t holds, and InvalidValue if a Context is engaged on this
thread (which stays engaged: set its number of threads instead). Raises TypeError
if `nthreads` isn't an integer, or is a bool.
"""
desc = get_serialize_desc(compression, level, nthreads)
desc = get_serialize_desc(compression, level)
data_ptr = ffi.new("void**")
size_ptr = ffi.new("GrB_Index*")
# Name the arena for the result, which is otherwise that of the engaged Context (if
# any), so that `claim_buffer` knows which allocator must free it
arena = global_get_int32(lib.GxB_ARENA_DATA)
desc = ffi.NULL if desc is None else desc
check_status(A, lib.GxB_Matrix_serialize_arena(data_ptr, size_ptr, A[0], arena, desc))
info = _call_with_nthreads(
nthreads, lib.GxB_Matrix_serialize_arena, data_ptr, size_ptr, A[0], arena, desc
)
check_status(A, info)
return claim_buffer(ffi, data_ptr[0], size_ptr[0], np.dtype(np.uint8), arena)


Expand All @@ -77,38 +163,59 @@ def serialize_vector(v, compression=lib.GxB_COMPRESSION_DEFAULT, level=None, *,
For GxB_COMPRESSION_LZ4HC, should be between 1 and 9, where 9 is most compressed.
For GxB_COMPRESSION_ZSTD, should be between 1 and 19, where 19 is most compressed.
nthreads : int, optional
The maximum number of OpenMP threads to use.
The maximum number of OpenMP threads to use. None (the default), 0 or any negative
integer, however large, means the number of threads of the GxB_Context engaged on
this thread, if any, or else of GxB_CONTEXT_WORLD. A positive integer makes the
call run under a new Context with that many threads. It raises OverflowError if
that is more than int32_t holds, and InvalidValue if a Context is engaged on this
thread (which stays engaged: set its number of threads instead). Raises TypeError
if `nthreads` isn't an integer, or is a bool.
"""
desc = get_serialize_desc(compression, level, nthreads)
desc = get_serialize_desc(compression, level)
data_ptr = ffi.new("void**")
size_ptr = ffi.new("GrB_Index*")
arena = global_get_int32(lib.GxB_ARENA_DATA) # see `serialize_matrix`
desc = ffi.NULL if desc is None else desc
check_status(v, lib.GxB_Vector_serialize_arena(data_ptr, size_ptr, v[0], arena, desc))
info = _call_with_nthreads(
nthreads, lib.GxB_Vector_serialize_arena, data_ptr, size_ptr, v[0], arena, desc
)
check_status(v, info)
return claim_buffer(ffi, data_ptr[0], size_ptr[0], np.dtype(np.uint8), arena)


def deserialize_matrix(data, *, free=True, nthreads=None):
"""Deserialize a Matrix from bytes.

The `free` argument is called when the object is garbage
collected, the default is `matrix.matrix_free()`. If `free` is None then
there is no automatic garbage collection and it is up to the user
to free the matrix.
Parameters
----------
data : bytes-like
A serialized Matrix, such as the result of `serialize_matrix`: bytes, a NumPy array, or
anything else with the buffer protocol.
free : callable or bool, optional
Called with the result when it is garbage collected. True (the default) means
`matrix.matrix_free`. If `free` is None or False, there is no automatic garbage
collection, and it is up to the caller to free the Matrix.
nthreads : int, optional
The maximum number of OpenMP threads to use. None (the default), 0 or any negative
integer, however large, means the number of threads of the GxB_Context engaged on
this thread, if any, or else of GxB_CONTEXT_WORLD. A positive integer makes the
call run under a new Context with that many threads. It raises OverflowError if
that is more than int32_t holds, and InvalidValue if a Context is engaged on this
thread (which stays engaged: set its number of threads instead). Raises TypeError
if `nthreads` isn't an integer, or is a bool.
"""
data = np.frombuffer(data, np.uint8)
desc = get_serialize_desc(None, nthreads)
A = ffi.new("GrB_Matrix*")
check_status(
info = _call_with_nthreads(
nthreads,
lib.GxB_Matrix_deserialize,
A,
lib.GxB_Matrix_deserialize(
A,
ffi.NULL, # dtype; we don't check for now
ffi.from_buffer("void*", data),
data.nbytes,
ffi.NULL if desc is None else desc,
),
ffi.NULL, # dtype; we don't check for now
ffi.from_buffer("void*", data),
data.nbytes,
ffi.NULL,
)
check_status(A, info)
if free:
if callable(free):
return ffi.gc(A, free)
Expand All @@ -119,24 +226,36 @@ def deserialize_matrix(data, *, free=True, nthreads=None):
def deserialize_vector(data, *, free=True, nthreads=None):
"""Deserialize a Vector from bytes.

The `free` argument is called when the object is garbage
collected, the default is `vector.vector_free()`. If `free` is None then
there is no automatic garbage collection and it is up to the user
to free the vector.
Parameters
----------
data : bytes-like
A serialized Vector, such as the result of `serialize_vector`: bytes, a NumPy array, or
anything else with the buffer protocol.
free : callable or bool, optional
Called with the result when it is garbage collected. True (the default) means
`vector.vector_free`. If `free` is None or False, there is no automatic garbage
collection, and it is up to the caller to free the Vector.
nthreads : int, optional
The maximum number of OpenMP threads to use. None (the default), 0 or any negative
integer, however large, means the number of threads of the GxB_Context engaged on
this thread, if any, or else of GxB_CONTEXT_WORLD. A positive integer makes the
call run under a new Context with that many threads. It raises OverflowError if
that is more than int32_t holds, and InvalidValue if a Context is engaged on this
thread (which stays engaged: set its number of threads instead). Raises TypeError
if `nthreads` isn't an integer, or is a bool.
"""
data = np.frombuffer(data, np.uint8)
desc = get_serialize_desc(None, nthreads)
v = ffi.new("GrB_Vector*")
check_status(
info = _call_with_nthreads(
nthreads,
lib.GxB_Vector_deserialize,
v,
lib.GxB_Vector_deserialize(
v,
ffi.NULL, # dtype; we don't check for now
ffi.from_buffer("void*", data),
data.nbytes,
ffi.NULL if desc is None else desc,
),
ffi.NULL, # dtype; we don't check for now
ffi.from_buffer("void*", data),
data.nbytes,
ffi.NULL,
)
check_status(v, info)
if free:
if callable(free):
return ffi.gc(v, free)
Expand Down
44 changes: 43 additions & 1 deletion suitesparse_graphblas/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import threading

import pytest

from suitesparse_graphblas import initialize
from suitesparse_graphblas import ffi, initialize, lib

try:
from numpy._core._multiarray_umath import _set_numpy_warn_if_no_mem_policy
Expand Down Expand Up @@ -37,3 +39,43 @@ def warn_if_no_memory_handler():
old = _set_numpy_warn_if_no_mem_policy(True)
yield
_set_numpy_warn_if_no_mem_policy(old)


class _FreedInThisThread(threading.local):
# Every thread starts with an empty list, so a free in any thread is recorded: an
# AttributeError in the cffi callback would only be printed, and the free not seen.
def __init__(self):
self.addresses = []


# GraphBLAS may call the recording arena's functions until the process ends
_recording_arena_callbacks = []


@pytest.fixture(scope="session")
def recording_arena():
"""An arena that records the addresses it frees: ``(k, freed)``.

`k` is its index. Tests may run in several threads at once, so each thread records only
its own frees, in ``freed.addresses``. An arena can't be changed, so it's made once. It
needs cffi callbacks, which Pyodide doesn't have.
"""
blocks = {}
freed = _FreedInThisThread()

@ffi.callback("void *(size_t)")
def malloc(size):
block = ffi.new("char[]", size or 1)
blocks[int(ffi.cast("uintptr_t", block))] = block
return block

@ffi.callback("void (void *)")
def free(ptr):
address = int(ffi.cast("uintptr_t", ptr))
blocks.pop(address, None)
freed.addresses.append(address)

k = lib.GxB_NARENAS - 2 # not 5: test_can_unclaim_buffer needs it uninitialized
assert lib.GxB_arena_init(k, malloc, ffi.NULL, ffi.NULL, free) == lib.GrB_SUCCESS
_recording_arena_callbacks.extend([malloc, free])
return k, freed
Loading
Loading