Repository navigation
Fix co-occurrence count modes and refactor EviCare counting to PyTorch - #1787
lee-leonardo wants to merge 2 commits into
Conversation
Test CoverageTotal: 89.25% (67877 / 76051 lines)
|
|
/review Generated by Claude Code |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: approve
decision: need change
Thank you for this contribution. It fixes silent miscounting of repeated codes in the co-occurrence counter. It adds an explicit count_mode with binary and occurrence modes, and it moves EviCare's counting onto the shared builder. The diff looks correct and complete to me. The description explains the new link from EviCare to build_cooccurrence, and it gives the reason. Tests compare both modes against independent incidence-matrix products, with both diagonal settings. They also cover single-pass inputs, error paths and EviCare label compatibility. Coverage is 100% for pyhealth/graph/cooccurrence.py and 99.68% for pyhealth/models/evicare.py. Whole-repository coverage is 89.33%. That clears the 80% per-file and 60% total bars. The docs match the code.
This change touches shared code, so a maintainer needs to make the final call. pyhealth/graph/cooccurrence.py is a shared generic counter that EviCare and the KEEP example both use. Its default binary mode now raises ValueError on repeated codes instead of silently miscounting. That changes the contract for every caller of the shared function. This is why it can't be approved automatically. Your description states the change clearly. I can't promise how the maintainer will decide.
Optional suggestions:
-
In the
build_cooccurrencedocstring, the sentence "Convert occurrence lists to sets explicitly when presence is intended" could say "lists with repeated codes" to read more clearly in binary mode. -
EviCare's counting now runs in a Python
Counterinstead of vectorized NumPy. You could add a rough timing at MIMIC scale to confirm it is acceptable. -
Warning: this PR can't be approved automatically because it touches the core part of PyHealth (base classes or shared code). To stay on automatic review, back out that part, or ask a maintainer to review it, then comment
/review. If the next review finds this again, the PR switches tostatus: manual.
Reviewed commit 9011348
6c5c3c4 to
d4957b6
Compare
Maintainer design input: performance and tensor interoperability at
|
| Complete EviCare fit | V=285, 12 codes/nonempty group | V=842, 32 codes/nonempty group |
|---|---|---|
Original NumPy implementation (7ea6bdac) |
7.291 ms | 19.155 ms |
Shared builder (d4957b6a) |
10.651 ms | 27.304 ms |
Exact vocabulary and raw-count agreement were checked. These generated, fixed-width cohorts are not full MIMIC benchmarks. The shared path is about 43–46% slower here; preserving vectorized accumulation alone did not remove the additional integration overhead.
The CPU NumPy -> tensor -> NumPy path shares matrix storage (verified on the actual EviCare call); its isolated round trip measured about 0.66 microseconds. This does not identify matrix copying as the cause. Redundant label encoding, validation, sorting and per-group index construction are candidates for further profiling. A direct per-group tensor prototype with matching validation was also slower than NumPy (13.673 vs 9.048 ms; 25.262 vs 22.686 ms), so replacing NumPy syntax is not a demonstrated optimization.
Would a tensor-backed CooccurrenceGraph, retaining a NumPy compatibility view and existing count/partner semantics, be a useful direction for PyTorch interoperability? In particular, batched tensor relation queries could avoid repeated Python scalar lookups. Construction speed and query speed need separate evaluation.
I will add this as one isolated follow-up commit, with correctness checks and reproducible construction/query timings against both the original implementation and d4957b6a. It can be dropped independently if the interface or performance tradeoff is not suitable. The earlier count-mode fix and documentation checkpoint remain available. No clinical-quality or GPU-performance claim is intended.
PyTorch counting and graph storageThe contribution is organized into Current implementation: the generic dense counter allocates CPU int64 tensors and uses PyTorch indexing, frequency outer products and diagonal selection. It no longer imports NumPy. EviCare retains the exact returned tensor as Validation (cleaned history Recorded CPU measurements (medians, milliseconds; one PyTorch thread): These measurements were recorded before history cleanup at the checkpoint IDs shown below. The counter and model source files in the cleaned history match the measured PyTorch files byte-for-byte.
Fixed-width fits are slower here; mixed-width counting is faster. The reason for this refactor is PyTorch construction and shared tensor storage, with these measured performance tradeoffs. Query speed was not remeasured in this run. Protocol: 2,000 generated groups, seed 20261202, every twentieth group empty; mixed nonempty widths sampled from 1, 4, 12, 32, 128 and 256. Duplicate events are included in occurrence inputs and at the EviCare boundary. Exact counts and selected relations agree before timing. macOS arm64, Python 3.12.12, PyTorch 2.15.0, NumPy 2.5.5; These are synthetic CPU measurements, without clinical data, GPU timing, LLM calls or peak-memory measurements. |
Reject repeated IDs in binary groups and support within-group frequency products in occurrence mode. Preserve axis order, empty groups, single-pass inputs, diagonal selection and transform placement across sparse COO and dense PyTorch output. Keep grouping terminology generic while preserving the published patient_concepts keyword. Document the contract and verify counts against independent incidence products. Validation: counter, KEEP preprocessing and baseline EviCare suites pass with 219 tests, 8 CUDA skips and 6 subtests.
Retain the dense builder tensor and expose a writable NumPy compatibility view of its CPU storage. Preserve vocabulary, label acceptance, integer query semantics and legacy pickle state, and batch relational-evidence queries. Verify storage identity, independent counts, query parity, real guide embedding updates, unchanged CPU graph counts and checkpoint recovery. Include optional CUDA query and training variants without claiming execution on this CPU-only runtime. Validation: counter, KEEP preprocessing and EviCare suites pass with 229 tests, 11 CUDA skips and 24 subtests.
30b5ae0 to
30bcd8b
Compare
|
/review |
| frequencies: dict[int, int] = {} | ||
| for code in codes: | ||
| if not isinstance(code, str): | ||
| raise TypeError("group concepts must be strings") |
There was a problem hiding this comment.
[low] Non-string group concept now raises TypeError instead of ValueError
Before this change, a non-string code that did not match an axis ID (for example an int) raised ValueError 'is not part of concept_ids'. It now raises TypeError 'group concepts must be strings' from _group_frequencies. The description and docs do not mention this change in exception type. Either keep the ValueError for unmatched non-string codes, or add the TypeError to the Raises section and mention it in the description.
| Args: | ||
| codes: The CCS vocabulary, in matrix order. | ||
| counts: The ``len(codes) x len(codes)`` count matrix. | ||
| counts: Dense real numeric NumPy array or PyTorch tensor of shape |
There was a problem hiding this comment.
[low] Docstring says counts must be real, but complex tensors are accepted
The CooccurrenceGraph Args say counts is a 'Dense real numeric' array or tensor. The constructor and counts setter accept complex tensors without checking. The error only surfaces later in best_partners, which raises TypeError 'requires real counts', while count() fails with a different message. Either validate real dtype in the counts setter or leave the docstring as is and accept the later failure.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: human review
Thank you for this contribution. It fixes the silent miscounting of repeated codes in the generic co-occurrence counter and adds explicit binary and occurrence modes. It also adds a dense PyTorch layout and moves EviCare's graph onto the shared builder with tensor storage and batched partner queries.
The diff looks correct and complete to me, and the description matches the code. The docs and docstring examples agree with the implementation. The new link from EviCare to build_cooccurrence is named in the description with a clear reason: deduplication and a shared dense binary path. Coverage meets the bar: 100% for pyhealth/graph/cooccurrence.py, 99.15% for pyhealth/models/evicare.py, and 89.25% for the whole repository.
This touches shared code, so a maintainer needs to make the final call. build_cooccurrence is a shared utility, and its default behavior changes: binary mode now raises ValueError on repeated codes, and a new dense return path is added. EviCare's CooccurrenceGraph also changes its storage contract, since counts is now a property backed by a tensor. Changes to a shared API contract can't be approved automatically. Looking at the diff, it appears well documented and tested, but I can't promise the outcome.
Optional suggestions:
-
Non-string group concepts now raise TypeError where the old code raised ValueError. A line in the docs would make this change explicit.
-
The EviCare docstring says counts must be "real numeric", but complex tensors are accepted at construction. They are only rejected in best_partners. You could align the wording or validate earlier.
-
The CUDA tests couldn't run in CI, so a maintainer may want to try them on a GPU machine.
-
Switched to
status: manual: it touches the core part of PyHealth (base classes or shared code), again after an earlier warning, so a maintainer will review this PR.
Reviewed commit 30bcd8b
Problem and change
Resolves #1786. Follow-up to the generic counter in #1707 and EviCare in #1599.
Repeated input codes could silently produce counts matching neither binary presence nor frequency products. For one group
["A", "A", "B"], the previous diagonal-inclusive matrix was[[3, 2], [2, 1]]. Binary presence should give[[1, 1], [1, 1]]; frequency products should give[[4, 2], [2, 1]].count_mode="binary"remains the default and requires unique concepts per group. Repeated codes raiseValueError; callers explicitly useset(codes)when presence is intended.count_mode="occurrence"accepts repetitions and sums within-group frequency outer products,X.T @ X. Its diagonals are squared-frequency sums.PyTorch counting and shared graph storage
The generic counter accepts caller-defined groups; patient-specific preprocessing stays with its callers. Its historical
patient_conceptskeyword remains compatible.torch.sparse_coo(default)torch.strided(opt-in)Dense allocation, indexing, accumulation and diagonal selection now use PyTorch throughout. The generic counter no longer imports NumPy. Counting runs on CPU;
deviceselects output placement. Transforms receive the selected layout/device after diagonal selection, with the total number of groups including empty groups.EviCare deduplicates codes and selects the shared dense binary path.
CooccurrenceGraphretains the builder's exact tensor ascounts_tensor; its legacycountsNumPy interface is a writable view of the same CPU storage. GPU-backed graphs export CPU snapshots through that compatibility property. Batchedbest_partnersdrives relational-evidence queries; scalar CPU lookups retain a cached view of the same storage. Vocabulary, label acceptance, prevalence diagonal, integer lookup, tie, unknown/self-code, no-partner and legacy-pickle behavior are preserved.The changes are split into two commits:
9c072785: generic count-mode corrections, dense PyTorch output, tests and API documentation.30bcd8bb: EviCare integration, shared tensor storage, batched queries, regression tests and documentation.The graph storage and dense counter use the same tensor; there is no separate NumPy accumulation matrix. Benchmark scripts are excluded from both commits.
KEEP: the preprocessing example retains its COO default, admission filtering and zero-diagonal SciPy CSR float32 output.
Validation and performance
At
30bcd8bb: 229 tests passed, 11 optional CUDA checks skipped; 24 subtests passed across the counter, KEEP preprocessing and EviCare suites. EviCare alone: 100 passed, 3 CUDA checks skipped. Tensor-count assertions use PyTorch; NumPy tests retain coverage of compatibility views, array inputs and historical pickle states.The EviCare lifecycle regression trains the real RETAIN guide for one synthetic epoch, verifies finite updated embeddings and unchanged CPU graph counts, runs relational prediction with a fake LLM, and checks exact guide weights and predictions after a Trainer checkpoint round trip and graph refit. Separate CUDA variants cover CPU-reference graph-query parity and CUDA guide training/checkpointing with a CPU graph; these remain unexecuted in this CPU-only runtime.
Regression checks also verify exact builder-tensor identity, bidirectional NumPy/tensor storage sharing, independent incidence products, single-pass/transform contracts, and CPU accumulation when another default tensor device is active.
Seventeen graph API doctest examples, both graph API-page code blocks, Ruff and contribution rules passed. A full Sphinx build was not run.
Current measurements and implementation details compare the final PyTorch accumulator with the NumPy checkpoint. Fixed-width EviCare fits are slower in the measured cases; mixed-width generic counting is faster. The refactor provides PyTorch construction and storage interoperability, with workload-dependent performance. Measurement tools and raw timing output are kept locally.
Fractional scoring, normalization redesign, other sparse layouts and Polars counting remain outside this change. No clinical-quality or GPU-performance result is claimed.