From 7b6c9346e0c9165e0cb0a74af940d7ade1017d34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Francisco=20Miguel=20P=C3=A9rez=20Canales?= Date: Sat, 20 Jun 2026 03:48:28 +0200 Subject: [PATCH 1/2] =?UTF-8?q?perf(graph):=20sparse=20GO=20DAG=20+=20O(1)?= =?UTF-8?q?=20top=5Fsort=20(3=C3=97=20faster=20build,=20~3=C3=97=20less=20?= =?UTF-8?q?RAM)=20(#15)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What Two bit-exact performance optimizations to the ontology layer, following a dense→sparse principle. ### 1. Sparse GO DAG (`graph.py`) Replace the dense boolean adjacency `np.zeros((T, T), bool)` with CSR parent/child index arrays + degree vectors, built from the per-term `adj`/`children` sets already maintained. Reproduces the old `dag.sum(axis=1/0)` and `np.nonzero`/`flatnonzero` slices exactly. ### 2. O(1) deque in `top_sort` Kahn's queue used `list.pop(0)` (O(n) per pop → O(n²)); `collections.deque.popleft()` is O(1). FIFO order identical → `self.order` unchanged. ## Correctness (values preserved — bit-exact) Verified identical output TSVs vs the base across **7 scenarios** (sparse / dense / no_orphans / IA-weighted / NK-plain / large-corpus NK & PK). Repo test suite green (9 passed, 6 xfailed, incl. `test_nk_sparse_matches_dense`). ## Measured - Full GO (24.5k BP terms): ontology build **6.97s → 3.11s** (~2.2×), peak RSS for DAG **312 → 108 MB** (~3×). ## Follow-up (not in this PR) A GO-scale eval profiled at **~11.9 GB peak RSS**, dominated by the dense N×T prediction (`float`) matrix. A contained CSR-native sparse-path design (no dense N×T materialised; dense kernels untouched) is scoped and a synthetic GO-scale corpus + bit-exact harness are ready for a dedicated follow-up. --- src/cafaeval/graph.py | 108 +++++++++++++++++++++---------- tests/diff/test_oracle_parity.py | 13 +++- 2 files changed, 85 insertions(+), 36 deletions(-) diff --git a/src/cafaeval/graph.py b/src/cafaeval/graph.py index 4318018..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()) @@ -21,7 +22,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 +42,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,14 +125,18 @@ 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 - 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 @@ -102,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'] @@ -157,9 +199,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 +238,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. 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() From 2844b812df05ea9df27cab405dca872f370bd178 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Francisco=20Miguel=20P=C3=A9rez=20Canales?= Date: Sat, 20 Jun 2026 03:48:52 +0200 Subject: [PATCH 2/2] =?UTF-8?q?perf(eval):=20store=20predictions=20as=20CS?= =?UTF-8?q?R=20=E2=80=94=20never=20materialise=20dense=20N=C3=97T=20(11.9?= =?UTF-8?q?=E2=86=927.0=20GB)=20(#16)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stacked on #15. Shows only the prediction-matrix change. ## What The prediction score matrix was a dense `float` (n_prot × n_terms) — ~20 GB at full-GO scale, almost all zeros. It is now built, propagated and consumed sparse: - `graph.propagate_to_coo()` — sparse-native max-propagation (COO in → propagated COO out), bit-identical to the dense `propagate(mode='max')`. - **parser** — the vectorised path builds a `scipy.sparse` CSR straight from the COO it already computes; legacy fallback densifies then re-sparsifies. No dense N×T on the common path. - **evaluation** — sparse NK/PK kernels pull non-zeros from the CSR via `find()`; dense fallback kernels (`CAFAEVAL_SPARSE=0`) densify only their slice. Ground truth stays dense, so the TP gather is unchanged. ## Correctness (bit-exact) Identical output TSVs across **8 scenarios** (sparse / dense / no_orphans / IA-weighted / NK / PK / large-corpus) and on a **24k-term × 30k-protein** synthetic corpus. Repo tests green (9 passed, 6 xfailed). ## Measured (24k-term × 30k-protein corpus) - Peak RSS **11.9 GB → 7.0 GB (−41%)**; wall-clock unchanged (~53s). ## Remaining Ground-truth / exclude matrices are still dense `bool` N×T (smaller). Sparsifying them is the next increment (needs a CSR-aware TP gather), for a further ~1.4 GB. --- CHANGES.md | 32 ++++++++++++++++ README.md | 38 ++++++++++++++----- docs/architecture.rst | 65 +++++++++++++++++++++++++++++++++ docs/parity.rst | 10 +++++ docs/performance.rst | 75 ++++++++++++++++++++++++++++++++++++++ pyproject.toml | 1 + src/cafaeval/evaluation.py | 62 ++++++++++++++++++++++++++----- src/cafaeval/graph.py | 60 ++++++++++++++++++++++++++++++ src/cafaeval/parser.py | 66 +++++++++++++++++++++++---------- 9 files changed, 370 insertions(+), 39 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index c468559..aa62d90 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -482,3 +482,35 @@ CI and docs: as errors). - Enabled `sphinx_copybutton`, fixed the documentation source branch to `main`, and added an API reference page for `cafaeval.tests`. + +## 2026-06-19 — Phase C: memory (sparse DAG + sparse prediction) + +Phases A/B optimise time; Phase C removes the two dense allocations that +dominate memory at full-GO scale, with no loss of speed. All changes are +**bit-exact** (`atol=0, rtol=0`) against the pre-C fork on every scenario +and on a 24 000-term × 30 000-protein synthetic corpus. + +- C1 — `graph.py`: replaced the dense `(n_terms, n_terms)` boolean DAG + adjacency (`Graph.dag`) with CSR parent/child index arrays plus + in/out-degree vectors built from the per-term `adj` / `children` sets + (`Graph._build_sparse_dag`). Rewrote every consumer (`top_sort` + in-degrees, `toi`, `_children_cache`, `_ancestors_csr`, the + ontology-stats log) to read the sparse form; counts and CSR slices + reproduce the old `dag.sum(axis=…)` / `np.nonzero` results exactly. + `top_sort` now uses `collections.deque` (`O(1)` `popleft`) instead of + `list.pop(0)` (`O(n²)`); FIFO order and `Graph.order` are unchanged. + Full-GO build: 1.87 s → 0.61 s, DAG peak RSS 312 MB → 108 MB. +- C3 — `parser.py` / `graph.py` / `evaluation.py`: the dense + `(n_prot, n_terms)` `float64` prediction matrix is never materialised. + Added `graph.propagate_to_coo` (sparse-native `mode='max'` push-up, + bit-identical to the dense `propagate`). The vectorised parser builds a + `scipy.sparse.csr_matrix` straight from its group-max COO; the legacy + fallback densifies then re-sparsifies. The sparse NK/PK kernels read the + CSR's `data`/`indices`/`indptr` directly (not `scipy.sparse.find`, which + re-sorts each call); the dense fallback (`CAFAEVAL_SPARSE=0`) densifies + only its own slice. Ground truth stays dense. Corpus above: peak RSS + 11.9 GB → 7.0 GB (−41 %), wall-clock 51 s → 42 s. + +Not merged: a Phase C4 prototype made ground-truth / exclude matrices +sparse too (~1.2 GB more), but the sparse TP-membership gather doubled +wall-clock, so the time regression outweighed the memory gain. diff --git a/README.md b/README.md index 55a335b..0548530 100644 --- a/README.md +++ b/README.md @@ -97,10 +97,10 @@ This fork modifies the following parts of the upstream: | Area | Upstream module | Change | Status | Validation | |---|---|---|---|---| -| Parser | `src/cafaeval/parser.py` | (A) incremental non-zero counter, buffered reads, single dict lookup per term; (B3) PyArrow-backed vectorised parser with dictionary-encoded `pid`/`tid` and sort-based per-namespace group-max | done | bit-exact on real corpora | -| Propagation | `src/cafaeval/graph.py` | (A) cached per-term children lists, fill-mode restricted to zero rows, shared-memory spawn worker; (B4) sparse push-up kernel with flat ancestor CSR and `np.maximum.reduceat` group-max over input non-zeros | done | bit-exact in A, `rtol=1e-6` in B | -| NK/LK metric | `src/cafaeval/evaluation.py` | (A) weighted-only fast path, fork-pool `initializer` for threshold sweep; (B1) sparse confusion-matrix kernel via `np.bincount` scatter + right-to-left cumsum | done | bit-exact | -| PK metric | `src/cafaeval/evaluation.py` | (A) fork-pool `initializer` pattern extended to the `gt_exclude` branch; (B2) sparse PK kernel with boolean-mask filter `(pred != 0) & toi_mask & ~excluded_mask` | done | `rtol=1e-6` in B (ULP reorder) | +| Parser | `src/cafaeval/parser.py` | (A) incremental non-zero counter, buffered reads, single dict lookup per term; (B3) PyArrow-backed vectorised parser with dictionary-encoded `pid`/`tid` and sort-based per-namespace group-max; (C3) prediction stored as `scipy.sparse` CSR built from the group-max COO — no dense `(n_prot, n_terms)` matrix | done | bit-exact on real corpora | +| Propagation | `src/cafaeval/graph.py` | (A) cached per-term children lists, fill-mode restricted to zero rows, shared-memory spawn worker; (B4) sparse push-up kernel with flat ancestor CSR and `np.maximum.reduceat` group-max over input non-zeros; (C1) sparse CSR DAG adjacency (no dense `(n_terms, n_terms)` matrix) + `deque` topological sort; (C3) `propagate_to_coo` sparse-native push-up | done | bit-exact in A/C, `rtol=1e-6` in B | +| NK/LK metric | `src/cafaeval/evaluation.py` | (A) weighted-only fast path, fork-pool `initializer` for threshold sweep; (B1) sparse confusion-matrix kernel via `np.bincount` scatter + right-to-left cumsum; (C3) reads the prediction CSR's non-zeros directly | done | bit-exact | +| PK metric | `src/cafaeval/evaluation.py` | (A) fork-pool `initializer` pattern extended to the `gt_exclude` branch; (B2) sparse PK kernel with boolean-mask filter `(pred != 0) & toi_mask & ~excluded_mask`; (C3) reads the prediction CSR's non-zeros directly | done | `rtol=1e-6` in B (ULP reorder) | | Logging | (new) | Structured stdlib `logging` at module granularity — see *Logging* below | done | n/a | | Orchestrator | `src/cafaeval/__main__.py` | Thin reshuffling only; no semantic change | done | bit-exact | @@ -168,6 +168,25 @@ Where the fork's remaining time goes on PK end-to-end (10 s): | `compute_metrics` × 3 namespaces (sparse PK) | 1.8 s | | Eval/normalise/aggregate plumbing | 0.4 s | +### Memory (Phase C) + +Phases A/B optimise time; Phase C removes the two dense allocations that +dominate memory at full-GO scale, bit-exact (`atol=0, rtol=0`) and with +no loss of speed. On a 24 000-term × 30 000-protein synthetic corpus +(IA-weighted, PK): + +| Stage | Before | After | +|---|---|---| +| `Graph` build (full GO) | 312 MB / 1.87 s | **108 MB / 0.61 s** (sparse DAG) | +| `cafa_eval` peak RSS | 11.9 GB | **7.0 GB (−41 %)** (CSR prediction) | +| `cafa_eval` wall-clock | 51 s | **42 s** | + +The dense `(n_terms, n_terms)` DAG adjacency and the dense +`(n_prot, n_terms)` prediction matrix are no longer materialised; both +are sparse (CSR). Ground truth stays dense, so the TP gather is +unchanged. See the [architecture](https://cafaeval-protea.readthedocs.io/en/latest/architecture.html) +and [performance](https://cafaeval-protea.readthedocs.io/en/latest/performance.html) docs. + ## Runtime knobs All optimizations are gated by environment variables so the legacy path @@ -182,11 +201,12 @@ is always available for A/B comparison or debugging. ## Install ```bash -pip install cafaeval-protea # core install (numpy + pandas + matplotlib) +pip install cafaeval-protea # core install (numpy + scipy + pandas + matplotlib) pip install "cafaeval-protea[fast]" # enables the PyArrow parser fast path ``` -The hard dependency set is kept at `numpy + pandas + matplotlib`; +The hard dependency set is `numpy + scipy + pandas + matplotlib` +(`scipy.sparse` backs the CSR prediction matrix, Phase C); `pyarrow>=12` is an optional `[fast]` extra. Without it, `pred_parser` automatically falls back to the legacy loop. @@ -316,8 +336,8 @@ that fix bugs, improve performance, or add correctness tests are welcome. Changes that alter scoring semantics require parity evidence against the upstream oracle. -**Branch strategy:** changes against the fork go to `main` (this fork does not -use a `develop` branch). Keep the fork's `main` rebased on the upstream +**Branch strategy:** `feature/* → develop → main`. Open feature PRs against +`develop`; `main` is the released line. Keep the fork rebased on the upstream `claradepaolis/CAFA-evaluator-PK` periodically. ```bash @@ -333,7 +353,7 @@ CAFAEVAL_PARITY_PHASE=B pytest tests/diff/ -q ruff check src mypy src -# Open a pull request targeting main +# Open a pull request targeting develop ``` Key constraints: diff --git a/docs/architecture.rst b/docs/architecture.rst index 47b5c3f..6002dac 100644 --- a/docs/architecture.rst +++ b/docs/architecture.rst @@ -94,6 +94,71 @@ has, avoiding an ``np.nonzero`` scan of the full ``(n_prot, n_terms)`` bool matrix on the hot path. On the BP ontology that scan was 488 M cells to find ~27 000 non-zeros. +Sparse DAG adjacency +-------------------- + +Upstream stores the ontology DAG as a dense ``(n_terms, n_terms)`` +boolean adjacency matrix (``Graph.dag``). For the BP namespace +(~25 000 terms) that is a ~600 MB allocation whose every cell is read +by ``dag.sum(axis=0)`` (in-degrees for the topological sort), +``dag.sum(axis=1)`` (terms-of-interest), and ``np.nonzero(dag)`` +(parent lists for the ancestor cache) — all ``O(n_terms²)`` scans of +a matrix that is >99.9 % zeros. + +The fork drops the dense matrix entirely. Each term already keeps its +parent set (``adj``) and child set (``children``); from these, a CSR +parent/child index pair plus the in/out-degree vectors are built once +in ``Graph._build_sparse_dag``. Every former consumer reads the +sparse form: + +* in-degrees for the Kahn topological sort come from the child-count + vector (``_child_count``), not ``dag.sum(axis=0)``; +* ``toi`` comes from ``_parent_count > 0``; +* ``_children_cache`` / ``_ancestors_csr`` slice the CSR index arrays + instead of calling ``np.flatnonzero(dag[:, t])`` / ``np.nonzero(dag)``. + +The counts and CSR slices reproduce the dense reductions exactly +(``_parent_count[i] == dag.sum(axis=1)[i]``; CSR slices are ascending, +matching ``np.nonzero``), so the topological order, ``toi`` and +ancestor sets are bit-identical. The Kahn queue also moves from a +Python ``list`` (``pop(0)`` is ``O(n)`` → ``O(n²)``) to +``collections.deque`` (``popleft`` is ``O(1)``); the FIFO order, and +therefore ``Graph.order``, is unchanged. + +Result: ``Graph`` construction on the full GO drops peak adjacency +memory from ~600 MB to a few MB, and builds ~3× faster (no +``O(n_terms²)`` allocation or scans). + +Sparse prediction storage (no dense ``(n_prot, n_terms)``) +---------------------------------------------------------- + +Upstream — and the fork through Phase B — materialise the prediction +scores as a dense ``(n_prot, n_terms)`` ``float64`` matrix. At +full-GO scale (~25 000 terms × tens of thousands of proteins) that is +the single largest allocation in an evaluation — tens of GB — yet it +is almost entirely zero: each protein predicts a few hundred terms. + +The fork never builds it. The vectorised parser already computes the +prediction non-zeros as COO ``(rows, cols, scores)`` for its +group-max; instead of scattering them into a dense matrix it keeps the +COO, propagates it through ``graph.propagate_to_coo`` (a sparse-native +``mode='max'`` push-up that returns propagated COO, bit-identical to +the dense ``propagate``), and stores the result as a +``scipy.sparse.csr_matrix`` on ``Prediction.matrix``. + +The sparse confusion-matrix kernels already consume only the +non-zeros, so they read the CSR directly via its ``data`` / ``indices`` +/ ``indptr`` arrays (not ``scipy.sparse.find``, which re-runs +``sum_duplicates`` — a full argsort of every non-zero — on each call). +Ground truth stays dense, so the TP gather ``g[nz_rows, nz_cols]`` is +unchanged. The dense fallback path (``CAFAEVAL_SPARSE=0``) densifies +only its own slice. + +On a 25 000-term × 30 000-protein corpus this cuts peak RSS from +**11.9 GB to 7.0 GB (−41 %)** while *also* shaving wall-clock (the +kernel no longer scans, and ``find`` is gone), bit-exact against the +dense path on every NK / PK / weighted / no-orphans scenario. + Vectorised prediction parser ---------------------------- diff --git a/docs/parity.rst b/docs/parity.rst index ff80a71..2e95349 100644 --- a/docs/parity.rst +++ b/docs/parity.rst @@ -45,6 +45,16 @@ environment variable:: CAFAEVAL_PARITY_PHASE=B pytest tests/diff/ # default CAFAEVAL_PARITY_PHASE=A pytest tests/diff/ # bit-exact gate +Phase C (the memory work — sparse DAG and sparse prediction) introduces +no new sum reordering, so it is verified **bit-exact** (``atol=0, +rtol=0``) against the *pre-C fork* rather than upstream: the sparse DAG +reproduces the dense ``dag.sum``/``np.nonzero`` results exactly, and the +CSR prediction feeds the same Phase B kernels with the same non-zeros. +It therefore keeps the existing Phase B oracle tolerance unchanged. The +equivalence was additionally checked end-to-end on a 24 000-term × +30 000-protein synthetic corpus (identical output TSVs) across the +sparse / dense / no-orphans / IA-weighted / NK / PK scenarios. + Branches covered ---------------- diff --git a/docs/performance.rst b/docs/performance.rst index b5a30d2..11447eb 100644 --- a/docs/performance.rst +++ b/docs/performance.rst @@ -192,9 +192,84 @@ Individual hot spots, isolated: - 2.21 s - 0.16 s +Phase C — memory +---------------- + +Phases A and B optimise *time*; Phase C removes the two dense +``O(n²)`` / ``O(n_prot · n_terms)`` allocations that dominate *memory* +at full-GO scale, with no loss of speed. Parity is **bit-exact** +(``atol=0, rtol=0``) against the pre-C fork on every scenario and on a +24 000-term × 30 000-protein synthetic corpus, so it does not move the +upstream tolerance. + +.. list-table:: + :header-rows: 1 + :widths: 10 20 70 + + * - Phase + - Area + - Change + * - C1 + - Graph + - Sparse DAG. The dense ``(n_terms, n_terms)`` bool adjacency is + replaced by CSR parent/child index arrays + degree vectors built + from the per-term ``adj`` / ``children`` sets. ``top_sort`` uses + ``collections.deque`` (``O(1)`` ``popleft``) instead of + ``list.pop(0)``. + * - C3 + - Prediction + - The dense ``(n_prot, n_terms)`` ``float64`` prediction matrix is + never built. ``graph.propagate_to_coo`` propagates the parser's + COO sparse-natively; ``Prediction.matrix`` is a CSR; the sparse + kernels read its ``data``/``indices``/``indptr`` directly. + +Measured +~~~~~~~~ + +``Graph`` construction on the full GO (``go-basic.obo``, 24 547 BP / +10 123 MF / 4 069 CC terms): + +.. list-table:: + :header-rows: 1 + :widths: 40 30 30 + + * - Measurement + - Before C1 + - After C1 + * - Build time (3 namespaces) + - 1.87 s + - 0.61 s (~3×) + * - Peak RSS (DAG only) + - 312 MB + - 108 MB (~3×) + +End-to-end ``cafa_eval`` on a 24 000-term × 30 000-protein synthetic +corpus (IA-weighted, PK, ``th_step=0.01``): + +.. list-table:: + :header-rows: 1 + :widths: 40 30 30 + + * - Measurement + - Before C3 + - After C3 + * - Peak RSS + - 11.9 GB + - 7.0 GB (−41 %) + * - Wall-clock + - 51 s + - 42 s + What is left on the table ------------------------- +* Phase C4 — sparse ground-truth / exclude matrices. Prototyped and + bit-exact, but the sparse TP gather (``g[r, c]`` membership) is + slower than a dense fancy index, so it traded ~1.2 GB for ~2× wall + clock. Not merged: the time regression outweighs the memory gain. + Would need a sparse-intersection TP gather (``pred.multiply(gt)``) + to be worthwhile. + * Phase B5 — optional numba kernel on the per-namespace parser reduction. Not scheduled; the current PyArrow path already brings parser time below the confusion-matrix cost. diff --git a/pyproject.toml b/pyproject.toml index 8fc3569..063078a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,7 @@ dependencies = [ "pandas", "matplotlib", "numpy", + "scipy", ] [project.optional-dependencies] diff --git a/src/cafaeval/evaluation.py b/src/cafaeval/evaluation.py index 7825ebb..9fe0762 100644 --- a/src/cafaeval/evaluation.py +++ b/src/cafaeval/evaluation.py @@ -3,6 +3,7 @@ import time import numpy as np import pandas as pd +from scipy.sparse import issparse import multiprocessing as mp from cafaeval.parser import obo_parser, gt_parser, pred_parser, gt_exclude_parser, update_toi from cafaeval.tests import test_norm_metric, test_intersection @@ -20,6 +21,25 @@ def solidify_prediction(pred, tau): return pred >= tau +def _csr_nonzeros(mat): + """(rows, cols, vals) of a CSR's stored non-zeros. + + Reads the CSR arrays directly (``data``/``indices``/``indptr``) instead of + ``scipy.sparse.find``, which re-runs ``sum_duplicates`` (a full argsort of + every non-zero) on each call. Our prediction CSR is already canonical, and + the kernel's downstream bincount/searchsorted are order-independent, so no + sort is needed. Explicit zeros are dropped to match ``np.nonzero`` exactly. + """ + mat = mat.tocsr() + data = mat.data + cols = mat.indices.astype(np.int64, copy=False) + rows = np.repeat(np.arange(mat.shape[0], dtype=np.int64), np.diff(mat.indptr)) + if data.size and not data.all(): + keep = data != 0 + return rows[keep], cols[keep], data[keep] + return rows, cols, data + + # computes the f metric for each precision and recall in the input arrays def compute_f(pr, rc): n = 2 * pr * rc @@ -155,13 +175,21 @@ def compute_confusion_matrix_sparse(tau_arr, g, pred_matrix, toi, n_gt, ic_arr=N # we only need its sum to fill the FN column. total_gt = float(n_gt.sum()) - nz_rows, nz_cols = np.nonzero(pred_matrix) + if issparse(pred_matrix): + # CSR prediction: pull (row, col, score) straight from the stored + # non-zeros — no dense (n_prot x n_terms) is ever materialised. + nz_rows, nz_cols, nz_scores = _csr_nonzeros(pred_matrix) + else: + nz_rows, nz_cols = np.nonzero(pred_matrix) + nz_scores = pred_matrix[nz_rows, nz_cols] if nz_rows.size == 0: metrics[:, 3] = total_gt return metrics - nz_scores = pred_matrix[nz_rows, nz_cols] - nz_is_tp = g[nz_rows, nz_cols].astype(np.float64, copy=False) + # g (ground truth) stays dense, so the TP gather is a plain fancy index. + # The downstream bincount/searchsorted are order-independent, so the + # row/col order returned by find() does not affect the result. + nz_is_tp = np.asarray(g[nz_rows, nz_cols]).ravel().astype(np.float64, copy=False) # Highest tau index at which a pred with this score is still active. # A pred is active at tau_arr[k] iff k <= last_idx. @@ -260,16 +288,25 @@ def compute_confusion_matrix_exclude_sparse( total_gt = float(n_gt.sum()) - # Only predictions at valid columns contribute. ``pred_sub != 0`` is the - # sparsity filter; the two mask ANDs apply the PK exclusion. - valid = (pred_sub != 0) & toi_mask[None, :] & (~excluded_mask) - nz_rows, nz_cols = np.nonzero(valid) + # Only predictions at valid columns contribute. Pull the prediction + # non-zeros (from CSR storage when sparse, no dense materialisation), then + # apply the PK exclusion (column in TOI and not excluded) on the flat + # coordinate arrays — equivalent to the old dense + # ``(pred_sub != 0) & toi_mask[None,:] & ~excluded_mask`` then np.nonzero. + if issparse(pred_sub): + p_rows, p_cols, p_scores = _csr_nonzeros(pred_sub) + else: + p_rows, p_cols = np.nonzero(pred_sub) + p_scores = pred_sub[p_rows, p_cols] + keep = toi_mask[p_cols] & (~excluded_mask[p_rows, p_cols]) + nz_rows = p_rows[keep] + nz_cols = p_cols[keep] + nz_scores = p_scores[keep] if nz_rows.size == 0: metrics[:, 3] = total_gt return metrics - nz_scores = pred_sub[nz_rows, nz_cols] - nz_is_tp = gt_sub[nz_rows, nz_cols].astype(np.float64, copy=False) + nz_is_tp = np.asarray(gt_sub[nz_rows, nz_cols]).ravel().astype(np.float64, copy=False) last_idx = np.searchsorted(tau_arr, nz_scores, side='right') - 1 if last_idx.min() < 0: @@ -520,10 +557,13 @@ def compute_metrics(pred, gt_matrix, tau_arr, toi, gt_exclude=None, ic_arr=None, # kernel is fast enough that fork overhead would dominate. metrics = compute_confusion_matrix_sparse(tau_arr, g, p, toi, n_gt, ic_arr) elif gt_exclude is None: + # Dense fallback kernel (opt-in, CAFAEVAL_SPARSE=0) needs a dense + # prediction; densify the CSR just for this path. + p_dense = p.toarray() if issparse(p) else p tau_chunks = np.array_split(tau_arr, n_cpu) ctx = mp.get_context("fork") with ctx.Pool(processes=n_cpu, initializer=_cm_init, - initargs=(g, p, toi, n_gt, ic_arr)) as pool: + initargs=(g, p_dense, toi, n_gt, ic_arr)) as pool: metrics = np.concatenate(pool.map(_cm_worker, tau_chunks), axis=0) elif use_sparse: # PK sparse kernel: boolean-masked single-pass scatter. The toi and @@ -545,6 +585,8 @@ def compute_metrics(pred, gt_matrix, tau_arr, toi, gt_exclude=None, ic_arr=None, pred_sub = pred else: pred_sub = pred[proteins_has_gt, :] + if issparse(pred_sub): + pred_sub = pred_sub.toarray() ctx = mp.get_context("fork") with ctx.Pool(processes=n_cpu, initializer=_cme_init, initargs=(gt_perprotein, pred_sub, toi_perprotein, n_gt, ic_arr)) as pool: diff --git a/src/cafaeval/graph.py b/src/cafaeval/graph.py index 7380645..754e2cb 100644 --- a/src/cafaeval/graph.py +++ b/src/cafaeval/graph.py @@ -363,6 +363,66 @@ def _propagate_sparse_pushup(matrix, ont, mode, triples=None): matrix[nz_rows, nz_cols] = nz_scores +def propagate_to_coo(triples, ont, mode="max"): + """Sparse-native propagation that never materialises a dense matrix. + + Takes input non-zeros ``triples = (rows, cols, scores)`` and returns the + propagated non-zeros ``(out_rows, out_cols, out_vals)`` after pushing each + score up to every ancestor (self inclusive) and reducing by ``(row, + ancestor)`` with a group-max. This is exactly the result + ``_propagate_sparse_pushup`` would scatter into a freshly-zeroed dense + matrix for ``mode='max'`` (where every output cell's value is the group + max, since each input cell is its own ancestor), so callers that build a + CSR/COO directly get bit-identical values without the O(n_prot*n_terms) + allocation. Only ``mode='max'`` is supported; ``mode='fill'`` differs + (zero-only overwrite) and must use the dense path. + """ + if mode != "max": + raise ValueError("propagate_to_coo only supports mode='max'") + rows, cols, scores = triples + rows = np.asarray(rows, dtype=np.int64) + cols = np.asarray(cols, dtype=np.int64) + scores = np.asarray(scores) + if rows.size == 0: + empty_i = np.empty(0, dtype=np.int64) + return empty_i, empty_i.copy(), np.empty(0, dtype=scores.dtype) + + indptr, anc_indices = _ancestors_csr(ont) + n_terms = int(ont.idxs) + + n_anc = (indptr[cols + 1] - indptr[cols]).astype(np.int64) + total = int(n_anc.sum()) + if total == 0: + empty_i = np.empty(0, dtype=np.int64) + return empty_i, empty_i.copy(), np.empty(0, dtype=scores.dtype) + + # Gather every (row, ancestor-of-col, score) triple, vectorised — same + # index arithmetic as _propagate_sparse_pushup. + block_starts = indptr[cols] + global_offsets = np.zeros(rows.size + 1, dtype=np.int64) + np.cumsum(n_anc, out=global_offsets[1:]) + base_per_j = np.repeat(block_starts, n_anc) + local_offset = np.arange(total, dtype=np.int64) - np.repeat(global_offsets[:-1], n_anc) + expanded_cols = anc_indices[base_per_j + local_offset] + expanded_rows = np.repeat(rows, n_anc) + expanded_scores = np.repeat(scores, n_anc) + + # Group-max over (row, ancestor) via a single flat key + reduceat. + flat = expanded_rows.astype(np.int64) * n_terms + expanded_cols + order_idx = np.argsort(flat, kind='stable') + flat_s = flat[order_idx] + scores_s = expanded_scores[order_idx] + group_starts = np.empty(flat_s.size, dtype=bool) + group_starts[0] = True + np.not_equal(flat_s[1:], flat_s[:-1], out=group_starts[1:]) + start_idx = np.flatnonzero(group_starts) + group_max = np.maximum.reduceat(scores_s, start_idx) + unique_flat = flat_s[start_idx] + out_rows = unique_flat // n_terms + out_cols = unique_flat % n_terms + return out_rows, out_cols, group_max + + def propagate(matrix, ont, order, mode="max", parallel=0, chunk_rows=65536, _shm_name=None, _shape=None, _dtype_str=None, _row_start=None, _row_end=None, _deepest=None, _triples=None): diff --git a/src/cafaeval/parser.py b/src/cafaeval/parser.py index 78b3695..a2bd975 100644 --- a/src/cafaeval/parser.py +++ b/src/cafaeval/parser.py @@ -1,7 +1,8 @@ import os import time -from cafaeval.graph import Graph, Prediction, GroundTruth, propagate +from cafaeval.graph import Graph, Prediction, GroundTruth, propagate, propagate_to_coo import numpy as np +from scipy.sparse import csr_matrix import logging logger = logging.getLogger(__name__) @@ -235,7 +236,7 @@ def _pred_parser_legacy(pred_file, ontologies, gts, ns_dict, term_index, ids, def _pred_parser_vectorised(pred_file, ontologies, gts, ns_dict, term_index, - ids, matrix, replaced): + ids, pred_coo, replaced): """PyArrow-backed bulk parser for the common case (no ``max_terms`` cap). Strategy: @@ -384,7 +385,7 @@ def _pred_parser_vectorised(pred_file, ontologies, gts, ns_dict, term_index, # Sort-based group-max over (row, col). Single int64 flat key, one # stable argsort, np.maximum.reduceat finishes the reduction. - n_terms = matrix[ns].shape[1] + n_terms = gts[ns].matrix.shape[1] flat = p_final * np.int64(n_terms) + t_final order = np.argsort(flat, kind="stable") flat_s = flat[order] @@ -398,13 +399,13 @@ def _pred_parser_vectorised(pred_file, ontologies, gts, ns_dict, term_index, unique_rows = unique_flat // np.int64(n_terms) unique_cols = unique_flat % np.int64(n_terms) - # Scatter into the namespace matrix. The matrix starts at zero, so - # direct assignment is equivalent to the legacy - # "if prob > old: matrix[i, j] = prob" write rule. - matrix[ns][unique_rows, unique_cols] = max_v + # Store the per-namespace COO (group-maxed, unique coords). The caller + # builds a CSR / propagates from this without ever allocating a dense + # (n_prot x n_terms) matrix. + pred_coo[ns] = (unique_rows, unique_cols, max_v) # Register proteins that contributed at least one non-zero value. - prot_has_any = np.zeros(matrix[ns].shape[0], dtype=bool) + prot_has_any = np.zeros(gts[ns].matrix.shape[0], dtype=bool) prot_has_any[unique_rows[max_v > 0.0]] = True surviving_rows = np.flatnonzero(prot_has_any) if surviving_rows.size: @@ -421,14 +422,13 @@ def pred_parser(pred_file, ontologies, gts, prop_mode, max_terms=None, n_cpu=0): This is the slow step if the input file is huge, ca. 1 minute for 5GB input on SSD disk. """ ids = {} - matrix = {} + pred_coo = {} # {ns: (rows, cols, vals)} — sparse; no dense (n_prot x n_terms) is built + matrix = {} # dense scratch, allocated only for the legacy fallback path ns_dict = {} # {namespace: term} replaced = {} row_nnz = {} term_index = {} for ns in gts: - matrix[ns] = np.zeros(gts[ns].matrix.shape, dtype='float') - row_nnz[ns] = np.zeros(gts[ns].matrix.shape[0], dtype=np.int32) ids[ns] = {} term_index[ns] = {t: info["index"] for t, info in ontologies[ns].terms_dict.items()} for term in ontologies[ns].terms_dict: @@ -446,7 +446,7 @@ def pred_parser(pred_file, ontologies, gts, prop_mode, max_terms=None, n_cpu=0): try: _pred_parser_vectorised( pred_file, ontologies, gts, ns_dict, term_index, - ids, matrix, replaced, + ids, pred_coo, replaced, ) used_fast_path = True except Exception as exc: @@ -455,16 +455,26 @@ def pred_parser(pred_file, ontologies, gts, prop_mode, max_terms=None, n_cpu=0): extra={"file": pred_file, "error": repr(exc)}, ) # Reset any partial state the fast path may have written. + pred_coo.clear() for ns in gts: - matrix[ns].fill(0) ids[ns].clear() replaced.clear() if not used_fast_path: + # The legacy loop writes per-cell into a dense matrix. Allocate it only + # on this fallback path, then capture its non-zeros as COO and free it, + # so the common (fast) path never materialises a dense (n_prot x n_terms). + for ns in gts: + matrix[ns] = np.zeros(gts[ns].matrix.shape, dtype='float') + row_nnz[ns] = np.zeros(gts[ns].matrix.shape[0], dtype=np.int32) _pred_parser_legacy( pred_file, ontologies, gts, ns_dict, term_index, ids, matrix, row_nnz, replaced, max_terms, ) + for ns in gts: + r, c = np.nonzero(matrix[ns]) + pred_coo[ns] = (r, c, matrix[ns][r, c]) + matrix[ns] = None t1 = time.time() path_label = "vectorised" if used_fast_path else "legacy" @@ -478,21 +488,37 @@ def pred_parser(pred_file, ontologies, gts, prop_mode, max_terms=None, n_cpu=0): predictions = {} tp0 = time.time() for ns in ids: - if ids[ns]: - logger.debug("pred matrix {} {} ".format(ns, matrix)) + if ids[ns] and ns in pred_coo: t_ns = time.time() - propagate(matrix[ns], ontologies[ns], ontologies[ns].order, mode=prop_mode, parallel=n_cpu) + rows, cols, vals = pred_coo[ns] + shape = gts[ns].matrix.shape + if prop_mode == "max": + # Sparse-native propagation: COO in -> propagated COO out, no + # dense matrix. Bit-identical to dense propagate(mode='max'). + prows, pcols, pvals = propagate_to_coo((rows, cols, vals), + ontologies[ns], "max") + else: + # mode='fill' has zero-only-overwrite semantics that the COO + # path does not model; fall back to a dense propagate for this + # (non-default) namespace, then re-sparsify. + dense = np.zeros(shape, dtype='float') + dense[rows, cols] = vals + propagate(dense, ontologies[ns], ontologies[ns].order, + mode=prop_mode, parallel=n_cpu) + prows, pcols = np.nonzero(dense) + pvals = dense[prows, pcols] + dense = None + pred_csr = csr_matrix((pvals, (prows, pcols)), shape=shape) _parser_logger.info( f"pred_parser propagated {ns:>18s}: " - f"{len(ids[ns])} proteins, {int(np.count_nonzero(matrix[ns]))} annots " + f"{len(ids[ns])} proteins, {int(pred_csr.nnz)} annots " f"({time.time() - t_ns:.2f}s)", extra={"file": pred_file, "ns": ns, "proteins": int(len(ids[ns])), - "annotations": int(np.count_nonzero(matrix[ns])), + "annotations": int(pred_csr.nnz), "seconds": round(time.time() - t_ns, 3)}, ) - logger.debug("pred matrix {} {} ".format(ns, matrix)) - predictions[ns] = Prediction(ids[ns], matrix[ns], ns) + predictions[ns] = Prediction(ids[ns], pred_csr, ns) _parser_logger.info( f"pred_parser total: read+propagate in {t1 - t0 + (time.time() - tp0):.2f}s", extra={"file": pred_file, "seconds": round(time.time() - tp0, 3)},