All notable changes to PyHealth are documented here. Versions follow the
major.minor.patch scheme; see the
releases page for the
corresponding tags and wheels.
A minor release focused on making PyHealth results trustworthy: leakage-free
preprocessing with split-aware set_task, reproducible training, calibration metrics
with patient-level confidence intervals, and a large set of cache and data-handling
fixes. It also adds an XGBoost model with exact TreeSHAP, Synthea synthetic-patient
generation, ICD-9 ↔ ICD-10 translation, and a new nine-notebook tutorial series.
Most 2.0.2 code runs unchanged, but read Upgrading from 2.0.2 below: dependency
floors moved (notably torch>=2.10), the EHR-generation tasks were reorganised,
and a few behaviours changed on purpose.
- Dependencies.
torch>=2.10,pyarrow>=23.0.1,dask[complete]>=2026.1.0andlitdata>=0.2.64,<0.2.68are now required; numpy, pandas, pydantic, scikit-learn and narwhals use bounded ranges instead of~=pins, so installs on Google Colab no longer downgrade preloaded packages.urllib3is no longer a dependency, andicd-mappingsis new. (#1254, #1287, #1273, #1257) - EHR-generation tasks. The
EHRGenerationbase class is gone. There are now six tasks, one per encoding and dataset:EHRGenerationMIMIC3/4(per-visit multi-hot, for HALO),EHRSequenceGenerationMIMIC3/4(per-visit code indices, for GPT-2 and PromptEHR) andEHRCodeSetGenerationMIMIC3/4(one code set per patient, for MedGAN and CorGAN).EHRGenerationMIMIC3/4now emitnested_multihotinstead ofnested_sequencerows; GPT-2 and PromptEHR users should switch toEHRSequenceGenerationMIMIC3/4. (#1233) - Missing
Eventtimestamps areNone.Eventused to substitutedatetime.now()for a missing timestamp (e.g. MIMICpatients, eICU tables), which sorted before every real event and silently passed time-window filters. Code that relied on a non-null timestamp must handleNone. (#1247) - Caches rebuild once. The dataset cache key now covers the YAML config and the source files' size and mtime, and the processed-sample cache key covers the new storage format, so existing caches are rebuilt on first use. Old cache folders are left in place and can be deleted. (#1265, #1277)
- Shuffle orders differ from 2.0.2. Dataloaders now draw shuffles from a seeded per-loader generator, and patient-level splitters sort patient IDs before shuffling. Runs are reproducible from here on, but the same seed selects different batches and splits than it did in 2.0.2. (#1280, #1286)
- Logging. The
pyhealthlogger no longer propagates to the root logger, so each message prints once in Jupyter and Colab. To route PyHealth messages through your own root configuration, removepyhealth.handlerand re-enable propagation. (#1285) - Default cache warning. Building a dataset without
cache_dirnow logs a warning naming the user cache folder it writes to; setPYHEALTH_REQUIRE_CACHE_DIR=1to make it an error. (#1264) - The unmaintained 2023
chat-assistant/demo was removed (it remains in git history). (#1252)
- Split-aware preprocessing —
dataset.set_task(task, split=PatientSplit(...))fits every processor (vocabularies and any learned statistics) on the training patients only and returns(train, val, test)views of one processed cache.PatientSplitaccepts two or more ratios, and custom splits implement the newSplitinterface. Processors that learn statistics warn when fitted on all samples. (#1273) - Reproducible training —
get_dataloader(..., seed=None)gives each loader its own seeded, per-epoch shuffle on both the in-memory and disk backends, sotorch.manual_seedalone makes runs repeatable.pyhealth.utils.preserve_rng_state()is new;set_task, dataset creation and interpretability methods no longer touch global RNG state, and importingpyhealth.modelsno longer reseeds numpy and torch.Trainer.trainrestores the best epoch even with logging off (keep_best_in_memory). (#1280) - Calibration and confidence intervals —
binary_metrics_fnaddsbrier,oe_ratio,calibration_slopeandcalibration_intercept; the newpyhealth.metrics.bootstrapmodule providesbootstrap_ciandpaired_bootstrap_diff, withgroups=for patient-clustered resampling. (#1268) - Imbalanced outcomes —
BaseModel.set_pos_weight(...)takes a number, a per-label list, or"balanced"computed from a training dataset, and applies to every model that uses the default binary/multilabel loss. (#1267)
XGBoostModel— gradient-boosted trees for binary, multiclass, multilabel and regression tasks, fit withmodel.fit(train, val=None)and evaluated through the usualTrainer. Supports tensor, timeseries, multi-hot and nested multi-hot inputs (and bag-of-codes for code sequences),scale_pos_weight, early stopping, and exact TreeSHAP throughexplain()and the newpyhealth.interpret.methods.TreeSHAP. Install withpip install "pyhealth[xgboost]". (#1278)- Synthea —
pyhealth.models.Synthearuns the Synthea synthetic-patient generator (Java 17+ required; the JAR is downloaded and cached), andSyntheaCSVDatasetloads its CSV output. (#1244) - HALO — visit encoding is now vectorised, removing a per-code Python loop that took ~85% of a training step on GPU. (#1233)
NestedMultiHotProcessor("nested_multihot") — one multi-hot row per visit, sized by the vocabulary rather than by the longest visit (8.6× smaller per patient on eICU). (#1233)- ICD-9 ↔ ICD-10 translation and grouper vocabularies —
CrossMapgains anicd-mappingsbackend for pairs PyHealth hosts no table for (ICD-9 ↔ ICD-10, CCSR, chapters and blocks, chronic-condition indicators, and more). Existing mappings such as ICD9CM→CCSCM are unchanged. ICD-9 ↔ ICD-10 is a primary-mapping approximation of the GEMs, reported through a warning andCrossMap.unmapped_codes.CrossMapalso downloads vocabulary tables only when they are used. (#1257) TensorProcessor.size()now returns the fitted feature width, and embeddings are sized from already-processed samples instead of re-runningprocess(). (#1262)
Data leakage and label correctness
MultimodalMortalityPredictionMIMIC4used chest X-rays from after the prediction time; X-rays are now limited to those available by the last included admission's discharge. (#1229)T1DDKAPredictionMIMIC4counted DKA events recorded before a separate T1DM diagnosis; those patients are now excluded. (#1230)- With more than 10 workers,
set_taskmerged worker indexes in string order (0, 1, 10, 11, …), sopatient_to_indexpointed at other patients' samples and patient-level splits shared patients (on full MIMIC-IV with 32 workers, ~3.6k patients appeared in both train and val). Fixed by requiringlitdata>=0.2.64. Caches built with more than 10 workers before this release keep the wrong order; delete and rebuild them. (#1273) - Supplying pre-fitted processors for some fields left the other fields without a processor, so raw values reached the model; missing processors are now fitted. (#1273)
Datasets, caching and samples
- Rewriting a source file or editing a dataset's YAML config silently reused the stale cached event table. (#1265)
- Sample fields whose length or shape varies between samples (notes, measurement
times,
Nonemixed with lists) failed, were truncated, or were misread on the disk-backed cache. Non-tensor fields are now stored as one opaque value per sample. (#1277) - Nested sequence and float processors now truncate visits longer than the fitted width (with a one-time warning) instead of producing ragged batches. (#1263)
Eventobjects could not be copied or unpickled (RecursionError), so a sample containing one was written to the cache but crashed when read back. (#1247)- Every dataset build leaked three file descriptors through dask's dashboard, eventually failing with "Too many open files" on macOS. (#1245)
- Downloads are now atomic with a timeout: an interrupted download no longer leaves a truncated file that later runs reuse, and a stalled server no longer hangs. medcode JSON downloads no longer re-download on every call. ChestX-ray14 extraction rejects unsafe archive members. (#1255)
split_by_patient,split_by_patient_conformaland the TUH patient splitters picked different patients for the same seed depending on sample order. (#1286)create_sample_dataset(in_memory=False)could leave helper processes running after an error and hang at exit; it now writes in-process. The in-memory dataset no longer yields every sample once per dataloader worker. (#1277, #1280)
Models
model.modewas overwritten with the raw schema entry in 16 models, so processor class or tupleoutput_schemaforms crashedTrainer.evaluate, calibration andAgent.BaseModel.modeis now a property that always resolves to a mode string. (#1246, fixes #914)- GRASP never built its similar-patient graph, falling back to an identity adjacency; the kNN cluster graph now works with self-connections. (#1194)
TransformerDeIDignored its configured feature and label keys. (#1224)
Metrics and interpretability
- Removal-based interpretability metrics (comprehensiveness, sufficiency) crashed for every model with integer code-sequence inputs; removed codes are now set to the padding id. (#1284)
- Ranking metrics used a bare
except. (#1237)
- A nine-notebook tutorial series under
examples/tutorials/series/, from a first model through datasets, tasks, training and evaluation, model choice, interpretation, medical codes, clinical text, and contributing. Each notebook runs on CPU in Colab. (#1281) - New docs sections and runnable examples covering reproducible runs, shuffling,
split-aware
set_task, reusing fitted processors, imbalanced outcomes, calibration and bootstrap CIs, cache behaviour, identified data, logging setup, and custom tensor processors. - Fixed the GAMENet drug-recommendation example;
minimal_legacy_*.pyscripts are labelled as PyHealth 1.1.6-only. (#1206)
SECURITY.mddescribes private vulnerability reporting and the trust model (pickle-based caches and checkpoints must come from trusted sources). Workflows declare least-privilege token permissions. (#1253)- Dependency floors were raised past known CVEs in torch, pyarrow, dask and urllib3; pip-audit reports no known vulnerabilities on a fresh install. (#1254)
- CI reports test coverage. (#1299)
- Tests find their resources relative to the test file, and a flaky ATC-3 ordering assertion is now order-insensitive. (#1292, #1261)
Full Changelog: https://github.com/sunlabuiuc/PyHealth/compare/v2.0.2...v2.1.0
The first release since 2.0.1 (2026-03-30). It adds four datasets, a synthetic-EHR generation and evaluation stack, several new models and interpretability methods, and a large batch of correctness fixes across models, tasks, metrics, and calibration. No public API was removed or renamed — 2.0.1 code continues to work unchanged.
- MEDS —
MEDSDatasetplus a typed Parquet scan path onBaseDataset..parquet/.pqfiles, globs, and directories now route through a typed_scan_parquetscanner, with a datetime fast path that skips the string round-trip. Includes thein_hospital_mortality_medstask. (#1179) - FHIR — a full FHIR pipeline under
pyhealth/datasets/fhir/, including a MIMIC-IV-on-FHIR dataset. (#1155) - EEGBCI — dataset, helper functions, and tasks. (#1177)
- PhysioNet De-Identification — dataset, NER task (
deid_ner), and theTransformerDeIDmodel. (#981)
- MedFuse — multi-modal fusion of EHR time series with chest X-rays. (#1003)
- Synthetic EHR generators —
pyhealth/models/generators/: HALO, MedGAN, CorGAN, PromptEHR, and a GPT-2 generator, with thegenerate_ehrtask. (#1148) - CaliForest — calibrated random forest; requires an explicit
fitbefore inference. (#999) - GRASP — migrated from the 1.x API to 2.0, with
static_keysupport for demographic features. (#905)
DrugRecommendationOMOP— a class-based OMOP drug recommendation task. (#1203)- Generative evaluation metrics —
pyhealth/metrics/generative/scores synthetic EHR data on privacy (NNAAR, membership inference, discriminator privacy), utility, and statistical fidelity. (#1148) - Attention rollout — interpretability method of Abnar & Zuidema (2020). (#1158)
- Conformal prediction — real Adaptive Prediction Sets (Romano, Sesia & Candès
2020) in the new
pyhealth/calib/predictionset/scores.py, with a dynamicscore_typeon conformal methods (#1189), plus additional conformal methods and example scripts (#942).
code_mapping—SequenceProcessoraccepts an optionalcode_mappingthat collapses granular codes into grouped vocabularies (ICD9CM→CCSCM, ICD9PROC→CCSPROC, NDC→ATC) before building the embedding table, andBaseTask.__init__accepts it directly so schemas no longer have to be patched by hand. Closes the functional gap left by the 1.x→2.0 rewrite. (#905, ref #535)
Data leakage and label correctness
- StageNet MIMIC-IV mortality/LOS tasks leaked post-outcome information: diagnosis and
procedure codes are timestamped at
dischtime, so for the admission being predicted they are only known at or after the outcome, and labs were pulled through discharge/death. Those codes are now excluded for that admission and its labs capped to the first 48 hours. (#1205) drug_recommendation_omop_fnnever excluded the current visit's own drugs fromdrugs_all, making the last history entry identical to the prediction target. (#1203)- Drug tasks extracted
event.drug(drug names, e.g. "Aspirin"), which produce zero matches in the NDC→ATC CrossMap; they now extractevent.ndc. (#905) - Drug recommendation NDC/ATC3 code handling and padding behaviour. (#1138)
Models
CNNcrashed on 1-D tensor and multi-hot inputs:forwardhardcoded a 3-D expectation forspatial_dim=1, butMultiHotProcessorand 1-DTensorProcessorinputs embed to[batch, embedding_dim]with no sequence axis. Now treated as a length-1 sequence. (#1208)TCNcrashed on tuple-schema features by passing raw kwargs (includingStageNetProcessor's(time, value)tuples) to the embedding model; it now unwraps thevaluetensor first, like its sibling sequence models. (#1212)BIOThardcodednn.Embedding(n_channels, 256)for channel tokens, crashing for anyemb_size != 256. (#1213)MoleRec's no-SMILES fallback predictor was created lazily insideforward, so an optimizer built frommodel.parameters()beforehand never saw its parameters and it never trained. It is now created in__init__. (#1214)SdohClassifierwas annn.Moduledecorated with@dataclass, whose generated__init__never callednn.Module.__init__, leaving the module without_parameters/_modulesand unusable in torch. (#1209)SinusoidalTimeEmbeddingdivided frequency indices byhalf - 1, sodim=2gave 0/0 and every embedding was NaN. Clamped to at least 1. (#1216)- Sparsemax in
AdaCare. (#1139) RNNLayerandConCarecrashed on zero-length sequences and onbatch_size=1;GRASPcollapsed its hidden state atbatch_size=1and raised whencluster_num > batch_size. (#905)- MedLink:
collate_fnbuilt output keys from only the first sample in a batch, so a batch mixing samples with and without a mined hard negative (s_n) either raisedKeyErroror silently produced a misaligned list; keys are now unioned across the batch. (#1222) - MedLink BM25 hard-negative mining did not preserve all positives. (#1195)
Datasets and tasks
- Patient merging crashed on tables with null
patient_id. (#1193) SampleDatasetsubset mappings were wrong. (#1211)PatientLinkageMIMIC3Task'sinput_schemanamed"integer"/"string"/"datetime"processors, none of which are registered, soset_task()failed immediately withValueError: Unknown processor. (#1204)
Metrics, calibration, and interpretability
ece_confidence_binaryindexedprob[:, 0]/label[:, 0], requiring 2-D arrays, but its only caller passes 1-D positive-class probabilities and 1-D 0/1 labels — soECEandECE_adaptalways raisedIndexErroron binary tasks. (#1215)disparate_impactandstatistical_parity_differencereturnednanfor empty subgroups instead of raising: the rate was a numpy 0/0, and sincenan == 0is alwaysFalsethe existing zero guard never caught it (and only ever checked the unprotected group). (#1199)fairness_metrics_fnwas commented out ofpyhealth.metrics; re-enabled and added to__all__. (#1200)- Removal-based interpretability metrics aliased
original_class_probstoy_probsand negated negative-class entries in place, flipping the sign on every iteration of the percentage loop — a sample's score depended on where its percentage sat in the list. (#1196) - Interpretability
target_class_idxhandling, argument naming, and sample-class filtering. (#926) - SCRIB: the overall-risk loss squared the chance-ambiguity term, contradicting Eq. 2
and Algorithm 2 of the paper and the already-correct class-specific loss in the same
file; fixed in both the Python and Cython paths, along with a
fill_maxinference gap. (#1190) - Covariate-shift conformal prediction fixes. (#1180)
Examples and docs
- Removed the deprecated
code_mapping,dev, andrefresh_cachearguments fromREADME.rst, example scripts, and leaderboard utilities — the 2.0MIMIC3Dataset/MIMIC4Datasetno longer accept them. (#935, fixes #535) - Fixed a
SyntaxErrorinexamples/benchmark_perf/loc/minimal_los.py, a missing__main__guard that hungreadmission_mimic3_fairness.pyunder multiprocessing, and a staleTransformer(...)call. (#1200) - Reinitialized the documentation tutorials lost in the UIUC purge and re-linked the Colab notebooks. (#1143, #1146)
- Added missing paper citations throughout the codebase. (#1181)
- CI gate enforcing the PR contribution rules for changes under
pyhealth/(tools/check_pr_rules.py). (#1176) - Unit tests for
RNNandMultimodalRNN. (#936) - Fixed a pixi warning and the version format for the build backend. (#917)
tools/bump_version.pynow keepspyhealth.__version__in sync withpyproject.toml, rewrites only the[project]version line, and no longer hangs when bumping from a non-pre-release version.
Full Changelog: https://github.com/sunlabuiuc/PyHealth/compare/v2.0.1...v2.0.2