From 6b809742bbeb8bf328b8cf00550a48554e7f1d6e Mon Sep 17 00:00:00 2001 From: Tamjit Kumar Date: Mon, 30 Nov 2026 00:29:37 -0500 Subject: [PATCH] [BTY-30] feat(models): add LLMCodeTransfer for cross-coding-system EHR transfer --- docs/api/models.rst | 1 + .../pyhealth.models.LLMCodeTransfer.rst | 60 + examples/llm_code_transfer.py | 141 ++ pyhealth/models/__init__.py | 8 + pyhealth/models/llm_code_transfer.py | 1629 +++++++++++++++++ tests/core/test_llm_code_transfer.py | 599 ++++++ 6 files changed, 2438 insertions(+) create mode 100644 docs/api/models/pyhealth.models.LLMCodeTransfer.rst create mode 100644 examples/llm_code_transfer.py create mode 100644 pyhealth/models/llm_code_transfer.py create mode 100644 tests/core/test_llm_code_transfer.py diff --git a/docs/api/models.rst b/docs/api/models.rst index d8a1325cb1..ff5277b167 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -421,4 +421,5 @@ API Reference models/pyhealth.models.HiCu models/pyhealth.models.WatchSleepNet models/pyhealth.models.DuETT + models/pyhealth.models.LLMCodeTransfer diff --git a/docs/api/models/pyhealth.models.LLMCodeTransfer.rst b/docs/api/models/pyhealth.models.LLMCodeTransfer.rst new file mode 100644 index 0000000000..8d7c3f723b --- /dev/null +++ b/docs/api/models/pyhealth.models.LLMCodeTransfer.rst @@ -0,0 +1,60 @@ +pyhealth.models.LLMCodeTransfer +=============================== + +.. currentmodule:: pyhealth.models + +Overview +-------- + +LLMCodeTransfer (`Kirchler et al., npj Digital Medicine 2026 `_; +reference repository `mkirchler/grasp `_) +enables EHR predictive models to transfer zero-shot across disparate medical +coding systems (such as ICD-9, ICD-10, OMOP, and ATC) by representing clinical +concepts in a shared, frozen LLM text-embedding space. + +Instead of training random per-code embedding tables from scratch, +:class:`~pyhealth.models.LLMCodeTransfer`: + +1. **Encodes medical concepts via LLM text vectors**: Maps codes from any + vocabulary to precomputed semantic vectors via + :class:`~pyhealth.models.LLMCodeEmbedding`, loaded from files or any user + text encoder with :func:`~pyhealth.models.load_llm_code_embeddings` and + :func:`~pyhealth.models.build_llm_code_embeddings`. +2. **Encodes continuous clinical measurements**: Adds optional 1D and 2D + sinusoidal encodings (:class:`~pyhealth.models.PositionalEncoding1D`, + :class:`~pyhealth.models.PositionalEncoding2D`) for patient age and numeric + values. +3. **Models event sets with a Pre-LN Transformer**: Applies a Pre-LN Set + Transformer with stochastic depth (``DropPath``), optional ``LayerScale``, + and padding-aware attention over clinical events. +4. **Transfers zero-shot across vocabularies**: Transfers all trained + Transformer and head weights to another dataset's coding system via + :meth:`~pyhealth.models.LLMCodeTransfer.transfer_to_dataset` without + requiring manual ontology crosswalks. + +API Reference +------------- + +.. autofunction:: pyhealth.models.load_llm_code_embeddings + +.. autofunction:: pyhealth.models.build_llm_code_embeddings + +.. autoclass:: pyhealth.models.PositionalEncoding1D + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.PositionalEncoding2D + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.LLMCodeEmbedding + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.LLMCodeTransfer + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/llm_code_transfer.py b/examples/llm_code_transfer.py new file mode 100644 index 0000000000..896b47c848 --- /dev/null +++ b/examples/llm_code_transfer.py @@ -0,0 +1,141 @@ +"""Cross-coding-system EHR transfer with LLMCodeTransfer. + +Demonstrates training ``LLMCodeTransfer`` on a source coding system (e.g., ICD-9) +via PyHealth's standard ``Trainer`` and transferring zero-shot to an unseen target +coding system (e.g., ICD-10 / OMOP) without retraining. + +Reference: + Kirchler et al., "Transferring EHR predictors across coding systems via + large language model embeddings", npj Digital Medicine (2026). + https://doi.org/10.1038/s41746-026-02363-5 +""" + +import numpy as np +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader, split_by_patient +from pyhealth.models import LLMCodeTransfer, build_llm_code_embeddings +from pyhealth.trainer import Trainer + + +def _synthetic_semantic_encoder(texts: list[str]) -> np.ndarray: + """Deterministic toy text encoder mapping clinical keywords to 8-D vectors. + + In real workflows, replace this function with any OpenAI, HuggingFace, or + SentenceTransformers batch embedding call. + """ + cardiac_kw = ("hypertension", "coronary", "heart", "cardiac", "angina") + respiratory_kw = ("pneumonia", "asthma", "copd", "respiratory", "bronchitis") + vecs = np.zeros((len(texts), 8), dtype=np.float32) + for i, text in enumerate(texts): + lower = text.lower() + if any(k in lower for k in cardiac_kw): + vecs[i, :4] = 1.0 + elif any(k in lower for k in respiratory_kw): + vecs[i, 4:] = 1.0 + else: + vecs[i] = 0.1 + return vecs + + +def main() -> None: + torch.manual_seed(0) + + icd9_descriptions = { + "401.9": "Unspecified essential hypertension", + "414.01": "Coronary atherosclerosis of native coronary artery", + "428.0": "Congestive heart failure unspecified", + "486": "Pneumonia organism unspecified", + "493.90": "Asthma unspecified", + "496": "Chronic airway obstruction COPD", + } + icd10_descriptions = { + "I10": "Essential (primary) hypertension", + "I25.10": "Atherosclerotic heart disease without angina pectoris", + "I50.9": "Heart failure unspecified", + "J18.9": "Pneumonia unspecified organism", + "J45.909": "Unspecified asthma uncomplicated", + "J44.9": "Chronic obstructive pulmonary disease unspecified", + } + + icd9_embs = build_llm_code_embeddings( + icd9_descriptions.keys(), + encoder_fn=_synthetic_semantic_encoder, + code_descriptions=icd9_descriptions, + normalize=True, + ) + icd10_embs = build_llm_code_embeddings( + icd10_descriptions.keys(), + encoder_fn=_synthetic_semantic_encoder, + code_descriptions=icd10_descriptions, + normalize=True, + ) + + # Build a small ICD-9 source dataset (label=1 for cardiac history, 0 for respiratory) + cardiac_icd9 = ["401.9", "414.01", "428.0"] + resp_icd9 = ["486", "493.90", "496"] + source_samples = [] + for i in range(40): + pos = i % 2 == 0 + codes = cardiac_icd9 if pos else resp_icd9 + source_samples.append( + { + "patient_id": f"src_{i}", + "codes": codes[: 2 + (i % 2)], + "label": int(pos), + } + ) + + source_ds = create_sample_dataset( + samples=source_samples, + input_schema={"codes": "sequence"}, + output_schema={"label": "binary"}, + dataset_name="icd9_source_demo", + ) + train_ds, val_ds, _ = split_by_patient(source_ds, [0.75, 0.25, 0.0], seed=42) + train_loader = get_dataloader(train_ds, batch_size=8, shuffle=True) + val_loader = get_dataloader(val_ds, batch_size=8, shuffle=False) + + model = LLMCodeTransfer( + dataset=source_ds, + code_embeddings=icd9_embs, + embed_dim=16, + depth=2, + num_heads=4, + ) + trainer = Trainer(model=model, metrics=["roc_auc", "accuracy"]) + trainer.train( + train_dataloader=train_loader, + val_dataloader=val_loader, + epochs=15, + optimizer_params={"lr": 5e-3}, + monitor="roc_auc", + ) + + # Zero-shot transfer to ICD-10 without retraining on target labels + cardiac_icd10 = ["I10", "I25.10", "I50.9"] + resp_icd10 = ["J18.9", "J45.909", "J44.9"] + target_samples = [ + { + "patient_id": f"tgt_{i}", + "codes": (cardiac_icd10 if i % 2 == 0 else resp_icd10)[: 2 + (i % 2)], + "label": int(i % 2 == 0), + } + for i in range(20) + ] + target_ds = create_sample_dataset( + samples=target_samples, + input_schema={"codes": "sequence"}, + output_schema={"label": "binary"}, + dataset_name="icd10_target_demo", + ) + target_model = model.transfer_to_dataset(target_ds, icd10_embs) + target_loader = get_dataloader(target_ds, batch_size=8, shuffle=False) + zero_shot_metrics = Trainer( + model=target_model, metrics=["roc_auc", "accuracy"] + ).evaluate(target_loader) + print(f"Zero-shot ICD-9 -> ICD-10 metrics: {zero_shot_metrics}") + + +if __name__ == "__main__": + main() diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 3bd1f4baa4..cb880abb7f 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -239,3 +239,11 @@ CausalTemporalBlock as CausalTemporalBlock, ) from .cnn2d_lstm import CNN2DLSTM as CNN2DLSTM +from .llm_code_transfer import ( + LLMCodeEmbedding as LLMCodeEmbedding, + LLMCodeTransfer as LLMCodeTransfer, + PositionalEncoding1D as PositionalEncoding1D, + PositionalEncoding2D as PositionalEncoding2D, + build_llm_code_embeddings as build_llm_code_embeddings, + load_llm_code_embeddings as load_llm_code_embeddings, +) diff --git a/pyhealth/models/llm_code_transfer.py b/pyhealth/models/llm_code_transfer.py new file mode 100644 index 0000000000..3a44ff4188 --- /dev/null +++ b/pyhealth/models/llm_code_transfer.py @@ -0,0 +1,1629 @@ +"""LLM Code-Embedding Transfer for Cross-Coding-System EHR Prediction. + +Paper: + Kirchler, M., et al. "Transferring EHR predictors across coding systems + via large language model embeddings." *npj Digital Medicine* (2026). + https://doi.org/10.1038/s41746-026-02363-5 + +Official repository: + https://github.com/mkirchler/grasp + +Adapted ``PositionalEncoding1D``, ``PositionalEncoding2D``, and Pre-LN Set +Transformer components from ``mkirchler/grasp`` (MIT License): + +.. code-block:: text + + MIT License + + Copyright (c) 2025 mkirchler + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +""" + +from __future__ import annotations + +import csv +import math +from collections.abc import Callable, Iterable, Mapping +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn + +from pyhealth.datasets import SampleDataset +from pyhealth.models.base_model import BaseModel +from pyhealth.processors import ( + MultiHotProcessor, + NestedSequenceProcessor, + SequenceProcessor, +) + +__all__ = [ + "LLMCodeEmbedding", + "LLMCodeTransfer", + "PositionalEncoding1D", + "PositionalEncoding2D", + "build_llm_code_embeddings", + "load_llm_code_embeddings", +] + + +def _normalize_vectors( + vectors: dict[str, torch.Tensor], + normalize: bool, +) -> dict[str, torch.Tensor]: + """Optionally L2-normalizes a dictionary of 1D float tensors.""" + if not normalize: + return vectors + out: dict[str, torch.Tensor] = {} + for code, vec in vectors.items(): + norm = vec.norm(p=2).clamp_min(1e-12) + out[code] = vec / norm + return out + + +def load_llm_code_embeddings( + source: Mapping[str, Any] | str | Path, + embedding_dim: int | None = None, + normalize: bool = False, +) -> dict[str, torch.Tensor]: + """Loads precomputed LLM medical code embeddings from memory or disk. + + Supports: + - In-memory ``dict``/``Mapping`` from code string to 1D vector. + - ``.csv`` / ``.tsv`` files (with optional header row such as + ``concept,embdim_0,embdim_1,...``, matching ``mkirchler/grasp``). + - ``.pt`` / ``.pth`` files storing a mapping of code names to tensors. + - ``.npz`` archives storing either ``("codes", "embeddings")`` arrays or + per-code array entries. + + Args: + source: Mapping of code strings to vectors, or path to a ``.csv``, + ``.tsv``, ``.pt``, ``.pth``, or ``.npz`` file. + embedding_dim: Expected vector dimensionality. When ``None``, inferred + from the loaded vectors and checked for consistency. + normalize: If ``True``, L2-normalizes every embedding vector. + + Returns: + Dictionary mapping code strings to 1D ``torch.float32`` tensors. + + Examples: + >>> import torch + >>> from pyhealth.models import load_llm_code_embeddings + >>> raw = {"401.9": [1.0, 0.0, 0.0], "250.00": torch.tensor([0.0, 2.0, 0.0])} + >>> loaded = load_llm_code_embeddings(raw, normalize=True) + >>> sorted(loaded.keys()) + ['250.00', '401.9'] + >>> round(loaded["250.00"].norm().item(), 4) + 1.0 + """ + if isinstance(source, Mapping): + result: dict[str, torch.Tensor] = {} + inferred_dim = embedding_dim + for raw_key, raw_vec in source.items(): + code = str(raw_key).strip() + if not code: + continue + if isinstance(raw_vec, torch.Tensor): + vec = raw_vec.detach().to(dtype=torch.float32, device="cpu") + else: + vec = torch.as_tensor(np.asarray(raw_vec), dtype=torch.float32) + if vec.ndim != 1: + raise ValueError( + f"Embedding for '{code}' must be 1D, got shape {tuple(vec.shape)}." + ) + if inferred_dim is None: + inferred_dim = vec.shape[0] + elif vec.shape[0] != inferred_dim: + raise ValueError( + f"Embedding for '{code}' has dimension {vec.shape[0]}, " + f"expected {inferred_dim}." + ) + result[code] = vec + return _normalize_vectors(result, normalize) + + if isinstance(source, (str, Path)): + path = Path(source) + if not path.exists(): + raise FileNotFoundError(f"LLM embedding file not found: {path}") + + ext = path.suffix.lower() + if ext in (".pt", ".pth"): + loaded = torch.load(path, map_location="cpu", weights_only=True) + if not isinstance(loaded, Mapping): + raise ValueError( + f"Expected a mapping in '{path}', got {type(loaded).__name__}." + ) + return load_llm_code_embeddings( + loaded, embedding_dim=embedding_dim, normalize=normalize + ) + + if ext == ".npz": + with np.load(path, allow_pickle=False) as archive: + if "codes" in archive and "embeddings" in archive: + codes = archive["codes"] + embs = archive["embeddings"] + if len(codes) != len(embs): + raise ValueError( + f"Mismatch in '{path}': {len(codes)} codes vs " + f"{len(embs)} embeddings." + ) + mapping = {str(c): embs[i] for i, c in enumerate(codes)} + else: + mapping = {str(k): archive[k] for k in archive.files} + return load_llm_code_embeddings( + mapping, embedding_dim=embedding_dim, normalize=normalize + ) + + if ext in (".csv", ".tsv"): + delimiter = "\t" if ext == ".tsv" else "," + rows_dict: dict[str, list[float]] = {} + with open(path, "r", encoding="utf-8", newline="") as handle: + reader = csv.reader(handle, delimiter=delimiter) + header_checked = False + for row in reader: + if not row: + continue + first = row[0].strip() + if not first or first.startswith("#"): + continue + if len(row) < 2: + continue + if not header_checked: + header_checked = True + try: + float(row[1]) + except ValueError: + # Header row such as `concept,embdim_0,...` + continue + vals = [float(x) for x in row[1:]] + rows_dict[first] = vals + return load_llm_code_embeddings( + rows_dict, embedding_dim=embedding_dim, normalize=normalize + ) + + raise ValueError( + f"Unsupported embedding file extension '{ext}'; expected one of " + "'.csv', '.tsv', '.pt', '.pth', or '.npz'." + ) + + raise TypeError( + f"Unsupported embedding source type: {type(source).__name__}. " + "Expected a mapping or a file path." + ) + + +def build_llm_code_embeddings( + codes: Iterable[str], + encoder_fn: Callable[[list[str]], np.ndarray | torch.Tensor], + code_descriptions: Mapping[str, str] | None = None, + normalize: bool = False, + batch_size: int = 64, +) -> dict[str, torch.Tensor]: + """Encodes medical codes into dense LLM vectors via a user encoder callable. + + Decouples PyHealth from any specific API client or local checkpoint: pass + any batch text-embedding function ``encoder_fn(texts) -> (B, D)`` (such as + OpenAI embeddings, SentenceTransformers, or a custom HuggingFace model). + + Args: + codes: Iterable of clinical code identifiers. + encoder_fn: Callable accepting a ``list[str]`` of text descriptions and + returning a 2D array or tensor of shape ``(len(texts), D)``. + code_descriptions: Optional map from code string to human-readable + description. Codes absent from this map fall back to the code + string itself. + normalize: If ``True``, L2-normalizes each returned vector. + batch_size: Number of descriptions passed per ``encoder_fn`` call. + + Returns: + Dictionary mapping each unique non-empty code string to its 1D + ``torch.float32`` embedding tensor. + + Examples: + >>> import numpy as np + >>> from pyhealth.models import build_llm_code_embeddings + >>> encoder = lambda texts: np.ones((len(texts), 4), dtype=np.float32) + >>> embs = build_llm_code_embeddings( + ... ["I10", "E11"], + ... encoder_fn=encoder, + ... code_descriptions={"I10": "Essential hypertension"}, + ... normalize=True, + ... ) + >>> sorted(embs.keys()) + ['E11', 'I10'] + >>> embs["I10"].shape + torch.Size([4]) + """ + if batch_size <= 0: + raise ValueError(f"batch_size must be positive, got {batch_size}.") + + unique_codes: list[str] = [] + seen: set[str] = set() + for raw in codes: + if raw is None: + continue + code = str(raw).strip() + if not code or code in seen: + continue + seen.add(code) + unique_codes.append(code) + + if not unique_codes: + return {} + + vectors: dict[str, torch.Tensor] = {} + for start in range(0, len(unique_codes), batch_size): + batch_codes = unique_codes[start : start + batch_size] + texts = [ + str(code_descriptions[c]) if (code_descriptions and c in code_descriptions) else c + for c in batch_codes + ] + encoded = encoder_fn(texts) + if isinstance(encoded, torch.Tensor): + batch_tensor = encoded.detach().to(dtype=torch.float32, device="cpu") + else: + batch_tensor = torch.as_tensor(np.asarray(encoded), dtype=torch.float32) + + if batch_tensor.ndim != 2 or batch_tensor.shape[0] != len(batch_codes): + raise ValueError( + f"encoder_fn must return shape ({len(batch_codes)}, D), " + f"got {tuple(batch_tensor.shape)}." + ) + for idx, code in enumerate(batch_codes): + vectors[code] = batch_tensor[idx].clone() + + return _normalize_vectors(vectors, normalize) + + +def _positional_encoding_1d( + d_model: int, + length: int, + normalized: bool = False, +) -> torch.Tensor: + """Computes a ``(length, d_model)`` 1D sinusoidal encoding table.""" + if d_model <= 0 or d_model % 2 != 0: + raise ValueError( + f"Cannot use 1D sin/cos positional encoding with odd/non-positive dim={d_model}." + ) + if length <= 0: + raise ValueError(f"bins/length must be positive, got {length}.") + + pe = torch.zeros(length, d_model, dtype=torch.float32) + position = torch.arange(0, length, dtype=torch.float32).unsqueeze(1) + div_term = torch.exp( + torch.arange(0, d_model, 2, dtype=torch.float32) + * -(math.log(10000.0) / d_model) + ) + pe[:, 0::2] = torch.sin(position * div_term) + pe[:, 1::2] = torch.cos(position * div_term) + if normalized: + pe = pe / pe.norm(dim=-1, keepdim=True).clamp_min(1e-12) + return pe + + +def _positional_encoding_2d( + d_model: int, + height: int, + width: int, + normalized: bool = False, +) -> torch.Tensor: + """Computes a ``(height, width, d_model)`` 2D sinusoidal encoding table.""" + if d_model <= 0 or d_model % 4 != 0: + raise ValueError( + f"Cannot use 2D sin/cos positional encoding with dim={d_model}; " + "must be a positive multiple of 4." + ) + if height <= 0 or width <= 0: + raise ValueError(f"bins_1 and bins_2 must be positive, got ({height}, {width}).") + + half = d_model // 2 + div_term = torch.exp( + torch.arange(0, half, 2, dtype=torch.float32) * -(math.log(10000.0) / half) + ) + pos_h = torch.arange(0, height, dtype=torch.float32).unsqueeze(1) + pos_w = torch.arange(0, width, dtype=torch.float32).unsqueeze(1) + + sin_w = torch.sin(pos_w * div_term) # (W, half/2) + cos_w = torch.cos(pos_w * div_term) # (W, half/2) + sin_h = torch.sin(pos_h * div_term) # (H, half/2) + cos_h = torch.cos(pos_h * div_term) # (H, half/2) + + pe = torch.zeros(height, width, d_model, dtype=torch.float32) + pe[:, :, 0:half:2] = sin_w.unsqueeze(0).expand(height, -1, -1) + pe[:, :, 1:half:2] = cos_w.unsqueeze(0).expand(height, -1, -1) + pe[:, :, half::2] = sin_h.unsqueeze(1).expand(-1, width, -1) + pe[:, :, half + 1 :: 2] = cos_h.unsqueeze(1).expand(-1, width, -1) + + if normalized: + pe = pe / pe.norm(dim=-1, keepdim=True).clamp_min(1e-12) + return pe + + +class PositionalEncoding1D(nn.Module): + """Binned 1D sinusoidal encoding for continuous clinical quantities (age or value). + + Maps scalar values in ``[min_val, max_val]`` onto ``bins`` discrete bins and + looks up sinusoidal vectors without leaving PyTorch or transferring to CPU. + + Args: + min_val: Lower clip bound of the input range. + max_val: Upper clip bound of the input range. + bins: Number of discretization bins. + emb_dim: Output embedding dimensionality (must be even). + eps: Small offset to keep clipped values strictly below ``max_val``. + add_learnable_constant: If ``True``, adds a learnable ``(emb_dim,)`` bias. + normalized: If ``True``, L2-normalizes each sinusoidal table entry. + + Examples: + >>> import torch + >>> from pyhealth.models import PositionalEncoding1D + >>> enc = PositionalEncoding1D(min_val=0.0, max_val=100.0, bins=51, emb_dim=16) + >>> out = enc(torch.tensor([25.0, 75.0])) + >>> out.shape + torch.Size([2, 16]) + """ + + def __init__( + self, + min_val: float = -5.0, + max_val: float = 5.0, + bins: int = 1001, + emb_dim: int = 64, + eps: float = 1e-6, + add_learnable_constant: bool = False, + normalized: bool = False, + ) -> None: + super().__init__() + if max_val <= min_val: + raise ValueError( + f"max_val ({max_val}) must be greater than min_val ({min_val})." + ) + self.min_val = float(min_val) + self.max_val = float(max_val) + self.bins = int(bins) + self.eps = float(eps) + + self.register_buffer( + "pos_embeddings", + _positional_encoding_1d(emb_dim, self.bins, normalized=normalized), + ) + self.register_buffer( + "positions", + torch.linspace(self.min_val, self.max_val, self.bins, dtype=torch.float32), + ) + if add_learnable_constant: + self.learnable_constant: nn.Parameter | torch.Tensor = nn.Parameter( + 0.02 * torch.randn(emb_dim) + ) + else: + self.register_buffer("learnable_constant", torch.zeros(emb_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Encodes a tensor of scalars into shape ``(*x.shape, emb_dim)``.""" + upper = max(self.min_val, self.max_val - self.eps) + clamped = x.to(dtype=torch.float32).clamp(self.min_val, upper) + idx = torch.bucketize(clamped, self.positions).clamp(0, self.bins - 1) + return self.pos_embeddings[idx] + self.learnable_constant + + +class PositionalEncoding2D(nn.Module): + """Joint 2D binned sinusoidal encoding for ``(age, value)`` pairs. + + Args: + min_val_1: Lower bound for first variable (e.g., age). + max_val_1: Upper bound for first variable. + bins_1: Number of bins along the first axis. + min_val_2: Lower bound for second variable (e.g., lab value). + max_val_2: Upper bound for second variable. + bins_2: Number of bins along the second axis. + emb_dim: Output embedding dimensionality (must be divisible by 4). + add_learnable_constant: If ``True``, adds a learnable ``(emb_dim,)`` bias. + eps: Small offset to keep clipped values strictly below upper bounds. + normalized: If ``True``, L2-normalizes each sinusoidal table entry. + + Examples: + >>> import torch + >>> from pyhealth.models import PositionalEncoding2D + >>> enc = PositionalEncoding2D( + ... min_val_1=0.0, max_val_1=100.0, bins_1=21, + ... min_val_2=-5.0, max_val_2=5.0, bins_2=21, + ... emb_dim=16, + ... ) + >>> out = enc(torch.tensor([40.0, 60.0]), torch.tensor([-1.0, 1.0])) + >>> out.shape + torch.Size([2, 16]) + """ + + def __init__( + self, + min_val_1: float = -5.0, + max_val_1: float = 5.0, + bins_1: int = 1001, + min_val_2: float = -5.0, + max_val_2: float = 5.0, + bins_2: int = 1001, + emb_dim: int = 64, + add_learnable_constant: bool = False, + eps: float = 1e-6, + normalized: bool = False, + ) -> None: + super().__init__() + if max_val_1 <= min_val_1: + raise ValueError( + f"max_val_1 ({max_val_1}) must be greater than min_val_1 ({min_val_1})." + ) + if max_val_2 <= min_val_2: + raise ValueError( + f"max_val_2 ({max_val_2}) must be greater than min_val_2 ({min_val_2})." + ) + self.min_val_1 = float(min_val_1) + self.max_val_1 = float(max_val_1) + self.bins_1 = int(bins_1) + self.min_val_2 = float(min_val_2) + self.max_val_2 = float(max_val_2) + self.bins_2 = int(bins_2) + self.eps = float(eps) + + self.register_buffer( + "pos_embeddings", + _positional_encoding_2d( + emb_dim, self.bins_1, self.bins_2, normalized=normalized + ), + ) + self.register_buffer( + "positions_1", + torch.linspace(self.min_val_1, self.max_val_1, self.bins_1, dtype=torch.float32), + ) + self.register_buffer( + "positions_2", + torch.linspace(self.min_val_2, self.max_val_2, self.bins_2, dtype=torch.float32), + ) + if add_learnable_constant: + self.learnable_constant: nn.Parameter | torch.Tensor = nn.Parameter( + 0.02 * torch.randn(emb_dim) + ) + else: + self.register_buffer("learnable_constant", torch.zeros(emb_dim)) + + def forward(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor: + """Encodes paired tensors of identical shape into ``(*x1.shape, emb_dim)``.""" + upper_1 = max(self.min_val_1, self.max_val_1 - self.eps) + upper_2 = max(self.min_val_2, self.max_val_2 - self.eps) + c1 = x1.to(dtype=torch.float32).clamp(self.min_val_1, upper_1) + c2 = x2.to(dtype=torch.float32).clamp(self.min_val_2, upper_2) + idx_1 = torch.bucketize(c1, self.positions_1).clamp(0, self.bins_1 - 1) + idx_2 = torch.bucketize(c2, self.positions_2).clamp(0, self.bins_2 - 1) + return self.pos_embeddings[idx_1, idx_2] + self.learnable_constant + + +class LLMCodeEmbedding(nn.Module): + """Lookup table mapping dataset token IDs to precomputed LLM code embeddings. + + Supports both sequence vocabs (with ``padding_idx=0``) and multi-hot vocabs + (with ``padding_idx=None``), as well as runtime vocabulary swapping via + :meth:`update_embeddings` for zero-shot cross-coding-system evaluation. + + Args: + code_vocab: Mapping from token string to dense integer index. + llm_embeddings: Precomputed code vectors (dict or file path). + embedding_dim: Dimensionality of the LLM vectors (inferred if ``None``). + freeze: If ``True`` (default), keeps the lookup weights frozen so + transfer across coding systems stays in the shared LLM space. + normalize: If ``True``, L2-normalizes stored vectors. + unknown_strategy: How to populate codes missing from ``llm_embeddings``: + ``"zero"`` (default) or ``"mean"`` of available vectors. + padding_idx: Padding token index to keep zeroed, or ``None``. + pad_token: Padding token name in ``code_vocab``. + unk_token: Unknown token name in ``code_vocab``. + + Examples: + >>> import torch + >>> from pyhealth.models import LLMCodeEmbedding + >>> vocab = {"": 0, "": 1, "401.9": 2, "250.00": 3} + >>> vecs = {"401.9": torch.ones(8), "250.00": torch.full((8,), 2.0)} + >>> layer = LLMCodeEmbedding(vocab, vecs) + >>> layer.coverage_ratio + 1.0 + >>> layer(torch.tensor([[2, 0]])).shape + torch.Size([1, 2, 8]) + """ + + def __init__( + self, + code_vocab: Mapping[Any, int], + llm_embeddings: Mapping[str, Any] | str | Path, + embedding_dim: int | None = None, + freeze: bool = True, + normalize: bool = False, + unknown_strategy: Literal["zero", "mean"] = "zero", + padding_idx: int | None = 0, + pad_token: str = "", + unk_token: str = "", + ) -> None: + super().__init__() + if unknown_strategy not in ("zero", "mean"): + raise ValueError( + f"unknown_strategy must be 'zero' or 'mean', got {unknown_strategy!r}." + ) + vectors = load_llm_code_embeddings( + llm_embeddings, embedding_dim=embedding_dim, normalize=normalize + ) + if not vectors and embedding_dim is None: + raise ValueError( + "llm_embeddings is empty and embedding_dim was not provided." + ) + inferred_dim = ( + embedding_dim if embedding_dim is not None else next(iter(vectors.values())).shape[0] + ) + + self.embedding_dim = int(inferred_dim) + self.freeze = bool(freeze) + self.normalize = bool(normalize) + self.unknown_strategy = unknown_strategy + self.padding_idx = padding_idx + self.pad_token = pad_token + self.unk_token = unk_token + + self._matched_codes: list[str] = [] + self._unmatched_codes: list[str] = [] + self.embedding = nn.Embedding( + max(1, len(code_vocab)), + self.embedding_dim, + padding_idx=padding_idx if (padding_idx is not None and len(code_vocab) > padding_idx) else None, + ) + self.update_embeddings(code_vocab, vectors, normalize=normalize) + + @property + def matched_codes(self) -> list[str]: + """List of non-special vocabulary codes found in ``llm_embeddings``.""" + return list(self._matched_codes) + + @property + def unmatched_codes(self) -> list[str]: + """List of non-special vocabulary codes missing from ``llm_embeddings``.""" + return list(self._unmatched_codes) + + @property + def coverage_ratio(self) -> float: + """Fraction of non-special vocabulary codes with a precomputed LLM vector.""" + total = len(self._matched_codes) + len(self._unmatched_codes) + if total == 0: + return 0.0 + return len(self._matched_codes) / total + + def update_embeddings( + self, + code_vocab: Mapping[Any, int], + llm_embeddings: Mapping[str, Any] | str | Path, + normalize: bool | None = None, + ) -> None: + """Rebuilds the embedding table for a new vocabulary and embedding source.""" + use_normalize = self.normalize if normalize is None else normalize + vectors = load_llm_code_embeddings( + llm_embeddings, embedding_dim=self.embedding_dim, normalize=use_normalize + ) + vocab_size = max(1, len(code_vocab)) + pad_idx = ( + self.padding_idx + if (self.padding_idx is not None and 0 <= self.padding_idx < vocab_size) + else None + ) + device = self.embedding.weight.device + weight = torch.zeros(vocab_size, self.embedding_dim, dtype=torch.float32) + + matched: list[str] = [] + unmatched: list[str] = [] + unmatched_indices: list[int] = [] + matched_tensors: list[torch.Tensor] = [] + + for raw_token, idx in code_vocab.items(): + tok_str = str(raw_token) + if idx == pad_idx or tok_str == self.pad_token: + continue + if tok_str == self.unk_token: + continue + vec = vectors.get(tok_str) + if vec is None: + vec = vectors.get(tok_str.strip()) + if vec is not None: + weight[idx] = vec + matched.append(tok_str) + matched_tensors.append(vec) + else: + unmatched.append(tok_str) + unmatched_indices.append(idx) + + if self.unknown_strategy == "mean" and unmatched_indices: + pool = matched_tensors if matched_tensors else list(vectors.values()) + if pool: + mean_vec = torch.stack(pool, dim=0).mean(dim=0) + if use_normalize: + mean_vec = mean_vec / mean_vec.norm(p=2).clamp_min(1e-12) + for idx in unmatched_indices: + weight[idx] = mean_vec + + if pad_idx is not None: + weight[pad_idx].zero_() + + new_emb = nn.Embedding( + num_embeddings=vocab_size, + embedding_dim=self.embedding_dim, + padding_idx=pad_idx, + ).to(device) + with torch.no_grad(): + new_emb.weight.copy_(weight.to(device)) + new_emb.weight.requires_grad_(not self.freeze) + self.embedding = new_emb + self._matched_codes = matched + self._unmatched_codes = unmatched + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Looks up precomputed LLM embeddings for integer token indices.""" + return self.embedding(x) + + +class _DropPath(nn.Module): + """Stochastic depth regularization per sample.""" + + def __init__(self, drop_prob: float = 0.0) -> None: + super().__init__() + self.drop_prob = float(drop_prob) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.drop_prob == 0.0 or not self.training: + return x + keep_prob = 1.0 - self.drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + return x * random_tensor.div(keep_prob) + + +class _Mlp(nn.Module): + """Position-wise feed-forward network inside each Transformer block.""" + + def __init__( + self, + in_features: int, + hidden_features: int | None = None, + drop: float = 0.0, + ) -> None: + super().__init__() + hidden = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden) + self.act = nn.GELU() + self.fc2 = nn.Linear(hidden, in_features) + self.drop = nn.Dropout(drop) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class _MultiHeadAttention(nn.Module): + """Multi-head self-attention with padding-mask support.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + use_opt_attention: bool = True, + ) -> None: + super().__init__() + if dim % num_heads != 0: + raise ValueError( + f"embed_dim ({dim}) must be divisible by num_heads ({num_heads})." + ) + self.use_opt_attention = use_opt_attention + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.attn_dropout_p = float(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + def forward( + self, + x: torch.Tensor, + mask: torch.Tensor | None = None, + ) -> torch.Tensor: + batch_size, seq_len, channels = x.shape + qkv = ( + self.qkv(x) + .reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim) + .permute(2, 0, 3, 1, 4) + ) + q, k, v = qkv[0], qkv[1], qkv[2] + + key_mask = None + if mask is not None: + # Broadcast over heads and query positions: (B, 1, 1, S) + key_mask = mask.unsqueeze(1).unsqueeze(2) + + if self.use_opt_attention: + drop_p = self.attn_dropout_p if self.training else 0.0 + out = F.scaled_dot_product_attention( + q, k, v, attn_mask=key_mask, dropout_p=drop_p + ) + else: + attn = (q * self.scale) @ k.transpose(-2, -1) + if key_mask is not None: + attn = attn.masked_fill(~key_mask, float("-inf")) + attn = torch.softmax(attn, dim=-1) + attn = self.attn_drop(attn) + out = attn @ v + + out = out.transpose(1, 2).reshape(batch_size, seq_len, channels) + out = self.proj(out) + out = self.proj_drop(out) + return out + + +class _Block(nn.Module): + """Pre-LN Transformer block with DropPath and optional LayerScale.""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + drop: float = 0.0, + drop_path: float = 0.0, + layer_scale_type: Literal["per_channel", "scalar"] | None = None, + layer_scale_init_value: float = 1e-4, + layer_norm_eps: float = 1e-6, + use_opt_attention: bool = True, + ) -> None: + super().__init__() + self.norm1 = nn.LayerNorm(dim, eps=layer_norm_eps) + self.attn = _MultiHeadAttention( + dim=dim, + num_heads=num_heads, + attn_drop=drop, + proj_drop=drop, + use_opt_attention=use_opt_attention, + ) + self.drop_path = _DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.norm2 = nn.LayerNorm(dim, eps=layer_norm_eps) + self.mlp = _Mlp( + in_features=dim, + hidden_features=int(dim * mlp_ratio), + drop=drop, + ) + + self.layer_scale_type = layer_scale_type + if layer_scale_type is not None: + if layer_scale_type == "per_channel": + gamma_shape = (1, 1, dim) + elif layer_scale_type == "scalar": + gamma_shape = (1, 1, 1) + else: + raise ValueError( + f"layer_scale_type must be None, 'per_channel', or 'scalar', " + f"got {layer_scale_type!r}." + ) + self.layer_scale_gamma1 = nn.Parameter( + torch.ones(gamma_shape) * layer_scale_init_value + ) + self.layer_scale_gamma2 = nn.Parameter( + torch.ones(gamma_shape) * layer_scale_init_value + ) + + def forward( + self, + x: torch.Tensor, + mask: torch.Tensor | None = None, + ) -> torch.Tensor: + attn_out = self.attn(self.norm1(x), mask=mask) + if self.layer_scale_type is not None: + attn_out = attn_out * self.layer_scale_gamma1 + x = x + self.drop_path(attn_out) + + mlp_out = self.mlp(self.norm2(x)) + if self.layer_scale_type is not None: + mlp_out = mlp_out * self.layer_scale_gamma2 + x = x + self.drop_path(mlp_out) + return x + + +class LLMCodeTransfer(BaseModel): + """LLM Code-Embedding Set Transformer for Cross-Coding-System EHR Transfer. + + Implements the frozen LLM code-embedding transfer architecture from + Kirchler et al. (*npj Digital Medicine*, 2026): medical codes from any + vocabulary (e.g., ICD-9, ICD-10, OMOP, ATC) are mapped to frozen LLM text + embeddings, optionally combined with 1D/2D binned sinusoidal encodings for + patient age and numeric values, projected to ``embed_dim``, and processed + by a Pre-LN Set Transformer with stochastic depth and optional LayerScale. + + Because no code-index embedding parameters are learned from scratch (when + ``freeze_embeddings=True``), a model trained on one coding system transfers + zero-shot to another coding system via :meth:`transfer_to_dataset` simply by + swapping the target vocabulary's precomputed LLM embedding table. + + Args: + dataset: PyHealth ``SampleDataset`` providing input and output schemas. + code_embeddings: Precomputed LLM code vectors. Either a single shared + source (dict or file path) applied to all code features, or a dict + mapping each code ``feature_key`` to its own embedding source. + llm_embedding_dim: Dimension of the frozen LLM code embeddings. If + ``None``, inferred from ``code_embeddings``. + embed_dim: Transformer hidden dimension. Default is ``64``. + depth: Number of Pre-LN Transformer blocks. Default is ``4``. + num_heads: Attention heads per block (``embed_dim % num_heads == 0``). + mlp_ratio: Feed-forward expansion ratio. Default is ``4.0``. + drop_rate: Dropout probability in attention/MLP/positional stage. + drop_path_rate: Maximum stochastic depth drop rate. Default is ``0.1``. + drop_path_type: ``"progressive"`` (linearly increasing across depth) or + ``"uniform"``. + layer_scale_type: Optional ``"per_channel"`` or ``"scalar"`` LayerScale. + layer_scale_init_value: Initial LayerScale multiplier. Default is ``1e-4``. + classifier_feature: ``"cls_token"`` (default) or ``"global_pool"``. + use_opt_attention: Whether to use ``F.scaled_dot_product_attention``. + freeze_embeddings: Freeze LLM code lookup weights (default ``True``). + normalize_embeddings: L2-normalize loaded LLM code vectors. + unknown_strategy: Fallback for unseen codes: ``"zero"`` or ``"mean"``. + age_key: Optional ``feature_keys`` entry supplying continuous ages. + value_key: Optional ``feature_keys`` entry supplying continuous values. + min_age: Minimum age bin bound when ``age_key`` is given. + max_age: Maximum age bin bound when ``age_key`` is given. + age_bins: Number of bins for age sinusoidal encoding. + min_val: Minimum value bin bound when ``value_key`` is given. + max_val: Maximum value bin bound when ``value_key`` is given. + val_bins: Number of bins for numeric value sinusoidal encoding. + positional_constant: Add a learnable bias inside sinusoidal encodings. + positional_embeddings_normalized: L2-normalize sinusoidal tables. + learnable_positional_factor: Learn the scale multiplier ``exp(factor)`` + on positional encodings instead of fixing it at ``1.0``. + nan_value: Sentinel numeric value treated identically to ``NaN`` (no + positional encoding added). Default is ``-9.0``. + + Examples: + >>> import torch + >>> from pyhealth.datasets import create_sample_dataset + >>> from pyhealth.models import LLMCodeTransfer + >>> samples = [ + ... {"patient_id": "p0", "codes": ["401.9", "250.00"], "label": 1}, + ... {"patient_id": "p1", "codes": ["414.01"], "label": 0}, + ... ] + >>> ds = create_sample_dataset( + ... samples, {"codes": "sequence"}, {"label": "binary"} + ... ) + >>> llm_vecs = { + ... "401.9": torch.tensor([1.0, 0.0, 1.0, 0.0]), + ... "250.00": torch.tensor([0.8, 0.2, 0.9, 0.1]), + ... "414.01": torch.tensor([-1.0, 0.0, -1.0, 0.0]), + ... } + >>> model = LLMCodeTransfer( + ... dataset=ds, code_embeddings=llm_vecs, embed_dim=16, depth=2, num_heads=4 + ... ) + >>> out = model(codes=torch.tensor([[2, 3], [4, 0]]), label=torch.tensor([[1.0], [0.0]])) + >>> sorted(out.keys()) + ['logit', 'loss', 'y_prob', 'y_true'] + """ + + def __init__( + self, + dataset: SampleDataset, + code_embeddings: Mapping[str, Any] | str | Path, + llm_embedding_dim: int | None = None, + embed_dim: int = 64, + depth: int = 4, + num_heads: int = 8, + mlp_ratio: float = 4.0, + drop_rate: float = 0.0, + drop_path_rate: float = 0.1, + drop_path_type: Literal["progressive", "uniform"] = "progressive", + layer_scale_type: Literal["per_channel", "scalar"] | None = None, + layer_scale_init_value: float = 1e-4, + classifier_feature: Literal["cls_token", "global_pool"] = "cls_token", + use_opt_attention: bool = True, + freeze_embeddings: bool = True, + normalize_embeddings: bool = False, + unknown_strategy: Literal["zero", "mean"] = "zero", + age_key: str | None = None, + value_key: str | None = None, + min_age: float = 0.0, + max_age: float = 100.0, + age_bins: int = 101, + min_val: float = -5.0, + max_val: float = 5.0, + val_bins: int = 101, + positional_constant: bool = False, + positional_embeddings_normalized: bool = False, + learnable_positional_factor: bool = False, + nan_value: float = -9.0, + ) -> None: + super().__init__(dataset) + if classifier_feature not in ("cls_token", "global_pool"): + raise ValueError( + f"classifier_feature must be 'cls_token' or 'global_pool', " + f"got {classifier_feature!r}." + ) + if drop_path_type not in ("progressive", "uniform"): + raise ValueError( + f"drop_path_type must be 'progressive' or 'uniform', got {drop_path_type!r}." + ) + if embed_dim <= 0: + raise ValueError(f"embed_dim must be positive, got {embed_dim}.") + if num_heads <= 0: + raise ValueError(f"num_heads must be positive, got {num_heads}.") + if depth < 0: + raise ValueError(f"depth must be non-negative, got {depth}.") + if embed_dim % num_heads != 0: + raise ValueError( + f"embed_dim ({embed_dim}) must be divisible by num_heads ({num_heads})." + ) + if len(self.label_keys) != 1: + raise ValueError( + f"LLMCodeTransfer expects a single label key, found {self.label_keys}." + ) + self.label_key = self.label_keys[0] + + if age_key is not None and age_key not in self.feature_keys: + raise ValueError( + f"age_key={age_key!r} is not in dataset feature_keys={self.feature_keys}." + ) + if value_key is not None and value_key not in self.feature_keys: + raise ValueError( + f"value_key={value_key!r} is not in dataset feature_keys={self.feature_keys}." + ) + self.age_key = age_key + self.value_key = value_key + self.nan_value = float(nan_value) + + aux_keys = {k for k in (age_key, value_key) if k is not None} + self.code_feature_keys = [k for k in self.feature_keys if k not in aux_keys] + if not self.code_feature_keys: + raise ValueError( + "Dataset must have at least one code feature key beyond age_key/value_key." + ) + + # Save architecture config for zero-shot transfer construction + self._init_config: dict[str, Any] = { + "embed_dim": embed_dim, + "depth": depth, + "num_heads": num_heads, + "mlp_ratio": mlp_ratio, + "drop_rate": drop_rate, + "drop_path_rate": drop_path_rate, + "drop_path_type": drop_path_type, + "layer_scale_type": layer_scale_type, + "layer_scale_init_value": layer_scale_init_value, + "classifier_feature": classifier_feature, + "use_opt_attention": use_opt_attention, + "freeze_embeddings": freeze_embeddings, + "normalize_embeddings": normalize_embeddings, + "unknown_strategy": unknown_strategy, + "age_key": age_key, + "value_key": value_key, + "min_age": min_age, + "max_age": max_age, + "age_bins": age_bins, + "min_val": min_val, + "max_val": max_val, + "val_bins": val_bins, + "positional_constant": positional_constant, + "positional_embeddings_normalized": positional_embeddings_normalized, + "learnable_positional_factor": learnable_positional_factor, + "nan_value": nan_value, + } + + per_field_sources = self._resolve_embedding_sources(code_embeddings) + + # Build code embedding tables (one per code feature) + self.code_embeddings = nn.ModuleDict() + self._field_types: dict[str, str] = {} + inferred_llm_dim = llm_embedding_dim + for field_name in self.code_feature_keys: + proc = self.dataset.input_processors[field_name] + if isinstance(proc, (SequenceProcessor, NestedSequenceProcessor)): + vocab = proc.code_vocab + padding_idx: int | None = 0 + self._field_types[field_name] = ( + "nested_sequence" + if isinstance(proc, NestedSequenceProcessor) + else "sequence" + ) + elif isinstance(proc, MultiHotProcessor): + vocab = proc.label_vocab + padding_idx = None + self._field_types[field_name] = "multi_hot" + else: + raise TypeError( + f"Unsupported processor {type(proc).__name__} for code feature " + f"{field_name!r}. Supported: SequenceProcessor, " + "NestedSequenceProcessor, MultiHotProcessor." + ) + + emb_layer = LLMCodeEmbedding( + code_vocab=vocab, + llm_embeddings=per_field_sources[field_name], + embedding_dim=inferred_llm_dim, + freeze=freeze_embeddings, + normalize=normalize_embeddings, + unknown_strategy=unknown_strategy, + padding_idx=padding_idx, + ) + inferred_llm_dim = emb_layer.embedding_dim + self.code_embeddings[field_name] = emb_layer + + assert inferred_llm_dim is not None + self.llm_embedding_dim = int(inferred_llm_dim) + self.embed_dim = int(embed_dim) + self.classifier_feature = classifier_feature + + # Positional encodings for continuous age / value + self.use_age_embeddings = age_key is not None + self.use_val_embeddings = value_key is not None + + self.age_only_embeddings: PositionalEncoding1D | None = None + self.val_only_embeddings: PositionalEncoding1D | None = None + self.both_embeddings: PositionalEncoding2D | None = None + + if self.use_age_embeddings: + self.age_only_embeddings = PositionalEncoding1D( + min_val=min_age, + max_val=max_age, + bins=age_bins, + emb_dim=embed_dim, + add_learnable_constant=positional_constant, + normalized=positional_embeddings_normalized, + ) + if self.use_val_embeddings: + self.val_only_embeddings = PositionalEncoding1D( + min_val=min_val, + max_val=max_val, + bins=val_bins, + emb_dim=embed_dim, + add_learnable_constant=positional_constant, + normalized=positional_embeddings_normalized, + ) + if self.use_age_embeddings and self.use_val_embeddings: + self.both_embeddings = PositionalEncoding2D( + min_val_1=min_age, + max_val_1=max_age, + bins_1=age_bins, + min_val_2=min_val, + max_val_2=max_val, + bins_2=val_bins, + emb_dim=embed_dim, + add_learnable_constant=positional_constant, + normalized=positional_embeddings_normalized, + ) + + if learnable_positional_factor: + self.positional_factor: nn.Parameter | torch.Tensor = nn.Parameter( + torch.zeros(1) + ) + else: + self.register_buffer("positional_factor", torch.zeros(1)) + + # Projection and Set Transformer backbone + self.token_embed = nn.Linear(self.llm_embedding_dim, embed_dim) + self.pos_drop = nn.Dropout(p=drop_rate) + if classifier_feature == "cls_token": + self.cls_token: nn.Parameter | None = nn.Parameter( + torch.zeros(1, 1, embed_dim) + ) + nn.init.trunc_normal_(self.cls_token, std=0.02) + else: + self.cls_token = None + + if depth <= 1 or drop_path_type == "uniform": + dpr = [float(drop_path_rate) for _ in range(depth)] + else: + dpr = [x.item() for x in torch.linspace(0.0, drop_path_rate, depth)] + + self.blocks = nn.ModuleList( + [ + _Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + drop=drop_rate, + drop_path=dpr[i], + layer_scale_type=layer_scale_type, + layer_scale_init_value=layer_scale_init_value, + use_opt_attention=use_opt_attention, + ) + for i in range(depth) + ] + ) + self.norm = nn.LayerNorm(embed_dim, eps=1e-6) + self.head = nn.Linear(embed_dim, self.label_processor.output_size()) + + self.apply(self._init_weights) + + def _init_weights(self, module: nn.Module) -> None: + if isinstance(module, nn.Linear): + nn.init.trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.constant_(module.bias, 0.0) + elif isinstance(module, nn.LayerNorm): + nn.init.constant_(module.bias, 0.0) + nn.init.constant_(module.weight, 1.0) + + def _resolve_embedding_sources( + self, + code_embeddings: Mapping[str, Any] | str | Path, + ) -> dict[str, Any]: + """Distinguishes per-field embedding dicts from a single shared source.""" + if ( + isinstance(code_embeddings, Mapping) + and code_embeddings + and all(isinstance(v, (Mapping, str, Path)) for v in code_embeddings.values()) + ): + unknown = [k for k in code_embeddings if k not in self.code_feature_keys] + if unknown: + raise ValueError( + f"Per-field code_embeddings contains unknown feature keys {unknown}; " + f"expected keys in {self.code_feature_keys}." + ) + missing = [k for k in self.code_feature_keys if k not in code_embeddings] + if missing: + raise ValueError( + f"Per-field code_embeddings is missing entries for {missing}." + ) + return {k: code_embeddings[k] for k in self.code_feature_keys} + return {k: code_embeddings for k in self.code_feature_keys} + + def _unwrap_tensor(self, value: Any, dtype: torch.dtype | None = None) -> torch.Tensor: + """Converts collated batch fields (possibly tuples or lists) to tensors.""" + if isinstance(value, tuple): + value = value[0] + if not isinstance(value, torch.Tensor): + value = torch.as_tensor(value) + if dtype is not None: + value = value.to(dtype=dtype) + return value.to(self.device) + + def _extract_code_embeddings( + self, + kwargs: Mapping[str, Any], + ) -> tuple[torch.Tensor, torch.Tensor]: + """Looks up code embeddings and validity masks for all code feature keys.""" + emb_parts: list[torch.Tensor] = [] + mask_parts: list[torch.Tensor] = [] + + for field_name in self.code_feature_keys: + if field_name not in kwargs: + raise KeyError( + f"Missing required feature '{field_name}' in batch kwargs." + ) + raw = self._unwrap_tensor(kwargs[field_name]) + ftype = self._field_types[field_name] + emb_layer = self.code_embeddings[field_name] + + if ftype == "sequence": + if raw.dim() == 1: + raw = raw.unsqueeze(0) + idx = raw.long() + mask = idx != 0 + emb = emb_layer(idx) + elif ftype == "nested_sequence": + if raw.dim() == 2: + raw = raw.unsqueeze(0) + batch_size = raw.shape[0] + idx = raw.reshape(batch_size, -1).long() + mask = idx != 0 + emb = emb_layer(idx) + else: + # MultiHotProcessor: extract active code indices per sample + if raw.dim() == 1: + raw = raw.unsqueeze(0) + batch_size = raw.shape[0] + active_lists = [ + torch.nonzero(raw[b] > 0, as_tuple=False).squeeze(-1) + for b in range(batch_size) + ] + max_len = max([len(a) for a in active_lists], default=0) + max_len = max(1, max_len) + idx = torch.zeros( + batch_size, max_len, dtype=torch.long, device=raw.device + ) + mask = torch.zeros( + batch_size, max_len, dtype=torch.bool, device=raw.device + ) + for b, active in enumerate(active_lists): + n_act = active.numel() + if n_act > 0: + idx[b, :n_act] = active + mask[b, :n_act] = True + emb = emb_layer(idx) * mask.unsqueeze(-1).to(dtype=torch.float32) + + emb_parts.append(emb) + mask_parts.append(mask) + + if len(emb_parts) == 1: + return emb_parts[0], mask_parts[0] + return torch.cat(emb_parts, dim=1), torch.cat(mask_parts, dim=1) + + def _align_aux_tensor( + self, + tensor: torch.Tensor, + batch_size: int, + seq_len: int, + ) -> torch.Tensor: + """Aligns continuous age or value tensor to shape ``(batch_size, seq_len)``.""" + t = tensor.to(device=self.device, dtype=torch.float32) + if t.dim() == 0: + t = t.view(1, 1).expand(batch_size, seq_len) + elif t.dim() == 1: + if t.shape[0] == batch_size: + t = t.unsqueeze(1).expand(batch_size, seq_len) + elif batch_size == 1 and t.shape[0] == seq_len: + t = t.unsqueeze(0) + else: + raise ValueError( + f"Cannot align 1D auxiliary tensor of shape {tuple(t.shape)} " + f"to ({batch_size}, {seq_len})." + ) + elif t.dim() == 2: + if t.shape == (batch_size, 1): + t = t.expand(batch_size, seq_len) + elif t.shape != (batch_size, seq_len): + raise ValueError( + f"Auxiliary tensor shape {tuple(t.shape)} does not match " + f"({batch_size}, {seq_len})." + ) + else: + t = t.reshape(batch_size, -1) + if t.shape[1] == 1: + t = t.expand(batch_size, seq_len) + elif t.shape[1] != seq_len: + raise ValueError( + f"Flattened auxiliary tensor shape {tuple(t.shape)} does not " + f"match ({batch_size}, {seq_len})." + ) + return t + + def _prepare_tokens( + self, + code_embs: torch.Tensor, + token_mask: torch.Tensor, + ages: torch.Tensor | None = None, + values: torch.Tensor | None = None, + ) -> torch.Tensor: + """Projects LLM code embeddings and adds optional age/value encodings.""" + x = self.token_embed(code_embs) + batch_size, seq_len, _ = x.shape + factor = self.positional_factor.exp() + + has_age = ( + (ages is not None) + and self.use_age_embeddings + and (self.age_only_embeddings is not None) + ) + has_val = ( + (values is not None) + and self.use_val_embeddings + and (self.val_only_embeddings is not None) + ) + + if has_age or has_val: + age_t = ( + self._align_aux_tensor(ages, batch_size, seq_len) + if ages is not None + else None + ) + val_t = ( + self._align_aux_tensor(values, batch_size, seq_len) + if values is not None + else None + ) + age_valid = ( + token_mask & (~torch.isnan(age_t)) & (age_t != self.nan_value) + if age_t is not None + else torch.zeros_like(token_mask) + ) + val_valid = ( + token_mask & (~torch.isnan(val_t)) & (val_t != self.nan_value) + if val_t is not None + else torch.zeros_like(token_mask) + ) + + both_mask = age_valid & val_valid + age_only_mask = age_valid & ~val_valid + val_only_mask = ~age_valid & val_valid + + pos_delta = torch.zeros_like(x) + if has_age: + assert age_t is not None and self.age_only_embeddings is not None + if age_only_mask.any(): + pos_delta[age_only_mask] = self.age_only_embeddings( + age_t[age_only_mask] + ).to(x.dtype) + if both_mask.any(): + if has_val and self.both_embeddings is not None: + assert val_t is not None + pos_delta[both_mask] = self.both_embeddings( + age_t[both_mask], val_t[both_mask] + ).to(x.dtype) + else: + pos_delta[both_mask] = self.age_only_embeddings( + age_t[both_mask] + ).to(x.dtype) + + if has_val: + assert val_t is not None and self.val_only_embeddings is not None + if val_only_mask.any(): + pos_delta[val_only_mask] = self.val_only_embeddings( + val_t[val_only_mask] + ).to(x.dtype) + if both_mask.any() and not has_age: + pos_delta[both_mask] = self.val_only_embeddings( + val_t[both_mask] + ).to(x.dtype) + + x = x + factor * pos_delta + + x = self.pos_drop(x) + x = x * token_mask.unsqueeze(-1).to(dtype=x.dtype) + return x + + def forward_from_embedding( + self, + inputs: Mapping[str, torch.Tensor] | torch.Tensor, + masks: Mapping[str, torch.Tensor] | torch.Tensor | None = None, + ages: torch.Tensor | None = None, + values: torch.Tensor | None = None, + return_embed: bool = False, + **kwargs: Any, + ) -> dict[str, torch.Tensor]: + """Runs the Transformer backbone directly from dense code embeddings. + + Args: + inputs: Dense LLM code embeddings as a tensor ``(B, N, llm_dim)`` or + a mapping ``{field_name: tensor}``. + masks: Optional boolean validity mask(s) of shape ``(B, N)``. + ages: Optional continuous age tensor for positional encoding. + values: Optional continuous value tensor for positional encoding. + return_embed: If ``True``, include ``"embed"`` in returned dict. + **kwargs: Optional label tensor under ``self.label_key``. + + Returns: + Dictionary containing ``"logit"``, ``"y_prob"``, and optionally + ``"loss"``, ``"y_true"``, and ``"embed"``. + """ + if isinstance(inputs, Mapping): + emb_parts: list[torch.Tensor] = [] + mask_parts: list[torch.Tensor] = [] + for field_name in self.code_feature_keys: + if field_name not in inputs: + raise KeyError( + f"Missing feature '{field_name}' in embedding inputs." + ) + t = inputs[field_name].to(device=self.device, dtype=torch.float32) + if t.dim() == 4: + # Flattened nested sequence embeddings (B, V, C, D) -> (B, V*C, D) + t = t.reshape(t.shape[0], -1, t.shape[-1]) + elif t.dim() == 2: + t = t.unsqueeze(1) + emb_parts.append(t) + if isinstance(masks, Mapping) and field_name in masks: + m = masks[field_name].to(device=self.device, dtype=torch.bool) + m = m.reshape(t.shape[0], -1) + else: + m = (t.abs().sum(dim=-1) > 0).to(dtype=torch.bool) + mask_parts.append(m) + code_embs = ( + emb_parts[0] if len(emb_parts) == 1 else torch.cat(emb_parts, dim=1) + ) + token_mask = ( + mask_parts[0] if len(mask_parts) == 1 else torch.cat(mask_parts, dim=1) + ) + else: + code_embs = inputs.to(device=self.device, dtype=torch.float32) + if code_embs.dim() == 4: + code_embs = code_embs.reshape( + code_embs.shape[0], -1, code_embs.shape[-1] + ) + elif code_embs.dim() == 2: + code_embs = code_embs.unsqueeze(1) + if isinstance(masks, torch.Tensor): + token_mask = masks.to(device=self.device, dtype=torch.bool).reshape( + code_embs.shape[0], -1 + ) + else: + token_mask = (code_embs.abs().sum(dim=-1) > 0).to(dtype=torch.bool) + + x = self._prepare_tokens(code_embs, token_mask, ages=ages, values=values) + batch_size = x.shape[0] + + if self.cls_token is not None: + cls_tokens = self.cls_token.expand(batch_size, -1, -1) + x = torch.cat((cls_tokens, x), dim=1) + cls_valid = torch.ones( + batch_size, 1, dtype=torch.bool, device=x.device + ) + attn_mask = torch.cat((cls_valid, token_mask), dim=1) + for block in self.blocks: + x = block(x, mask=attn_mask) + patient_emb = self.norm(x[:, 0]) + else: + if x.shape[1] == 0: + patient_emb = self.norm( + torch.zeros( + batch_size, self.embed_dim, device=x.device, dtype=x.dtype + ) + ) + else: + has_any = token_mask.any(dim=1) + safe_mask = token_mask.clone() + if not has_any.all(): + safe_mask[~has_any, 0] = True + for block in self.blocks: + x = block(x, mask=safe_mask) + weights = token_mask.unsqueeze(-1).to(dtype=x.dtype) + pooled = (x * weights).sum(dim=1) / weights.sum(dim=1).clamp_min(1.0) + patient_emb = self.norm(pooled) + + logits = self.head(patient_emb) + y_prob = self.label_processor.activation(logits) + results: dict[str, torch.Tensor] = { + "logit": logits, + "y_prob": y_prob, + } + if return_embed: + results["embed"] = patient_emb + + if self.label_key in kwargs: + y_true = self._unwrap_tensor(kwargs[self.label_key]) + loss = self.label_processor.loss(logits, y_true) + results["loss"] = loss + results["y_true"] = y_true + + return results + + def forward( + self, + return_embed: bool = False, + **kwargs: Any, + ) -> dict[str, torch.Tensor]: + """Forward pass from PyHealth dataset batch dictionaries.""" + code_embs, token_mask = self._extract_code_embeddings(kwargs) + ages = ( + self._unwrap_tensor(kwargs[self.age_key], dtype=torch.float32) + if self.age_key is not None and self.age_key in kwargs + else None + ) + values = ( + self._unwrap_tensor(kwargs[self.value_key], dtype=torch.float32) + if self.value_key is not None and self.value_key in kwargs + else None + ) + label_kwargs = ( + {self.label_key: kwargs[self.label_key]} + if self.label_key in kwargs + else {} + ) + return self.forward_from_embedding( + code_embs, + masks=token_mask, + ages=ages, + values=values, + return_embed=return_embed, + **label_kwargs, + ) + + def transfer_to_dataset( + self, + target_dataset: SampleDataset, + target_code_embeddings: Mapping[str, Any] | str | Path, + *, + freeze_embeddings: bool | None = None, + normalize_embeddings: bool | None = None, + unknown_strategy: Literal["zero", "mean"] | None = None, + ) -> LLMCodeTransfer: + """Creates a zero-shot transferred copy of this model on a new coding system. + + Copies all trained Transformer, projection, positional-encoding, and + classification head parameters into a new :class:`LLMCodeTransfer` + bound to ``target_dataset`` while building fresh LLM code lookup tables + for ``target_dataset``'s coding vocabulary. + + Args: + target_dataset: Target ``SampleDataset`` (e.g., ICD-10 or OMOP) + having compatible feature keys and output label size. + target_code_embeddings: Precomputed LLM embeddings for the target + dataset's vocabulary (dict, per-field dict, or file path). + freeze_embeddings: Override ``freeze_embeddings`` on the target + model (defaults to this model's setting). + normalize_embeddings: Override ``normalize_embeddings`` on the + target model (defaults to this model's setting). + unknown_strategy: Override ``unknown_strategy`` on the target model + (defaults to this model's setting). + + Returns: + New :class:`LLMCodeTransfer` instance on the same device as ``self``. + + Examples: + >>> import torch + >>> from pyhealth.datasets import create_sample_dataset + >>> from pyhealth.models import LLMCodeTransfer + >>> src_samples = [ + ... {"patient_id": "p0", "codes": ["401.9"], "label": 1}, + ... {"patient_id": "p1", "codes": ["414.01"], "label": 0}, + ... ] + >>> tgt_samples = [ + ... {"patient_id": "p2", "codes": ["I10"], "label": 1}, + ... {"patient_id": "p3", "codes": ["I25.10"], "label": 0}, + ... ] + >>> src_ds = create_sample_dataset(src_samples, {"codes": "sequence"}, {"label": "binary"}) + >>> tgt_ds = create_sample_dataset(tgt_samples, {"codes": "sequence"}, {"label": "binary"}) + >>> src_embs = {"401.9": torch.ones(4), "414.01": -torch.ones(4)} + >>> tgt_embs = {"I10": torch.ones(4), "I25.10": -torch.ones(4)} + >>> src_model = LLMCodeTransfer(src_ds, src_embs, embed_dim=8, depth=1, num_heads=2) + >>> tgt_model = src_model.transfer_to_dataset(tgt_ds, tgt_embs) + >>> tgt_model.code_embeddings["codes"].coverage_ratio + 1.0 + """ + cfg = dict(self._init_config) + if freeze_embeddings is not None: + cfg["freeze_embeddings"] = freeze_embeddings + if normalize_embeddings is not None: + cfg["normalize_embeddings"] = normalize_embeddings + if unknown_strategy is not None: + cfg["unknown_strategy"] = unknown_strategy + + transferred = LLMCodeTransfer( + dataset=target_dataset, + code_embeddings=target_code_embeddings, + llm_embedding_dim=self.llm_embedding_dim, + **cfg, + ) + if transferred.code_feature_keys != self.code_feature_keys: + raise ValueError( + f"Target dataset code_feature_keys {transferred.code_feature_keys} " + f"do not match source {self.code_feature_keys}." + ) + if ( + transferred.label_processor.output_size() + != self.label_processor.output_size() + ): + raise ValueError( + f"Target output_size ({transferred.label_processor.output_size()}) " + f"does not match source ({self.label_processor.output_size()})." + ) + + # Copy all shared backbone weights while preserving target LLMCodeEmbedding tables + src_state = self.state_dict() + tgt_state = transferred.state_dict() + for key, param in src_state.items(): + if key.startswith("code_embeddings."): + continue + tgt_state[key] = param.detach().clone() + transferred.load_state_dict(tgt_state) + transferred.to(self.device) + transferred.train(self.training) + return transferred diff --git a/tests/core/test_llm_code_transfer.py b/tests/core/test_llm_code_transfer.py new file mode 100644 index 0000000000..8a0a2b0534 --- /dev/null +++ b/tests/core/test_llm_code_transfer.py @@ -0,0 +1,599 @@ +"""Unit tests for LLMCodeTransfer and its embedding/positional components.""" + +import numpy as np +import pytest +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import ( + LLMCodeEmbedding, + LLMCodeTransfer, + PositionalEncoding1D, + PositionalEncoding2D, + build_llm_code_embeddings, + load_llm_code_embeddings, +) +from pyhealth.trainer import Trainer + + +def _make_seq_dataset(samples, task_type="binary", extra_input=None): + input_schema = {"codes": "sequence"} + if extra_input: + input_schema.update(extra_input) + return create_sample_dataset( + samples=samples, + input_schema=input_schema, + output_schema={"label": task_type}, + ) + + +class TestLoadAndBuildEmbeddings: + """Tests for load_llm_code_embeddings and build_llm_code_embeddings.""" + + def test_load_from_dict_and_normalize(self): + raw = { + " 401.9 ": [3.0, 4.0], + "250.00": np.array([0.0, 5.0], dtype=np.float32), + "414.01": torch.tensor([1.0, 1.0]), + " ": [1.0, 1.0], + } + loaded = load_llm_code_embeddings(raw, normalize=True) + assert set(loaded.keys()) == {"401.9", "250.00", "414.01"} + for vec in loaded.values(): + assert vec.dtype == torch.float32 + assert torch.isclose(vec.norm(), torch.tensor(1.0), atol=1e-5) + + def test_load_csv_tsv_pt_npz(self, tmp_path): + csv_path = tmp_path / "embs.csv" + csv_path.write_text( + "# comment line\n" + "concept,embdim_0,embdim_1,embdim_2\n" + "401.9,1.0,2.0,3.0\n" + "\n" + "250.00,4.0,5.0,6.0\n", + encoding="utf-8", + ) + csv_loaded = load_llm_code_embeddings(csv_path, embedding_dim=3) + assert torch.allclose(csv_loaded["401.9"], torch.tensor([1.0, 2.0, 3.0])) + + tsv_path = tmp_path / "embs.tsv" + tsv_path.write_text("I10\t0.5\t1.5\nE11\t2.5\t3.5\n", encoding="utf-8") + tsv_loaded = load_llm_code_embeddings(tsv_path) + assert torch.allclose(tsv_loaded["I10"], torch.tensor([0.5, 1.5])) + + pt_path = tmp_path / "embs.pt" + torch.save({"A": torch.tensor([1.0, 0.0])}, pt_path) + pt_loaded = load_llm_code_embeddings(pt_path) + assert torch.allclose(pt_loaded["A"], torch.tensor([1.0, 0.0])) + + npz_structured = tmp_path / "structured.npz" + np.savez( + npz_structured, + codes=np.array(["C1", "C2"]), + embeddings=np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32), + ) + npz_loaded = load_llm_code_embeddings(npz_structured) + assert torch.allclose(npz_loaded["C2"], torch.tensor([3.0, 4.0])) + + npz_keyed = tmp_path / "keyed.npz" + np.savez(npz_keyed, X1=np.array([7.0, 8.0], dtype=np.float32)) + assert torch.allclose( + load_llm_code_embeddings(npz_keyed)["X1"], torch.tensor([7.0, 8.0]) + ) + + def test_load_errors(self, tmp_path): + with pytest.raises(FileNotFoundError): + load_llm_code_embeddings(tmp_path / "missing.csv") + + bad_ext = tmp_path / "embs.txt" + bad_ext.write_text("a 1 2", encoding="utf-8") + with pytest.raises(ValueError, match="Unsupported embedding file extension"): + load_llm_code_embeddings(bad_ext) + + bad_pt = tmp_path / "bad.pt" + torch.save([1.0, 2.0], bad_pt) + with pytest.raises(ValueError, match="Expected a mapping"): + load_llm_code_embeddings(bad_pt) + + bad_npz = tmp_path / "bad_mismatch.npz" + np.savez(bad_npz, codes=np.array(["a"]), embeddings=np.zeros((2, 2))) + with pytest.raises(ValueError, match="Mismatch"): + load_llm_code_embeddings(bad_npz) + + with pytest.raises(ValueError, match="must be 1D"): + load_llm_code_embeddings({"a": [[1.0, 2.0]]}) + + with pytest.raises(ValueError, match="dimension"): + load_llm_code_embeddings({"a": [1.0, 2.0], "b": [1.0, 2.0, 3.0]}) + + with pytest.raises(TypeError): + load_llm_code_embeddings(12345) # type: ignore[arg-type] + + def test_build_llm_code_embeddings(self): + seen_batches = [] + + def encoder(texts): + seen_batches.append(texts) + return np.stack([np.full(4, float(len(t)), dtype=np.float32) for t in texts]) + + embs = build_llm_code_embeddings( + ["I10", "E11", "I10", None, " ", "J18"], + encoder_fn=encoder, + code_descriptions={"I10": "Essential hypertension"}, + normalize=True, + batch_size=2, + ) + assert seen_batches == [["Essential hypertension", "E11"], ["J18"]] + assert set(embs.keys()) == {"I10", "E11", "J18"} + assert embs["I10"].shape == (4,) + + assert build_llm_code_embeddings([], encoder_fn=encoder) == {} + + with pytest.raises(ValueError, match="batch_size"): + build_llm_code_embeddings(["I10"], encoder_fn=encoder, batch_size=0) + + with pytest.raises(ValueError, match="encoder_fn must return shape"): + build_llm_code_embeddings( + ["I10"], encoder_fn=lambda texts: np.zeros((2, 4)) + ) + + +class TestPositionalEncodings: + """Tests for PositionalEncoding1D and PositionalEncoding2D.""" + + def test_1d_and_2d_forward_and_clamping(self): + enc1 = PositionalEncoding1D( + min_val=0.0, + max_val=100.0, + bins=51, + emb_dim=16, + add_learnable_constant=True, + normalized=True, + ) + out1 = enc1(torch.tensor([-50.0, 0.0, 50.0, 100.0, 200.0])) + assert out1.shape == (5, 16) + assert not torch.isnan(out1).any() + assert torch.allclose(out1[0], out1[1]) + assert torch.allclose(out1[3], out1[4]) + + enc2 = PositionalEncoding2D( + min_val_1=0.0, + max_val_1=100.0, + bins_1=11, + min_val_2=-5.0, + max_val_2=5.0, + bins_2=11, + emb_dim=16, + add_learnable_constant=True, + normalized=True, + ) + out2 = enc2( + torch.tensor([[-10.0, 50.0], [150.0, 20.0]]), + torch.tensor([[-99.0, 0.0], [99.0, 1.0]]), + ) + assert out2.shape == (2, 2, 16) + assert not torch.isnan(out2).any() + + def test_invalid_positional_configs(self): + with pytest.raises(ValueError): + PositionalEncoding1D(min_val=5.0, max_val=5.0, emb_dim=8) + with pytest.raises(ValueError): + PositionalEncoding1D(emb_dim=7) + with pytest.raises(ValueError): + PositionalEncoding1D(bins=0, emb_dim=8) + with pytest.raises(ValueError): + PositionalEncoding2D(min_val_1=5.0, max_val_1=1.0, emb_dim=8) + with pytest.raises(ValueError): + PositionalEncoding2D(min_val_2=5.0, max_val_2=1.0, emb_dim=8) + with pytest.raises(ValueError): + PositionalEncoding2D(emb_dim=6) + with pytest.raises(ValueError): + PositionalEncoding2D(bins_1=0, emb_dim=8) + + +class TestLLMCodeEmbedding: + """Tests for LLMCodeEmbedding.""" + + def test_freeze_coverage_and_unknown_strategies(self): + vocab = {"": 0, "": 1, "401.9": 2, "250.00": 3, "MISSING": 4} + vecs = {"401.9": torch.tensor([1.0, 0.0]), "250.00": torch.tensor([3.0, 0.0])} + + emb_zero = LLMCodeEmbedding(vocab, vecs, freeze=True, unknown_strategy="zero") + assert emb_zero.coverage_ratio == pytest.approx(2 / 3) + assert set(emb_zero.matched_codes) == {"401.9", "250.00"} + assert emb_zero.unmatched_codes == ["MISSING"] + assert not emb_zero.embedding.weight.requires_grad + assert torch.allclose(emb_zero.embedding.weight[0], torch.zeros(2)) + assert torch.allclose(emb_zero.embedding.weight[4], torch.zeros(2)) + + emb_mean = LLMCodeEmbedding( + vocab, vecs, freeze=False, normalize=True, unknown_strategy="mean" + ) + assert emb_mean.embedding.weight.requires_grad + assert torch.allclose(emb_mean.embedding.weight[0], torch.zeros(2)) + assert torch.isclose(emb_mean.embedding.weight[4].norm(), torch.tensor(1.0), atol=1e-5) + + emb_zero.update_embeddings( + {"": 0, "": 1, "I10": 2}, {"I10": [2.0, -1.0]} + ) + assert emb_zero.coverage_ratio == 1.0 + assert torch.allclose(emb_zero(torch.tensor([2])), torch.tensor([[2.0, -1.0]])) + + def test_invalid_embedding_args(self): + with pytest.raises(ValueError, match="unknown_strategy"): + LLMCodeEmbedding({"a": 0}, {"a": [1.0, 2.0]}, unknown_strategy="bad") # type: ignore[arg-type] + with pytest.raises(ValueError, match="empty"): + LLMCodeEmbedding({"a": 0}, {}) + + +class TestLLMCodeTransfer: + """Tests for LLMCodeTransfer model variants, Trainer, and zero-shot transfer.""" + + def _vecs(self): + return { + "401.9": torch.tensor([1.0, 0.0, 1.0, 0.0]), + "250.00": torch.tensor([0.9, 0.1, 0.8, 0.2]), + "414.01": torch.tensor([-1.0, 0.0, -1.0, 0.0]), + "486": torch.tensor([-0.8, -0.2, -0.9, -0.1]), + } + + def test_sequence_nested_multihot_and_multifield(self): + # Sequence + seq_ds = _make_seq_dataset( + [ + {"patient_id": "p0", "codes": ["401.9", "250.00"], "label": 1}, + {"patient_id": "p1", "codes": ["414.01"], "label": 0}, + ] + ) + model = LLMCodeTransfer( + seq_ds, + self._vecs(), + embed_dim=16, + depth=2, + num_heads=4, + layer_scale_type="per_channel", + ) + batch = next(iter(get_dataloader(seq_ds, batch_size=2))) + out = model(**batch, return_embed=True) + assert out["logit"].shape == (2, 1) + assert out["embed"].shape == (2, 16) + assert torch.isfinite(out["loss"]) + + # Nested sequence + global_pool + scalar LayerScale + manual attention + nested_ds = create_sample_dataset( + samples=[ + {"patient_id": "p0", "codes": [["401.9"], ["250.00"]], "label": 1}, + {"patient_id": "p1", "codes": [[]], "label": 0}, + ], + input_schema={"codes": "nested_sequence"}, + output_schema={"label": "binary"}, + ) + nested_model = LLMCodeTransfer( + nested_ds, + self._vecs(), + embed_dim=16, + depth=2, + num_heads=4, + drop_path_type="uniform", + layer_scale_type="scalar", + classifier_feature="global_pool", + use_opt_attention=False, + ) + nested_batch = next(iter(get_dataloader(nested_ds, batch_size=2))) + nested_out = nested_model(**nested_batch) + assert nested_out["logit"].shape == (2, 1) + assert torch.isfinite(nested_out["loss"]) + + # MultiHot + multi-field per-field embeddings + multi_ds = create_sample_dataset( + samples=[ + { + "patient_id": "p0", + "diag": ["401.9"], + "drug": ["250.00"], + "label": 1, + }, + { + "patient_id": "p1", + "diag": ["414.01"], + "drug": [], + "label": 0, + }, + ], + input_schema={"diag": "multi_hot", "drug": "multi_hot"}, + output_schema={"label": "binary"}, + ) + multi_model = LLMCodeTransfer( + multi_ds, + {"diag": self._vecs(), "drug": self._vecs()}, + embed_dim=16, + depth=1, + num_heads=4, + ) + multi_batch = next(iter(get_dataloader(multi_ds, batch_size=2))) + multi_out = multi_model(**multi_batch) + assert multi_out["logit"].shape == (2, 1) + assert torch.isfinite(multi_out["loss"]) + + @pytest.mark.parametrize( + "output_type,labels,expected_dim", + [ + ("multiclass", [0, 1, 2, 1], 3), + ("multilabel", [["a"], ["b"], ["a", "b"], ["c"]], 3), + ("regression", [1.5, 2.0, 3.5, 0.5], 1), + ], + ) + def test_label_modes(self, output_type, labels, expected_dim): + ds = _make_seq_dataset( + [ + {"patient_id": f"p{i}", "codes": ["401.9", "250.00"], "label": lbl} + for i, lbl in enumerate(labels) + ], + task_type=output_type, + ) + model = LLMCodeTransfer(ds, self._vecs(), embed_dim=16, depth=1, num_heads=4) + batch = next(iter(get_dataloader(ds, batch_size=4))) + out = model(**batch) + assert out["logit"].shape == (4, expected_dim) + assert torch.isfinite(out["loss"]) + + def test_age_and_value_positional_encodings(self): + ds = create_sample_dataset( + samples=[ + { + "patient_id": "p0", + "codes": ["401.9", "250.00", "414.01"], + "ages": [55.0, 55.0, -9.0], + "vals": [1.2, -9.0, 2.5], + "label": 1, + }, + { + "patient_id": "p1", + "codes": ["486", "401.9"], + "ages": [70.0, 70.0], + "vals": [float("nan"), 0.5], + "label": 0, + }, + ], + input_schema={ + "codes": "sequence", + "ages": "tensor", + "vals": "tensor", + }, + output_schema={"label": "binary"}, + ) + # Ensure padded sequence batches align cleanly with continuous tensors + model = LLMCodeTransfer( + ds, + self._vecs(), + embed_dim=16, + depth=2, + num_heads=4, + age_key="ages", + value_key="vals", + min_age=0.0, + max_age=100.0, + age_bins=21, + min_val=-5.0, + max_val=5.0, + val_bins=21, + positional_constant=True, + positional_embeddings_normalized=True, + learnable_positional_factor=True, + ) + # Test forward with scalar, matching 2D, and age-only / val-only variants + out = model( + codes=torch.tensor([[2, 3, 4], [5, 2, 0]]), + ages=torch.tensor([[55.0, 55.0, -9.0], [70.0, 70.0, 70.0]]), + vals=torch.tensor([[1.2, -9.0, 2.5], [float("nan"), 0.5, -9.0]]), + label=torch.tensor([[1.0], [0.0]]), + ) + assert out["logit"].shape == (2, 1) + assert torch.isfinite(out["loss"]) + + # Partial auxiliary inputs on a dual-key model should not raise + out_partial_age = model( + codes=torch.tensor([[2, 3, 4], [5, 2, 0]]), + ages=torch.tensor([55.0, 70.0]), + ) + assert out_partial_age["logit"].shape == (2, 1) + + out_partial_val = model( + codes=torch.tensor([[2, 3, 4], [5, 2, 0]]), + vals=torch.tensor([[1.2, -9.0, 2.5], [float("nan"), 0.5, -9.0]]), + ) + assert out_partial_val["logit"].shape == (2, 1) + + # Age-only and val-only models + ds_age = _make_seq_dataset( + [ + {"patient_id": "p0", "codes": ["401.9", "250.00"], "ages": [45.0], "label": 1}, + {"patient_id": "p1", "codes": ["486"], "ages": [65.0], "label": 0}, + ], + extra_input={"ages": "tensor"}, + ) + age_only_model = LLMCodeTransfer( + ds_age, self._vecs(), embed_dim=16, depth=1, num_heads=4, age_key="ages" + ) + assert age_only_model.val_only_embeddings is None + out_age = age_only_model( + codes=torch.tensor([[2, 3], [4, 0]]), + ages=torch.tensor([45.0, 65.0]), + ) + assert out_age["logit"].shape == (2, 1) + + ds_val = _make_seq_dataset( + [ + {"patient_id": "p0", "codes": ["401.9", "250.00"], "vals": [1.0, 2.0], "label": 1}, + {"patient_id": "p1", "codes": ["486", "401.9"], "vals": [-1.0, -9.0], "label": 0}, + ], + extra_input={"vals": "tensor"}, + ) + val_only_model = LLMCodeTransfer( + ds_val, self._vecs(), embed_dim=16, depth=1, num_heads=4, value_key="vals" + ) + out_val = val_only_model( + codes=torch.tensor([[2, 3], [4, 0]]), + vals=torch.tensor([[1.0, 2.0], [-1.0, -9.0]]), + ) + assert out_val["logit"].shape == (2, 1) + + def test_forward_from_embedding_variants(self): + ds = _make_seq_dataset( + [ + {"patient_id": "p0", "codes": ["401.9"], "label": 1}, + {"patient_id": "p1", "codes": ["414.01"], "label": 0}, + ] + ) + model = LLMCodeTransfer(ds, self._vecs(), embed_dim=16, depth=1, num_heads=4) + emb_tensor = torch.randn(2, 3, 4) + out = model.forward_from_embedding( + {"codes": emb_tensor}, + masks={"codes": torch.tensor([[True, True, False], [True, False, False]])}, + ) + assert out["logit"].shape == (2, 1) + + out4d = model.forward_from_embedding(torch.randn(2, 2, 3, 4)) + assert out4d["logit"].shape == (2, 1) + + with pytest.raises(KeyError): + model.forward_from_embedding({"wrong_key": emb_tensor}) + + def test_zero_shot_cross_coding_system_transfer_and_trainer(self): + torch.manual_seed(7) + # Disjoint vocabularies sharing latent semantic clusters + src_embs = { + "401.9": torch.tensor([1.0, 1.0, -1.0, -1.0]), + "414.01": torch.tensor([1.0, 0.8, -0.9, -1.0]), + "486": torch.tensor([-1.0, -1.0, 1.0, 1.0]), + "496": torch.tensor([-0.9, -1.0, 0.8, 1.0]), + } + tgt_embs = { + "I10": torch.tensor([1.0, 1.0, -1.0, -1.0]), + "I25.10": torch.tensor([0.9, 1.0, -1.0, -0.8]), + "J18.9": torch.tensor([-1.0, -0.9, 1.0, 1.0]), + "J44.9": torch.tensor([-1.0, -1.0, 0.9, 0.9]), + } + + src_samples = [ + { + "patient_id": f"src_{i}", + "codes": ["401.9", "414.01"] if i % 2 == 0 else ["486", "496"], + "label": int(i % 2 == 0), + } + for i in range(24) + ] + tgt_samples = [ + { + "patient_id": f"tgt_{i}", + "codes": ["I10", "I25.10"] if i % 2 == 0 else ["J18.9", "J44.9"], + "label": int(i % 2 == 0), + } + for i in range(16) + ] + + src_ds = _make_seq_dataset(src_samples) + tgt_ds = _make_seq_dataset(tgt_samples) + + model = LLMCodeTransfer( + dataset=src_ds, + code_embeddings=src_embs, + embed_dim=16, + depth=2, + num_heads=4, + drop_path_rate=0.0, + ) + train_loader = get_dataloader(src_ds, batch_size=8, shuffle=True) + trainer = Trainer(model=model, metrics=["accuracy"]) + trainer.train( + train_dataloader=train_loader, + epochs=15, + optimizer_params={"lr": 5e-3}, + ) + + model.eval() + transferred = model.transfer_to_dataset(tgt_ds, tgt_embs) + assert transferred is not model + assert transferred.training is False + assert transferred.code_embeddings["codes"].coverage_ratio == 1.0 + + # Evaluate zero-shot without any gradient updates on target data + tgt_loader = get_dataloader(tgt_ds, batch_size=8, shuffle=False) + metrics = Trainer(model=transferred, metrics=["accuracy"]).evaluate(tgt_loader) + assert metrics["accuracy"] >= 0.9 + + def test_validation_errors(self): + ds = _make_seq_dataset( + [ + {"patient_id": "p0", "codes": ["401.9"], "label": 1}, + {"patient_id": "p1", "codes": ["250.00"], "label": 0}, + ] + ) + vecs = self._vecs() + + with pytest.raises(ValueError, match="classifier_feature"): + LLMCodeTransfer(ds, vecs, embed_dim=16, num_heads=4, classifier_feature="bad") # type: ignore[arg-type] + with pytest.raises(ValueError, match="drop_path_type"): + LLMCodeTransfer(ds, vecs, embed_dim=16, num_heads=4, drop_path_type="bad") # type: ignore[arg-type] + with pytest.raises(ValueError, match="divisible"): + LLMCodeTransfer(ds, vecs, embed_dim=10, num_heads=4) + with pytest.raises(ValueError, match="embed_dim must be positive"): + LLMCodeTransfer(ds, vecs, embed_dim=0, num_heads=4) + with pytest.raises(ValueError, match="num_heads must be positive"): + LLMCodeTransfer(ds, vecs, embed_dim=16, num_heads=0) + with pytest.raises(ValueError, match="depth must be non-negative"): + LLMCodeTransfer(ds, vecs, embed_dim=16, num_heads=4, depth=-1) + with pytest.raises(ValueError, match="unknown feature keys"): + LLMCodeTransfer( + ds, {"codes": vecs, "typo": vecs}, embed_dim=16, num_heads=4 + ) + multi_ds = create_sample_dataset( + samples=[ + {"patient_id": "p0", "diag": ["401.9"], "drug": ["250.00"], "label": 1}, + {"patient_id": "p1", "diag": ["414.01"], "drug": ["486"], "label": 0}, + ], + input_schema={"diag": "sequence", "drug": "sequence"}, + output_schema={"label": "binary"}, + ) + with pytest.raises(ValueError, match="missing entries"): + LLMCodeTransfer(multi_ds, {"diag": vecs}, embed_dim=16, num_heads=4) + with pytest.raises(ValueError, match="layer_scale_type"): + LLMCodeTransfer(ds, vecs, embed_dim=16, num_heads=4, layer_scale_type="bad") # type: ignore[arg-type] + with pytest.raises(ValueError, match="age_key"): + LLMCodeTransfer(ds, vecs, embed_dim=16, num_heads=4, age_key="missing") + with pytest.raises(ValueError, match="value_key"): + LLMCodeTransfer(ds, vecs, embed_dim=16, num_heads=4, value_key="missing") + + tensor_only_ds = create_sample_dataset( + samples=[ + {"patient_id": "p0", "x": [1.0, 2.0], "label": 1}, + {"patient_id": "p1", "x": [3.0, 4.0], "label": 0}, + ], + input_schema={"x": "tensor"}, + output_schema={"label": "binary"}, + ) + with pytest.raises(TypeError, match="Unsupported processor"): + LLMCodeTransfer(tensor_only_ds, vecs, embed_dim=16, num_heads=4) + + no_code_ds = create_sample_dataset( + samples=[ + {"patient_id": "p0", "ages": [50.0], "label": 1}, + {"patient_id": "p1", "ages": [60.0], "label": 0}, + ], + input_schema={"ages": "tensor"}, + output_schema={"label": "binary"}, + ) + with pytest.raises(ValueError, match="at least one code feature"): + LLMCodeTransfer(no_code_ds, vecs, embed_dim=16, num_heads=4, age_key="ages") + + model = LLMCodeTransfer(ds, vecs, embed_dim=16, num_heads=4) + multiclass_ds = _make_seq_dataset( + [ + {"patient_id": "p0", "codes": ["401.9"], "label": 0}, + {"patient_id": "p1", "codes": ["250.00"], "label": 1}, + {"patient_id": "p2", "codes": ["414.01"], "label": 2}, + ], + task_type="multiclass", + ) + with pytest.raises(ValueError, match="output_size"): + model.transfer_to_dataset(multiclass_ds, vecs)