diff --git a/pyhealth/datasets/base_dataset.py b/pyhealth/datasets/base_dataset.py index ba0648245f..b55373b32c 100644 --- a/pyhealth/datasets/base_dataset.py +++ b/pyhealth/datasets/base_dataset.py @@ -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. @@ -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.") @@ -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( @@ -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 diff --git a/pyhealth/datasets/collate.py b/pyhealth/datasets/collate.py index 9e4c113c06..eb178c61e7 100644 --- a/pyhealth/datasets/collate.py +++ b/pyhealth/datasets/collate.py @@ -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]: @@ -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 {} @@ -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 diff --git a/pyhealth/datasets/mimic4.py b/pyhealth/datasets/mimic4.py index e06aee4ec1..afcba95298 100644 --- a/pyhealth/datasets/mimic4.py +++ b/pyhealth/datasets/mimic4.py @@ -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 @@ -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") @@ -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 @@ -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") @@ -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") @@ -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") @@ -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") diff --git a/pyhealth/datasets/utils.py b/pyhealth/datasets/utils.py index e0e596d7be..607d87e386 100644 --- a/pyhealth/datasets/utils.py +++ b/pyhealth/datasets/utils.py @@ -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 MODULE_CACHE_PATH = os.path.join(BASE_CACHE_PATH, "datasets") create_directory(MODULE_CACHE_PATH) @@ -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. @@ -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) @@ -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: diff --git a/pyhealth/models/transformer.py b/pyhealth/models/transformer.py index 9b483375eb..5336061f9f 100644 --- a/pyhealth/models/transformer.py +++ b/pyhealth/models/transformer.py @@ -7,6 +7,7 @@ from typing import Any, Dict, Optional, Tuple, Union, cast import torch +import torch.nn.functional as F from torch import nn from pyhealth.datasets import SampleDataset @@ -18,7 +19,19 @@ class Attention(nn.Module): - """Scaled dot-product attention helper.""" + """Scaled dot-product attention helper. + + Example: + Called inside :class:`MultiHeadedAttention` for each head. + + >>> import torch + >>> from pyhealth.models.transformer import Attention + >>> attn = Attention() + >>> q = k = torch.zeros(1, 1, 2, 4) + >>> out, weights = attn(q, k, torch.ones(1, 1, 2, 4)) + >>> out.shape + torch.Size([1, 1, 2, 4]) + """ def __init__(self): super().__init__() @@ -51,11 +64,13 @@ def forward( scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(query.size(-1)) if mask is not None: - # Use -inf so softmax produces exact zeros on padded positions, - # avoiding a second masked_fill after softmax (saves one full - # [B, H, S, S] boolean allocation and an extra copy). - pad_mask = (mask == 0) - scores = scores.masked_fill(pad_mask, -1e9) + # Fill with the dtype minimum (not -1e9, which is outside the + # fp16 range and overflows under AMP) so softmax produces exact + # zeros on padded positions, avoiding a second masked_fill + # after softmax (saves one full [B, H, S, S] boolean allocation + # and an extra copy). + pad_mask = mask == 0 + scores = scores.masked_fill(pad_mask, torch.finfo(scores.dtype).min) p_attn = self.softmax(scores) if dropout is not None: p_attn = dropout(p_attn) @@ -64,7 +79,15 @@ def forward( class MultiHeadedAttention(nn.Module): - """Multi-head attention wrapper used by the Transformer block.""" + """Multi-head attention wrapper used by the Transformer block. + + Example: + >>> import torch + >>> from pyhealth.models.transformer import MultiHeadedAttention + >>> mha = MultiHeadedAttention(h=2, d_model=8) + >>> mha(torch.zeros(2, 5, 8), torch.zeros(2, 5, 8), torch.zeros(2, 5, 8)).shape + torch.Size([2, 5, 8]) + """ def __init__(self, h: int, d_model: int, dropout: float = 0.1): """Initialize the attention module. @@ -149,19 +172,45 @@ def forward( ] # 2) Apply attention on all the projected vectors in batch. - if mask is not None: - mask = mask.unsqueeze(1) - x, attn = self.attention(query, key, value, mask=mask, dropout=self.dropout) - - if register_hook: - # Only store attn_map and hook during interpretability passes. - # Using .detach() gives an independent copy whose storage - # is NOT shared with the live graph, so the graph can be freed - # normally after .backward() without leaking GPU memory. + # Ordinary training uses fused SDPA. The explicit path stays behind + # register_hook=True for interpretability. + if not register_hook: + query_mask = None + attn_mask = None + if mask is not None: + valid = mask.bool() + if mask.dim() == 2: + query_mask = valid[:, None, :, None] + attn_mask = valid[:, None, None, :] + else: + query_mask = valid.any(dim=-1)[:, None, :, None] + attn_mask = valid.unsqueeze(1) + # A fully-masked query row attends to nothing, which is NaN + # or garbage depending on backend and dtype. Let such rows + # attend uniformly, then zero their outputs below. + attn_mask = attn_mask | ~attn_mask.any(dim=-1, keepdim=True) + x = F.scaled_dot_product_attention( + query, + key, + value, + attn_mask=attn_mask, + dropout_p=self.dropout.p if self.training else 0.0, + ) + if query_mask is not None: + x = x * query_mask.to(x.dtype) + self.attn_map = None + self.attn_gradients = None + else: + if mask is not None: + mask = mask.unsqueeze(1) + x, attn = self.attention( + query, key, value, mask=mask, dropout=self.dropout + ) + # .detach() gives a copy whose storage is NOT shared with the + # live graph, so the graph can be freed normally after + # .backward() without leaking GPU memory. self.attn_map = attn.detach() attn.register_hook(self.save_attn_grad) - else: - self.attn_map = None # 3) "Concat" using a view and apply a final linear. x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.h * self.d_k) diff --git a/pyhealth/processors/stagenet_processor.py b/pyhealth/processors/stagenet_processor.py index bd61822e74..90e5488981 100644 --- a/pyhealth/processors/stagenet_processor.py +++ b/pyhealth/processors/stagenet_processor.py @@ -69,7 +69,9 @@ def fit(self, samples: Iterable[Dict[str, Any]], field: str) -> None: samples: List of sample dictionaries key: The key in samples that contains tuple (time, values) """ - # Examine first non-None sample to determine structure + # Scan for the first sample that determines the structure. Empty + # samples (e.g. a stay with no codes) carry no structural + # information, so they are skipped, not stopping the scan. for sample in samples: if field in sample and sample[field] is not None: # Unpack tuple: (time, values) @@ -82,11 +84,12 @@ def fit(self, samples: Iterable[Dict[str, Any]], field: str) -> None: if isinstance(first_elem, str): # Case 1: ["code1", "code2", ...] self._is_nested = False + break elif isinstance(first_elem, list): if len(first_elem) > 0 and isinstance(first_elem[0], str): # Case 2: [["A", "B"], ["C"], ...] self._is_nested = True - break + break # Build vocabulary for codes and find max nested length max_inner_len = 0 @@ -181,9 +184,9 @@ def process( def _encode_codes(self, codes: List[str]) -> torch.Tensor: """Encode flat code list to indices.""" - # Handle empty code list - return single padding token + # Handle empty code list — zero events, not a fake pad token. if len(codes) == 0: - return torch.tensor([self.code_vocab[""]], dtype=torch.long) + return torch.zeros((0,), dtype=torch.long) indices = [] for code in codes: @@ -200,11 +203,10 @@ def _encode_nested_codes(self, nested_codes: List[List[str]]) -> torch.Tensor: """ assert self._max_nested_len is not None, "Max nested length must be set during fit()" - # Handle empty nested codes (no visits/events) - # Return single padding token with shape (1, max_len) + # Handle empty nested codes (no visits/events) — zero events. if len(nested_codes) == 0: - pad_token = self.code_vocab[""] - return torch.tensor([[pad_token] * self._max_nested_len], dtype=torch.long) + max_len = self._max_nested_len if self._max_nested_len is not None else 1 + return torch.zeros((0, max_len), dtype=torch.long) encoded_sequences = [] # Use global max length determined during fit @@ -328,8 +330,13 @@ class StageNetTensorProcessor(TemporalFeatureProcessor): - List of lists of numbers -> nested numeric sequences (feature vectors) Imputation Strategy: - - Forward-fill: Missing values (NaN/None) are filled with the last observed - value for that feature dimension. If no prior value exists, 0.0 is used. + - Forward-fill (default, ``forward_fill=True``): Missing values (NaN/None) + are filled with the last observed value for that feature dimension. + If no prior value exists, 0.0 is used. + - No fill (``forward_fill=False``): Missing values are set to 0.0 in + place and never propagate earlier rows. Use this for observation-mask + fields, where forward-filling a 0/1 mask would turn later missing + values into observed ones. - Applied per feature dimension independently Returns: @@ -348,9 +355,10 @@ class StageNetTensorProcessor(TemporalFeatureProcessor): >>> time.shape # (3,) """ - def __init__(self): + def __init__(self, forward_fill: bool = True): self._size = None # Feature dimension (set during fit) self._is_nested = None + self.forward_fill = forward_fill def fit(self, samples: Iterable[Dict[str, Any]], field: str) -> None: """Determine input structure. @@ -359,7 +367,9 @@ def fit(self, samples: Iterable[Dict[str, Any]], field: str) -> None: samples: List of sample dictionaries key: The key in samples that contains tuple (time, values) """ - # Examine first non-None sample to determine structure + # Scan for the first sample that determines the structure. Empty + # samples (e.g. a stay with no lab events) carry no structural + # information, so they are skipped, not stopping the scan. for sample in samples: if field in sample and sample[field] is not None: # Unpack tuple: (time, values) @@ -373,20 +383,23 @@ def fit(self, samples: Iterable[Dict[str, Any]], field: str) -> None: # Flat numeric: [1.5, 2.0, ...] self._is_nested = False self._size = 1 + break elif isinstance(first_elem, list): if len(first_elem) > 0: if isinstance(first_elem[0], (int, float)): # Nested numerics: [[1.0, 2.0], [3.0, 4.0]] self._is_nested = True self._size = len(first_elem) - break + break def process( self, value: Tuple[Optional[List], List] ) -> Tuple[Optional[torch.Tensor], torch.Tensor]: """Process tuple format numeric data into tensors. - Applies forward-fill imputation to handle NaN/None values. + Applies forward-fill imputation to handle NaN/None values, unless + the processor was built with ``forward_fill=False`` (observation + masks), in which case missing values become 0.0 in place. For each feature dimension, missing values are filled with the last observed value (or 0.0 if no prior value exists). @@ -398,14 +411,32 @@ def process( """ # Unpack tuple: (time, values) time_data, value_data = value + value_data = list(value_data or []) - # Convert to numpy for easier imputation handling import numpy as np + if len(value_data) == 0: + n_feat = self._size if self._size is not None else 1 + nested = True if self._is_nested is None else self._is_nested + if nested: + value_tensor = torch.zeros((0, n_feat), dtype=torch.float) + else: + value_tensor = torch.zeros((0,), dtype=torch.float) + time_tensor = ( + torch.zeros((0,), dtype=torch.float) if time_data is not None else None + ) + return time_tensor, value_tensor + + # Convert to numpy for easier imputation handling value_array = np.array(value_data, dtype=float) + # Observation-mask fields must preserve false after a true observation; + # forward-filling a 0/1 mask would turn later missing labs into observed + # values. Ordinary numeric time-series retain the historical behaviour. + if not self.forward_fill: + value_array = np.nan_to_num(value_array, nan=0.0, posinf=0.0, neginf=0.0) # Apply forward-fill imputation - if value_array.ndim == 1: + elif value_array.ndim == 1: # Flat numeric: [1.5, 2.0, nan, 3.0, ...] last_value = 0.0 for i in range(len(value_array)): diff --git a/pyhealth/processors/time_image_processor.py b/pyhealth/processors/time_image_processor.py index 9d313e6bc5..451e996f72 100644 --- a/pyhealth/processors/time_image_processor.py +++ b/pyhealth/processors/time_image_processor.py @@ -75,6 +75,11 @@ class TimeImageProcessor(TemporalFeatureProcessor): patient has more images, the most recent (by timestamp) are kept. If None, all images are kept. Defaults to None. + padding: Sentinel string that marks a missing image. When + a path equals this value, a zero tensor of shape + (C, H, W) is returned instead of loading from disk. + If None, all paths are treated as real file paths. + Defaults to None. Raises: ValueError: If normalize is True but mean or std is missing. @@ -107,6 +112,7 @@ def __init__( std: Optional[List[float]] = None, mode: Optional[str] = None, max_images: Optional[int] = None, + padding: str | None = None, ) -> None: self.image_size = image_size self.to_tensor = to_tensor @@ -115,6 +121,7 @@ def __init__( self.std = std self.mode = mode self.max_images = max_images + self.padding = padding self.n_channels = None if self.normalize and ( @@ -166,16 +173,41 @@ def _build_transform(self) -> transforms.Compose: ) return transforms.Compose(transform_list) + def _zero_image_tensor(self) -> torch.Tensor: + """Return a zero tensor matching the expected image shape (C, H, W). + + Used as a placeholder when an image path is an empty string. + Channel count is inferred from self.n_channels if available, + otherwise derived from self.mode ("L"->1, "RGBA"->4, else 3). + + Returns: + Zero tensor of shape (C, image_size, image_size). + """ + if self.n_channels is not None: + c = self.n_channels + elif self.mode == "L": + c = 1 + elif self.mode == "RGBA": + c = 4 + else: + c = 3 + return torch.zeros(c, self.image_size, self.image_size) + def _load_single_image( self, path: Union[str, Path] ) -> torch.Tensor: """Load and transform a single image from disk. + If path equals the padding sentinel, returns a zero tensor of + the same shape as a normal image (C, H, W) via _zero_image_tensor. + Called internally by process() for each image path in the input list. Args: - path: Path to the image file. + path: Path to the image file. If this equals the padding + sentinel, a zero-filled placeholder tensor is returned + instead. Returns: Transformed image tensor of shape (C, H, W). @@ -183,6 +215,8 @@ def _load_single_image( Raises: FileNotFoundError: If the image file does not exist. """ + if self.padding is not None and str(path) == self.padding: + return self._zero_image_tensor() image_path = Path(path) if not image_path.exists(): raise FileNotFoundError( @@ -214,8 +248,10 @@ def fit( for sample in samples: if field in sample and sample[field] is not None: image_paths, _ = sample[field] - if len(image_paths) > 0: - path = Path(image_paths[0]) + for raw_path in image_paths: + if self.padding is not None and str(raw_path) == self.padding: + continue + path = Path(raw_path) if path.exists(): with Image.open(path) as img: if img.mode == "L": @@ -225,6 +261,8 @@ def fit( else: self.n_channels = 3 break + if self.n_channels is not None: + break if self.n_channels is None: self.n_channels = 3 @@ -264,7 +302,6 @@ def process( Raises: ValueError: If image_paths and time_diffs have different lengths. - ValueError: If image_paths is empty. FileNotFoundError: If any image file does not exist. """ image_paths, time_diffs = value @@ -276,7 +313,19 @@ def process( f"match." ) if len(image_paths) == 0: - raise ValueError("image_paths must be non-empty.") + if self.n_channels is not None: + c = self.n_channels + elif self.mode == "L": + c = 1 + elif self.mode == "RGBA": + c = 4 + else: + c = 3 + images = torch.zeros( + (0, c, self.image_size, self.image_size), dtype=torch.float32 + ) + timestamps = torch.zeros((0,), dtype=torch.float32) + return images, timestamps, "image" paired = sorted( zip(time_diffs, image_paths), key=lambda x: x[0] @@ -344,5 +393,6 @@ def __repr__(self) -> str: f"mean={self.mean}, " f"std={self.std}, " f"mode={self.mode}, " - f"max_images={self.max_images})" + f"max_images={self.max_images}, " + f"padding={self.padding!r})" ) \ No newline at end of file diff --git a/pyhealth/processors/tuple_time_text_processor.py b/pyhealth/processors/tuple_time_text_processor.py index bbe74c4e66..3fbd1c6b6e 100644 --- a/pyhealth/processors/tuple_time_text_processor.py +++ b/pyhealth/processors/tuple_time_text_processor.py @@ -15,24 +15,31 @@ class TupleTimeTextProcessor(TemporalFeatureProcessor): If `tokenizer_model` is provided, the text will be tokenized using a HuggingFace AutoTokenizer, and the output will differ from the raw text version. + + Example: + >>> proc = TupleTimeTextProcessor() + >>> texts, times, tag = proc.process((["note one"], [0.0])) + >>> tag + 'note' """ def __init__( self, type_tag: str = "note", tokenizer_model: Optional[str] = None, - max_length: int = 128, + max_length: int = 512, padding: bool = True, truncation: bool = True, ): """Initialize the processor. - + Args: type_tag: Modality identifier for automatic routing. Default: "note" tokenizer_model: Name or path of the HuggingFace tokenizer to use. If None, texts are returned as raw strings. Default: None - max_length: Maximum sequence length for tokenization. Default: 128 - padding: Whether to pad sequences to max_length. Default: True + max_length: Maximum sequence length for tokenization. Default: 512 + padding: Whether to pad sequences to the longest note in the sample. + Default: True truncation: Whether to truncate sequences to max_length. Default: True """ super().__init__() @@ -81,28 +88,65 @@ def process(self, value: Tuple[List[str], List[float]]) -> Union[Tuple[List[str] - str: Type tag """ texts, time_diffs = value + texts = list(texts or []) + time_diffs = list(time_diffs or []) + + # Keep text/time aligned and filter malformed text entries. + pair_count = min(len(texts), len(time_diffs)) + cleaned_texts: list[str] = [] + cleaned_times: list[float] = [] + for i in range(pair_count): + raw_text = texts[i] + raw_time = time_diffs[i] + + # Normalize text; skip null/whitespace-only entries. + if raw_text is None: + continue + text = str(raw_text).strip() + if text == "": + continue + + # Best-effort float normalization; skip unparseable timestamps. + try: + t = float(raw_time) + except (TypeError, ValueError): + continue + + cleaned_texts.append(text) + cleaned_times.append(t) + + texts = cleaned_texts + time_diffs = cleaned_times time_tensor = torch.tensor(time_diffs, dtype=torch.float32) if self.tokenizer is not None: - # Tokenize the list of texts + # Fast tokenizers crash on tokenizer([]). Build empty tensors + # ourselves so a patient with no notes is zero events, not a + # fake "[MISSING_TEXT]" row whose BERT embedding is a constant + # the classifier can use as a mortality feature. + if len(texts) == 0: + empty = torch.zeros((0, 1), dtype=torch.long) + return empty, empty.clone(), empty.clone(), time_tensor, self.type_tag encoded = self.tokenizer( texts, - padding="max_length" if self.padding else False, + padding="longest" if self.padding else False, truncation=self.truncation, max_length=self.max_length, return_tensors="pt" ) - - input_ids = encoded["input_ids"] - attention_mask = encoded["attention_mask"] - + + input_ids = encoded.get("input_ids") + if input_ids is None: + raise ValueError("Tokenizer output is missing required `input_ids`.") + + attention_mask = encoded.get("attention_mask") + if attention_mask is None: + attention_mask = torch.ones_like(input_ids) + # Not all tokenizers return token_type_ids (e.g. RoBERTa might not, BERT does) - if "token_type_ids" in encoded: - token_type_ids = encoded["token_type_ids"] - else: - # meaningful text usually 0, padding 0? BERT uses 0 for sent A. - # If not provided, we can just use zeros or omit. - # For consistency with schema, let's provide zeros if expected. + token_type_ids = encoded.get("token_type_ids") + if token_type_ids is None: + # Some tokenizers do not return token_type_ids. token_type_ids = torch.zeros_like(input_ids) return input_ids, attention_mask, token_type_ids, time_tensor, self.type_tag @@ -119,6 +163,38 @@ def is_token(self) -> bool: """Returns True if the processor outputs discrete tokens (when tokenizer is used).""" return self.tokenizer is not None + def collate(self, values: list[tuple]) -> Any: + """Batches tokenized samples by stacking each tuple position. + + Samples differ in both the number of notes and the note length, so + every tensor position is right-padded with zeros to the largest shape + in the batch and stacked. A padded note has an all-zero attention + mask, which is how a model tells it from a real note. The type tags + stay a list. Without a tokenizer the batch stays a list of + per-sample tuples. + + Args: + values: One processed tuple per sample. + + Returns: + With a tokenizer, a tuple in :meth:`schema` order whose tensors + have a leading batch dimension. Otherwise ``values`` as a list. + """ + if self.tokenizer is None: + return list(values) + from pyhealth.datasets.collate import _pad_stack + + stacked: list[Any] = [] + for elems in zip(*values): + if all(isinstance(e, torch.Tensor) for e in elems): + if elems[0].dim() == 0: + stacked.append(torch.stack(elems)) + else: + stacked.append(_pad_stack(list(elems))) + else: + stacked.append(list(elems)) + return tuple(stacked) + def schema(self) -> tuple[str, ...]: """Returns the schema of the processed feature.""" if self.tokenizer is not None: diff --git a/pyhealth/trainer.py b/pyhealth/trainer.py index abf44efad2..5271e8b3e0 100644 --- a/pyhealth/trainer.py +++ b/pyhealth/trainer.py @@ -23,6 +23,77 @@ logger = logging.getLogger(__name__) +_AMP_DTYPES = { + "bf16": torch.bfloat16, + "bfloat16": torch.bfloat16, + "fp16": torch.float16, + "float16": torch.float16, +} + + +def resolve_amp_dtype(amp_dtype: str, use_amp: bool = False) -> torch.dtype: + """Validate the mixed-precision dtype and return it. + + The previous expression was ``bfloat16 if amp_dtype == "bf16" else + float16``, so every other spelling silently selected fp16 and, through + GradScaler, changed gradient behaviour too. + + Args: + amp_dtype: Dtype name, one of ``"bf16"``, ``"bfloat16"``, + ``"fp16"`` or ``"float16"`` (case-insensitive). + use_amp: Whether mixed precision will be used. When True and the + resolved dtype is bf16, a CUDA device without bf16 support + raises instead of silently running an unsupported mode. + + Returns: + The matching ``torch.dtype``. + + Examples: + >>> from pyhealth.trainer import resolve_amp_dtype + >>> import torch + >>> resolve_amp_dtype("bfloat16") is torch.bfloat16 + True + """ + name = str(amp_dtype).lower() + if name not in _AMP_DTYPES: + raise ValueError( + f"amp_dtype must be one of {sorted(_AMP_DTYPES)}, got {amp_dtype!r}." + ) + dtype = _AMP_DTYPES[name] + if ( + use_amp + and dtype == torch.bfloat16 + and torch.cuda.is_available() + and not torch.cuda.is_bf16_supported() + ): + raise RuntimeError( + "bf16 mixed precision was requested, but this CUDA device does " + "not support bf16." + ) + return dtype + + +def autocast_device_type(device) -> str: + """Device type string for ``torch.autocast``, from the trainer device. + + Args: + device: Device or device string used by the trainer, e.g. + ``"cuda:0"``, ``"cpu"`` or ``"mps"``. + + Returns: + One of ``"cuda"``, ``"cpu"`` or ``"mps"``; anything else falls + back to ``"cpu"``. + + Examples: + >>> from pyhealth.trainer import autocast_device_type + >>> autocast_device_type("cuda:0") + 'cuda' + """ + name = str(device).split(":", 1)[0].lower() + if name in ("cuda", "cpu", "mps"): + return name + return "cpu" + def _cpu_state_dict(model: nn.Module) -> dict: """A detached CPU copy of the model's state, safe from later updates.""" @@ -211,6 +282,9 @@ def train( load_best_model_at_last: bool = True, patience=None, keep_best_in_memory: bool = True, + accumulation_steps: int = 1, + use_amp: bool = False, + amp_dtype: str = "bf16", ): """Trains the model. @@ -238,6 +312,12 @@ def train( last epoch's weights are kept (with a warning). With an output directory the best weights are saved to ``best.ckpt`` instead. Default is True. + accumulation_steps: Gradient accumulation steps to simulate a larger + effective batch size. Default is 1 (no accumulation). + use_amp: Whether to use automatic mixed precision. Default is False. + amp_dtype: AMP dtype — "bf16" (stable, recommended) or "fp16". + Unknown spellings raise instead of silently using fp16. + Default is "bf16". Raises: TypeError: If the model is fit outside the trainer (it sets @@ -253,10 +333,24 @@ def train( ) if optimizer_params is None: optimizer_params = {"lr": 1e-3} + if accumulation_steps < 1: + raise ValueError( + f"accumulation_steps must be at least 1, got {accumulation_steps}." + ) + + _amp_dtype = resolve_amp_dtype(amp_dtype, use_amp=use_amp) + # GradScaler only needed for fp16; bf16 has fp32 dynamic range + scaler = ( + torch.amp.GradScaler("cuda") + if (use_amp and _amp_dtype == torch.float16) + else None + ) # logging logger.info("Training:") logger.info(f"Batch size: {train_dataloader.batch_size}") + logger.info(f"Accumulation steps: {accumulation_steps}") + logger.info(f"AMP: {use_amp} (dtype={amp_dtype})") logger.info(f"Optimizer: {optimizer_class}") logger.info(f"Optimizer params: {optimizer_params}") logger.info(f"Weight decay: {weight_decay}") @@ -310,7 +404,7 @@ def train( self.model.train() # batch training loop logger.info("") - for _ in trange( + for step_idx in trange( steps_per_epoch, desc=f"Epoch {epoch} / {epochs}", smoothing=0.05, @@ -320,20 +414,46 @@ def train( except StopIteration: data_iterator = iter(train_dataloader) data = next(data_iterator) - # forward - output = self.model(**data) - loss = output["loss"] + # forward (with optional AMP) + if use_amp: + with torch.autocast( + device_type=autocast_device_type(self.device), + dtype=_amp_dtype, + ): + output = self.model(**data) + loss = output["loss"] / accumulation_steps + else: + output = self.model(**data) + loss = output["loss"] / accumulation_steps # backward - loss.backward() - if max_grad_norm is not None: - torch.nn.utils.clip_grad_norm_( - self.model.parameters(), max_grad_norm - ) - # update - optimizer.step() - optimizer.zero_grad() - training_loss.append(loss.item()) - global_step += 1 + if scaler is not None: + scaler.scale(loss).backward() + else: + loss.backward() + training_loss.append(loss.item() * accumulation_steps) + # optimizer step every accumulation_steps batches or epoch end + is_update_step = ( + (step_idx + 1) % accumulation_steps == 0 + or (step_idx + 1) == steps_per_epoch + ) + if is_update_step: + if scaler is not None: + # Unscale before clipping; step() then skips + # non-finite gradients itself. + scaler.unscale_(optimizer) + # Clip only when configured: the default path matches + # upstream exactly (no unconditional grad-norm pass). + if max_grad_norm is not None: + torch.nn.utils.clip_grad_norm_( + self.model.parameters(), max_grad_norm + ) + if scaler is not None: + scaler.step(optimizer) + scaler.update() + else: + optimizer.step() + optimizer.zero_grad() + global_step += 1 # log and save logger.info(f"--- Train epoch-{epoch}, step-{global_step} ---") logger.info(f"loss: {sum(training_loss) / len(training_loss):.4f}") diff --git a/tests/core/test_attention_mask_dtype_min.py b/tests/core/test_attention_mask_dtype_min.py new file mode 100644 index 0000000000..1b855b4980 --- /dev/null +++ b/tests/core/test_attention_mask_dtype_min.py @@ -0,0 +1,132 @@ +"""Attention mask fill is fp16-safe and ordinary forwards use fused SDPA. + +``-1e9`` is outside the fp16 range, so padding an fp16 forward raised +``value cannot be converted to type ... without overflow``. Ordinary +training forwards now use fused ``scaled_dot_product_attention``; the +explicit path stays behind ``register_hook=True`` for interpretability +and fills with ``finfo(dtype).min``. + +A fully-masked query row attends to nothing, which is NaN or garbage +depending on backend and dtype. The fused path lets such rows attend +uniformly and then zeroes their outputs, so an all-padded sample (reachable +once empty modalities become zero-length fields) stays finite. + +Repro:: + + PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONPATH=. \\ + python -m pytest tests/core/test_attention_mask_dtype_min.py -q +""" + +from __future__ import annotations + +import unittest +from unittest import mock + +import torch + + +class TestAttentionMaskDtypeMin(unittest.TestCase): + def test_fp16_attention_mask_fill_does_not_overflow(self): + from pyhealth.models.transformer import Attention + + attn = Attention() + q = torch.zeros(1, 1, 2, 4, dtype=torch.float16) + k = torch.zeros(1, 1, 2, 4, dtype=torch.float16) + v = torch.ones(1, 1, 2, 4, dtype=torch.float16) + mask = torch.tensor([[[[1, 0], [1, 0]]]], dtype=torch.float16) + out, weights = attn(q, k, v, mask=mask) + self.assertTrue(torch.isfinite(out).all()) + self.assertTrue(torch.isfinite(weights).all()) + self.assertEqual(float(weights[0, 0, 0, 1]), 0.0) + + def test_explicit_path_finite_for_all_padded_row(self): + from pyhealth.models.transformer import Attention + + attn = Attention() + q = torch.randn(1, 1, 4, 8) + k = torch.randn(1, 1, 4, 8) + v = torch.randn(1, 1, 4, 8) + mask = torch.ones(1, 1, 4, 4) + mask[:, :, 0, :] = 0 # first query row fully masked + out, weights = attn(q, k, v, mask=mask) + self.assertTrue(torch.isfinite(out).all()) + self.assertTrue(torch.isfinite(weights).all()) + + def test_raw_minus_1e9_still_overflows_fp16(self): + scores = torch.zeros(2, 2, dtype=torch.float16) + with self.assertRaises(RuntimeError): + scores.masked_fill(torch.tensor([[True, False], [False, True]]), -1e9) + + def test_ordinary_forward_uses_fused_sdpa(self): + from pyhealth.models import transformer as transformer_module + + torch.manual_seed(0) + mha = transformer_module.MultiHeadedAttention(h=2, d_model=8).eval() + q = k = v = torch.zeros(2, 5, 8) + mask = torch.ones(2, 5) + real_sdpa = transformer_module.F.scaled_dot_product_attention + with mock.patch.object( + transformer_module.F, + "scaled_dot_product_attention", + wraps=real_sdpa, + ) as sdpa: + mha(q, k, v, mask=mask, register_hook=False) + self.assertEqual(sdpa.call_count, 1) + with mock.patch.object( + transformer_module.F, + "scaled_dot_product_attention", + wraps=real_sdpa, + ) as sdpa: + mha(q, k, v, mask=mask, register_hook=True) + sdpa.assert_not_called() + + def test_fused_and_explicit_paths_agree(self): + from pyhealth.models.transformer import TransformerLayer + + torch.manual_seed(0) + layer = TransformerLayer(feature_size=128, heads=4, num_layers=2).eval() + x = torch.randn(4, 32, 128, requires_grad=True) + mask = torch.ones(4, 32) + fused, _ = layer(x, mask, register_hook=False) + explicit, _ = layer(x, mask, register_hook=True) + self.assertLessEqual(float((fused - explicit).abs().max()), 1e-5) + + mask_pad = torch.cat([torch.ones(4, 20), torch.zeros(4, 12)], dim=1) + fused_pad, _ = layer(x, mask_pad, register_hook=False) + explicit_pad, _ = layer(x, mask_pad, register_hook=True) + # Padded query outputs are discarded downstream (the feed-forward + # zeroes them), so the paths must agree at valid positions. + self.assertLessEqual( + float((fused_pad[:, :20] - explicit_pad[:, :20]).abs().max()), 1e-5 + ) + + def test_all_padded_sample_stays_finite(self): + from pyhealth.models.transformer import MultiHeadedAttention + + torch.manual_seed(0) + for mask_2d in (True, False): + mha = MultiHeadedAttention(h=2, d_model=8).eval() + q = k = v = torch.randn(3, 6, 8) + valid = torch.ones(3, 6) + valid[0, :] = 0 # one all-padded sample + mask = valid if mask_2d else torch.einsum("ab,ac->abc", valid, valid) + out = mha(q, k, v, mask=mask, register_hook=False) + self.assertTrue(torch.isfinite(out).all()) + # Padded query rows produce exact zeros in the fused path. + self.assertTrue(torch.equal(out[0], torch.zeros_like(out[0]))) + self.assertFalse(torch.equal(out[1], torch.zeros_like(out[1]))) + + def test_all_padded_sample_layer_forward(self): + from pyhealth.models.transformer import TransformerLayer + + torch.manual_seed(0) + layer = TransformerLayer(feature_size=64, heads=4, num_layers=2).eval() + x = torch.randn(3, 16, 64) + x[0] = 0.0 # all-padded sample carries no signal + mask = torch.ones(3, 16) + mask[0, :] = 0 + fused, _ = layer(x, mask, register_hook=False) + explicit, _ = layer(x, mask, register_hook=True) + self.assertTrue(torch.isfinite(fused).all()) + self.assertTrue(torch.isfinite(explicit).all()) + self.assertTrue(torch.equal(fused[0], torch.zeros_like(fused[0]))) diff --git a/tests/core/test_collate_pad_mask.py b/tests/core/test_collate_pad_mask.py new file mode 100644 index 0000000000..fab7cb3a61 --- /dev/null +++ b/tests/core/test_collate_pad_mask.py @@ -0,0 +1,52 @@ +"""Collators emit {field}__pad_mask for legacy tuple fields.""" + +import unittest + +import torch + +from pyhealth.datasets.collate import collate_temporal +from pyhealth.datasets.utils import PAD_MASK_SUFFIX, collate_fn_dict_with_padding + + +class TestCollatePadMask(unittest.TestCase): + def test_temporal_collator_marks_time_padding(self): + batch = [ + {"labs": {"value": torch.ones(3, 2), "time": torch.tensor([0.0, 1.0, 2.0])}}, + {"labs": {"value": torch.ones(1, 2), "time": torch.tensor([0.0])}}, + ] + out = collate_temporal(batch) + self.assertEqual(out["labs"]["value"].shape, (2, 3, 2)) + self.assertEqual( + out["labs"]["pad_mask"].tolist(), + [[True, True, True], [True, False, False]], + ) + + def test_dict_collator_emits_suffix_mask(self): + batch = [ + {"notes": (torch.ones(3, 4, dtype=torch.long), torch.ones(3, 4))}, + {"notes": (torch.ones(1, 4, dtype=torch.long), torch.ones(1, 4))}, + ] + collated = collate_fn_dict_with_padding(batch) + self.assertEqual(tuple(collated["notes"][1].shape), (2, 3, 4)) + self.assertEqual( + collated[f"notes{PAD_MASK_SUFFIX}"].tolist(), + [[True, True, True], [True, False, False]], + ) + + def test_equal_shapes_emit_no_mask(self): + batch = [ + {"labs": (torch.tensor([0.0, 1.0]), torch.ones(2, 2))}, + {"labs": (torch.tensor([0.0, 2.0]), torch.ones(2, 2))}, + ] + collated = collate_fn_dict_with_padding(batch) + self.assertNotIn(f"labs{PAD_MASK_SUFFIX}", collated) + + def test_collator_keys_skip_padding_and_mask(self): + batch = [{"x": torch.tensor([1, 2])}, {"x": torch.tensor([3])}] + out = collate_fn_dict_with_padding(batch, collators={"x": len}) + self.assertEqual(out["x"], 2) + self.assertNotIn(f"x{PAD_MASK_SUFFIX}", out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_dask_distributed_flag.py b/tests/core/test_dask_distributed_flag.py new file mode 100644 index 0000000000..ea82ae2ab3 --- /dev/null +++ b/tests/core/test_dask_distributed_flag.py @@ -0,0 +1,132 @@ +"""Opt out of the Dask distributed cluster for event caching. + +``BaseDataset(use_dask_distributed=False)`` makes ``_event_transform`` write +the cache with the local Dask scheduler instead of starting a distributed +cluster, for sandboxes where the cluster cannot start. The default ``True`` +keeps the distributed path (with ``dashboard_address=None``) unchanged, and +the flag does not affect the cache key or the written contents. + +Repro:: + + PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONPATH=. \ + python -m pytest tests/core/test_dask_distributed_flag.py -q +""" + +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import dask.dataframe as dd +import pandas as pd + + +class TestDaskDistributedFlag(unittest.TestCase): + def _dataset(self, cache_root: str, use_dask_distributed: bool = True, dev=False): + from pyhealth.datasets.base_dataset import BaseDataset + + class MockDataset(BaseDataset): + def __init__(self, data: dd.DataFrame, **kwargs): + self._data = data + super().__init__(**kwargs) + + def load_data(self) -> dd.DataFrame: + return self._data + + data = dd.from_pandas( + pd.DataFrame( + { + # Unsorted on purpose: both paths sort by patient_id. + "patient_id": ["2", "1", "3", "2"], + "event_type": ["test", "test", "test", "test"], + "timestamp": [None, None, None, None], + "test/value": [2, 0, 1, 3], + } + ), + npartitions=2, + ) + with patch( + "pyhealth.datasets.base_dataset.platformdirs.user_cache_dir", + return_value=cache_root, + ): + dataset = MockDataset( + data=data, + root="/data/root_a", + tables=["table_a"], + dataset_name="FlagDataset", + dev=dev, + num_workers=2, + use_dask_distributed=use_dask_distributed, + ) + return dataset + + def _cached_frame(self, out): + frame = dd.read_parquet(out).compute() + return ( + frame.sort_values(list(frame.columns)) + .reset_index(drop=True) + .astype({"test/value": "int64"}) + ) + + def test_flag_defaults_to_distributed(self): + import inspect + + from pyhealth.datasets.base_dataset import BaseDataset + + sig = inspect.signature(BaseDataset.__init__) + self.assertIn("use_dask_distributed", sig.parameters) + self.assertTrue(sig.parameters["use_dask_distributed"].default) + + def test_false_bypasses_cluster(self): + with tempfile.TemporaryDirectory() as cache_root: + dataset = self._dataset(cache_root, use_dask_distributed=False) + self.assertFalse(dataset.use_dask_distributed) + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "events.parquet" + with patch( + "pyhealth.datasets.base_dataset.DaskCluster", + side_effect=AssertionError("cluster must not start"), + ): + dataset._event_transform(out) + self.assertTrue(out.exists()) + + def test_true_uses_cluster(self): + with tempfile.TemporaryDirectory() as cache_root: + dataset = self._dataset(cache_root, use_dask_distributed=True) + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "events.parquet" + with patch( + "pyhealth.datasets.base_dataset.DaskCluster", + side_effect=RuntimeError("cluster entry reached"), + ): + with self.assertRaises(RuntimeError): + dataset._event_transform(out) + + def test_flag_does_not_change_cache_key(self): + with tempfile.TemporaryDirectory() as cache_root: + on = self._dataset(cache_root, use_dask_distributed=True) + off = self._dataset(cache_root, use_dask_distributed=False) + self.assertEqual(on.cache_dir, off.cache_dir) + + def test_flag_path_matches_distributed_contents(self): + for dev in (False, True): + with tempfile.TemporaryDirectory() as cache_root: + local = self._dataset( + cache_root, use_dask_distributed=False, dev=dev + ) + dist = self._dataset( + cache_root, use_dask_distributed=True, dev=dev + ) + # Same key so the same directory would be reused; write the + # two arms to separate output dirs to compare contents. + with tempfile.TemporaryDirectory() as tmp: + flag_out = Path(tmp) / "flag.parquet" + dist_out = Path(tmp) / "dist.parquet" + local._event_transform(flag_out) + dist._event_transform(dist_out) + pd.testing.assert_frame_equal( + self._cached_frame(flag_out), + self._cached_frame(dist_out), + ) diff --git a/tests/core/test_p1_pad_masks.py b/tests/core/test_p1_pad_masks.py new file mode 100644 index 0000000000..584e2aaa3d --- /dev/null +++ b/tests/core/test_p1_pad_masks.py @@ -0,0 +1,96 @@ +"""Ragged text tuples collate positionally like (time, values) pairs.""" + +from __future__ import annotations + +import unittest + +import torch + + +class TestP1TextTupleCollate(unittest.TestCase): + """Ragged text tuples collate positionally like (time, values) pairs. + + Regression tests: tokenized note fields collate as one 5-tuple per + sample ``(value, mask, token_type_ids, time, tag)`` with a ragged note + count, which the old 2-tuple-only branch kept as a nested list. Every + unified backbone then crashed in ``_build_unified_inputs`` indexing + into per-sample tuples (``'tuple' object has no attribute 'to'``). + """ + + @staticmethod + def _note(n, l, t0): + return ( + torch.ones(n, l, dtype=torch.long), + torch.ones(n, l, dtype=torch.long), + torch.zeros(n, l, dtype=torch.long), + torch.tensor([t0 + i for i in range(n)], dtype=torch.float), + "note", + ) + + @staticmethod + def _text_processor(tokenized=True): + from pyhealth.processors import TupleTimeTextProcessor + + # collate() only reads whether a tokenizer is set, so skip the download. + processor = TupleTimeTextProcessor.__new__(TupleTimeTextProcessor) + processor.tokenizer = object() if tokenized else None + return processor + + def test_ragged_text_tuples_stack_through_the_processor_collate(self): + from pyhealth.datasets.utils import collate_fn_dict_with_padding + + batch = [ + {"notes": self._note(2, 4, 0.0)}, + {"notes": self._note(1, 4, 5.0)}, + {"notes": self._note(0, 1, 0.0)}, + ] + collated = collate_fn_dict_with_padding( + batch, collators={"notes": self._text_processor().collate} + ) + value, mask, type_ids, time, tag = collated["notes"] + self.assertEqual(tuple(value.shape), (3, 2, 4)) + self.assertEqual(tuple(mask.shape), (3, 2, 4)) + self.assertEqual(tuple(type_ids.shape), (3, 2, 4)) + self.assertEqual(tuple(time.shape), (3, 2)) + self.assertEqual(tag, ["note", "note", "note"]) + # A padded note slot has an all-zero attention mask. + self.assertEqual( + mask.any(dim=-1).tolist(), + [[True, True], [True, False], [False, False]], + ) + + def test_text_tuples_stay_a_list_without_the_processor_collate(self): + from pyhealth.datasets.utils import collate_fn_dict_with_padding + + batch = [{"notes": self._note(2, 4, 0.0)}, {"notes": self._note(1, 4, 5.0)}] + # The shared collator stacks pairs only; longer tuples stay a list. + self.assertIsInstance(collate_fn_dict_with_padding(batch)["notes"], list) + untokenized = self._text_processor(tokenized=False).collate + collated = collate_fn_dict_with_padding(batch, collators={"notes": untokenized}) + self.assertIsInstance(collated["notes"], list) + + def test_two_tuple_contract_unchanged(self): + from pyhealth.datasets.utils import PAD_MASK_SUFFIX, collate_fn_dict_with_padding + + same = [ + {"x": (torch.tensor([1.0, 2.0]), torch.tensor([[1.0], [2.0]]))}, + {"x": (torch.tensor([3.0, 4.0]), torch.tensor([[3.0], [4.0]]))}, + ] + collated = collate_fn_dict_with_padding(same) + self.assertEqual(tuple(collated["x"][0].shape), (2, 2)) + self.assertEqual(tuple(collated["x"][1].shape), (2, 2, 1)) + self.assertNotIn(f"x{PAD_MASK_SUFFIX}", collated) + + ragged = [ + {"x": (torch.tensor([1.0, 2.0]), torch.tensor([[1.0], [2.0]]))}, + {"x": (torch.tensor([3.0]), torch.tensor([[3.0]]))}, + ] + collated = collate_fn_dict_with_padding(ragged) + self.assertEqual(tuple(collated["x"][1].shape), (2, 2, 1)) + self.assertEqual( + collated[f"x{PAD_MASK_SUFFIX}"].tolist(), [[True, True], [True, False]] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_stagenet_processor.py b/tests/core/test_stagenet_processor.py index 6e217dc7d7..25dd3feb9c 100644 --- a/tests/core/test_stagenet_processor.py +++ b/tests/core/test_stagenet_processor.py @@ -199,9 +199,8 @@ def test_empty_codes_flat(self): time, values = processor.process((None, [])) - # Should return single padding token - self.assertEqual(values.shape, (1,)) - self.assertEqual(values[0].item(), processor.code_vocab[""]) + # Empty codes are zero events, not a fake pad token + self.assertEqual(values.shape, (0,)) def test_empty_codes_nested(self): """Test processing empty nested codes.""" @@ -211,10 +210,8 @@ def test_empty_codes_nested(self): time, values = processor.process((None, [])) - # Should return single row of padding tokens - self.assertEqual(values.shape, (1, 2)) - self.assertEqual(values[0, 0].item(), processor.code_vocab[""]) - self.assertEqual(values[0, 1].item(), processor.code_vocab[""]) + # Empty nested codes are zero events + self.assertEqual(values.shape, (0, 2)) def test_vocab_size_method(self): """Test vocab_size() returns correct size.""" @@ -370,6 +367,16 @@ def test_no_time_tensor(self): self.assertIsNone(time) self.assertEqual(values.shape, (2, 2)) + def test_empty_values_returns_zero_length(self): + """Empty values are zero events, not imputed rows.""" + processor = StageNetTensorProcessor() + samples = [{"data": ([0.0], [[1.0, 2.0]])}] + processor.fit(samples, "data") + + time, values = processor.process(([0.0], [])) + self.assertEqual(values.shape, (0, 2)) + self.assertEqual(time.shape, (0,)) + def test_repr_tensor(self): """Test string representation for tensor processor.""" processor = StageNetTensorProcessor() @@ -461,5 +468,103 @@ def test_vocab_size_for_embedding_layer(self): self.assertLess(max_idx, vocab_size) +class TestStageNetTensorProcessorForwardFill(unittest.TestCase): + """Tests for the ``forward_fill`` switch (observation masks). + + Regression tests: the multimodal MIMIC-IV tasks declare + ``"labs_mask": ("stagenet_tensor", {"forward_fill": False})``, which + raised ``TypeError`` before ``StageNetTensorProcessor`` accepted the + kwarg, and would silently corrupt masks if the flag were ignored. + """ + + def test_spec_instantiation_with_forward_fill_kwarg(self): + """The task schema spec instantiates through the processor registry.""" + from pyhealth.processors import get_processor + + default = get_processor("stagenet_tensor")() + self.assertTrue(default.forward_fill) + no_fill = get_processor("stagenet_tensor")(forward_fill=False) + self.assertFalse(no_fill.forward_fill) + + def test_default_still_forward_fills(self): + """Default construction keeps the historical forward-fill behaviour.""" + processor = StageNetTensorProcessor() + samples = [{"data": ([0.0], [1.0, 2.0])}] + processor.fit(samples, "data") + _, values = processor.process(([0.0, 1.0, 2.0], [1.0, None, 3.0])) + self.assertEqual(values.tolist(), [1.0, 1.0, 3.0]) + + def test_no_forward_fill_keeps_missing_as_zero(self): + """With ``forward_fill=False`` missing values never propagate.""" + processor = StageNetTensorProcessor(forward_fill=False) + samples = [{"data": ([0.0], [[1.0, 2.0]])}] + processor.fit(samples, "data") + _, values = processor.process( + ([0.0, 1.0, 2.0], [[1.0, None, 3.0], [None, 5.0, 6.0], [7.0, 8.0, None]]) + ) + self.assertEqual( + values.tolist(), + [[1.0, 0.0, 3.0], [0.0, 5.0, 6.0], [7.0, 8.0, 0.0]], + ) + + def test_no_forward_fill_preserves_observation_mask(self): + """A mask with gaps round-trips instead of filling gaps with 1s.""" + observed = [[True, None], [None, True], [True, True]] + filled = StageNetTensorProcessor() # default: forward_fill=True + samples = [{"data": ([0.0], observed)}] + filled.fit(samples, "data") + _, filled_values = filled.process(([0.0, 1.0, 2.0], observed)) + # Forward-filling the mask corrupts it: the gap at [1, 0] becomes + # the earlier observed True. + self.assertEqual(filled_values.tolist(), [[1.0, 0.0], [1.0, 1.0], [1.0, 1.0]]) + + masked = StageNetTensorProcessor(forward_fill=False) + masked.fit(samples, "data") + _, masked_values = masked.process(([0.0, 1.0, 2.0], observed)) + self.assertEqual(masked_values.tolist(), [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]) + + +class TestStageNetFitSkipsEmptySamples(unittest.TestCase): + """``fit`` must scan past samples with no structural information. + + Regression tests: real task streams start with whatever patient sorts + first, and empty-lab stays are legitimate records (the series emits no + placeholder rows). The old ``fit`` stopped after the first non-None + sample even when it was empty, leaving ``_size``/``_is_nested`` unset; + downstream ``value_dim()`` then reported 1 and the unified numeric + encoder was built with the wrong input width. + """ + + def test_tensor_fit_skips_empty_first_sample(self): + processor = StageNetTensorProcessor() + processor.fit( + [ + {"data": ([], [])}, + {"data": ([0.0, 1.0], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])}, + ], + "data", + ) + self.assertTrue(processor._is_nested) + self.assertEqual(processor.size(), 3) + self.assertEqual(processor.value_dim(), 3) + + def test_tensor_fit_all_empty_stays_unfitted(self): + processor = StageNetTensorProcessor() + processor.fit([{"data": ([], [])}, {"data": ([], [])}], "data") + self.assertIsNone(processor._size) + self.assertEqual(processor.value_dim(), 1) + + def test_code_fit_skips_empty_first_sample(self): + processor = StageNetProcessor() + processor.fit( + [ + {"data": ([], [])}, + {"data": ([0.0], [["A", "B"], ["C"]])}, + ], + "data", + ) + self.assertTrue(processor._is_nested) + + if __name__ == "__main__": unittest.main() diff --git a/tests/core/test_time_image_processor.py b/tests/core/test_time_image_processor.py index 51467aa5ce..52cc1e6539 100644 --- a/tests/core/test_time_image_processor.py +++ b/tests/core/test_time_image_processor.py @@ -207,11 +207,21 @@ def test_process_mismatched_lengths_raises(self): (self.rgb_paths[:3], self.times[:2]) ) - def test_process_empty_paths_raises(self): - """ValueError for empty image list.""" - proc = TimeImageProcessor() - with self.assertRaises(ValueError): - proc.process(([], [])) + def test_process_empty_paths_returns_zero_length(self): + """Empty image list is zero events, not an error.""" + proc = TimeImageProcessor(image_size=32) + images, timestamps, tag = proc.process(([], [])) + self.assertEqual(images.shape, (0, 3, 32, 32)) + self.assertEqual(timestamps.shape, (0,)) + self.assertEqual(tag, "image") + + def test_padding_sentinel_returns_zero_tensor(self): + """Sentinel paths decode to zero tensors without disk access.""" + proc = TimeImageProcessor(image_size=32, padding="MISSING") + images, timestamps, tag = proc.process((["MISSING"], [1.0])) + self.assertEqual(images.shape, (1, 3, 32, 32)) + self.assertTrue(bool((images == 0).all())) + self.assertEqual(tag, "image") def test_process_invalid_path_raises(self): """FileNotFoundError for nonexistent image.""" diff --git a/tests/core/test_trainer_amp.py b/tests/core/test_trainer_amp.py new file mode 100644 index 0000000000..ce77f15c6c --- /dev/null +++ b/tests/core/test_trainer_amp.py @@ -0,0 +1,243 @@ +"""Trainer mixed precision and gradient accumulation. + +``amp_dtype`` used to fall through to fp16 for any unknown spelling, and the +autocast context was hardcoded to CUDA. Accumulation lets small synthetic +batches simulate a larger effective batch size. + +With ``use_amp=False`` the step matches ``upstream/master`` exactly: clip only +when ``max_grad_norm`` is set, no unconditional grad-norm pass, no skipping. +``accumulation_steps=1`` is bit-identical in effect to upstream. + +Repro:: + + PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTHONPATH=. \\ + python -m pytest tests/core/test_trainer_amp.py -q +""" + +from __future__ import annotations + +import unittest +from unittest import mock + +import torch +from torch import nn +from torch.utils.data import DataLoader, TensorDataset + + +class _TinyModel(nn.Module): + mode = None + + def __init__(self): + super().__init__() + self.fc = nn.Linear(4, 1) + + def forward(self, x, y): + logit = self.fc(x).squeeze(-1) + loss = nn.functional.binary_cross_entropy_with_logits(logit, y) + return {"loss": loss} + + +def _loader(n=16, batch_size=4, seed=0): + torch.manual_seed(seed) + xs = torch.randn(n, 4) + ys = (xs.sum(dim=1) > 0).float() + ds = TensorDataset(xs, ys) + + def collate(batch): + xs_b, ys_b = zip(*batch) + return {"x": torch.stack(list(xs_b)), "y": torch.stack(list(ys_b))} + + return DataLoader(ds, batch_size=batch_size, shuffle=False, collate_fn=collate) + + +def _upstream_reference_train(model, loader, epochs, max_grad_norm, lr=1e-3): + """The upstream/master batch loop, copied for equivalence checking.""" + no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"] + param = list(model.named_parameters()) + optimizer = torch.optim.Adam( + [ + { + "params": [p for n, p in param if not any(nd in n for nd in no_decay)], + "weight_decay": 0.0, + }, + { + "params": [p for n, p in param if any(nd in n for nd in no_decay)], + "weight_decay": 0.0, + }, + ], + lr=lr, + ) + data_iterator = iter(loader) + steps_per_epoch = len(loader) + for _ in range(epochs): + model.zero_grad() + model.train() + for _ in range(steps_per_epoch): + try: + data = next(data_iterator) + except StopIteration: + data_iterator = iter(loader) + data = next(data_iterator) + output = model(**data) + loss = output["loss"] + loss.backward() + if max_grad_norm is not None: + torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm) + optimizer.step() + optimizer.zero_grad() + + +class TestTrainerAmp(unittest.TestCase): + def test_known_spellings_map_to_the_named_dtype(self): + from pyhealth.trainer import resolve_amp_dtype + + self.assertIs(resolve_amp_dtype("bf16"), torch.bfloat16) + self.assertIs(resolve_amp_dtype("bfloat16"), torch.bfloat16) + self.assertIs(resolve_amp_dtype("fp16"), torch.float16) + self.assertIs(resolve_amp_dtype("float16"), torch.float16) + + def test_unknown_spelling_raises(self): + from pyhealth.trainer import resolve_amp_dtype + + for bad in ("bfloat_16", "f16", "int8", ""): + with self.assertRaises(ValueError): + resolve_amp_dtype(bad) + + def test_train_rejects_unknown_amp_dtype(self): + from pyhealth.trainer import Trainer + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + with self.assertRaises(ValueError): + trainer.train(_loader(), epochs=1, amp_dtype="f16") + + def test_invalid_accumulation_steps_raises(self): + from pyhealth.trainer import Trainer + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + for bad in (0, -2): + with self.assertRaises(ValueError): + trainer.train(_loader(), epochs=1, accumulation_steps=bad) + + def test_autocast_device_follows_the_trainer_device(self): + from pyhealth.trainer import autocast_device_type + + self.assertEqual(autocast_device_type("cuda:0"), "cuda") + self.assertEqual(autocast_device_type("cpu"), "cpu") + self.assertEqual(autocast_device_type("mps"), "mps") + self.assertEqual(autocast_device_type("xpu"), "cpu") + + def test_default_path_clips_only_when_configured(self): + from pyhealth.trainer import Trainer + + with mock.patch( + "torch.nn.utils.clip_grad_norm_", wraps=torch.nn.utils.clip_grad_norm_ + ) as clip: + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + trainer.train(_loader(), epochs=1, max_grad_norm=None) + clip.assert_not_called() + with mock.patch( + "torch.nn.utils.clip_grad_norm_", wraps=torch.nn.utils.clip_grad_norm_ + ) as clip: + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + trainer.train(_loader(), epochs=1, max_grad_norm=1.0) + self.assertEqual(clip.call_count, len(_loader())) + + def test_accumulation_one_matches_upstream_bit_identical(self): + from pyhealth.trainer import Trainer + + torch.manual_seed(123) + model_new = _TinyModel() + torch.manual_seed(123) + model_ref = _TinyModel() + loader = _loader() + Trainer(model_new, enable_logging=False, device="cpu").train( + loader, epochs=2, accumulation_steps=1, max_grad_norm=1.0 + ) + _upstream_reference_train(model_ref, _loader(), 2, max_grad_norm=1.0) + for p_new, p_ref in zip( + model_new.parameters(), model_ref.parameters(), strict=True + ): + self.assertTrue(torch.equal(p_new, p_ref)) + + def test_accumulated_halves_match_full_batch(self): + from pyhealth.trainer import Trainer + + torch.manual_seed(7) + model_full = _TinyModel() + torch.manual_seed(7) + model_acc = _TinyModel() + Trainer(model_full, enable_logging=False, device="cpu").train( + _loader(n=8, batch_size=8), + epochs=1, + accumulation_steps=1, + optimizer_class=torch.optim.SGD, + optimizer_params={"lr": 0.1}, + ) + Trainer(model_acc, enable_logging=False, device="cpu").train( + _loader(n=8, batch_size=4), + epochs=1, + accumulation_steps=2, + optimizer_class=torch.optim.SGD, + optimizer_params={"lr": 0.1}, + ) + for p_full, p_acc in zip( + model_full.parameters(), model_acc.parameters(), strict=True + ): + self.assertTrue(torch.allclose(p_full, p_acc, atol=1e-6)) + + def test_trailing_partial_window_still_steps(self): + from pyhealth.trainer import Trainer + + counts = [] + + class CountingSGD(torch.optim.SGD): + def step(self, *args, **kwargs): + counts.append(1) + return super().step(*args, **kwargs) + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + trainer.train( + _loader(n=12, batch_size=4), + epochs=1, + steps_per_epoch=3, + accumulation_steps=2, + optimizer_class=CountingSGD, + optimizer_params={"lr": 0.1}, + ) + # batches 1-2 form one update, batch 3 is flushed at epoch end + self.assertEqual(len(counts), 2) + + def test_steps_per_epoch_shorter_than_loader(self): + from pyhealth.trainer import Trainer + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + before = [p.detach().clone() for p in trainer.model.parameters()] + trainer.train(_loader(n=16, batch_size=4), epochs=2, steps_per_epoch=2) + after = [p.detach().clone() for p in trainer.model.parameters()] + self.assertTrue(any(not torch.equal(b, a) for b, a in zip(before, after))) + + def test_accumulation_trains_on_cpu(self): + from pyhealth.trainer import Trainer + + for accumulation_steps in (1, 2): + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + before = [p.detach().clone() for p in trainer.model.parameters()] + trainer.train( + _loader(), epochs=1, accumulation_steps=accumulation_steps + ) + after = [p.detach().clone() for p in trainer.model.parameters()] + self.assertTrue( + any(not torch.equal(b, a) for b, a in zip(before, after)) + ) + + def test_amp_bf16_trains_on_cpu(self): + from pyhealth.trainer import Trainer + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + trainer.train(_loader(), epochs=1, use_amp=True, amp_dtype="bf16") + + def test_amp_fp16_trains_on_cpu(self): + from pyhealth.trainer import Trainer + + trainer = Trainer(_TinyModel(), enable_logging=False, device="cpu") + trainer.train(_loader(), epochs=1, use_amp=True, amp_dtype="fp16") diff --git a/tests/core/test_tuple_time_text_processor.py b/tests/core/test_tuple_time_text_processor.py index 7a8dfd5b59..539349d083 100644 --- a/tests/core/test_tuple_time_text_processor.py +++ b/tests/core/test_tuple_time_text_processor.py @@ -29,3 +29,69 @@ def test_tuple_time_text_processor(): from pyhealth.processors import get_processor ProcessorClass = get_processor("tuple_time_text") assert ProcessorClass is TupleTimeTextProcessor + + +def test_tuple_time_text_cleans_malformed_entries(): + """Null, blank, and misaligned entries are dropped with their times.""" + from pyhealth.processors import TupleTimeTextProcessor + + processor = TupleTimeTextProcessor() + texts = [" real note ", None, " ", "second note"] + time_diffs = [0.0, 1.0, 2.0, 3.0] + result_texts, time_tensor, tag = processor.process((texts, time_diffs)) + + assert result_texts == ["real note", "second note"] + assert torch.equal(time_tensor, torch.tensor([0.0, 3.0])) + assert tag == "note" + + +def test_tuple_time_text_empty_is_zero_events_with_stub_tokenizer(): + """Tokenizer path returns (0, 1) empties instead of a fake row.""" + from pyhealth.processors import TupleTimeTextProcessor + + processor = TupleTimeTextProcessor() + calls = [] + + def fake_tokenizer(texts, **kwargs): + calls.append((list(texts), kwargs.get("padding"), kwargs.get("max_length"))) + raise AssertionError("tokenizer must not run on zero notes") + + processor.tokenizer = fake_tokenizer + input_ids, attn, token_types, time_tensor, tag = processor.process(([], [])) + + assert calls == [] + assert input_ids.shape == (0, 1) + assert attn.shape == (0, 1) + assert token_types.shape == (0, 1) + assert time_tensor.shape == (0,) + assert tag == "note" + + +def test_tuple_time_text_longest_padding_bounded_by_max_length(): + """Padding follows the longest note in the sample, capped at max_length.""" + from pyhealth.processors import TupleTimeTextProcessor + + processor = TupleTimeTextProcessor(max_length=16) + seen = {} + + def fake_tokenizer(texts, **kwargs): + seen["padding"] = kwargs.get("padding") + seen["max_length"] = kwargs.get("max_length") + width = max(len(t.split()) + 2 for t in texts) + n = len(texts) + return { + "input_ids": torch.ones((n, width), dtype=torch.long), + "attention_mask": torch.ones((n, width), dtype=torch.long), + } + + processor.tokenizer = fake_tokenizer + input_ids, attn, token_types, time_tensor, tag = processor.process( + (["hi", "a much longer note here"], [0.0, 1.0]) + ) + + assert seen["padding"] == "longest" + assert seen["max_length"] == 16 + assert input_ids.shape == (2, 7) + assert attn.shape == (2, 7) + assert token_types.shape == (2, 7) + assert torch.equal(time_tensor, torch.tensor([0.0, 1.0])) diff --git a/tests/core/test_tuple_time_text_tokenizer.py b/tests/core/test_tuple_time_text_tokenizer.py index 3a5eeb5998..1e58aa2f6b 100644 --- a/tests/core/test_tuple_time_text_tokenizer.py +++ b/tests/core/test_tuple_time_text_tokenizer.py @@ -86,18 +86,18 @@ def test_tuple_time_text_processor_with_tokenizer(): input_ids, attention_mask, token_type_ids, time_tensor, tag = result - # Check shapes + # Check shapes: per-sample longest padding bounded by max_length N = 2 # number of sentences - L = 16 # max_length - + assert isinstance(input_ids, torch.Tensor) - assert input_ids.shape == (N, L) - + assert input_ids.shape[0] == N + assert input_ids.shape[1] <= 16 + assert isinstance(attention_mask, torch.Tensor) - assert attention_mask.shape == (N, L) - + assert attention_mask.shape == input_ids.shape + assert isinstance(token_type_ids, torch.Tensor) - assert token_type_ids.shape == (N, L) + assert token_type_ids.shape == input_ids.shape assert isinstance(time_tensor, torch.Tensor) assert time_tensor.shape == (N,) @@ -177,8 +177,9 @@ def test_tuple_in_schema_canonical_form(): assert isinstance(sample["notes"], tuple) assert len(sample["notes"]) == 5 input_ids, mask, type_ids, time, tag = sample["notes"] - assert input_ids.shape == (2, 16) # (N_notes, L) - assert mask.shape == (2, 16) + assert input_ids.shape[0] == 2 + assert input_ids.shape[1] <= 16 + assert mask.shape == input_ids.shape assert time.shape == (2,) assert tag == "note"