Repository navigation
Description
Problem
Follow-up to merged generic co-occurrence PR #1707 and EviCare PR #1599, prompted by the repeated-code review finding.
The problem is an implicit counting assumption, beyond the opportunity to share arithmetic. For patient-level presence, multiple diagnoses mapped to the same vocabulary concept should contribute one presence per patient. A general counter may instead need to retain within-group frequencies. Silently deduplicating every input would choose the first interpretation for all callers.
The merged builder expects unique patient concepts but can accept repeated list entries and silently produce inconsistent counts. For one input group ["A", "A", "B"], axes ["A", "B"]:
| Interpretation | Matrix |
|---|---|
| Merged implementation, diagonal included | [[3, 2], [2, 1]] |
| Binary presence, after explicitly converting to a set | [[1, 1], [1, 1]] |
| Frequency outer product | [[4, 2], [2, 1]] |
With the diagonal excluded, the merged implementation still produces a same-concept entry: [[1, 2], [2, 0]].
Draft resolution
Make the counting contract explicit:
count_mode="binary"remains the default. Each group must contain unique IDs; repeated IDs raise an informative error. Callers select presence semantics explicitly withset(codes).count_mode="occurrence"accepts repetitions and sums within-group frequency outer products,X.T @ X. Off-diagonal contributions are frequency products; diagonal contributions are squared frequencies. This is not a temporal-window or distinct-event-pair counter.- Accept one iterable per group, including empty groups and single-pass generators. Preserve exact ordered axes, zero rows, sparse int64 output and CPU counting.
- Apply diagonal exclusion in either mode before the existing transform callback. The callback receives the total group count, including empty groups.
KEEP's preprocessing example continues to use binary presence after its existing admission filtering.
Shared builder with vectorized EviCare counting
The initial draft delegated EviCare to the sparse Python pair counter. R317 identified the loss of its vectorized NumPy updates. The revised implementation keeps EviCare connected to the builder while restoring vectorized accumulation inside the shared utility.
layout=torch.sparse_coo remains the default. The opt-in layout=torch.strided path accumulates dense CPU int64 counts through NumPy np.ix_ updates (and frequency outer products in occurrence mode), with no Python pair enumeration or sparse intermediate. Both paths share validation, axes and count-mode semantics and return PyTorch tensors. Output is placed on device, then the transform receives the selected layout after diagonal handling and the full group count.
EviCare explicitly selects dense binary counting and converts the result to its existing NumPy representation. Its vocabulary, deduplication, accepted labels, prevalence diagonals and partner selection are retained. Positional IDs preserve EviCare label acceptance without weakening the generic axis contract. KEEP retains the default COO path.
The temporary review commits that removed EviCare delegation have been replaced. Vectorized execution is verified by regression tests; no MIMIC-scale speed claim is made.
Validation and boundaries
- Check both modes against independent binary/frequency incidence-matrix products.
- Reproduce duplicate-input and zero-diagonal failures; verify explicit rejection or selected occurrence behavior.
- Cover generators, empty inputs, identical patients, axis order, invalid inputs and transform ordering.
- Retain KEEP example regression and EviCare raw-count/query regressions, including label compatibility.
Fractional query scores, normalization API redesign and sparse EviCare storage are separate discussions. This change does not alter EviCare's inference method or claim better predictive performance or construction speed.
This issue tracks the draft resolution; it remains open until the implementation is reviewed and merged.
Sparse layout and Polars investigation: why retain COO for now
We explored storage-layout alternatives separately from count construction. Layout conversion should preserve the matrix, axes and counting semantics; it does not resolve the binary-versus-frequency ambiguity.
| Alternative explored | Potential benefit | Integration and implementation tradeoff |
|---|---|---|
| CSR | Compressed row storage for consumers operating on row segments; may reduce index storage for suitable sparsity patterns. | Existing consumers and transforms use COO coordinates and coalescing. Supporting CSR throughout would require layout-aware accessors or conversion back to COO, plus operation/device compatibility checks. Row pointers describe stored entries, not patient prevalence. |
| CSC | Compressed column storage for column-oriented consumers. | Introduces analogous compatibility work for column pointers and row indices. We have not identified a current consumer whose measured workload justifies selecting CSC as the utility's output. |
| BSC | Stores dense blocks in compressed-column form; potentially useful when nonzeros form sufficiently occupied blocks and downstream kernels support the layout. | Requires selecting block sizes, measuring occupancy, and checking supported operations. Partially occupied blocks also store zeros within their dense blocks. Caller-defined vocabulary order does not guarantee useful block structure; any reordering would require preserving concept alignment. |
| Native Polars counting | Could replace Python pair counting with columnar frequency aggregation, within-group joins and pair-product aggregation, while still returning COO. | A within-group self-join can generate quadratic intermediate data. Requires evaluating batching, peak memory and input-conversion costs while preserving empty groups, single-pass behavior and validation. Iterating over Polars rows in Python would retain the Python-loop overhead rather than provide the native columnar approach. |
References: PyTorch sparse formats, Polars row-iteration guidance.
What was checked
A small local probe with PyTorch 2.15 converted the same COO fixture to CSR and CSC. Dense values, matrix shape and the empty vocabulary row were preserved. The probe also confirmed that the existing .indices() and .coalesce() calls do not work directly on CSR or CSC. BSC and native Polars counting were considered at the design level; no comparative performance benchmark was run.
The default COO path counts pairs in Python dictionaries and loops, then constructs a PyTorch COO tensor. Merely converting that output to another layout would not optimize the loop. The EviCare integration now instead explicitly selects a dense path that performs vectorized NumPy updates before creating its dense tensor.
Decision for this fix
Retain coalesced COO output for now:
- Performance: there is no demonstrated end-to-end benefit from changing layouts or the counting backend. Adding format conversions can introduce runtime and temporary-memory costs. This is not a claim that COO is universally faster or smaller.
- Storage simplicity: coordinate/value storage fits the existing pair accumulator, explicit vocabulary axes, diagonal filtering and KEEP pair extraction without block-size or vocabulary-reordering decisions.
- Compatibility-layer overhead: KEEP adapters and current transforms already consume COO. Supporting several layouts would expand access/conversion logic, operation checks and the test matrix without a demonstrated consumer benefit. EviCare retains its dense public result via the shared builder's vectorized dense path.
- Scope: the current change fixes counting ambiguity and adds an explicit dense path to preserve vectorized EviCare reuse. CSR/CSC/BSC output options and a Polars backend are not added. Consumers can convert the default COO tensor when a particular workload benefits.
Revisit this decision after profiling validation, pair counting and tensor construction separately. Any follow-up should compare exact results, total runtime and peak memory on representative group sizes, vocabulary sizes and sparsity patterns, including conversion costs. Native Polars counting can be evaluated independently of the output layout.
Compatibility evidence for the current implementation
Historical checks at draft revision 901134824a7b92b473255e6899582734ac3f841b:
- Counter, KEEP preprocessing and EviCare tests: 185 passed, 4 optional CUDA checks skipped; 9 subtests passed.
- Targeted PR #1706 snapshot at
6d2ebaed87d0bac8a7b60db7226a4a5d5a8fb0dd: 80 passed, 19 subtests passed with its original counter. - The identical snapshot with only
pyhealth/graph/cooccurrence.pyreplaced by the candidate: 80 passed, 19 subtests passed. Checks include diagnosis/admission support, synthetic readers, expected matrices, axis alignment and KEEP training integration.
These are synthetic compatibility checks, not clinical performance results. KEEP's diagnosis/admission occurrence threshold precedes binary presence counting; it is distinct from the generic utility's new frequency-product occurrence mode. The intended behavior change is that repeated binary inputs now fail explicitly instead of silently producing inconsistent counts.
Reauthored review fixes
At d4957b6a, EviCare delegates to the builder's vectorized dense path and KEEP retains COO by default. The focused suite passes 220 tests, with 8 optional CUDA skips and 9 subtests passing. Tests explicitly guard shared-builder dispatch, vectorized dense updates, avoidance of Python pair enumeration, layout parity and transform ordering. All six public docstring examples, both API examples, lint and contribution rules passed.
The separate documentation commit c5439ca9 addresses R69: the summary points to Args for explicit binary/occurrence and repeated-input behavior. The older 185-test and #1706 checks above identify their historical revision; they are not claimed as a fresh cross-PR run of this revision.
Activity
[-]Unify EviCare co-occurrence counting with the generic utility[/-][+]Make co-occurrence count modes explicit and share binary counting with EviCare[/+][-]Make co-occurrence count modes explicit and share binary counting with EviCare[/-][+]Make binary and occurrence co-occurrence counting explicit[/+][-]Make binary and occurrence co-occurrence counting explicit[/-][+]Make count modes explicit and preserve vectorized EviCare reuse[/+]