Skip to content
Merged
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
32 changes: 32 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
54 changes: 37 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ python -c "from cafaeval.evaluation import cafa_eval" # same import

## Attribution

### Upstream authors (primary: always cite)
### Upstream authors (primary, always cite)

The original evaluator and all of its scoring logic are the work of:

Expand Down Expand Up @@ -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 |

Expand All @@ -112,9 +112,9 @@ Detailed per-commit diff against the upstream is maintained in
No optimization lands in this fork without a passing parity test against a
frozen upstream oracle. The oracle is built in `bench/` by running the
**unmodified upstream** against a set of deterministic synthetic corpora
(tiny / medium / large) and serializing the full output (Fmax, Smin,
weighted Fmax, weighted Smin, precision-recall curves, optimal thresholds)
into `bench/oracle/*.pkl`. The diff tests under `tests/diff/` reload
(tiny / medium / large) and serializing the full output, Fmax, Smin,
weighted Fmax, weighted Smin, precision-recall curves, optimal thresholds
- into `bench/oracle/*.pkl`. The diff tests under `tests/diff/` reload
that oracle and compare the fork's output:

- **Phase A** (parser cherry-picks, cached children, weighted-only,
Expand Down Expand Up @@ -153,7 +153,7 @@ prediction file, `known_terms.tsv` exclude set for PK).
| PK | 418.53 s | **10.33 s** | **40.5×** |

The sparse confusion-matrix kernels (Phase B1/B2) are approximately flat
in `n_tau`: moving from `th_step=0.05` (20 thresholds) to the CAFA
in `n_tau` - moving from `th_step=0.05` (20 thresholds) to the CAFA
default `th_step=0.01` (99 thresholds) costs the fork virtually nothing,
while upstream's per-threshold scan scales linearly. Hence the speedup
ratio grows with `n_tau`.
Expand All @@ -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
Expand All @@ -177,22 +196,23 @@ is always available for A/B comparison or debugging.
|---|---|---|
| `CAFAEVAL_SPARSE` | `1` | Sparse NK + PK confusion-matrix kernels and sparse push-up propagation. Set to `0` to fall back to the dense/pool path. |
| `CAFAEVAL_FAST_PARSER` | `1` | PyArrow-backed vectorised `pred_parser`. Set to `0` to force the legacy per-line loop. Also falls back automatically when `max_terms` is set or the fast path raises. |
| `CAFAEVAL_PARITY_PHASE` | `B` | Tolerance used by `tests/diff/test_oracle_parity.py`: `A` for bit-exact, `B` for `rtol=1e-6, atol=1e-9`. |
| `CAFAEVAL_PARITY_PHASE` | `B` | Tolerance used by `tests/diff/test_oracle_parity.py` - `A` for bit-exact, `B` for `rtol=1e-6, atol=1e-9`. |

## 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.

Full documentation (installation, quickstart, per-phase performance
Full documentation, installation, quickstart, per-phase performance
breakdown, parity harness, architecture of the sparse kernels, and
API reference) is hosted at
API reference, is hosted at
[**cafaeval-protea.readthedocs.io**](https://cafaeval-protea.readthedocs.io).

---
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down
65 changes: 65 additions & 0 deletions docs/architecture.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------------------------

Expand Down
10 changes: 10 additions & 0 deletions docs/parity.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------------

Expand Down
75 changes: 75 additions & 0 deletions docs/performance.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ dependencies = [
"pandas",
"matplotlib",
"numpy",
"scipy",
]

[project.optional-dependencies]
Expand Down
Loading
Loading