Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
8 changes: 7 additions & 1 deletion graphblas_algorithms/algorithms/_helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from graphblas import binary, dtypes, monoid, unary

from ..classes._utils import current_snapshot

_ADVICE = (
"which 64-bit integers cannot hold; NetworkX computes with Python integers. Convert the "
"weights to float, or call with backend='networkx'."
Expand Down Expand Up @@ -45,6 +47,8 @@ def checked_sum_type(G, kind, *, count=1):
- "sum": the absolute values, each counted up to `count` times, must sum to less than 2**63.
Other values are added in their own type, and never raise.
"""
# One snapshot throughout: the matrix, its properties and the sum cached for it agree
G = current_snapshot(G)
A = G._A
if A.dtype.np_type.kind not in "biu":
return A.dtype
Expand All @@ -61,7 +65,9 @@ def checked_sum_type(G, kind, *, count=1):
heaviest = max(-least.get(0), greatest.get(0))
# The cheap bound first: the absolute sum is needed only when it fails.
if A.nvals * heaviest * count >= 2**63:
total = G._cacheit("abs_sum+", _abs_sum, A)
cache = G._properties
if (total := cache.get("abs_sum+")) is None:
total = cache["abs_sum+"] = _abs_sum(A)
if total * count >= 2**63:
times = f", counted up to {count} times," if count > 1 else ""
raise OverflowError(
Expand Down
5 changes: 3 additions & 2 deletions graphblas_algorithms/algorithms/dag.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from graphblas import Vector, replace
from graphblas.semiring import any_pair

from ..classes._utils import current_snapshot
from ._bfs import _bfs_plain

__all__ = ["ancestors", "descendants", "is_acyclic"]
Expand All @@ -27,10 +28,10 @@ def is_acyclic(G):
whatever survives when nothing can be peeled is on a cycle. One vector-matrix product per
round, as many rounds as the longest path, so the answer is cached on the graph.
"""
cache = G._cache
snapshot = current_snapshot(G) # the matrix and the cache the answer is kept in
cache, A = snapshot._properties, snapshot._A
if (cached := cache.get("is_acyclic")) is not None:
return cached
A = G._A
alive = Vector(bool, size=A.nrows, name="alive")
alive << True
while alive.nvals > 0:
Expand Down
10 changes: 5 additions & 5 deletions graphblas_algorithms/classes/_caching.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def get_reduce_to_vector(key, opname, methodname):
if key[-1] == "-":

def get_reduction(G, mask=None):
cache = G._cache
cache = G._properties
if mask is not None:
if key in cache:
return cache[key].dup(mask=mask)
Expand Down Expand Up @@ -66,7 +66,7 @@ def get_reduction(G, mask=None):

def get_reduction(G, mask=None):
A = G._A
cache = G._cache
cache = G._properties
if mask is not None:
if key in cache:
return cache[key].dup(mask=mask)
Expand Down Expand Up @@ -103,7 +103,7 @@ def get_reduce_to_scalar(key, opname):
if key[-1] == "-":

def get_reduction(G, mask=None):
cache = G._cache
cache = G._properties
if key not in cache:
if cache.get("has_self_edges") is False and f"{keybase}+" in cache:
cache[key] = cache[f"{keybase}+"]
Expand Down Expand Up @@ -144,7 +144,7 @@ def get_reduction(G, mask=None):

def get_reduction(G, mask=None):
A = G._A
cache = G._cache
cache = G._properties
if key not in cache:
if cache.get("has_self_edges") is False and f"{keybase}-" in cache:
cache[key] = cache[f"{keybase}-"]
Expand Down Expand Up @@ -172,7 +172,7 @@ def get_reduction(G, mask=None):

def get_reduction(G, mask=None):
A = G._A
cache = G._cache
cache = G._properties
if key not in cache:
if not G.get_property("has_self_edges"):
cache[key] = Scalar(op_[A.dtype].return_type, name=key)
Expand Down
188 changes: 177 additions & 11 deletions graphblas_algorithms/classes/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

import graphblas as gb
import numpy as np
from graphblas import Matrix, Vector, binary, dtypes, unary
from graphblas import Matrix, Scalar, Vector, binary, dtypes, unary
from graphblas.core import ffi, lib
from graphblas.core.matrix import TransposedMatrix


Expand Down Expand Up @@ -84,6 +85,7 @@ def from_networkx(cls, G, weight=None, dtype=None):
else:
rv._A = Matrix(dtype if dtype is not None else float)
rv._weight = weight
rv.clear_cache()
return rv


Expand All @@ -104,22 +106,28 @@ def id_to_key(self):


def get_property(self, name, *, mask=None):
return self._get_property[self._cache_aliases.get(name, name)](self, mask)
return self._get_property[self._cache_aliases.get(name, name)](current_snapshot(self), mask)


def get_properties(self, names, *, mask=None):
return _get_properties(self, None, names, mask)


def _get_properties(G, snapshot, names, mask):
# `G` is the graph or its class: the property tables. A graph's own call takes its current
# snapshot; a getter's call (through `_Snapshot.get_properties`) stays on its own.
if isinstance(names, str):
# Separated by commas and/or spaces
names = [
self._cache_aliases.get(name, name)
for name in names.replace(" ", ",").split(",")
if name
G._cache_aliases.get(name, name) for name in names.replace(" ", ",").split(",") if name
]
else:
names = [self._cache_aliases.get(name, name) for name in names]
names = [G._cache_aliases.get(name, name) for name in names]
if snapshot is None:
snapshot = current_snapshot(G)
results = {
name: self._get_property[name](self, mask)
for name in sorted(names, key=self._property_priority.__getitem__)
name: G._get_property[name](snapshot, mask)
for name in sorted(names, key=G._property_priority.__getitem__)
}
return [results[name] for name in names]

Expand Down Expand Up @@ -337,9 +345,167 @@ def to_networkx(self, edge_attribute=PRESERVE):


def _cacheit(self, key, func, *args, **kwargs):
if key not in self._cache:
self._cache[key] = func(*args, **kwargs)
return self._cache[key]
snapshot = current_snapshot(self)
cache = snapshot._properties
if key in cache:
return cache[key]
value = func(*args, **kwargs)
# `func` reads the graph itself, so its value is kept only if the matrix is still the one
# stamped (one replaced and then put back during `func` is not seen)
if current_snapshot(self) is snapshot:
cache[key] = value
return value


#########
# Cache #
#########
# A graph's cache is one `_Snapshot`: its matrix, read once, that matrix's GraphBLAS handle and
# number of entries (the stamp), and the properties computed from it. `get_property`,
# `get_properties`, `_cacheit`, `_cache` and `cache_info` take the graph's current snapshot,
# making a new one when `_A` was replaced or gained or lost entries, and put it in place with one
# store. A getter is given the snapshot in place of the graph: it reads `_A` and `_properties`
# from it and asks it for the properties it needs, so a value lands only in the dict of the
# matrix it was computed from, whatever other threads do to the graph meanwhile. A snapshot
# another thread has replaced serves its call to the end and is then dropped. Code that reads
# the matrix and caches from it outside a getter (`checked_sum_type`, `is_acyclic`) takes one
# snapshot with `current_snapshot` and reads both from it.
#
# Readers that share a snapshot fill one dict, and each store can give the GIL to another
# thread, so a reader can find any part of what another call stores. A getter reads only keys
# it has found or stored itself, never one it leaves to a nested call to store.
#
# The snapshot holds the matrix, so its handle is not freed and given to another matrix while it
# is compared; a handle keeps its dtype for its life. The count is read by one C call into a
# buffer the snapshot holds, half the cost of `A._nvals` and a sixth of `A.nvals`; threads
# sharing a snapshot write the same matrix's count into it.

_MISSING = object()


class _PropertyCache(dict):
"""A graph's cached properties.

A GraphBLAS value is finished (`wait`) as it is stored, so that threads sharing the graph
only ever read it. The getters store a value again on every call (filling one key from
another); a value the key already holds is left as it is, without a second `wait`.
"""

__slots__ = ()

def __setitem__(self, key, value):
if dict.get(self, key, _MISSING) is value:
return
if isinstance(value, (Matrix, Vector, Scalar)):
value.wait() # a cached graph (`structure`) finished its matrix as it was made
dict.__setitem__(self, key, value)


class _Snapshot:
"""A graph's matrix as one stamp saw it, with the properties computed from that matrix."""

__slots__ = ("_A", "_buffer", "_graph_type", "_handle", "_nvals", "_properties")

def __init__(self, graph_type, A):
# Once per stamp: an unfinished matrix is written to by the reads of later checks
A.wait()
self._A = A
self._handle = A.gb_obj[0]
self._nvals = A._nvals
self._buffer = ffi.new("GrB_Index*")
self._properties = _PropertyCache()
self._graph_type = graph_type

def get_property(self, name, *, mask=None):
G = self._graph_type
return G._get_property[G._cache_aliases.get(name, name)](self, mask)

def get_properties(self, names, *, mask=None):
return _get_properties(self._graph_type, self, names, mask)


_matrix_nvals = lib.GrB_Matrix_nvals


def current_snapshot(self):
"""The graph's snapshot, made anew if `_A` was replaced or gained or lost entries."""
snapshot = self._snapshot
A = self._A
handle = A.gb_obj[0]
# A failed call (a freed handle) makes a new snapshot too, whose `_nvals` raises the error
if (
snapshot._handle != handle
or _matrix_nvals(snapshot._buffer, handle)
or snapshot._buffer[0] != snapshot._nvals
):
snapshot = self._snapshot = _Snapshot(type(self), A)
return snapshot


def cache(self):
return current_snapshot(self)._properties


def clear_cache(self):
"""Forget the cached properties; the next call computes what it needs again.

This happens by itself when the matrix is replaced or gains or loses entries. Call it after
a change that keeps the number of entries: new values, `A << B` with as many entries, one
entry added and another removed, a resize.
"""
self._snapshot = _Snapshot(type(self), self._A)


def cache_info(self):
"""The bytes each cached property holds, by key.

GraphBLAS objects and numpy arrays are counted. Memory counted already (the matrix itself,
or a value stored under two keys) counts 0, and a cached graph counts its matrix and its
own cache.
"""
snapshot = current_snapshot(self)
seen = {id(snapshot._A)}
# a copy of the items: a reader sharing the graph may store a property meanwhile
return {key: _nbytes(value, seen) for key, value in list(snapshot._properties.items())}


def _nbytes(value, seen):
if id(value) in seen:
return 0
if isinstance(value, (tuple, list)):
return sum(_nbytes(item, seen) for item in value)
seen.add(id(value))
if isinstance(value, (Matrix, Vector)):
return value.ss.nbytes
if isinstance(value, Scalar): # what GraphBLAS holds, as `ss.nbytes` counts it
return value.__sizeof__() - object.__sizeof__(value)
if isinstance(value, np.ndarray):
return value.nbytes
if isinstance(getattr(value, "_A", None), Matrix):
items = list(value._cache.values())
return _nbytes(value._A, seen) + sum(_nbytes(item, seen) for item in items)
return 0


def getstate(self):
# A snapshot's handle and buffer do not pickle: a copy carries its matrix and properties,
# both from one snapshot, and is stamped afresh in `setstate`
snapshot = current_snapshot(self)
state = self.__dict__.copy()
state["_A"] = snapshot._A
state["_snapshot"] = dict(snapshot._properties)
return state


def setstate(self, state):
state = dict(state)
# A graph pickled before snapshots, by any earlier release, holds its properties in `_cache`
properties = state.pop("_snapshot", None) or state.pop("_cache", {})
self.__dict__.update(state)
self.clear_cache()
cache = self._snapshot._properties
for key, value in properties.items():
cache[key] = value


def renumber_key_to_id(self, indices):
Expand Down
Loading
Loading