Skip to content

Fix co-occurrence count modes and refactor EviCare counting to PyTorch - #1787

Open
lee-leonardo wants to merge 2 commits into
sunlabuiuc:masterfrom
lee-leonardo:fix/cooccurence_count_modes
Open

lee-leonardo wants to merge 2 commits into
sunlabuiuc:masterfrom
lee-leonardo:fix/cooccurence_count_modes

Conversation

@lee-leonardo

@lee-leonardo lee-leonardo commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

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 raise ValueError; callers explicitly use set(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.
  • Both modes preserve axis order, zero rows, empty groups, single-pass inputs and int64 counts. Excluding the diagonal removes every same-concept entry in either mode.

PyTorch counting and shared graph storage

The generic counter accepts caller-defined groups; patient-specific preprocessing stays with its callers. Its historical patient_concepts keyword remains compatible.

Layout Accumulation Output
torch.sparse_coo (default) Sparse pair counter Coalesced PyTorch COO tensor
torch.strided (opt-in) Vectorized PyTorch block updates per group; tensor frequency outer products in occurrence mode Dense PyTorch int64 tensor

Dense allocation, indexing, accumulation and diagonal selection now use PyTorch throughout. The generic counter no longer imports NumPy. Counting runs on CPU; device selects 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. CooccurrenceGraph retains the builder's exact tensor as counts_tensor; its legacy counts NumPy interface is a writable view of the same CPU storage. GPU-backed graphs export CPU snapshots through that compatibility property. Batched best_partners drives 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.

python -m pytest \
  tests/core/test_graph_cooccurrence.py \
  tests/core/test_keep_mimic_preprocessing.py \
  tests/core/test_evicare.py -q

Fractional scoring, normalization redesign, other sparse layouts and Polars counting remain outside this change. No clinical-quality or GPU-performance result is claimed.

@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 89.25% (67877 / 76051 lines)

Modified file Coverage Lines
pyhealth/graph/cooccurrence.py 100.00% 81 / 81
pyhealth/models/evicare.py 99.15% 352 / 355

Workflow run · 30bcd8b

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Dec 2, 2026 — with Claude

solarsys commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

/review


Generated by Claude Code

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 9011348

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_cooccurrence docstring, 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 Counter instead 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 to status: manual.

Reviewed commit 9011348

@lee-leonardo lee-leonardo changed the title Fix repeated-code co-occurrence counting and share binary counting with EviCare Fix repeated-code co-occurrence counting with explicit modes Dec 2, 2026
@lee-leonardo
lee-leonardo force-pushed the fix/cooccurence_count_modes branch from 6c5c3c4 to d4957b6 Compare December 2, 2026 19:14
@lee-leonardo lee-leonardo changed the title Fix repeated-code co-occurrence counting with explicit modes Fix co-occurrence count modes and retain vectorized EviCare reuse Dec 2, 2026
@lee-leonardo

lee-leonardo commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Historical checkpoint: This discussion records d4957b6a, before construction moved to PyTorch. The completed refactor and fresh measurements describe the current implementation, now consolidated into 9c072785 and 30bcd8bb.

Maintainer design input: performance and tensor interoperability at d4957b6a

I measured the current shared-builder checkpoint against the original EviCare implementation before proposing a further refactor.

Synthetic CPU measurements (2,000 groups; 5% empty; fixed seed; duplicate events included at the EviCare boundary; PyTorch 2.15.0, NumPy 2.5.5; torch.utils.benchmark.Timer, one PyTorch thread, blocked autorange >=0.2 s per case):

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.

@lee-leonardo

lee-leonardo commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

PyTorch counting and graph storage

The contribution is organized into 9c072785 for the generic counter and 30bcd8bb for EviCare integration. The history cleanup preserves the validated source, tests and documentation byte-for-byte and excludes the benchmark script from both commits.

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 counts_tensor; its writable CPU counts NumPy view references the same storage. GPU compatibility exports are CPU snapshots. Batched relational-evidence queries use PyTorch; scalar CPU lookups use a cached view of the same storage. Both count modes, generic validation, EviCare's existing semantics and KEEP's default COO path are preserved.

Validation (cleaned history 30bcd8bb): 229 tests passed, 11 optional CUDA checks skipped; 24 subtests passed. EviCare alone passes 100 tests with 3 CUDA skips. Tensor assertions check count values, dtype and device; NumPy coverage remains for shared views, array inputs and legacy pickle state. The new real-guide lifecycle test checks embedding updates, unchanged CPU counts, relational predictions and exact checkpoint recovery. CUDA variants for query parity and guide training/checkpointing are included but could not run on this CPU-only runtime. Local negative controls confirmed that disabling training or checkpoint loading makes the lifecycle test fail. Seventeen graph API doctest examples and both graph API-page code blocks were validated at the unchanged construction checkpoint; Ruff and contribution rules pass.

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.

Operation NumPy checkpoint dfcc5d16 PyTorch 6a24c4f2
Complete EviCare fit: V=285, 12 codes/nonempty group 10.8720 15.3403
Complete EviCare fit: V=842, 32 codes/nonempty group 28.3060 30.0656
Generic binary counting: V=842, mixed widths 160.8607 106.0775
Generic occurrence counting: V=842, mixed widths 181.1969 119.2910

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; torch.utils.benchmark.Timer.blocked_autorange(min_run_time=1). Separate 1- and 6-thread runs also cover single-group, tiny and 20,000-group inputs. Tools and raw medians/IQRs/source hashes are kept locally; benchmark code is excluded from both cleaned commits.

These are synthetic CPU measurements, without clinical data, GPU timing, LLM calls or peak-memory measurements.

@lee-leonardo lee-leonardo changed the title Fix co-occurrence count modes and retain vectorized EviCare reuse Fix co-occurrence count modes and extend EviCare tensor interoperability Dec 2, 2026
@lee-leonardo
lee-leonardo marked this pull request as draft December 2, 2026 20:09
@lee-leonardo lee-leonardo changed the title Fix co-occurrence count modes and extend EviCare tensor interoperability Fix co-occurrence count modes and refactor EviCare counting to PyTorch Dec 2, 2026
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.
@lee-leonardo
lee-leonardo force-pushed the fix/cooccurence_count_modes branch from 30b5ae0 to 30bcd8b Compare December 2, 2026 21:40
@lee-leonardo
lee-leonardo marked this pull request as ready for review December 2, 2026 21:45
@lee-leonardo

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 30bcd8b

frequencies: dict[int, int] = {}
for code in codes:
if not isinstance(code, str):
raise TypeError("group concepts must be strings")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@github-actions github-actions Bot added status: manual Pending maintainer's review and removed status: automatic The PR will go through automatic review process. labels Dec 3, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Make count modes explicit and preserve vectorized EviCare reuse

2 participants