Skip to content
Draft
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
54 changes: 43 additions & 11 deletions pyhealth/datasets/base_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,7 @@ def __init__(
cache_dir: str | Path | None = None,
num_workers: int = 1,
dev: bool = False,
use_dask_distributed: bool = True,
):
"""Initializes the BaseDataset.

Expand All @@ -533,6 +534,10 @@ def __init__(
is appended to the provided path to capture dataset configuration.
num_workers (int): Number of worker processes for parallel operations.
dev (bool): Whether to run in dev mode (limits to 1000 patients).
use_dask_distributed (bool): Whether event caching uses the Dask
distributed cluster. ``False`` writes the cache with the local
Dask scheduler instead, for sandboxes where the cluster cannot
start. Defaults to ``True``. It does not affect the cache key.
"""
if len(set(tables)) != len(tables):
logger.warning("Duplicate table names in tables list. Removing duplicates.")
Expand All @@ -542,6 +547,7 @@ def __init__(
self.dataset_name = dataset_name or self.__class__.__name__
self.num_workers = num_workers
self.dev = dev
self.use_dask_distributed = use_dask_distributed
self.config = load_yaml_config(config_path) if config_path else None

logger.info(
Expand Down Expand Up @@ -861,17 +867,43 @@ def _event_transform(self, output_dir: Path) -> None:
compute_ok = False
try:
df = self.load_data()
with DaskCluster(
n_workers=self.num_workers,
threads_per_worker=1,
processes=not in_notebook(),
# Use cache_dir for Dask's scratch space to avoid filling up /tmp or home directory
local_directory=str(self.create_tmpdir()),
# No dashboard: its bokeh server fails to stop on cluster close and
# leaks sockets, hitting "Too many open files" after repeated builds.
dashboard_address=None,
) as cluster:
with DaskClient(cluster) as client:
if not self.use_dask_distributed:
logger.info(
"use_dask_distributed=False; caching "
"with the local Dask scheduler."
)
if self.dev:
logger.info("Dev mode enabled: limiting to 1000 patients")
# head() reads only the first partition unless told
# otherwise, which gave far fewer than 1000 patients.
unique = df["patient_id"].unique()
patients = unique.head(1000, npartitions=-1).tolist()
patient_filter = df["patient_id"].isin(patients)
df = df[patient_filter]
logger.info(f"Caching event dataframe to {output_dir}...")
df.sort_values("patient_id").to_parquet(
output_dir,
write_index=False,
compute=True,
**_event_parquet_options(df.dtypes),
)
compute_ok = True
else:
with (
DaskCluster(
n_workers=self.num_workers,
threads_per_worker=1,
processes=not in_notebook(),
# Use cache_dir for Dask's scratch space to avoid
# filling up /tmp or home directory
local_directory=str(self.create_tmpdir()),
# No dashboard: its bokeh server fails to stop on
# cluster close and leaks sockets, hitting "Too many
# open files" after repeated builds.
dashboard_address=None,
) as cluster,
DaskClient(cluster) as client,
):
if self.dev:
logger.info("Dev mode enabled: limiting to 1000 patients")
# head() reads only the first partition unless told
Expand Down
52 changes: 49 additions & 3 deletions pyhealth/datasets/collate.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,51 @@
from typing import Any

import torch
from torch.nn.utils.rnn import pad_sequence
import torch.nn.functional as F


def _pad_stack(tensors: list[torch.Tensor]) -> torch.Tensor:
"""Right-pad same-rank tensors to the per-dimension max, then stack.

``pad_sequence`` only pads dimension 0 and requires every trailing dimension
to already match. Tokenized notes are ``(n_notes, seq_len)`` and, once the
text processor pads to the longest note in a sample rather than to a fixed
``max_length``, BOTH dimensions vary across samples.
"""
if len({t.dim() for t in tensors}) != 1:
raise ValueError("cannot pad tensors of differing rank")
target = [max(t.shape[d] for t in tensors) for d in range(tensors[0].dim())]
padded = []
for t in tensors:
spec: list[int] = []
for d in range(t.dim() - 1, -1, -1):
spec.extend([0, target[d] - t.shape[d]])
padded.append(F.pad(t, spec) if any(spec) else t)
return torch.stack(padded)


def _stack_or_pad(tensors: list[torch.Tensor]) -> torch.Tensor:
"""Stack if all shapes match; pad along dim-0 otherwise."""
"""Stack if all shapes match; pad every ragged dimension otherwise."""
if all(t.shape == tensors[0].shape for t in tensors):
return torch.stack(tensors)
return pad_sequence(tensors, batch_first=True)
return _pad_stack(tensors)


def _pad_mask(tensors: list[torch.Tensor]) -> torch.Tensor:
"""Event-level validity for the tensor :func:`_stack_or_pad` just built.

Batch padding is created here and nowhere else, so it has to be recorded
here. A padded slot carries value 0.0 and time 0.0, which is
indistinguishable from a real measurement taken at admission time, so a
model given no mask treats padding as data.

This is deliberately NOT called ``mask``. A field may carry its own
``{field}_mask`` meaning "was this value observed", which is a different
question from "is this slot real".
"""
lengths = torch.tensor([t.shape[0] for t in tensors])
width = int(lengths.max())
return torch.arange(width)[None, :] < lengths[:, None]


def collate_temporal(batch: list[dict[str, Any]]) -> dict[str, Any]:
Expand All @@ -43,6 +80,13 @@ def collate_temporal(batch: list[dict[str, Any]]) -> dict[str, Any]:

Returns:
A single collated dict ready for model ``forward(**batch)``.

Example:
>>> import torch
>>> batch = [{"x": {"value": torch.ones(2, 2), "time": torch.zeros(2)}}]
>>> out = collate_temporal(batch)
>>> out["x"]["pad_mask"].tolist()
[[True, True]]
"""
if not batch:
return {}
Expand All @@ -62,6 +106,8 @@ def collate_temporal(batch: list[dict[str, Any]]) -> dict[str, Any]:
sub_result[sub_key] = [None] * len(sub_vals)
elif isinstance(sub_vals[0], torch.Tensor):
sub_result[sub_key] = _stack_or_pad(sub_vals)
if sub_key == "time":
sub_result["pad_mask"] = _pad_mask(sub_vals)
else:
sub_result[sub_key] = sub_vals
result[key] = sub_result
Expand Down
9 changes: 9 additions & 0 deletions pyhealth/datasets/mimic4.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,9 @@ class MIMIC4Dataset(BaseDataset):
ed_config_path: Path to the ED config file
dataset_name: Name of the dataset
dev: Whether to enable dev mode (limit to 1000 patients)
use_dask_distributed: Whether event caching uses the Dask
distributed cluster. ``False`` takes the local-scheduler path.
It does not affect the cache key.

Examples:
>>> from pyhealth.datasets import MIMIC4Dataset
Expand Down Expand Up @@ -422,6 +425,7 @@ def __init__(
ed_root: str | None = None,
ed_tables: list[str] | None = None,
ed_config_path: str | None = None,
use_dask_distributed: bool = True,
):
log_memory_usage("Starting MIMIC4Dataset init")

Expand Down Expand Up @@ -451,6 +455,7 @@ def __init__(
dev=dev,
cache_dir=cache_dir,
num_workers=num_workers,
use_dask_distributed=use_dask_distributed,
)

# Initialize child datasets
Expand All @@ -468,6 +473,7 @@ def __init__(
cache_dir=str(self.cache_dir),
dev=dev,
num_workers=num_workers,
use_dask_distributed=use_dask_distributed,
)
log_memory_usage("After EHR dataset initialization")

Expand All @@ -483,6 +489,7 @@ def __init__(
cache_dir=str(self.cache_dir),
dev=dev,
num_workers=num_workers,
use_dask_distributed=use_dask_distributed,
)
log_memory_usage("After Note dataset initialization")

Expand All @@ -498,6 +505,7 @@ def __init__(
cache_dir=str(self.cache_dir),
dev=dev,
num_workers=num_workers,
use_dask_distributed=use_dask_distributed,
)
log_memory_usage("After CXR dataset initialization")

Expand All @@ -512,6 +520,7 @@ def __init__(
cache_dir=str(self.cache_dir),
dev=dev,
num_workers=num_workers,
use_dask_distributed=use_dask_distributed,
)
log_memory_usage("After ED dataset initialization")

Expand Down
89 changes: 53 additions & 36 deletions pyhealth/datasets/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
import litdata
import torch
from dateutil.parser import parse as dateutil_parse
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader

from pyhealth import BASE_CACHE_PATH
from pyhealth.utils import create_directory
from pyhealth.datasets.collate import _pad_stack

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Dataset collation imports private _pad_stack from collate.py without a description of the link

datasets/utils.py now imports the underscore-prefixed _pad_stack from datasets/collate.py, replacing pad_sequence. The description calls collate.py the shared collator but does not mention this import or why the helper is shared. Either confirm the sharing and explain it in the description, or make the helper public or keep a local copy. Both are reasonable; the description should say which.


MODULE_CACHE_PATH = os.path.join(BASE_CACHE_PATH, "datasets")
create_directory(MODULE_CACHE_PATH)
Expand Down Expand Up @@ -240,6 +240,9 @@ def _restore_from_cache(sample: Dict[str, Any]) -> Dict[str, Any]:
return restored


PAD_MASK_SUFFIX = "__pad_mask"


def collate_fn_dict(batch: List[dict]) -> dict:
"""Collates a batch of data into a dictionary of lists.

Expand Down Expand Up @@ -286,39 +289,55 @@ def collate_fn_dict_with_padding(

if collators is not None and key in collators:
collated[key] = collators[key](values)
# Check if this is a temporal feature tuple (time, values)
elif isinstance(values[0], tuple) and len(values[0]) == 2:
# Handle (time, values) tuples from processors
time_tensors = [v[0] for v in values]
value_tensors = [v[1] for v in values]

# Collate values
if value_tensors[0].dim() == 0:
# Scalars
collated_values = torch.stack(value_tensors)
elif all(v.shape == value_tensors[0].shape for v in value_tensors):
# All same shape
collated_values = torch.stack(value_tensors)
else:
# Variable shapes, use pad_sequence
collated_values = pad_sequence(
value_tensors, batch_first=True, padding_value=0
)

# Collate times (if present)
collated_times = None
# Check if ALL samples have time (not just some)
if all(t is not None for t in time_tensors):
time_tensors_all = [t for t in time_tensors if t is not None]
if all(t.shape == time_tensors_all[0].shape for t in time_tensors_all):
collated_times = torch.stack(time_tensors_all)
# Check if this is a temporal feature pair such as (time, values).
# Its two positions collate independently. Tuples of any other
# length stay a list of per-sample tuples, unless their processor
# defines collate() (TupleTimeTextProcessor does, to stack text).
elif isinstance(values[0], tuple) and all(
isinstance(v, tuple) and len(v) == 2 for v in values
):
arity = len(values[0])
stacked = []
for pos in range(arity):
elems = [v[pos] for v in values]
if all(e is None for e in elems):
stacked.append(None)
elif all(e is None or isinstance(e, torch.Tensor) for e in elems):
if any(e is None for e in elems):
# Partial time info is dropped, as before
stacked.append(None)
elif elems[0].dim() == 0:
# Scalars
stacked.append(torch.stack(elems))
else:
# Same shape stacks; ragged pads every dimension
stacked.append(_pad_stack(elems))
else:
collated_times = pad_sequence(
time_tensors_all, batch_first=True, padding_value=0
)

# Return as tuple (time, values)
collated[key] = (collated_times, collated_values)
# Non-tensor positions (e.g. the text type tag) stay lists
stacked.append(elems)

# Return as a tuple in the processor's schema order
collated[key] = tuple(stacked)
# Event-level validity from the first non-scalar tensor
# position: every tensor position shares dim 0 (the event
# count). For (time, values) pairs this matches the old
# values-based lengths exactly.
event_lengths = None
for pos in range(arity):
elems = [v[pos] for v in values]
if (
all(isinstance(e, torch.Tensor) for e in elems)
and elems[0].dim() > 0
):
if not all(e.shape == elems[0].shape for e in elems):
event_lengths = [e.shape[0] for e in elems]
break
if event_lengths is not None:
lengths = torch.tensor(event_lengths)
width = int(lengths.max())
collated[f"{key}{PAD_MASK_SUFFIX}"] = (
torch.arange(width)[None, :] < lengths[:, None]
)
# PyG Data objects (graph processor output)
elif HAS_PYG and isinstance(values[0], PyGData):
collated[key] = PyGBatch.from_data_list(values)
Expand All @@ -335,9 +354,7 @@ def collate_fn_dict_with_padding(
# Scalars, treat as stackable
collated[key] = torch.stack(values)
elif values[0].dim() >= 1:
collated[key] = pad_sequence(
values, batch_first=True, padding_value=0
)
collated[key] = _pad_stack(values)
else:
raise ValueError(f"Unsupported tensor shape: {values[0].shape}")
else:
Expand Down
Loading
Loading