Implement sparse matrix optimizations and update architecture documentation
This commit introduces significant functional improvements related to sparse matrix handling, including new storage layers, performance fixes for sparse operations, and bug corrections in matrix logic. Additionally, architectural documentation is cleaned up by removing obsolete entries and modifying structural text related to the Sibling Annex discussion.
This commit is contained in:
1 parent
fdfc1eb3dd
commit
95bbc0b2ae
64 files changed
+1374
-2330
No files matched your search
@@ -298,13 +298,11 @@ Both matrix types are enums behind a transparent API — the caller never matche
|
||||
|---|---|---|
|
||||
| `Columnar` | one `.pbiv`/`.pciv` file per column + `meta.json` | build-time default (`*Builder::new`) |
|
||||
| `Packed` | single `matrix.pbmx`/`matrix.pcmx` mmap file | query-optimised, produced by `pack_bit_matrix`/`pack_compact_int_matrix` |
|
||||
| `Sparse` | bit: `sparse_meta.json` + PFIV/Elias-Fano component files, row-major. Int: same support files (built on `PersistentSparseBitMatrix` internally) plus `singleton_values.pciv`/`multi_values.pciv`/`multi_offsets` for the per-row, non-deduplicated values | `pack --sparse`; see [siblings.md](../architecture/siblings.md) for the sparse-vs-dense access-pattern trade-off |
|
||||
| `Sparse` | bit: `sparse_meta.json` + PFIV/Elias-Fano component files, row-major. Int: same support files (built on `PersistentSparseBitMatrix` internally) plus `singleton_values.pciv`/`multi_values.pciv`/`multi_offsets` for the per-row, non-deduplicated values | `pack --sparse`; see "Sparse matrix formats" below for the sparse-vs-dense access-pattern trade-off |
|
||||
| `Implicit` (bit only) | no file at all | mono-genome presence layers — `n_cols` is always reported as `1`, every value is `true` |
|
||||
|
||||
`PersistentBitMatrix::open(layer_dir)` auto-detects the variant, in order: `matrix.pbmx` → Packed, `presence/meta.json` → Columnar, `presence/sparse_meta.json` → Sparse, `layer_meta.json` (no presence dir at all) → Implicit. `PersistentCompactIntMatrix::open(layer_dir)` mirrors the same priority order minus `Implicit` (there's no implicit count matrix — counts always have at least one on-disk column): `matrix.pcmx` → Packed, `counts/meta.json` → Columnar, `counts/singleton_values.pciv` → Sparse. `col_view`/`col`/`sub_matrix` panic on `Sparse`/`Implicit` where the operation has no direct-slice equivalent (Sparse is k-mer-major, not column-major; Implicit has no backing storage) — callers needing per-column data on those variants go through `row`/`fill_row`.
|
||||
|
||||
Unlike the bit side, `PersistentSparseCompactIntMatrix`'s values are *not* deduplicated across rows — two rows can share the same non-zero column set (same `dict_id` in the shared support) while carrying different counts — so its `CountPartials` impl can't reuse the support's dict-multiplicity shortcut the way `BitPartials for PersistentSparseBitMatrix` does. It still avoids the naive `O(n_cols² × n)` column-pair scan via a single row-major pass (`row_major_pairwise` in `sparse_intmatrix.rs`), reconstructing the squared-difference formulas (`euclidean`/`relfreq_euclidean`/`hellinger`) from per-column marginals via `Σ(a-b)² = Σa²+Σb²-2Σab` — see [siblings.md](../architecture/siblings.md)'s "`PersistentCompactIntMatrix::Sparse` — implemented" entry for the full derivation.
|
||||
|
||||
`col_view(c)` returns the appropriate view directly:
|
||||
|
||||
```rust
|
||||
@@ -321,6 +319,163 @@ No wrapper enums (`BitColView`, `IntColView`): the caller receives a `Copy` view
|
||||
|
||||
---
|
||||
|
||||
## Sparse matrix formats
|
||||
|
||||
Motivated by real k-mer-family data being extremely row-sparse (most rows —
|
||||
k-mers — present in only a handful of genome columns out of dozens to
|
||||
thousands): a row-major, deduplicated alternative to the dense column-major
|
||||
formats above, built once per layer like the rest of the pipeline (never the
|
||||
whole multi-billion-row index at once). Implements the exact-duplicate
|
||||
special case of Alanko, Bille, Gørtz, Navarro, Puglisi, "Compact Data
|
||||
Structures for Collections of Sets" (2025,
|
||||
`biblio/Alanko et al. - Compact Data Structures for Collections of
|
||||
Sets.pdf`) — a plain dedup dictionary, not their full subset-containment
|
||||
hierarchy.
|
||||
|
||||
### `PersistentSparseBitMatrix`
|
||||
|
||||
Four mmap-backed on-disk components: an `is_multi` rank-capable flag per row
|
||||
(singleton vs. multi-genome), a fixed-bit-width array for singleton rows
|
||||
(genome index directly, `ceil(log2(n_cols))` bits), a separate fixed-width
|
||||
array for multi-genome rows (`dict_id`, `ceil(log2(n_distinct_multi_sets))`
|
||||
bits — kept apart from the singleton array because `n_distinct_multi_sets`
|
||||
can be large in absolute terms even when multi-genome rows are a small
|
||||
*fraction* of all rows, and a shared array would force every row, singletons
|
||||
included, to pay the wider width), and a deduplicated dictionary of distinct
|
||||
multi-genome sets (Elias-Fano-encoded byte offsets + a varint-encoded values
|
||||
blob). Supporting primitives: `PersistentFixedIntVec` (arbitrary,
|
||||
runtime-parameterised bit width, width `0` included — needed once an
|
||||
`EliasFano` reopen bug surfaced, see below), `PersistentRankSelectBitVec`
|
||||
(rank1/rank0/select1 on top of the crate's existing `count_ones`, via
|
||||
`common_traits::SelectInWord`), `EliasFano` (composes the two). `BinaryMatrix`
|
||||
(`n`, `n_cols`, `row`/`fill_row`, `fill_sub_matrix`, `count_ones`) is the
|
||||
trait unifying dense and sparse at the call sites that need both
|
||||
interchangeably; column-oriented methods (`col`, `col_view`, the
|
||||
`partial_*_dist_matrix` family) stay dense-only — `Sparse`/`Implicit` panic
|
||||
there (see the `PersistentBitMatrix::open` note above).
|
||||
|
||||
Measured on real data (one layer, 30.2M rows, 91 genomes):
|
||||
|
||||
| | dense | sparse | ratio |
|
||||
|---|---|---|---|
|
||||
| on-disk size | 328.1MB | 43.7MB | **7.5x** smaller |
|
||||
| build time / peak RSS | — | 4.26s / 628MB | per-layer, in-memory construction |
|
||||
| row access, sequential (2M reads) | 43ns/row | 32ns/row | sparse faster (smaller structure, better cache fit) |
|
||||
| row access, random (2M reads) | 409ns/row | 85ns/row | sparse **~4.8x faster** — the `--shannon`/family-lookup access shape |
|
||||
| column access, one full column (30.2M rows) | 11.5ms | 993ms | sparse **86x slower** — no native column method, every read decodes a full row to keep one bit |
|
||||
|
||||
The row-access wins (compactness was the stated design goal, not speed) come
|
||||
from dense's genome-major layout scattering a single row read across a much
|
||||
bigger file — costlier than sparse's rank/select/varint decode once the file
|
||||
is this much smaller. Column access is the flip side of the same layout
|
||||
choice; `nonzero_iter` (below) is what removes it from the hot path that
|
||||
actually matters (`query`).
|
||||
|
||||
Two reopen-correctness bugs, now fixed at the source: (1) `EliasFano::open`
|
||||
re-derived its low-bits width from the persisted low-vector's own width
|
||||
byte; the width-`0` case was built with a dummy 1-bit placeholder (the
|
||||
builder used to reject true width `0`), silently doubling every reopened
|
||||
value. Fixed by making `PersistentFixedIntVec` genuinely support width `0`
|
||||
(no storage, `get` always `0`). (2) An empty row (cardinality 0) used to be
|
||||
recorded as a singleton at genome `0`, indistinguishable on read-back from a
|
||||
*real* singleton at genome `0`. Fixed by routing cardinality-0 rows through
|
||||
the dictionary path (a genuine empty entry).
|
||||
|
||||
Still deferred: full Alanko et al. subset-hierarchy compression (only the
|
||||
exact-duplicate case is built), a sparse `PersistentCompactIntMatrix`
|
||||
variant beyond what's described below, BRWT-style column-correlation
|
||||
exploitation, and a row-major rewrite of
|
||||
`partial_jaccard_dist_matrix`/`partial_hamming_dist_matrix`/etc. as a
|
||||
per-row co-occurrence accumulation (`O(Σ_rows k̄²)`) so `obikindex`'s
|
||||
`--metric` distance-matrix path stops paying the column-access penalty on
|
||||
`Sparse` — needs its own design pass (how it plugs into
|
||||
`BitPartials`/`ColumnWeights` so both matrix types keep serving `--metric`),
|
||||
not just "port the loop".
|
||||
|
||||
### `nonzero_iter` — the one traversal per format
|
||||
|
||||
`fn nonzero_iter<'a>(&'a self, slots: &'a [usize]) -> Box<dyn Iterator<Item = (usize, usize, u32)> + 'a>`
|
||||
(item: index into `slots`, column, value) is the single foundational
|
||||
per-format traversal primitive every consumer builds on — `fill_sub_matrix`
|
||||
and a `for_each`-style callback are both trivial, free consumers of it
|
||||
(`.for_each(f)` is `Iterator::for_each`; `fill_sub_matrix` drains the
|
||||
iterator and scatters into `out[][]`), instead of two independently
|
||||
hand-maintained traversals that can silently diverge. `Box<dyn Iterator>`,
|
||||
not a bare `impl Iterator`: `Columnar`/`Packed`/`Sparse`/`Implicit` are
|
||||
genuinely different concrete types and the method isn't on a
|
||||
dyn-compatible trait (`BinaryMatrix` is used as `dyn BinaryMatrix`
|
||||
elsewhere, and RPITIT methods aren't dyn-compatible) — one `Box` per
|
||||
`nonzero_iter` call, not per cell.
|
||||
|
||||
Per-format implementation: `PersistentSparseBitMatrix` decodes natively,
|
||||
buffered one row at a time (`std::iter::from_fn` over the existing
|
||||
`for_each_genome_in_row`, no `n_cols`-wide allocation ever). `Columnar`/
|
||||
`Packed` loop columns, collecting each column's hits via
|
||||
`BitSliceView::nonzero_among_sorted`/`IntSliceView::nonzero_among_sorted`
|
||||
(a `filter`/`filter_map` over the vector-level `get()`, no new state
|
||||
machine — `std`'s own `Filter` iterator already is one) into one `Vec` via
|
||||
`.extend()` (not `flat_map`: a `flat_map` closure can't lazily return
|
||||
something borrowing its own captured sort permutation across separate calls
|
||||
without either boxing per-column or fighting the borrow checker — eager
|
||||
collection sidesteps it at zero extra cost, since `fill_sub_matrix` already
|
||||
fully materialises anyway). `Implicit` is trivial (`slots.iter().map(|&i| (i, 0, 1))`).
|
||||
|
||||
This closed a real dispatch bug by construction, not by patching it:
|
||||
`PersistentBitMatrix::fill_sub_matrix`/`sub_matrix` used to reimplement a
|
||||
naive per-`(column, slot)` loop instead of delegating to
|
||||
`PersistentSparseBitMatrix`'s own efficient native method for `Self::Sparse`
|
||||
— two hand-written traversals for the same format, free to drift apart, and
|
||||
they had (`obikphylo`'s own cache layer had independently built a parallel
|
||||
enum wrapper that *did* dispatch correctly, evidence the bug was worked
|
||||
around rather than fixed at the source). With `fill_sub_matrix`/`sub_matrix`
|
||||
rewritten to drain `nonzero_iter`, there is only one traversal per format
|
||||
left to get right. `KmerPartition::query_partition_with`
|
||||
(`obikindex/src/partition/query_layer.rs`) — previously column-major
|
||||
(`for g { for slot { col_value } }`, which for `Sparse` rebuilt a full row
|
||||
per single cell touched, O(hits × n_cols) instead of O(hits) — the original
|
||||
motivation for this primitive) — now issues one `layer.nonzero_iter(&slot_list)`
|
||||
call per layer, format-agnostic. Dense/sparse query performance parity
|
||||
confirmed on real data (previously sparse 30-50% slower than dense,
|
||||
reproducibly; now within ~1-3% either way — noise level).
|
||||
|
||||
### `PersistentSparseCompactIntMatrix`
|
||||
|
||||
The count-matrix analogue, built on `PersistentSparseBitMatrix` as its
|
||||
"which columns are non-zero" support, values **not** deduplicated (unlike
|
||||
the bit side, two rows can share the same non-zero column set — same
|
||||
`dict_id` — while carrying different counts, so the dict-multiplicity
|
||||
shortcut `BitPartials for PersistentSparseBitMatrix` uses doesn't carry
|
||||
over). `CountPartials` here: a single row-major pass (`row_major_pairwise`
|
||||
in `sparse_intmatrix.rs`, decodes each row once via
|
||||
`for_each_cell_in_row`, nests over that row's own co-present columns) —
|
||||
`O(Σ k̄²)` over populated rows, avoiding the naive `O(n_cols² × n)`
|
||||
column-pair rescan. `min(a,b)`-based kernels (`bray`, `relfreq_bray`) need
|
||||
no correction — they vanish when either side is absent. `a·b` and `√(a·b)`
|
||||
kernels (`euclidean`/`relfreq_euclidean`/`hellinger`) do need one, since
|
||||
`(a-0)² = a² ≠ 0` unlike the `min`-based formulas — reconstructed from
|
||||
per-column marginals via `Σ(a-b)² = Σa²+Σb²-2Σab`.
|
||||
`threshold_jaccard(1)` shortcuts to `BitPartials::partial_jaccard`
|
||||
(threshold 1 is exactly presence); `threshold_jaccard(0)` is closed-form
|
||||
(every `u32` is `≥ 0`).
|
||||
|
||||
Wiring the `threshold==1` shortcut surfaced two pre-existing formula bugs in
|
||||
`BitPartials for PersistentSparseBitMatrix` (present since that type's own
|
||||
introduction, never caught because no test had compared `Sparse`'s raw
|
||||
`partial_*` output against dense on real data — only the diagonal-blind
|
||||
`jaccard_dist_matrix`/`hamming_dist_matrix` finalisations were tested),
|
||||
fixed at the source:
|
||||
|
||||
1. `partial_jaccard`'s diagonal used to be `(0, 2×col_weights[i])` instead
|
||||
of a genuine self-comparison `(col_weights[i], col_weights[i])` —
|
||||
`col_weights_and_pair_counts`'s `inter` never pairs a column with itself
|
||||
by construction, so the diagonal needs its own case.
|
||||
2. `partial_hamming`'s off-diagonal formula itself was wrong: it computed
|
||||
`total - union` (rows where *neither* column is present) instead of the
|
||||
actual Hamming distance `col_weights[i] + col_weights[j] - 2×inter[i,j]`
|
||||
(symmetric-difference size) — the two only coincide when
|
||||
`col_weights[i] + col_weights[j] == total`, which small/synthetic test
|
||||
data can easily satisfy by accident.
|
||||
|
||||
## Aggregation traits (matrix level)
|
||||
|
||||
### ColumnWeights
|
||||
|
||||
Reference in new issue
Block a user