From a6f87fc75f68fdd2bf73bfdeccc0bfd3a20936d3 Mon Sep 17 00:00:00 2001 From: mysteryyoi Date: Wed, 2 Dec 2026 22:31:56 +0530 Subject: [PATCH 1/2] Opt in to litdata pickle reads for PyHealth's own caches litdata 0.2.77 (Lightning-AI/litData#979) unpickles values only when the reader passes allow_pickle=True, so reading records with a pickled field (the StageNet LIME tests) fails. Pass it wherever PyHealth opens its own caches, when the installed litdata has the option; older litdata is unchanged. --- pyhealth/datasets/base_dataset.py | 8 +++- pyhealth/datasets/sample_dataset.py | 18 +++++++- tests/core/test_sample_dataset.py | 68 ++++++++++++++++++++++++++++- 3 files changed, 90 insertions(+), 4 deletions(-) diff --git a/pyhealth/datasets/base_dataset.py b/pyhealth/datasets/base_dataset.py index ba0648245f..d9efdb2d19 100644 --- a/pyhealth/datasets/base_dataset.py +++ b/pyhealth/datasets/base_dataset.py @@ -50,6 +50,7 @@ STORAGE_FORMAT, SampleBuilder, SampleDataset, + _LITDATA_READER_KWARGS, _litdata_add, _litdata_merge, ) @@ -458,7 +459,7 @@ def _proc_transform_fn(args: tuple[int, Path, int, int, Path]) -> None: ): writer = BinaryWriter(cache_dir=str(output_dir), chunk_bytes="64MB") - dataset = litdata.StreamingDataset(str(task_df)) + dataset = litdata.StreamingDataset(str(task_df), **_LITDATA_READER_KWARGS) builder = SampleBuilder.load(f"{output_dir}/schema.pkl") complete = 0 @@ -1305,7 +1306,9 @@ def _proc_transform( self._main_guard(self._proc_transform.__name__) logger.info(f"Applying processors on data with {num_workers} workers...") - num_samples = len(litdata.StreamingDataset(str(task_df))) + num_samples = len( + litdata.StreamingDataset(str(task_df), **_LITDATA_READER_KWARGS) + ) if in_notebook(): logger.info( @@ -1508,6 +1511,7 @@ def _is_valid_litdata_cache(path: Path) -> bool: dataset = litdata.StreamingDataset( str(task_df_path), transform=lambda x: pickle.loads(x["sample"]), + **_LITDATA_READER_KWARGS, ) builder = SampleBuilder( input_schema=task.input_schema, # type: ignore diff --git a/pyhealth/datasets/sample_dataset.py b/pyhealth/datasets/sample_dataset.py index 11163f0ede..208a22c879 100644 --- a/pyhealth/datasets/sample_dataset.py +++ b/pyhealth/datasets/sample_dataset.py @@ -34,6 +34,19 @@ # Record key holding one pickled payload with every non-tensor field. _OBJECTS_KEY = "_pyhealth_objects" _PICKLE_PROTOCOL = 5 +# Keyword arguments for every litdata reader PyHealth opens on its own caches. +# litdata pickles values it has no serializer for (such as a ``None`` in a +# record written from ``SampleBuilder.transform``), and from 0.2.77 a reader +# unpickles them only with ``allow_pickle=True`` (Lightning-AI/litData#979). +# Reading these caches already unpickles ``schema.pkl`` and each record's +# objects payload, so opting in trusts nothing new. Older litdata has no +# such option and always unpickles. +_LITDATA_READER_KWARGS: dict[str, Any] = ( + {"allow_pickle": True} + if "allow_pickle" + in inspect.signature(litdata.StreamingDataset.__init__).parameters + else {} +) def _decode_record(item: Any) -> Any: @@ -534,8 +547,11 @@ def __init__( reserved for temporary datasets owned by PyHealth. **kwargs: Extra keyword arguments forwarded to `litdata.StreamingDataset` (such as streaming options). + ``allow_pickle`` defaults to True on litdata versions that + have it (0.2.77 and later), since ``path`` is a PyHealth + cache whose ``schema.pkl`` is unpickled anyway. """ - super().__init__(path, **kwargs) + super().__init__(path, **{**_LITDATA_READER_KWARGS, **kwargs}) self.path = path self.dataset_name = "" if dataset_name is None else dataset_name diff --git a/tests/core/test_sample_dataset.py b/tests/core/test_sample_dataset.py index 459d017ec1..734343dd15 100644 --- a/tests/core/test_sample_dataset.py +++ b/tests/core/test_sample_dataset.py @@ -1,9 +1,20 @@ +import json +import pickle +import shutil +import tempfile import unittest from pathlib import Path +import torch +from litdata.streaming.writer import BinaryWriter from torch.utils.data import IterableDataset -from pyhealth.datasets.sample_dataset import SampleDataset, create_sample_dataset +from pyhealth.datasets.sample_dataset import ( + SampleBuilder, + SampleDataset, + _litdata_merge, + create_sample_dataset, +) from pyhealth.datasets.utils import get_dataloader @@ -237,5 +248,60 @@ def test_persistent_workers_with_shuffle_is_rejected(self): dataset.close() +class TestSampleDatasetReadsLitdataPickledValues(unittest.TestCase): + """Values that litdata pickles on write must read back. + + Records written from ``SampleBuilder.transform`` output (the layout before + ``STORAGE_FORMAT`` 2, still written by several tests) keep each value as + its own litdata field, and litdata pickles the ones it has no serializer + for, such as the ``None`` time of a ``stagenet_tensor`` field. From + litdata 0.2.77 a reader unpickles them only when opened with + ``allow_pickle=True``. + """ + + def setUp(self): + self.samples = [ + {"patient_id": "p0", "labs": (None, [[1.0, 2.5], [4.1, 5.5]]), "label": 1}, + {"patient_id": "p1", "labs": (None, [[1.4, 3.2]]), "label": 0}, + ] + builder = SampleBuilder({"labs": "stagenet_tensor"}, {"label": "binary"}) + builder.fit(self.samples) + self.expected = [ + builder.transform({"sample": pickle.dumps(s)}) for s in self.samples + ] + self.path = tempfile.mkdtemp() + # On Windows the reader's memory map keeps the chunk file open. + self.addCleanup(shutil.rmtree, self.path, ignore_errors=True) + builder.save(f"{self.path}/schema.pkl") + writer = BinaryWriter(cache_dir=self.path, chunk_bytes="64MB") + for i, record in enumerate(self.expected): + writer.add_item(i, record) + writer.done() + _litdata_merge(Path(self.path)) + + def assertSameSample(self, got, expected): + self.assertEqual(got["patient_id"], expected["patient_id"]) + self.assertIsNone(got["labs"][0]) + self.assertTrue(torch.equal(got["labs"][1], expected["labs"][1])) + self.assertTrue(torch.equal(got["label"], expected["label"])) + + def test_pickled_values_read_back(self): + with open(f"{self.path}/index.json") as f: + data_format = json.load(f)["config"]["data_format"] + self.assertIn("pickle", data_format) # else this test checks nothing + + dataset = SampleDataset(path=self.path) + for i, expected in enumerate(self.expected): + with self.subTest(read="index", i=i): + self.assertSameSample(dataset[i], expected) + with self.subTest(read="iteration"): + got = list(dataset) + self.assertEqual(len(got), len(self.expected)) + for sample, expected in zip(got, self.expected): + self.assertSameSample(sample, expected) + with self.subTest(read="subset"): + self.assertSameSample(dataset.subset([1])[0], self.expected[1]) + + if __name__ == "__main__": unittest.main() From 8e5256bc2f0d52431d6a589abc53b80aca6c9385 Mon Sep 17 00:00:00 2001 From: mysteryyoi Date: Wed, 2 Dec 2026 23:55:21 +0530 Subject: [PATCH 2/2] Lift the litdata<0.2.77 cap PyHealth's readers now pass allow_pickle=True on litdata 0.2.77 and later, so the cap added in #1796 is no longer needed and CI can test against the newest litdata again. --- pyproject.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 63306e97a4..a78d223296 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,9 +43,9 @@ dependencies = [ "dask[complete]>=2026.1.0", # >=0.2.64: worker indexes merge in numeric rank order (patient_to_index relies # on it). >=0.2.71: map-style readers use mmap, so forked workers do not share - # a chunk handle. <0.2.77: 0.2.77 disables PickleSerializer deserialization by - # default, breaking SampleDataset chunks with pickle-inferred fields. - "litdata>=0.2.71,<0.2.77", + # a chunk handle. From 0.2.77 a reader unpickles fields only when opened with + # allow_pickle=True, which PyHealth's readers pass (_LITDATA_READER_KWARGS). + "litdata>=0.2.71", "pyarrow>=23.0.1", "orjson~=3.10", "narwhals>=2.13,<3",