Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions pyhealth/datasets/base_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
STORAGE_FORMAT,
SampleBuilder,
SampleDataset,
_LITDATA_READER_KWARGS,
_litdata_add,
_litdata_merge,
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down
18 changes: 17 additions & 1 deletion pyhealth/datasets/sample_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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})

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] Caller override of allow_pickle is untested

The description promises that a caller-passed allow_pickle wins over the default, implemented here by the dict merge {**_LITDATA_READER_KWARGS, **kwargs}. No test covers this branch. Add a small test in tests/core/test_sample_dataset.py that passes allow_pickle explicitly and checks the value reaches litdata, for example by asserting on the reader's attribute or by expecting the pickled-read failure when allow_pickle=False on 0.2.77+. This is non-blocking because the default path is covered by the new test.


self.path = path
self.dataset_name = "" if dataset_name is None else dataset_name
Expand Down
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
68 changes: 67 additions & 1 deletion tests/core/test_sample_dataset.py
Original file line number Diff line number Diff line change
@@ -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


Expand Down Expand Up @@ -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()
Loading