Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/api/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ API Reference
models/pyhealth.models.Transformer
models/pyhealth.models.BEHRT
models/pyhealth.models.BiteNet
models/pyhealth.models.BottleneckTransformer
models/pyhealth.models.TransformersModel
models/pyhealth.models.LLMEHREncoder
models/pyhealth.models.HFEHRFoundationModel
Expand Down
15 changes: 15 additions & 0 deletions docs/api/models/pyhealth.models.BottleneckTransformer.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
pyhealth.models.BottleneckTransformer
======================================


The shared bottleneck encoder and the complete Bottleneck Transformer model.

.. autoclass:: pyhealth.models.MultimodalBottleneckTransformerEncoder

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Autodoc target for the encoder is not exported from pyhealth.models

The page autodocs pyhealth.models.MultimodalBottleneckTransformerEncoder, but pyhealth/models/init.py only exports BottleneckTransformer (from .bottleneck_transformer import BottleneckTransformer as BottleneckTransformer). Sphinx will not resolve the class, so this part of the API page will be broken. Fix: point the autoclass at pyhealth.models.bottleneck_transformer.MultimodalBottleneckTransformerEncoder, or export the encoder from pyhealth/models/init.py and describe that export in the PR.

:members:
:undoc-members:
:show-inheritance:

.. autoclass:: pyhealth.models.BottleneckTransformer
:members:
:undoc-members:
:show-inheritance:
1 change: 1 addition & 0 deletions pyhealth/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
)
from .transformer_deid import TransformerDeID
from .biot import BIOT
from .bottleneck_transformer import BottleneckTransformer as BottleneckTransformer
from .cnn import CNN, CNNLayer
from .concare import ConCare, ConCareLayer
from .contrawr import ContraWR, ResBlock2D
Expand Down
540 changes: 540 additions & 0 deletions pyhealth/models/bottleneck_transformer.py

Large diffs are not rendered by default.

100 changes: 89 additions & 11 deletions pyhealth/models/ehrmamba.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from pyhealth.datasets import SampleDataset
from pyhealth.models import BaseModel
from pyhealth.models.embedding import EmbeddingModel
from pyhealth.datasets.utils import PAD_MASK_SUFFIX
from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel
from pyhealth.models.utils import get_last_visit
from pyhealth.processors import (
MultiHotProcessor,
Expand Down Expand Up @@ -111,13 +113,20 @@ class EHRMamba(BaseModel):
Electronic Health Records (arxiv 2405.14567). Uses Mamba (SSM) for linear
complexity in sequence length; supports long EHR sequences.

When ``unified_embedding`` is supplied the model switches to **unified
mode**: all temporal fields are jointly embedded and time-sorted by
:class:`UnifiedMultimodalEmbeddingModel`, then processed by a *single*
stack of :class:`MambaBlock` layers rather than one stack per field.

Args:
dataset: SampleDataset for token/embedding setup.
embedding_dim: Embedding and hidden dimension. Default 128.
num_layers: Number of Mamba blocks. Default 2.
state_size: SSM state size per channel. Default 16.
conv_kernel: Causal conv kernel size in block. Default 4.
dropout: Dropout before classification head. Default 0.1.
unified_embedding: Optional pre-built UnifiedMultimodalEmbeddingModel.
When provided, enables unified multi-modal mode.

Examples:
>>> from pyhealth.datasets import create_sample_dataset, get_dataloader
Expand All @@ -140,25 +149,25 @@ def __init__(
state_size: int = 16,
conv_kernel: int = 4,
dropout: float = 0.1,
unified_embedding: UnifiedMultimodalEmbeddingModel | None = None,
):
super().__init__(dataset=dataset)
self.embedding_dim = embedding_dim
self.num_layers = num_layers
self.state_size = state_size
self.conv_kernel = conv_kernel
self.dropout_rate = dropout
self._use_unified = unified_embedding is not None

assert len(self.label_keys) == 1, "EHRMamba supports single label key only"
self.label_key = self.label_keys[0]

self.embedding_model = EmbeddingModel(dataset, embedding_dim)
self.feature_processors = {
k: self.dataset.input_processors[k] for k in self.feature_keys
}
output_size = self.label_processor.output_size()
self.dropout = nn.Dropout(dropout)

self.blocks = nn.ModuleDict()
for feature_key in self.feature_keys:
self.blocks[feature_key] = nn.ModuleList(
if self._use_unified:
self.embedding_model = unified_embedding
self._unified_blocks = nn.ModuleList(
[
MambaBlock(
d_model=embedding_dim,
Expand All @@ -168,10 +177,76 @@ def __init__(
for _ in range(num_layers)
]
)

output_size = self.label_processor.output_size()
self.dropout = nn.Dropout(dropout)
self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size)
self.fc = nn.Linear(embedding_dim, output_size)
else:
self.embedding_model = EmbeddingModel(dataset, embedding_dim)
self.feature_processors = {
k: self.dataset.input_processors[k] for k in self.feature_keys
}
self.blocks = nn.ModuleDict()
for feature_key in self.feature_keys:
self.blocks[feature_key] = nn.ModuleList(
[
MambaBlock(
d_model=embedding_dim,
state_size=state_size,
conv_kernel=conv_kernel,
)
for _ in range(num_layers)
]
)
self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size)

def _build_unified_inputs(
self, kwargs: dict[str, Any]
) -> dict[str, dict[str, torch.Tensor]]:
"""Build the inputs dict required by UnifiedMultimodalEmbeddingModel."""
inputs: dict[str, dict[str, torch.Tensor]] = {}
for field_name in self.feature_keys:
feature = kwargs[field_name]
if isinstance(feature, torch.Tensor):
feature = (feature,)
schema = self.dataset.input_processors[field_name].schema()
field_dict: dict[str, torch.Tensor] = {}
if "value" in schema:
field_dict["value"] = feature[schema.index("value")].to(self.device)
if "time" in schema:
field_dict["time"] = feature[schema.index("time")].to(self.device)
if "mask" in schema:
field_dict["mask"] = feature[schema.index("mask")].to(self.device)
pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}")
if pad_mask is not None:
field_dict["pad_mask"] = pad_mask.to(self.device)
inputs[field_name] = field_dict
return inputs

def _forward_unified(self, **kwargs) -> dict[str, torch.Tensor]:
"""Forward pass in unified-embedding mode.

Calls UnifiedMultimodalEmbeddingModel to produce a single
temporally-sorted event sequence, then encodes it with one shared
MambaBlock stack and pools to the last valid event.
"""
inputs = self._build_unified_inputs(kwargs)
out = self.embedding_model(inputs)
x = out["sequence"] # (B, S_total, E)
mask = out["mask"].bool() # (B, S_total)

for blk in self._unified_blocks:
x = blk(x)

last_h = get_last_visit(x, mask)
logits = self.fc(self.dropout(last_h))
y_prob = self.label_processor.activation(logits)
results: dict[str, torch.Tensor] = {"y_prob": y_prob, "logit": logits}
# The label is optional, so the model can predict without it.
if self.label_key in kwargs:
y_true = kwargs[self.label_key].to(self.device)
results["loss"] = self.label_processor.loss(logits, y_true)
results["y_true"] = y_true
if kwargs.get("embed", False):
results["embed"] = last_h
return results

@staticmethod
def _split_temporal(feature: Any) -> Tuple[Optional[torch.Tensor], Any]:
Expand Down Expand Up @@ -222,6 +297,9 @@ def _pool_embedding(x: torch.Tensor) -> torch.Tensor:
return x

def forward(self, **kwargs) -> Dict[str, torch.Tensor]:
if self._use_unified:
return self._forward_unified(**kwargs)

patient_emb = []
embedding_inputs: Dict[str, torch.Tensor] = {}
masks: Dict[str, torch.Tensor] = {}
Expand Down
89 changes: 78 additions & 11 deletions pyhealth/models/jamba_ehr.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from pyhealth.datasets import SampleDataset
from pyhealth.models import BaseModel
from pyhealth.models.embedding import EmbeddingModel
from pyhealth.datasets.utils import PAD_MASK_SUFFIX
from pyhealth.models.unified_embedding import UnifiedMultimodalEmbeddingModel
from pyhealth.models.transformer import TransformerBlock
from pyhealth.models.ehrmamba import MambaBlock
from pyhealth.models.utils import get_last_visit
Expand Down Expand Up @@ -177,6 +179,11 @@ class JambaEHR(BaseModel):
by an independent :class:`JambaLayer`. The resulting patient embeddings
are concatenated and projected through a classification head.

When ``unified_embedding`` is supplied the model switches to **unified
mode**: all temporal fields are jointly embedded and time-sorted by
:class:`UnifiedMultimodalEmbeddingModel`, then processed by a *single*
:class:`JambaLayer` rather than one layer per field.

Args:
dataset (SampleDataset): Dataset providing processed inputs.
embedding_dim (int): Embedding and hidden dimension. Default 128.
Expand All @@ -186,6 +193,8 @@ class JambaEHR(BaseModel):
dropout (float): Dropout rate. Default 0.3.
state_size (int): SSM state size in Mamba blocks. Default 16.
conv_kernel (int): Causal conv kernel in Mamba blocks. Default 4.
unified_embedding (UnifiedMultimodalEmbeddingModel, optional): when
provided, enables unified multi-modal mode with a single JambaLayer.

Examples:
>>> from pyhealth.datasets import create_sample_dataset, get_dataloader
Expand Down Expand Up @@ -234,6 +243,7 @@ def __init__(
dropout: float = 0.3,
state_size: int = 16,
conv_kernel: int = 4,
unified_embedding: UnifiedMultimodalEmbeddingModel | None = None,
):
super(JambaEHR, self).__init__(dataset=dataset)
self.embedding_dim = embedding_dim
Expand All @@ -243,17 +253,19 @@ def __init__(
self.dropout_rate = dropout
self.state_size = state_size
self.conv_kernel = conv_kernel
self._use_unified = unified_embedding is not None

assert (
len(self.label_keys) == 1
), "Only one label key is supported if JambaEHR is initialized"
self.label_key = self.label_keys[0]

self.embedding_model = EmbeddingModel(dataset, embedding_dim)
output_size = self.label_processor.output_size()
self.dropout = nn.Dropout(dropout)

self.jamba: nn.ModuleDict = nn.ModuleDict()
for feature_key in self.feature_keys:
self.jamba[feature_key] = JambaLayer(
if self._use_unified:
self.embedding_model = unified_embedding
self._unified_jamba = JambaLayer(
feature_size=embedding_dim,
num_transformer_layers=num_transformer_layers,
num_mamba_layers=num_mamba_layers,
Expand All @@ -262,12 +274,62 @@ def __init__(
state_size=state_size,
conv_kernel=conv_kernel,
)
self.fc = nn.Linear(embedding_dim, output_size)
else:
self.embedding_model = EmbeddingModel(dataset, embedding_dim)
self.jamba: nn.ModuleDict = nn.ModuleDict()
for feature_key in self.feature_keys:
self.jamba[feature_key] = JambaLayer(
feature_size=embedding_dim,
num_transformer_layers=num_transformer_layers,
num_mamba_layers=num_mamba_layers,
heads=heads,
dropout=dropout,
state_size=state_size,
conv_kernel=conv_kernel,
)
self.fc = nn.Linear(len(self.feature_keys) * embedding_dim, output_size)

def _build_unified_inputs(
self, kwargs: dict[str, Any]
) -> dict[str, dict[str, torch.Tensor]]:
inputs: dict[str, dict[str, torch.Tensor]] = {}
for field_name in self.feature_keys:
feature = kwargs[field_name]
if isinstance(feature, torch.Tensor):
feature = (feature,)
schema = self.dataset.input_processors[field_name].schema()
field_dict: dict[str, torch.Tensor] = {}
if "value" in schema:
field_dict["value"] = feature[schema.index("value")].to(self.device)
if "time" in schema:
field_dict["time"] = feature[schema.index("time")].to(self.device)
if "mask" in schema:
field_dict["mask"] = feature[schema.index("mask")].to(self.device)
pad_mask = kwargs.get(f"{field_name}{PAD_MASK_SUFFIX}")
if pad_mask is not None:
field_dict["pad_mask"] = pad_mask.to(self.device)
inputs[field_name] = field_dict
return inputs

def _forward_unified(self, **kwargs: Any) -> dict[str, torch.Tensor]:
inputs = self._build_unified_inputs(kwargs)
out = self.embedding_model(inputs)
sequence = out["sequence"]
mask = out["mask"]

_, cls_emb = self._unified_jamba(sequence, mask)
logits = self.fc(self.dropout(cls_emb))
y_prob = self.label_processor.activation(logits)

output_size = self.label_processor.output_size()
self.dropout = nn.Dropout(dropout)
self.fc = nn.Linear(
len(self.feature_keys) * embedding_dim, output_size
)
results: dict[str, torch.Tensor] = {"logit": logits, "y_prob": y_prob}
if self.label_key in kwargs:
y_true = cast(torch.Tensor, kwargs[self.label_key]).to(self.device)
results["loss"] = self.label_processor.loss(logits, y_true)
results["y_true"] = y_true
if kwargs.get("embed", False):
results["embed"] = cls_emb
return results

@staticmethod
def _pool_embedding(x: torch.Tensor) -> torch.Tensor:
Expand Down Expand Up @@ -318,7 +380,9 @@ def forward(

Embeds each feature stream, encodes through the hybrid
Transformer-Mamba stack, concatenates per-stream patient
representations, and projects to label space.
representations, and projects to label space. In **unified mode**
(when ``unified_embedding`` was supplied at init) all temporal
fields share one time-sorted sequence through a single backbone.

Args:
**kwargs: Must include all feature keys (tensors or tuples
Expand All @@ -329,6 +393,9 @@ def forward(
``y_prob``, ``y_true``, ``logit``, and optionally
``embed`` if ``kwargs["embed"] is True``.
"""
if self._use_unified:
return self._forward_unified(**kwargs)

patient_emb = []

for feature_key in self.feature_keys:
Expand Down Expand Up @@ -477,4 +544,4 @@ def forward(
out = model_m(**batch)
print("keys:", sorted(out.keys()))
out["loss"].backward()
print("backward OK")
print("backward OK")
Loading
Loading