From 6351f1b8aae86d142b1f873ff04ee27982bd72dc Mon Sep 17 00:00:00 2001 From: frapercan Date: Fri, 19 Jun 2026 12:32:31 +0200 Subject: [PATCH 1/3] =?UTF-8?q?perf(graph):=20sparsify=20GO=20DAG=20(dense?= =?UTF-8?q?=20T=C3=97T=20=E2=86=92=20CSR)=20=E2=80=94=203=C3=97=20faster?= =?UTF-8?q?=20build,=20~3=C3=97=20less=20RAM?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the dense boolean adjacency `self.dag = np.zeros((T, T), bool)` with CSR parent/child index arrays + degree vectors, built from the per-term adj/children sets the code already maintained. Bit-exact by construction: parent/child counts reproduce the old dag.sum(axis=1)/sum(axis=0), and CSR slices are ascending — matching what np.nonzero/np.flatnonzero yielded from the dense matrix. Verified identical outputs across sparse / dense / no_orphans / IA-weighted / NK scenarios and end-to-end on a 25k-protein corpus; repo test suite green (9 passed, 6 xfailed). Full GO (24.5k BPO terms): build 1.87s → 0.61s, peak RSS 312 → 108 MB. Touches only graph.py (__init__, top_sort, toi, logging, _children_cache, _ancestors_csr). No remaining `.dag` references. --- src/cafaeval/graph.py | 99 +++++++++++++++++++++++++++++-------------- 1 file changed, 68 insertions(+), 31 deletions(-) diff --git a/src/cafaeval/graph.py b/src/cafaeval/graph.py index 4318018..a05062e 100644 --- a/src/cafaeval/graph.py +++ b/src/cafaeval/graph.py @@ -21,7 +21,6 @@ def __init__(self, namespace, terms_dict, ia_dict=None, orphans=False): terms_dict = {term: {name: , namespace: , def: , alt_id: , rel:}} """ self.namespace = namespace - self.dag = [] # [[], ...] terms (rows, axis 0) x parents (columns, axis 1) self.terms_dict = {} # {term: {index: , name: , namespace: , def: } used to assign term indexes in the gt self.terms_dict_alt = {} # {alt_id: set(term, ...) } alternative ids to canonical ids self.terms_list = [] # [{id: term, name:, namespace: , def:, adj: set(), children: set()}, ...] @@ -42,44 +41,82 @@ def __init__(self, namespace, terms_dict, ia_dict=None, orphans=False): self.idxs += 1 - self.dag = np.zeros((self.idxs, self.idxs), dtype='bool') - + # Sparse DAG: ``dag[i, j] == 1`` (i is_a/part_of j) is held as the + # per-term parent (``adj``) and child sets plus CSR index arrays, not a + # dense (idxs x idxs) boolean matrix that is almost entirely zeros. # id1 term (row, axis 0), id2 parent (column, axis 1) for id1, id2, ns in rel_list: if self.terms_dict.get(id2): i = self.terms_dict[id1]['index'] j = self.terms_dict[id2]['index'] - self.dag[i, j] = 1 - # Remove duplicates in adj and children lists - # This ensures that a parent-child term does not have multiple edges, which could lead to wrong topological sorting + # Sets dedupe duplicate edges, exactly like the boolean matrix: + # a parent-child pair contributes a single edge. self.terms_list[i]['adj'].add(j) self.terms_list[j]['children'].add(i) logging.debug("i,j {},{} {},{}".format(i, j, id1, id2)) else: logging.debug('Skipping branch to external namespace: {}'.format(id2)) - logging.debug("dag {}".format(self.dag)) - + + self._build_sparse_dag() + logging.debug("dag edges {}".format(int(self._par_indptr[-1]))) + # Topological sorting self.top_sort() logging.debug("order sorted {}".format(self.order)) if orphans: - self.toi = np.arange(self.dag.shape[0]) # All terms, also those without parents + self.toi = np.arange(self.idxs) # All terms, also those without parents else: - self.toi = np.nonzero(self.dag.sum(axis=1) > 0)[0] # Only terms with parents + self.toi = np.nonzero(self._parent_count > 0)[0] # Only terms with parents logging.debug("toi {}".format(self.toi)) if ia_dict is not None: self.set_ia(ia_dict) + # total = terms with >=1 parent; roots = no parents; leaves = no children logging.info("Ontology: {}, total {}, roots {}, leaves {}, alternative_ids {}".format(self.namespace, - len(np.where(self.dag.sum(axis=1) != 0)[0]), - len(np.where(self.dag.sum(axis=1) == 0)[0]), - len(np.where(self.dag.sum(axis=0) == 0)[0]), + int(np.count_nonzero(self._parent_count)), + int(np.count_nonzero(self._parent_count == 0)), + int(np.count_nonzero(self._child_count == 0)), len(self.terms_dict_alt))) return + def _build_sparse_dag(self): + """Build CSR parent/child index arrays and degree vectors from the + per-term ``adj`` (parents) and ``children`` sets, reproducing the old + dense boolean adjacency exactly: + + * ``self._parent_count[i] == old_dag.sum(axis=1)[i]`` (parents of i) + * ``self._child_count[j] == old_dag.sum(axis=0)[j]`` (children of j) + * ``self._par_idx[self._par_indptr[t]:...]`` are the parents of ``t``, + ascending, i.e. exactly ``np.nonzero(old_dag[t, :])``. + * ``self._chi_idx[self._chi_indptr[t]:...]`` are the children of ``t``, + ascending, i.e. exactly ``np.flatnonzero(old_dag[:, t])``. + """ + n = self.idxs + parent_count = np.fromiter((len(t['adj']) for t in self.terms_list), + dtype=np.int64, count=n) + child_count = np.fromiter((len(t['children']) for t in self.terms_list), + dtype=np.int64, count=n) + par_indptr = np.zeros(n + 1, dtype=np.int64) + np.cumsum(parent_count, out=par_indptr[1:]) + chi_indptr = np.zeros(n + 1, dtype=np.int64) + np.cumsum(child_count, out=chi_indptr[1:]) + par_idx = np.empty(int(par_indptr[-1]), dtype=np.int64) + chi_idx = np.empty(int(chi_indptr[-1]), dtype=np.int64) + for t in range(n): + adj = self.terms_list[t]['adj'] + if adj: + par_idx[par_indptr[t]:par_indptr[t + 1]] = sorted(adj) + chl = self.terms_list[t]['children'] + if chl: + chi_idx[chi_indptr[t]:chi_indptr[t + 1]] = sorted(chl) + self._parent_count = parent_count + self._child_count = child_count + self._par_indptr, self._par_idx = par_indptr, par_idx + self._chi_indptr, self._chi_idx = chi_indptr, chi_idx + def top_sort(self): """ Takes a sparse matrix representing a DAG and returns an array with nodes indexes in topological order @@ -87,10 +124,12 @@ def top_sort(self): """ indexes = [] visited = 0 - (rows, cols) = self.dag.shape + rows = self.idxs # create a vector containing the in-degree of each node - in_degree = self.dag.sum(axis=0) + # (number of children per node == old dense dag.sum(axis=0)); copy so + # the Kahn sweep below can decrement it in place + in_degree = self._child_count.copy() # logging.debug("degree {}".format(in_degree)) # find the nodes with in-degree 0 (leaves) and add them to the queue @@ -157,9 +196,13 @@ def __init__(self, ids, matrix, namespace=None): def _children_cache(ont): children_by_term = getattr(ont, "_children_by_term", None) if children_by_term is None: + # CSR children slices (ascending), identical to the old + # ``np.flatnonzero(dag[:, term_id])`` per-term scan but without the + # dense matrix. + indptr, idx = ont._chi_indptr, ont._chi_idx children_by_term = [ - np.flatnonzero(ont.dag[:, term_id]) - for term_id in range(ont.dag.shape[1]) + idx[indptr[term_id]:indptr[term_id + 1]] + for term_id in range(len(indptr) - 1) ] ont._children_by_term = children_by_term return children_by_term @@ -192,20 +235,14 @@ def _ancestors_csr(ont): if cached is not None: return cached - dag = ont.dag - n = int(dag.shape[0]) - - # Vectorised build of parents_by_term: one full np.nonzero scan instead - # of n_terms per-row flatnonzero calls. ``dag[i, j] == 1`` means ``i`` - # is_a ``j``, so the non-zero rows of ``dag[t, :]`` are the parents of - # ``t``. Grouping by child row gives us the per-term parent list. - edge_rows, edge_cols = np.nonzero(dag) - sort_idx = np.argsort(edge_rows, kind='stable') - sorted_rows = edge_rows[sort_idx] - sorted_cols = edge_cols[sort_idx] - p_counts = np.bincount(sorted_rows, minlength=n) - p_indptr = np.zeros(n + 1, dtype=np.int64) - np.cumsum(p_counts, out=p_indptr[1:]) + n = int(ont.idxs) + + # Parent CSR is precomputed on the Graph: ``sorted_cols[p_indptr[t]:p_indptr[t+1]]`` + # are the parents of ``t``, ascending. This reproduces exactly what the old + # ``np.nonzero(dense_dag)`` + group-by-child-row built, without ever + # materialising the dense matrix. + p_indptr = ont._par_indptr + sorted_cols = ont._par_idx # ont.order is leaves → roots; reverse so parents are always finished # before we look them up. From c2a5526a7bb0bcef29309e38f72c4eb1ab77a7c6 Mon Sep 17 00:00:00 2001 From: frapercan Date: Fri, 19 Jun 2026 12:45:32 +0200 Subject: [PATCH 2/3] perf(graph): O(1) deque in top_sort instead of list.pop(0) Kahn's queue used list.pop(0) (O(n) per pop -> O(n^2) total). A collections.deque with popleft() is O(1); FIFO order is identical so self.order is unchanged (bit-exact). Verified identical outputs across all scenarios. --- src/cafaeval/graph.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/cafaeval/graph.py b/src/cafaeval/graph.py index a05062e..7380645 100644 --- a/src/cafaeval/graph.py +++ b/src/cafaeval/graph.py @@ -1,6 +1,7 @@ import numpy as np import logging import os +from collections import deque logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) @@ -132,8 +133,10 @@ def top_sort(self): in_degree = self._child_count.copy() # logging.debug("degree {}".format(in_degree)) - # find the nodes with in-degree 0 (leaves) and add them to the queue - queue = np.nonzero(in_degree == 0)[0].tolist() + # find the nodes with in-degree 0 (leaves) and add them to the queue. + # deque gives O(1) popleft; a plain list's pop(0) is O(n) -> O(n^2) total. + # FIFO order is identical, so self.order is unchanged. + queue = deque(np.nonzero(in_degree == 0)[0].tolist()) # logging.debug("queue {}".format(queue)) # for each element of the queue increment visits, add them to the list of ordered nodes @@ -141,7 +144,7 @@ def top_sort(self): # and add them to the queue if they reach in-degree == 0 while queue: visited += 1 - idx = queue.pop(0) + idx = queue.popleft() indexes.append(idx) in_degree[idx] -= 1 adj = self.terms_list[idx]['adj'] From e780ba763366df62e04c57155c19db97d3495cfe Mon Sep 17 00:00:00 2001 From: frapercan Date: Sat, 20 Jun 2026 03:36:41 +0200 Subject: [PATCH 3/3] test(parity): compare oracle index by value, not dtype-sensitive equals The py3.10 CI leg installs pandas 2.x (the last release line that supports Python 3.10), which keeps the filename/ns MultiIndex levels as object dtype. The py3.11/3.12 legs install pandas 3.x, which infers the PyArrow-backed StringDtype for those same levels. The parity oracle was frozen under pandas 3.x, so Index.equals returned False on py3.10 despite identical labels and ordering, failing the parity gate only on 3.10. Comparing the materialised index tuples is dtype-agnostic and still pins exact row alignment, so the sparse kernels stay bit/ULP-exact across all three Python versions without changing any math. --- tests/diff/test_oracle_parity.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/diff/test_oracle_parity.py b/tests/diff/test_oracle_parity.py index 1913c22..5a69174 100644 --- a/tests/diff/test_oracle_parity.py +++ b/tests/diff/test_oracle_parity.py @@ -85,8 +85,17 @@ def _assert_df_equal(actual: pd.DataFrame, expected: pd.DataFrame, label: str) - assert list(actual.columns) == list(expected.columns), ( f"{label}: column mismatch\nfork={list(actual.columns)}\noracle={list(expected.columns)}" ) - assert actual.index.equals(expected.index), ( - f"{label}: index mismatch ({len(actual)} vs {len(expected)} rows)" + # Compare the index by value, not via ``Index.equals``. The latter is + # dtype-sensitive: pandas 3.x (resolved under py3.11/3.12) infers the + # PyArrow-backed ``StringDtype`` for the ``filename``/``ns`` levels, + # while pandas 2.x (the last release supporting py3.10) keeps them as + # plain ``object``. The frozen oracle was serialized under pandas 3.x, + # so ``equals`` returns False on py3.10 despite identical labels and + # ordering. Comparing the materialised tuples is dtype-agnostic and + # still pins exact row alignment. + assert actual.index.tolist() == expected.index.tolist(), ( + f"{label}: index mismatch ({len(actual)} vs {len(expected)} rows)\n" + f"fork={actual.index.tolist()}\noracle={expected.index.tolist()}" ) for col in expected.columns: a = actual[col].to_numpy()