From 6ea9136dfedab5c55532c09525787a63c148cfad Mon Sep 17 00:00:00 2001 From: AxelNoun <150222552+AxelNoun@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:29:23 +0100 Subject: [PATCH 1/2] Add Brain Network Transformer for connectome classification Port BrainNetworkTransformer (Kan et al., NeurIPS 2022) from Wayfear/BrainNetworkTransformer (MIT License) without the omegaconf dependency. The model reads a square connectivity matrix, runs a transformer over the nodes and pools them with the orthonormal clustering readout. The number of nodes comes from the dataset, the classifier is sized by the label processor, and the attention weights and cluster assignments stay available. The encoder layer is written out instead of subclassing nn.TransformerEncoderLayer: the official override does not accept the is_causal argument of PyTorch 2, and its positional constructor call drops the layer biases on PyTorch 2.1 and later. bnt_parity_check.py loads the official weights into the port and finds identical logits and cluster assignments. abide_autism_bnt.py trains BNT, the GCN baseline and logistic regression on the same patient splits over several seeds. --- docs/api/models.rst | 1 + ...yhealth.models.BrainNetworkTransformer.rst | 35 + examples/fmri/abide_autism_bnt.py | 233 +++++++ examples/fmri/bnt_parity_check.py | 253 ++++++++ pyhealth/models/__init__.py | 1 + pyhealth/models/brain_network_transformer.py | 611 ++++++++++++++++++ tests/core/test_brain_network_transformer.py | 278 ++++++++ 7 files changed, 1412 insertions(+) create mode 100644 docs/api/models/pyhealth.models.BrainNetworkTransformer.rst create mode 100644 examples/fmri/abide_autism_bnt.py create mode 100644 examples/fmri/bnt_parity_check.py create mode 100644 pyhealth/models/brain_network_transformer.py create mode 100644 tests/core/test_brain_network_transformer.py diff --git a/docs/api/models.rst b/docs/api/models.rst index 033c3c43da..40131289fb 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -392,6 +392,7 @@ API Reference models/pyhealth.models.TextEmbedding models/pyhealth.models.BIOT models/pyhealth.models.LaBraM + models/pyhealth.models.BrainNetworkTransformer models/pyhealth.models.unified_multimodal_embedding_docs models/pyhealth.models.califorest models/pyhealth.models.XGBoostModel diff --git a/docs/api/models/pyhealth.models.BrainNetworkTransformer.rst b/docs/api/models/pyhealth.models.BrainNetworkTransformer.rst new file mode 100644 index 0000000000..3f79df9527 --- /dev/null +++ b/docs/api/models/pyhealth.models.BrainNetworkTransformer.rst @@ -0,0 +1,35 @@ +pyhealth.models.BrainNetworkTransformer +======================================= + +Overview +-------- + +Brain Network Transformer (BNT) classifies a brain network given as a square +connectivity matrix. Each region is a node whose features are its row of the +matrix; a transformer runs over the nodes, and an orthonormal clustering +readout (OCRead) pools them into soft clusters before a small classifier. It +takes the ``connectivity`` field of +:class:`~pyhealth.tasks.ABIDEAutismClassification` and reads the number of +nodes from the data, so any atlas works. + +The defaults are the authors' configuration: two transformer layers with 4 +heads, the second pooling the nodes into 100 clusters with frozen orthonormal +centres. The attention weights of the last forward pass are available from +:meth:`~pyhealth.models.BrainNetworkTransformer.get_attention_weights`, and +the cluster assignments from ``forward(..., return_assignments=True)``. + +``examples/fmri/abide_autism_bnt.py`` trains it on ABIDE next to the GCN and +logistic regression baselines, and ``examples/fmri/bnt_parity_check.py`` +compares this implementation with the official one. + +Paper: X. Kan, W. Dai, H. Cui, Z. Zhang, Y. Guo, C. Yang, `Brain Network +Transformer `_, NeurIPS 2022. Official +code: https://github.com/Wayfear/BrainNetworkTransformer (MIT License). + +API Reference +------------- + +.. autoclass:: pyhealth.models.BrainNetworkTransformer + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/fmri/abide_autism_bnt.py b/examples/fmri/abide_autism_bnt.py new file mode 100644 index 0000000000..2a35e329e5 --- /dev/null +++ b/examples/fmri/abide_autism_bnt.py @@ -0,0 +1,233 @@ +"""ABIDE I autism vs. control with Brain Network Transformer, and two baselines. + +Author: Axel Coiffard-Donaty +Paper: X. Kan, W. Dai, H. Cui, Z. Zhang, Y. Guo, C. Yang. "Brain Network + Transformer". NeurIPS 2022. https://arxiv.org/abs/2210.06681 +Description: Trains ``BrainNetworkTransformer`` on the cc200 connectivity + matrices of ``ABIDEAutismClassification``, and, for comparison on the + same splits, the ``BrainGCN`` of ``abide_autism_gcn.py`` and PyHealth's + ``LogisticRegression`` on the upper triangle. For each seed the scans are + split by patient 70/10/20 (one scan per subject), the model is trained + for ``--epochs`` epochs, the epoch with the best validation AUROC is + kept, and the test set is scored at that epoch. The script prints the + test AUROC, accuracy, sensitivity and specificity (threshold 0.5) of + every seed, then their mean and standard deviation. + + Training follows the authors' configuration for BNT: Adam, learning + rate 1e-4, weight decay 1e-4, batch size 16, 200 epochs, and continuous + mixup of the inputs and labels during training. Known differences with + the official run: the learning rate stays constant (the official run + decays it from 1e-4 to 1e-5 with a cosine schedule), PyHealth's + ``Trainer`` exempts biases and layer norms from weight decay (the + official run decays every parameter), the split is + stratified by neither site nor label, and the cohort is PyHealth's + (1,035 C-PAC scans) rather than the authors' preprocessed file (1,009 + subjects). The baselines keep the settings of their own examples + (``abide_autism_gcn.py`` and ``abide_autism_logistic_regression.py``: + Adam, learning rate 1e-3, no weight decay, batch size 32) with the same + epochs, splits and selection rule; mixup is applied to BNT only, as in + the paper. ``--lr``, ``--weight-decay`` and ``--batch-size`` override + the settings of the chosen model. + +Data: ABIDE Preprocessed (CC BY-NC-SA 3.0, non-commercial), + http://preprocessed-connectomes-project.org/abide/ ; ``--download`` + fetches it from the open ``fcp-indi`` S3 bucket (about 430 MB). + +Usage: + python examples/fmri/abide_autism_bnt.py --root /data/abide --download \\ + --model bnt --seeds 0 1 2 3 4 + python examples/fmri/abide_autism_bnt.py --root /data/abide \\ + --model gcn --seeds 0 1 2 3 4 +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +import numpy as np + +from pyhealth.datasets import ABIDEDataset, PatientSplit, get_dataloader +from pyhealth.models import BrainNetworkTransformer, LogisticRegression +from pyhealth.tasks import ABIDEAutismClassification +from pyhealth.trainer import Trainer + +# BrainGCN lives in the GCN example next to this file. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from abide_autism_gcn import BrainGCN + +SPLIT_RATIOS = (0.7, 0.1, 0.2) # train / validation / test, by patient +# Authors' configuration (source/conf in the official repository). +EPOCHS = 200 +# Optimizer settings per model: BNT follows the authors' configuration; the +# baselines follow their PyHealth examples (Trainer defaults, batch size 32). +SETTINGS = { + "bnt": {"lr": 1e-4, "weight_decay": 1e-4, "batch_size": 16}, + "gcn": {"lr": 1e-3, "weight_decay": 0.0, "batch_size": 32}, + "logistic_regression": {"lr": 1e-3, "weight_decay": 0.0, "batch_size": 32}, +} +MIXUP_ALPHA = 1.0 +THRESHOLD = 0.5 +# Hidden sizes of the GCN, as in abide_autism_gcn.py. +GCN_DIM = 64 + + +class MixupBrainNetworkTransformer(BrainNetworkTransformer): + """``BrainNetworkTransformer`` trained with continuous mixup. + + In training mode each batch is mixed with a shuffled copy of itself, + inputs and labels alike, with a weight drawn from Beta(alpha, alpha), as + ``continus_mixup_data`` does in the official code. Evaluation batches + are left unchanged. + + Args: + *args: Positional arguments of the parent class. + alpha: Parameter of the Beta distribution. Default is 1. + seed: Seed of the generator that draws the mixing weights and + permutations. + **kwargs: Keyword arguments of the parent class. + """ + + def __init__(self, *args, alpha: float = MIXUP_ALPHA, seed: int = 0, **kwargs): + super().__init__(*args, **kwargs) + self.alpha = alpha + self.rng = np.random.default_rng(seed) + + def forward(self, **kwargs): + """Mix the batch in training mode, then run the model.""" + import torch # after pyhealth; see the note in abide_autism_gcn.py + + label_key = self.label_keys[0] + if self.training and label_key in kwargs: + lam = float(self.rng.beta(self.alpha, self.alpha)) + x = kwargs[self.feature_key] + perm = torch.as_tensor(self.rng.permutation(x.shape[0])) + y = kwargs[label_key].float() + kwargs = dict(kwargs) + kwargs[self.feature_key] = lam * x + (1 - lam) * x[perm] + kwargs[label_key] = lam * y + (1 - lam) * y[perm] + return super().forward(**kwargs) + + +def parse_args() -> argparse.Namespace: + """Parse the command-line arguments. + + Returns: + The parsed arguments. + """ + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--root", required=True) + parser.add_argument("--download", action="store_true") + parser.add_argument("--max-subjects", type=int, default=None) + parser.add_argument( + "--model", choices=("bnt", "gcn", "logistic_regression"), default="bnt" + ) + parser.add_argument("--seeds", type=int, nargs="+", default=[0]) + parser.add_argument("--epochs", type=int, default=EPOCHS) + parser.add_argument("--lr", type=float, default=None) + parser.add_argument("--weight-decay", type=float, default=None) + parser.add_argument("--batch-size", type=int, default=None) + parser.add_argument("--no-mixup", action="store_true", help="BNT without mixup.") + parser.add_argument("--device", default=None, help="Default: cuda if available.") + return parser.parse_args() + + +def build_model(name: str, train, seed: int, mixup: bool): + """Create the model to train. + + Args: + name: ``"bnt"``, ``"gcn"`` or ``"logistic_regression"``. + train: The training SampleDataset. + seed: Seed of the mixup generator. + mixup: Use mixup for BNT. + + Returns: + The model. + """ + if name == "bnt": + if mixup: + return MixupBrainNetworkTransformer(dataset=train, seed=seed) + return BrainNetworkTransformer(dataset=train) + if name == "gcn": + return BrainGCN(dataset=train, embedding_dim=GCN_DIM, nhid=GCN_DIM) + return LogisticRegression(dataset=train) + + +def test_scores(trainer: Trainer, loader) -> dict[str, float]: + """Score the test set at the selected epoch. + + Args: + trainer: Trainer holding the selected model. + loader: Test dataloader. + + Returns: + AUROC, accuracy, sensitivity and specificity. + """ + from sklearn.metrics import roc_auc_score + + y_true, y_prob, _ = trainer.inference(loader) + y_true = np.asarray(y_true).ravel() + y_prob = np.asarray(y_prob).ravel() + y_pred = (y_prob > THRESHOLD).astype(int) + positives, negatives = y_true == 1, y_true == 0 + return { + "auroc": float(roc_auc_score(y_true, y_prob)), + "accuracy": float((y_pred == y_true).mean()), + "sensitivity": float((y_pred[positives] == 1).mean()), + "specificity": float((y_pred[negatives] == 0).mean()), + } + + +def main() -> None: + """Train and evaluate the chosen model over the seeds.""" + import torch # after pyhealth; see the note in abide_autism_gcn.py + + args = parse_args() + dataset = ABIDEDataset( + root=args.root, download=args.download, max_subjects=args.max_subjects + ) + task = ABIDEAutismClassification(vectorize=args.model == "logistic_regression") + settings = dict(SETTINGS[args.model]) + for key in settings: + if getattr(args, key) is not None: + settings[key] = getattr(args, key) + print(f"{args.model}: {settings}") + results = [] + for seed in args.seeds: + torch.manual_seed(seed) + np.random.seed(seed) + # One scan per subject, so a patient split does not leak. + train, val, test = dataset.set_task( + task, split=PatientSplit(ratios=SPLIT_RATIOS, seed=seed) + ) + print(f"seed {seed}: train={len(train)} val={len(val)} test={len(test)}") + model = build_model(args.model, train, seed, mixup=not args.no_mixup) + trainer = Trainer(model=model, metrics=["roc_auc"], device=args.device) + trainer.train( + train_dataloader=get_dataloader( + train, batch_size=settings["batch_size"], shuffle=True, seed=seed + ), + val_dataloader=get_dataloader(val, batch_size=settings["batch_size"]), + epochs=args.epochs, + optimizer_class=torch.optim.Adam, + optimizer_params={"lr": settings["lr"]}, + weight_decay=settings["weight_decay"], + monitor="roc_auc", + monitor_criterion="max", + ) + test_loader = get_dataloader(test, batch_size=settings["batch_size"]) + scores = test_scores(trainer, test_loader) + print(f"seed {seed} test: {scores}") + results.append(scores) + + print(f"\n{args.model}, {len(results)} seed(s), test set (%):") + for metric in results[0]: + values = 100 * np.array([r[metric] for r in results]) + # Sample standard deviation over seeds; 0 for a single seed. + std = values.std(ddof=1) if len(values) > 1 else 0.0 + print(f" {metric:12s} {values.mean():5.1f} +- {std:4.1f}") + + +if __name__ == "__main__": + main() diff --git a/examples/fmri/bnt_parity_check.py b/examples/fmri/bnt_parity_check.py new file mode 100644 index 0000000000..7b3180ad05 --- /dev/null +++ b/examples/fmri/bnt_parity_check.py @@ -0,0 +1,253 @@ +"""Check that the PyHealth port of Brain Network Transformer matches the original. + +Author: Axel Coiffard-Donaty +Paper: X. Kan, W. Dai, H. Cui, Z. Zhang, Y. Guo, C. Yang. "Brain Network + Transformer". NeurIPS 2022. https://arxiv.org/abs/2210.06681 +Description: Builds the official ``BrainNetworkTransformer`` and + ``pyhealth.models.BrainNetworkTransformer`` with the same configuration, + copies the official weights into the port, feeds both the same random + connectivity matrices in evaluation mode, and reports the largest + absolute difference of the logits and of the cluster assignments, in + single and double precision. It also checks that a freshly built port + initializes its cluster centres the same way as the official code from + the same random seed. The script exits with status 1 if a double- + precision difference exceeds ``--tolerance``. + + The official encoder layer was written for PyTorch 1.x and needs two + shims on PyTorch 2, applied here without changing what it computes: + its ``_sa_block`` override does not accept the ``is_causal`` argument + that PyTorch 2 passes, and its constructor passes ``device`` and + ``dtype`` by position, so that on PyTorch 2.1 and later ``device=None`` + lands on the new ``bias`` argument and the layer is built without any + bias. The shim passes them by keyword, which restores the biases of the + model the authors trained. + +Requirements: a clone of https://github.com/Wayfear/BrainNetworkTransformer + and ``pip install omegaconf``, which the official code imports. + +Usage: + git clone https://github.com/Wayfear/BrainNetworkTransformer /path/to/BNT + python examples/fmri/bnt_parity_check.py --official-repo /path/to/BNT +""" + +import argparse +import sys +from pathlib import Path + +import numpy as np +import torch + +from pyhealth.datasets import create_sample_dataset +from pyhealth.models import BrainNetworkTransformer + +SEED = 0 +BATCH_SIZE = 4 +# cc200 atlas, the authors' setting for ABIDE. +NODE_NUM = 200 +CLUSTERS = 100 +DEFAULT_TOLERANCE = 1e-9 + + +def parse_args() -> argparse.Namespace: + """Parse the command-line arguments. + + Returns: + The parsed arguments. + """ + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument( + "--official-repo", + required=True, + help="Path to a clone of https://github.com/Wayfear/BrainNetworkTransformer.", + ) + parser.add_argument("--tolerance", type=float, default=DEFAULT_TOLERANCE) + return parser.parse_args() + + +def official_model(repo: Path, pos_encoding: str) -> torch.nn.Module: + """Build the official model with the configuration of ``bnt.yaml``. + + Args: + repo: Clone of the official repository. + pos_encoding: ``"none"`` or ``"identity"``. + + Returns: + The official model. + """ + sys.path.insert(0, str(repo)) + from omegaconf import OmegaConf + from source.models.BNT import bnt, components + + layer = components.InterpretableTransformerEncoder + if not getattr(layer, "_pytorch2_shims", False): + original = layer._sa_block + + def _sa_block(self, x, attn_mask, key_padding_mask, is_causal=False): + return original(self, x, attn_mask, key_padding_mask) + + def __init__( + self, + d_model, + nhead, + dim_feedforward=2048, + dropout=0.1, + activation=torch.nn.functional.relu, + layer_norm_eps=1e-5, + batch_first=False, + norm_first=False, + device=None, + dtype=None, + ): + torch.nn.TransformerEncoderLayer.__init__( + self, + d_model, + nhead, + dim_feedforward=dim_feedforward, + dropout=dropout, + activation=activation, + layer_norm_eps=layer_norm_eps, + batch_first=batch_first, + norm_first=norm_first, + device=device, + dtype=dtype, + ) + self.attention_weights = None + + layer._sa_block = _sa_block + layer.__init__ = __init__ + layer._pytorch2_shims = True + + config = OmegaConf.create( + { + "dataset": {"node_sz": NODE_NUM}, + "model": { + "sizes": [360, CLUSTERS], + "pooling": [False, True], + "pos_encoding": pos_encoding, + "orthogonal": True, + "freeze_center": True, + "project_assignment": True, + "pos_embed_dim": NODE_NUM, + }, + } + ) + return bnt.BrainNetworkTransformer(config) + + +def port_model(pos_encoding: str) -> BrainNetworkTransformer: + """Build the port on a two-class dataset, so that it has two logits. + + Args: + pos_encoding: ``"none"`` or ``"identity"``. + + Returns: + The port. + """ + rng = np.random.default_rng(SEED) + samples = [ + { + "patient_id": f"p{i}", + "connectivity": rng.uniform(-1, 1, (NODE_NUM, NODE_NUM)).astype(np.float32), + "label": i % 2, + } + for i in range(4) + ] + dataset = create_sample_dataset( + samples=samples, + input_schema={"connectivity": "tensor"}, + output_schema={"label": "multiclass"}, + dataset_name="bnt_parity", + ) + return BrainNetworkTransformer(dataset, pos_encoding=pos_encoding) + + +def official_outputs(model, x): + """Logits and assignments of the official model, read with hooks.""" + assignments = [] + hooks = [ + layer.dec.register_forward_hook(lambda _m, _i, out: assignments.append(out[1])) + for layer in model.attention_list + if layer.pooling + ] + logits = model(None, x) + for hook in hooks: + hook.remove() + return logits, assignments + + +def main() -> int: + """Run the comparison. + + Returns: + 0 if every double-precision difference is within the tolerance, + 1 otherwise. + """ + args = parse_args() + repo = Path(args.official_repo) + worst = {torch.float32: 0.0, torch.float64: 0.0} + + # Same seed, same construction order: the cluster centres must match. + torch.manual_seed(SEED) + official_centres = ( + official_model(repo, "none").attention_list[1].dec.assignment.cluster_centers + ) + torch.manual_seed(SEED) + port_centres = port_model("none").attention_list[1].dec.assignment.cluster_centers + centre_diff = (official_centres - port_centres).abs().max().item() + print(f"initial cluster centres, max |diff| = {centre_diff:.3e}") + + for pos_encoding in ("none", "identity"): + torch.manual_seed(SEED) + official = official_model(repo, pos_encoding) + port = port_model(pos_encoding) + # The official layer registers the node encoder twice, under + # ``encoder`` and ``dec.encoder``; the port keeps only the second. + state = { + key: value + for key, value in official.state_dict().items() + if ".encoder." not in key or ".dec.encoder." in key + } + port.load_state_dict(state, strict=False) + missing = set(port.state_dict()) - set(state) - {"_dummy_param"} + unexpected = set(state) - set(port.state_dict()) + print( + f"{pos_encoding}: missing {sorted(missing)}, unexpected {sorted(unexpected)}" + ) + if missing or unexpected: + return 1 + official.eval() + port.eval() + generator = torch.Generator().manual_seed(SEED) + x = torch.rand(BATCH_SIZE, NODE_NUM, NODE_NUM, generator=generator) * 2 - 1 + for dtype in (torch.float32, torch.float64): + official.to(dtype) + port.to(dtype) + with torch.no_grad(): + ref_logits, ref_assign = official_outputs(official, x.to(dtype)) + out = port(connectivity=x.to(dtype), return_assignments=True) + diffs = { + "logits": (ref_logits - out["logit"]).abs().max().item(), + "assignments": max( + (a - b).abs().max().item() + for a, b in zip(ref_assign, out["assignments"]) + ), + } + for name, diff in diffs.items(): + worst[dtype] = max(worst[dtype], diff) + print( + f"{pos_encoding:8s} {str(dtype)[6:]:7s} {name:11s}: " + f"max |diff| = {diff:.3e}" + ) + + print(f"worst difference in float32: {worst[torch.float32]:.3e} (rounding)") + passed = worst[torch.float64] <= args.tolerance and centre_diff == 0.0 + print( + f"worst difference in float64: {worst[torch.float64]:.3e}, " + f"tolerance {args.tolerance:.0e}; centres identical: {centre_diff == 0.0}: " + f"{'PASS' if passed else 'FAIL'}" + ) + return 0 if passed else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 36227e5a5b..ea34d47da6 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -32,6 +32,7 @@ from .clip_stress import CLIPStress as CLIPStress from .transformer_deid import TransformerDeID from .biot import BIOT +from .brain_network_transformer import BrainNetworkTransformer as BrainNetworkTransformer from .camchex import CaMCheXMultiView as CaMCheXMultiView from .camchex import CaMCheXSingleView as CaMCheXSingleView from .cnn import CNN, CNNLayer diff --git a/pyhealth/models/brain_network_transformer.py b/pyhealth/models/brain_network_transformer.py new file mode 100644 index 0000000000..e69cd84951 --- /dev/null +++ b/pyhealth/models/brain_network_transformer.py @@ -0,0 +1,611 @@ +"""Brain Network Transformer for connectome classification. + +Author: Axel Coiffard-Donaty +Paper: X. Kan, W. Dai, H. Cui, Z. Zhang, Y. Guo, C. Yang. "Brain Network + Transformer". Advances in Neural Information Processing Systems + (NeurIPS), 2022. +Paper link: https://arxiv.org/abs/2210.06681 +Description: Port of ``BrainNetworkTransformer`` (``source/models/BNT/`` of + https://github.com/Wayfear/BrainNetworkTransformer, MIT License, + Copyright (c) 2022 Xuan Kan), whose cluster assignment comes from + https://github.com/vlukiyanov/pt-dec (MIT License). The model reads a + ``(nodes, nodes)`` connectivity matrix, uses each row as the feature + vector of its node, runs a transformer over the nodes and pools them into + soft clusters with orthonormal centres (OCRead). The ``omegaconf`` + configuration is replaced by arguments, the classification head is sized + by the label processor, and the encoder layer is written out so that it + does not depend on a private method of ``torch.nn.TransformerEncoderLayer``. + Parameter names follow the official code. +""" + +from collections.abc import Sequence +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from pyhealth.datasets import SampleDataset +from pyhealth.models import BaseModel + +# Hidden size of the MLP that encodes the nodes before the cluster +# assignment, fixed in the official ``TransPoolingEncoder``. +ENCODER_HIDDEN_DIM = 32 +# Width of each node after the final dimension reduction, and sizes of the +# classifier, fixed in the official ``BrainNetworkTransformer``. +REDUCED_NODE_DIM = 8 +CLASSIFIER_HIDDEN_DIMS = (256, 32) +# Defaults of ``torch.nn.TransformerEncoderLayer``, which the official +# encoder layer subclasses. +TRANSFORMER_DROPOUT = 0.1 +LAYER_NORM_EPS = 1e-5 + + +class InterpretableTransformerEncoderLayer(nn.Module): + """Post-norm transformer encoder layer that keeps its attention weights. + + Same computation and parameter names as + ``torch.nn.TransformerEncoderLayer(batch_first=True)`` with its default + ReLU activation and post-normalization. The attention weights of the last + forward pass, averaged over heads, are kept in ``attention_weights``. + + Args: + d_model: Token dimension. + nhead: Number of attention heads; must divide ``d_model``. + dim_feedforward: Hidden size of the feed-forward block. + dropout: Dropout probability. Default is 0.1. + + Examples: + >>> layer = InterpretableTransformerEncoderLayer(16, 4, 32) + >>> layer(torch.randn(2, 5, 16)).shape + torch.Size([2, 5, 16]) + >>> layer.attention_weights.shape + torch.Size([2, 5, 5]) + """ + + def __init__( + self, + d_model: int, + nhead: int, + dim_feedforward: int, + dropout: float = TRANSFORMER_DROPOUT, + ) -> None: + super().__init__() + if d_model % nhead != 0: + raise ValueError( + f"The node feature size ({d_model}) must be divisible by the " + f"number of heads ({nhead})." + ) + self.self_attn = nn.MultiheadAttention( + d_model, nhead, dropout=dropout, batch_first=True + ) + self.linear1 = nn.Linear(d_model, dim_feedforward) + self.dropout = nn.Dropout(dropout) + self.linear2 = nn.Linear(dim_feedforward, d_model) + self.norm1 = nn.LayerNorm(d_model, eps=LAYER_NORM_EPS) + self.norm2 = nn.LayerNorm(d_model, eps=LAYER_NORM_EPS) + self.dropout1 = nn.Dropout(dropout) + self.dropout2 = nn.Dropout(dropout) + self.attention_weights: torch.Tensor | None = None + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply the layer. + + Args: + x: Tokens of shape ``(batch, nodes, d_model)``. + + Returns: + Tokens of the same shape. + """ + attended, weights = self.self_attn(x, x, x, need_weights=True) + self.attention_weights = weights + x = self.norm1(x + self.dropout1(attended)) + feedforward = self.linear2(self.dropout(F.relu(self.linear1(x)))) + return self.norm2(x + self.dropout2(feedforward)) + + +def orthogonal_centers(centers: torch.Tensor) -> torch.Tensor: + """Orthogonalize cluster centres as the official code does. + + Classical Gram-Schmidt over the rows. Rows 1 and onward are scaled to unit + norm; row 0 keeps its norm, as in ``ClusterAssignment`` of the official + code. + + Args: + centers: Initial centres of shape ``(clusters, dimension)``, with at + most ``dimension`` rows. + + Returns: + Centres of the same shape, pairwise orthogonal. + + Examples: + >>> c = orthogonal_centers(torch.tensor([[2.0, 0.0], [1.0, 1.0]])) + >>> c + tensor([[2., 0.], + [0., 1.]]) + """ + centers = centers.clone() + out = torch.zeros_like(centers) + out[0] = centers[0] + for i in range(1, centers.shape[0]): + projection = torch.zeros_like(centers[i]) + for j in range(i): + u = centers[j] + projection = projection + (u @ centers[i]) / (u @ u) * u + centers[i] = centers[i] - projection + out[i] = centers[i] / torch.linalg.vector_norm(centers[i]) + return out + + +class ClusterAssignment(nn.Module): + """Soft assignment of node embeddings to cluster centres. + + With ``project_assignment`` (the BNT setting), the score of a node for a + centre is its squared projection on the centre divided by the centre's + norm, followed by a softmax over the centres. Otherwise the Student's t + kernel of deep embedded clustering (Xie et al., 2016) is used. + + Args: + cluster_number: Number of clusters. + embedding_dimension: Size of the node embeddings. + alpha: Degrees of freedom of the Student's t kernel. Default is 1. + orthogonal: Orthogonalize the initial centres. Default is True. + freeze_center: Keep the centres fixed during training. Default is + True. + project_assignment: Use the projection score. Default is True. + + Examples: + >>> assign = ClusterAssignment(cluster_number=3, embedding_dimension=8) + >>> probs = assign(torch.randn(5, 8)) + >>> probs.shape, bool(torch.allclose(probs.sum(dim=-1), torch.ones(5))) + (torch.Size([5, 3]), True) + """ + + def __init__( + self, + cluster_number: int, + embedding_dimension: int, + alpha: float = 1.0, + orthogonal: bool = True, + freeze_center: bool = True, + project_assignment: bool = True, + ) -> None: + super().__init__() + if orthogonal and cluster_number > embedding_dimension: + raise ValueError( + f"Cannot build {cluster_number} orthogonal centres in " + f"dimension {embedding_dimension}." + ) + self.alpha = alpha + self.project_assignment = project_assignment + centers = torch.zeros(cluster_number, embedding_dimension) + nn.init.xavier_uniform_(centers) + if orthogonal: + centers = orthogonal_centers(centers) + self.cluster_centers = nn.Parameter(centers, requires_grad=not freeze_center) + + def forward(self, batch: torch.Tensor) -> torch.Tensor: + """Assign embeddings to clusters. + + Args: + batch: Embeddings of shape ``(n, embedding_dimension)``. + + Returns: + Assignment probabilities of shape ``(n, cluster_number)``. + """ + if self.project_assignment: + scores = (batch @ self.cluster_centers.T) ** 2 + norm = torch.linalg.vector_norm(self.cluster_centers, dim=-1) + return torch.softmax(scores / norm, dim=-1) + squared = ((batch.unsqueeze(1) - self.cluster_centers) ** 2).sum(dim=2) + numerator = (1.0 / (1.0 + squared / self.alpha)) ** ((self.alpha + 1) / 2) + return numerator / numerator.sum(dim=1, keepdim=True) + + +class DEC(nn.Module): + """Encode the nodes, then pool them into cluster representations. + + The flattened node features of a graph go through ``encoder``; each node + is then softly assigned to the clusters, and each cluster representation + is the assignment-weighted sum of the encoded nodes. + + Args: + cluster_number: Number of clusters. + hidden_dimension: Size of each encoded node. + encoder: Module mapping ``(batch, nodes * hidden_dimension)`` to the + same shape. + alpha: Degrees of freedom of the Student's t kernel. Default is 1. + orthogonal: Orthogonalize the initial centres. Default is True. + freeze_center: Keep the centres fixed. Default is True. + project_assignment: Use the projection score. Default is True. + + Examples: + >>> dec = DEC(3, 4, nn.Identity()) + >>> pooled, assignment = dec(torch.randn(2, 6, 4)) + >>> pooled.shape, assignment.shape + (torch.Size([2, 3, 4]), torch.Size([2, 6, 3])) + """ + + def __init__( + self, + cluster_number: int, + hidden_dimension: int, + encoder: nn.Module, + alpha: float = 1.0, + orthogonal: bool = True, + freeze_center: bool = True, + project_assignment: bool = True, + ) -> None: + super().__init__() + self.encoder = encoder + self.assignment = ClusterAssignment( + cluster_number, + hidden_dimension, + alpha, + orthogonal=orthogonal, + freeze_center=freeze_center, + project_assignment=project_assignment, + ) + + def forward(self, batch: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Pool the nodes of a batch of graphs. + + Args: + batch: Node features of shape ``(batch, nodes, hidden_dimension)``. + + Returns: + Cluster representations of shape ``(batch, clusters, + hidden_dimension)`` and assignments of shape ``(batch, nodes, + clusters)``. + """ + batch_size, node_num, _ = batch.shape + encoded = self.encoder(batch.reshape(batch_size, -1)) + encoded = encoded.reshape(batch_size * node_num, -1) + assignment = self.assignment(encoded).reshape(batch_size, node_num, -1) + encoded = encoded.reshape(batch_size, node_num, -1) + return torch.bmm(assignment.transpose(1, 2), encoded), assignment + + +class TransPoolingEncoder(nn.Module): + """Transformer layer over the nodes, optionally followed by OCRead pooling. + + Args: + input_feature_size: Size of each node's features. + input_node_num: Number of input nodes. + hidden_size: Hidden size of the transformer feed-forward block. + output_node_num: Number of clusters when pooling. + pooling: Pool the nodes into ``output_node_num`` clusters. + num_heads: Number of attention heads. Default is 4. + dropout: Dropout of the transformer layer. Default is 0.1. + orthogonal: Orthogonalize the initial centres. Default is True. + freeze_center: Keep the centres fixed. Default is True. + project_assignment: Use the projection score. Default is True. + + Examples: + >>> layer = TransPoolingEncoder(8, 6, 16, 3, pooling=True) + >>> out, assignment = layer(torch.randn(2, 6, 8)) + >>> out.shape, assignment.shape + (torch.Size([2, 3, 8]), torch.Size([2, 6, 3])) + """ + + def __init__( + self, + input_feature_size: int, + input_node_num: int, + hidden_size: int, + output_node_num: int, + pooling: bool = True, + num_heads: int = 4, + dropout: float = TRANSFORMER_DROPOUT, + orthogonal: bool = True, + freeze_center: bool = True, + project_assignment: bool = True, + ) -> None: + super().__init__() + self.transformer = InterpretableTransformerEncoderLayer( + d_model=input_feature_size, + nhead=num_heads, + dim_feedforward=hidden_size, + dropout=dropout, + ) + self.pooling = pooling + if pooling: + flat = input_feature_size * input_node_num + encoder = nn.Sequential( + nn.Linear(flat, ENCODER_HIDDEN_DIM), + nn.LeakyReLU(), + nn.Linear(ENCODER_HIDDEN_DIM, ENCODER_HIDDEN_DIM), + nn.LeakyReLU(), + nn.Linear(ENCODER_HIDDEN_DIM, flat), + ) + self.dec = DEC( + cluster_number=output_node_num, + hidden_dimension=input_feature_size, + encoder=encoder, + orthogonal=orthogonal, + freeze_center=freeze_center, + project_assignment=project_assignment, + ) + + def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]: + """Encode, and pool when enabled. + + Args: + x: Node features of shape ``(batch, nodes, features)``. + + Returns: + The output nodes and the cluster assignment (None without + pooling). + """ + x = self.transformer(x) + if self.pooling: + return self.dec(x) + return x, None + + def get_attention_weights(self) -> torch.Tensor | None: + """Attention weights of the last forward pass, averaged over heads.""" + return self.transformer.attention_weights + + +class BrainNetworkTransformer(BaseModel): + """Brain Network Transformer (Kan et al., NeurIPS 2022). + + The input is one square connectivity matrix per sample, for example the + ``connectivity`` field of + :class:`~pyhealth.tasks.ABIDEAutismClassification` (``(200, 200)`` for + the cc200 atlas). Row ``i`` is the feature vector of brain region ``i``. + The nodes go through ``len(layer_sizes)`` transformer layers; a layer + whose ``pooling`` flag is set pools them into ``layer_sizes[i]`` soft + clusters with orthonormal, frozen centres (OCRead). Each output node is + reduced to 8 features, and the flattened result goes through a + three-layer classifier. + + The defaults are the authors' configuration: two layers, the first + keeping the nodes and the second pooling them into 100 clusters, 4 heads, + a feed-forward size of 1024, no positional encoding. The number of nodes + is read from the dataset, so any atlas works. With + ``pos_encoding="identity"``, a learned embedding of size + ``pos_embed_dim`` is appended to each node. + + Differences with the official code: the classifier ends with + ``label_processor.output_size()`` units instead of two logits (one logit + with a sigmoid for a binary label), and mixup, which the authors use + during training, belongs to the training script. Weights use the + official initialization. + + The attention weights of the last forward pass are available from + :meth:`get_attention_weights`, and the cluster assignments from the + ``assignments`` output of :meth:`forward` (``return_assignments=True``). + + Args: + dataset: The :class:`~pyhealth.datasets.SampleDataset` to train on. + It must have exactly one label key and one feature key holding a + square matrix. + layer_sizes: Output node count of each layer. The first entry is + replaced by the number of nodes, as in the official code. + Default is ``(nodes, 100)``. + pooling: Whether each layer pools its nodes. Default is + ``(False, True)``. + num_heads: Number of attention heads; must divide the node feature + size. Default is 4. + hidden_size: Feed-forward size of the transformer layers. Default is + 1024. + dropout: Dropout of the transformer layers. Default is 0.1. + pos_encoding: ``"none"`` or ``"identity"``. Default is ``"none"``. + pos_embed_dim: Size of the identity embedding. Default is the number + of nodes. + orthogonal: Orthogonalize the initial cluster centres. Default is + True. + freeze_center: Keep the cluster centres fixed. Default is True. + project_assignment: Use the projection score for the assignment. + Default is True. + + Raises: + ValueError: If the dataset does not have exactly one label key and + one feature key, if the feature is not a square matrix, or if the + layer settings are inconsistent. + + Examples: + >>> import numpy as np + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> from pyhealth.models import BrainNetworkTransformer + >>> rng = np.random.default_rng(0) + >>> samples = [ + ... { + ... "patient_id": f"p{i}", + ... "connectivity": rng.uniform(-1, 1, (16, 16)).astype(np.float32), + ... "autism": i % 2, + ... } + ... for i in range(4) + ... ] + >>> dataset = create_sample_dataset( + ... samples=samples, + ... input_schema={"connectivity": "tensor"}, + ... output_schema={"autism": "binary"}, + ... dataset_name="bnt_demo", + ... ) + >>> model = BrainNetworkTransformer(dataset, layer_sizes=(16, 4)) + >>> batch = next(iter(get_dataloader(dataset, batch_size=4))) + >>> out = model(**batch) + >>> sorted(out) + ['logit', 'loss', 'y_prob', 'y_true'] + >>> tuple(out["y_prob"].shape) + (4, 1) + >>> [tuple(w.shape) for w in model.get_attention_weights()] + [(4, 16, 16), (4, 16, 16)] + """ + + def __init__( + self, + dataset: SampleDataset, + layer_sizes: Sequence[int] | None = None, + pooling: Sequence[bool] = (False, True), + num_heads: int = 4, + hidden_size: int = 1024, + dropout: float = TRANSFORMER_DROPOUT, + pos_encoding: str = "none", + pos_embed_dim: int | None = None, + orthogonal: bool = True, + freeze_center: bool = True, + project_assignment: bool = True, + ) -> None: + super().__init__(dataset=dataset) + if len(self.label_keys) != 1: + raise ValueError("BrainNetworkTransformer supports exactly one label key.") + if len(self.feature_keys) != 1: + raise ValueError( + "BrainNetworkTransformer supports exactly one feature key, got " + f"{self.feature_keys}." + ) + if pos_encoding not in ("none", "identity"): + raise ValueError( + f"pos_encoding must be 'none' or 'identity', got {pos_encoding!r}." + ) + self.feature_key = self.feature_keys[0] + self.node_num = self._infer_node_num() + + sizes = list(layer_sizes) if layer_sizes is not None else [self.node_num, 100] + pooling = list(pooling) + if len(sizes) != len(pooling): + raise ValueError( + f"layer_sizes has {len(sizes)} entries but pooling has {len(pooling)}." + ) + # The first layer keeps the nodes; the official code overwrites its + # size with the node count. + sizes[0] = self.node_num + for size, pools, previous in zip(sizes, pooling, [self.node_num] + sizes): + if not pools and size != previous: + raise ValueError( + "A layer without pooling keeps its node count; got " + f"layer_sizes={sizes} with pooling={pooling}." + ) + self.layer_sizes = sizes + self.pooling = pooling + + forward_dim = self.node_num + self.pos_encoding = pos_encoding + if pos_encoding == "identity": + embed_dim = pos_embed_dim if pos_embed_dim is not None else self.node_num + self.node_identity = nn.Parameter(torch.zeros(self.node_num, embed_dim)) + nn.init.kaiming_normal_(self.node_identity) + forward_dim += embed_dim + + in_sizes = [self.node_num] + sizes[:-1] + self.attention_list = nn.ModuleList( + TransPoolingEncoder( + input_feature_size=forward_dim, + input_node_num=in_sizes[i], + hidden_size=hidden_size, + output_node_num=size, + pooling=pooling[i], + num_heads=num_heads, + dropout=dropout, + orthogonal=orthogonal, + freeze_center=freeze_center, + project_assignment=project_assignment, + ) + for i, size in enumerate(sizes) + ) + self.dim_reduction = nn.Sequential( + nn.Linear(forward_dim, REDUCED_NODE_DIM), nn.LeakyReLU() + ) + self.embedding_dim = REDUCED_NODE_DIM * sizes[-1] + first, second = CLASSIFIER_HIDDEN_DIMS + self.fc = nn.Sequential( + nn.Linear(self.embedding_dim, first), + nn.LeakyReLU(), + nn.Linear(first, second), + nn.LeakyReLU(), + nn.Linear(second, self.label_processor.output_size()), + ) + + def _infer_node_num(self) -> int: + """Read the number of nodes from the first sample of the dataset. + + Returns: + The size of the square connectivity matrix. + + Raises: + ValueError: If no sample has the feature or it is not square. + """ + for sample in self.dataset: + if self.feature_key not in sample: + continue + shape = tuple(sample[self.feature_key].shape) + if len(shape) != 2 or shape[0] != shape[1]: + raise ValueError( + "BrainNetworkTransformer expects a square (nodes, nodes) " + f"matrix for {self.feature_key!r}, got shape {shape}." + ) + return shape[0] + raise ValueError( + f"No sample in the dataset has the feature {self.feature_key!r}." + ) + + def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: + """Run the model on a batch. + + Args: + **kwargs: A batch from ``pyhealth.datasets.get_dataloader``: the + connectivity of shape ``(batch, nodes, nodes)`` and, + optionally, the label. Pass ``embed=True`` to also return the + flattened node features fed to the classifier, and + ``return_assignments=True`` to return the cluster assignment + of each pooling layer. + + Returns: + A dict with ``y_prob`` and ``logit`` of shape + ``(batch, output_size)``, ``loss`` (scalar) and ``y_true`` when + the batch has the label, ``embed`` of shape + ``(batch, embedding_dim)`` and ``assignments`` (a list with one + ``(batch, nodes, clusters)`` tensor per pooling layer) when + requested. + + Raises: + ValueError: If the matrix of the batch does not have the node + count of the dataset. + """ + # Cast to the dtype of the weights (float32 unless the model was cast). + dtype = self.dim_reduction[0].weight.dtype + x = kwargs[self.feature_key].to(self.device, dtype=dtype) + if x.dim() != 3 or tuple(x.shape[1:]) != (self.node_num, self.node_num): + raise ValueError( + f"Expected a batch of ({self.node_num}, {self.node_num}) " + f"matrices, got shape {tuple(x.shape)}." + ) + batch_size = x.shape[0] + if self.pos_encoding == "identity": + identity = self.node_identity.expand(batch_size, -1, -1) + x = torch.cat([x, identity], dim=-1) + + assignments = [] + for layer in self.attention_list: + x, assignment = layer(x) + if assignment is not None: + assignments.append(assignment) + emb = self.dim_reduction(x).reshape(batch_size, -1) + logits = self.fc(emb) + + results = { + "y_prob": self.label_processor.activation(logits), + "logit": logits, + } + # Inference batches may come without labels; loss needs them. + if self.label_keys[0] in kwargs: + y_true = kwargs[self.label_keys[0]].to(self.device) + results["loss"] = self.label_processor.loss(logits, y_true) + results["y_true"] = y_true + if kwargs.get("embed", False): + results["embed"] = emb + if kwargs.get("return_assignments", False): + results["assignments"] = assignments + return results + + def get_attention_weights(self) -> list[torch.Tensor | None]: + """Attention weights of each layer for the last forward pass. + + Returns: + One ``(batch, nodes, nodes)`` tensor per layer, averaged over + heads, or None for a layer that has not run yet. + """ + return [layer.get_attention_weights() for layer in self.attention_list] diff --git a/tests/core/test_brain_network_transformer.py b/tests/core/test_brain_network_transformer.py new file mode 100644 index 0000000000..bc5a33cace --- /dev/null +++ b/tests/core/test_brain_network_transformer.py @@ -0,0 +1,278 @@ +"""Tests for the Brain Network Transformer model, on small synthetic graphs.""" + +import unittest + +import numpy as np +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import BrainNetworkTransformer +from pyhealth.models.brain_network_transformer import ( + ClusterAssignment, + InterpretableTransformerEncoderLayer, + orthogonal_centers, +) +from pyhealth.trainer import Trainer + +NODES = 16 +CLUSTERS = 4 +SMALL = {"layer_sizes": (NODES, CLUSTERS), "hidden_size": 32} + + +def _dataset(nodes=NODES, mode="binary", n_samples=4, shape=None, extra=None): + """Build a tiny SampleDataset of random symmetric connectivity matrices. + + Args: + nodes: Number of nodes. + mode: Output schema of the label. + n_samples: Number of samples. + shape: Shape of the feature, to build an invalid one. + extra: Optional extra input field name added to every sample. + + Returns: + The SampleDataset. + """ + rng = np.random.default_rng(0) + samples = [] + for i in range(n_samples): + if shape is None: + a = rng.uniform(-1, 1, (nodes, nodes)) + matrix = (a + a.T) / 2 + np.fill_diagonal(matrix, 1.0) + else: + matrix = rng.uniform(-1, 1, shape) + sample = { + "patient_id": f"p{i}", + "connectivity": matrix.astype(np.float32), + "label": i % 3 if mode == "multiclass" else i % 2, + } + if extra is not None: + sample[extra] = matrix.astype(np.float32) + samples.append(sample) + input_schema = {"connectivity": "tensor"} + if extra is not None: + input_schema[extra] = "tensor" + return create_sample_dataset( + samples=samples, + input_schema=input_schema, + output_schema={"label": mode}, + dataset_name="test_bnt", + ) + + +def _batch(dataset, batch_size=4): + return next(iter(get_dataloader(dataset, batch_size=batch_size, shuffle=False))) + + +class TestBuildingBlocks(unittest.TestCase): + def test_encoder_layer_matches_torch_layer(self): + torch.manual_seed(0) + ours = InterpretableTransformerEncoderLayer(16, 4, 32).eval() + reference = torch.nn.TransformerEncoderLayer( + 16, 4, 32, dropout=0.1, batch_first=True + ).eval() + reference.load_state_dict(ours.state_dict()) + x = torch.randn(3, 7, 16) + with torch.no_grad(): + torch.testing.assert_close(ours(x), reference(x)) + self.assertEqual(tuple(ours.attention_weights.shape), (3, 7, 7)) + torch.testing.assert_close(ours.attention_weights.sum(dim=-1), torch.ones(3, 7)) + + def test_heads_must_divide_feature_size(self): + with self.assertRaisesRegex(ValueError, "divisible"): + InterpretableTransformerEncoderLayer(10, 4, 32) + + def test_orthogonal_centers(self): + torch.manual_seed(0) + initial = torch.randn(5, 12) + centers = orthogonal_centers(initial) + gram = centers @ centers.T + off_diagonal = gram - torch.diag(torch.diagonal(gram)) + self.assertLess(off_diagonal.abs().max().item(), 1e-5) + # Rows 1 and onward have unit norm; row 0 keeps its norm, as in + # the official code. + norms = torch.linalg.vector_norm(centers, dim=1) + torch.testing.assert_close(norms[1:], torch.ones(4)) + torch.testing.assert_close(centers[0], initial[0]) + # The input is not modified. + self.assertFalse(torch.equal(initial, centers)) + + def test_cluster_assignment(self): + torch.manual_seed(0) + assign = ClusterAssignment(CLUSTERS, 8) + self.assertFalse(assign.cluster_centers.requires_grad) + probs = assign(torch.randn(6, 8)) + self.assertEqual(tuple(probs.shape), (6, CLUSTERS)) + torch.testing.assert_close(probs.sum(dim=-1), torch.ones(6)) + trainable = ClusterAssignment(CLUSTERS, 8, freeze_center=False) + self.assertTrue(trainable.cluster_centers.requires_grad) + student = ClusterAssignment(CLUSTERS, 8, project_assignment=False) + torch.testing.assert_close( + student(torch.randn(6, 8)).sum(dim=-1), torch.ones(6) + ) + + def test_too_many_orthogonal_clusters_raise(self): + with self.assertRaisesRegex(ValueError, "orthogonal centres"): + ClusterAssignment(9, 8) + # Without orthogonalization any number of clusters is allowed. + ClusterAssignment(9, 8, orthogonal=False) + + +class TestBrainNetworkTransformer(unittest.TestCase): + def setUp(self): + torch.manual_seed(0) + self.dataset = _dataset() + self.model = BrainNetworkTransformer(self.dataset, **SMALL) + + def test_structure_follows_the_official_configuration(self): + self.assertEqual(self.model.node_num, NODES) + self.assertEqual(self.model.layer_sizes, [NODES, CLUSTERS]) + self.assertEqual(self.model.pooling, [False, True]) + first, second = self.model.attention_list + self.assertFalse(first.pooling) + self.assertTrue(second.pooling) + self.assertEqual(second.transformer.self_attn.num_heads, 4) + self.assertEqual(second.transformer.linear1.out_features, 32) + self.assertEqual(self.model.embedding_dim, 8 * CLUSTERS) + + def test_default_sizes_on_a_cc200_graph(self): + dataset = _dataset(nodes=200, n_samples=2) + model = BrainNetworkTransformer(dataset).eval() + self.assertEqual(model.layer_sizes, [200, 100]) + self.assertEqual(model.attention_list[0].transformer.linear1.out_features, 1024) + with torch.no_grad(): + out = model(**_batch(dataset, batch_size=2), return_assignments=True) + self.assertEqual(tuple(out["logit"].shape), (2, 1)) + self.assertEqual(tuple(out["assignments"][0].shape), (2, 200, 100)) + + def test_forward_binary_outputs(self): + out = self.model(**_batch(self.dataset)) + self.assertEqual(set(out), {"loss", "y_prob", "y_true", "logit"}) + self.assertEqual(out["loss"].dim(), 0) + self.assertEqual(tuple(out["y_prob"].shape), (4, 1)) + self.assertTrue(bool(((out["y_prob"] >= 0) & (out["y_prob"] <= 1)).all())) + + def test_forward_multiclass_outputs(self): + dataset = _dataset(mode="multiclass", n_samples=6) + out = BrainNetworkTransformer(dataset, **SMALL)(**_batch(dataset, 6)) + self.assertEqual(tuple(out["logit"].shape), (6, 3)) + torch.testing.assert_close(out["y_prob"].sum(dim=1), torch.ones(6)) + + def test_forward_without_label_skips_loss(self): + batch = _batch(self.dataset) + del batch["label"] + self.model.eval() + out = self.model(**batch) + self.assertEqual(set(out), {"y_prob", "logit"}) + + def test_embeddings_assignments_and_attention(self): + self.model.eval() + self.assertEqual(self.model.get_attention_weights(), [None, None]) + with torch.no_grad(): + out = self.model( + **_batch(self.dataset), embed=True, return_assignments=True + ) + self.assertEqual(tuple(out["embed"].shape), (4, 8 * CLUSTERS)) + (assignment,) = out["assignments"] + self.assertEqual(tuple(assignment.shape), (4, NODES, CLUSTERS)) + torch.testing.assert_close(assignment.sum(dim=-1), torch.ones(4, NODES)) + weights = self.model.get_attention_weights() + self.assertEqual([tuple(w.shape) for w in weights], [(4, NODES, NODES)] * 2) + + def test_identity_positional_encoding(self): + model = BrainNetworkTransformer( + self.dataset, pos_encoding="identity", pos_embed_dim=8, **SMALL + ) + self.assertEqual(tuple(model.node_identity.shape), (NODES, 8)) + out = model(**_batch(self.dataset), embed=True) + self.assertEqual(tuple(out["logit"].shape), (4, 1)) + # The node features grow by the embedding size. + transformer = model.attention_list[0].transformer + self.assertEqual(transformer.linear1.in_features, NODES + 8) + + def test_without_pooling(self): + model = BrainNetworkTransformer( + self.dataset, layer_sizes=(NODES, NODES), pooling=(False, False) + ) + out = model(**_batch(self.dataset), return_assignments=True) + self.assertEqual(out["assignments"], []) + self.assertEqual(model.embedding_dim, 8 * NODES) + + def test_backward_reaches_every_trainable_parameter(self): + out = self.model(**_batch(self.dataset)) + out["loss"].backward() + for name, param in self.model.named_parameters(): + if name == "_dummy_param": + continue + if name.endswith("cluster_centers"): + # Frozen by default, as in the official configuration. + self.assertFalse(param.requires_grad) + self.assertIsNone(param.grad) + continue + self.assertIsNotNone(param.grad, name) + self.assertTrue(bool(torch.isfinite(param.grad).all()), name) + + def test_cluster_centres_are_orthogonal_and_stay_frozen(self): + centers = self.model.attention_list[1].dec.assignment.cluster_centers + before = centers.detach().clone() + gram = before @ before.T + off_diagonal = gram - torch.diag(torch.diagonal(gram)) + self.assertLess(off_diagonal.abs().max().item(), 1e-5) + loader = get_dataloader(self.dataset, batch_size=2, shuffle=False) + trainer = Trainer(model=self.model, device="cpu", enable_logging=False) + trainer.train(train_dataloader=loader, val_dataloader=loader, epochs=1) + self.assertTrue(np.isfinite(trainer.evaluate(loader)["loss"])) + torch.testing.assert_close(centers.detach(), before) + + def test_non_square_feature_raises(self): + dataset = _dataset(shape=(NODES, NODES + 1)) + with self.assertRaisesRegex(ValueError, "square"): + BrainNetworkTransformer(dataset, **SMALL) + + def test_batch_of_another_size_raises(self): + batch = _batch(self.dataset) + batch["connectivity"] = torch.zeros(4, NODES - 1, NODES - 1) + with self.assertRaisesRegex(ValueError, "Expected a batch"): + self.model(**batch) + + def test_invalid_settings_raise(self): + with self.assertRaisesRegex(ValueError, "pos_encoding"): + BrainNetworkTransformer(self.dataset, pos_encoding="sin", **SMALL) + with self.assertRaisesRegex(ValueError, "entries"): + BrainNetworkTransformer( + self.dataset, layer_sizes=(NODES, 4, 2), pooling=(False, True) + ) + with self.assertRaisesRegex(ValueError, "keeps its node count"): + BrainNetworkTransformer( + self.dataset, layer_sizes=(NODES, 4), pooling=(False, False) + ) + with self.assertRaisesRegex(ValueError, "divisible"): + BrainNetworkTransformer(self.dataset, num_heads=3, **SMALL) + + def test_several_keys_raise(self): + dataset = _dataset(extra="second") + with self.assertRaisesRegex(ValueError, "one feature key"): + BrainNetworkTransformer(dataset, **SMALL) + + def test_eval_mode_is_deterministic(self): + self.model.eval() + batch = _batch(self.dataset) + with torch.no_grad(): + torch.testing.assert_close( + self.model(**batch)["logit"], self.model(**batch)["logit"] + ) + + def test_state_dict_round_trip(self): + clone = BrainNetworkTransformer(self.dataset, **SMALL) + clone.load_state_dict(self.model.state_dict()) + self.model.eval() + clone.eval() + batch = _batch(self.dataset) + with torch.no_grad(): + torch.testing.assert_close( + self.model(**batch)["logit"], clone(**batch)["logit"] + ) + + +if __name__ == "__main__": + unittest.main() From 816b5bd4b4be8d3ed756cf0753d23995195a2bd6 Mon Sep 17 00:00:00 2001 From: AxelNoun <150222552+AxelNoun@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:03:04 +0100 Subject: [PATCH 2/2] Correct the node-count and weight-decay statements of BNT The default 100 orthogonal clusters need at least 100 features per node, so the docstring and docs page no longer say that any atlas works, and the model now raises a ValueError naming layer_sizes when a pooling layer asks for more clusters than that. The example states that the Trainer exempts only the biases from weight decay, and the docs page says the parity check is not run in CI. --- ...yhealth.models.BrainNetworkTransformer.rst | 7 ++++-- examples/fmri/abide_autism_bnt.py | 5 +++-- pyhealth/models/brain_network_transformer.py | 22 ++++++++++++++++--- tests/core/test_brain_network_transformer.py | 15 +++++++++++++ 4 files changed, 42 insertions(+), 7 deletions(-) diff --git a/docs/api/models/pyhealth.models.BrainNetworkTransformer.rst b/docs/api/models/pyhealth.models.BrainNetworkTransformer.rst index 3f79df9527..d20f2a9bcb 100644 --- a/docs/api/models/pyhealth.models.BrainNetworkTransformer.rst +++ b/docs/api/models/pyhealth.models.BrainNetworkTransformer.rst @@ -10,7 +10,9 @@ matrix; a transformer runs over the nodes, and an orthonormal clustering readout (OCRead) pools them into soft clusters before a small classifier. It takes the ``connectivity`` field of :class:`~pyhealth.tasks.ABIDEAutismClassification` and reads the number of -nodes from the data, so any atlas works. +nodes from the data. The default 100 clusters need at least 100 features per +node, so they suit cc200 and larger atlases; for a smaller graph, pass +``layer_sizes`` with fewer clusters. The defaults are the authors' configuration: two transformer layers with 4 heads, the second pooling the nodes into 100 clusters with frozen orthonormal @@ -20,7 +22,8 @@ the cluster assignments from ``forward(..., return_assignments=True)``. ``examples/fmri/abide_autism_bnt.py`` trains it on ABIDE next to the GCN and logistic regression baselines, and ``examples/fmri/bnt_parity_check.py`` -compares this implementation with the official one. +compares this implementation with the official one. The parity check needs a +clone of the official repository and ``omegaconf``, so it is not run in CI. Paper: X. Kan, W. Dai, H. Cui, Z. Zhang, Y. Guo, C. Yang, `Brain Network Transformer `_, NeurIPS 2022. Official diff --git a/examples/fmri/abide_autism_bnt.py b/examples/fmri/abide_autism_bnt.py index 2a35e329e5..5d44ef3584 100644 --- a/examples/fmri/abide_autism_bnt.py +++ b/examples/fmri/abide_autism_bnt.py @@ -18,8 +18,9 @@ mixup of the inputs and labels during training. Known differences with the official run: the learning rate stays constant (the official run decays it from 1e-4 to 1e-5 with a cosine schedule), PyHealth's - ``Trainer`` exempts biases and layer norms from weight decay (the - official run decays every parameter), the split is + ``Trainer`` exempts the biases from weight decay (the official run + decays every parameter; the layer norm weights are decayed in both), the + split is stratified by neither site nor label, and the cohort is PyHealth's (1,035 C-PAC scans) rather than the authors' preprocessed file (1,009 subjects). The baselines keep the settings of their own examples diff --git a/pyhealth/models/brain_network_transformer.py b/pyhealth/models/brain_network_transformer.py index e69cd84951..a198f09f6d 100644 --- a/pyhealth/models/brain_network_transformer.py +++ b/pyhealth/models/brain_network_transformer.py @@ -363,7 +363,12 @@ class BrainNetworkTransformer(BaseModel): The defaults are the authors' configuration: two layers, the first keeping the nodes and the second pooling them into 100 clusters, 4 heads, a feed-forward size of 1024, no positional encoding. The number of nodes - is read from the dataset, so any atlas works. With + is read from the dataset. The orthonormal centres of a pooling layer + live in the node feature space, so a layer can pool into at most as many + clusters as each node has features (the node count, plus + ``pos_embed_dim`` with ``pos_encoding="identity"``): the default 100 + clusters suit cc200 and larger atlases, and a graph of fewer than 100 + nodes needs a smaller ``layer_sizes``, for example ``(nodes, 16)``. With ``pos_encoding="identity"``, a learned embedding of size ``pos_embed_dim`` is appended to each node. @@ -402,8 +407,9 @@ class BrainNetworkTransformer(BaseModel): Raises: ValueError: If the dataset does not have exactly one label key and - one feature key, if the feature is not a square matrix, or if the - layer settings are inconsistent. + one feature key, if the feature is not a square matrix, if the + layer settings are inconsistent, or if a pooling layer asks for + more orthogonal clusters than the node feature size. Examples: >>> import numpy as np @@ -490,6 +496,16 @@ def __init__( nn.init.kaiming_normal_(self.node_identity) forward_dim += embed_dim + if orthogonal: + for size, pools in zip(sizes, pooling): + if pools and size > forward_dim: + raise ValueError( + f"A pooling layer asks for {size} orthogonal clusters, " + f"but each node has {forward_dim} features; pass " + f"layer_sizes with at most {forward_dim} clusters, for " + f"example layer_sizes=({self.node_num}, " + f"{min(16, forward_dim)})." + ) in_sizes = [self.node_num] + sizes[:-1] self.attention_list = nn.ModuleList( TransPoolingEncoder( diff --git a/tests/core/test_brain_network_transformer.py b/tests/core/test_brain_network_transformer.py index bc5a33cace..f17ee860ac 100644 --- a/tests/core/test_brain_network_transformer.py +++ b/tests/core/test_brain_network_transformer.py @@ -249,6 +249,21 @@ def test_invalid_settings_raise(self): with self.assertRaisesRegex(ValueError, "divisible"): BrainNetworkTransformer(self.dataset, num_heads=3, **SMALL) + def test_too_many_default_clusters_for_a_small_graph(self): + # 16 nodes give 16 features per node: the default 100 orthogonal + # clusters do not fit, and the error names the fix. + with self.assertRaisesRegex(ValueError, r"at most 16 clusters"): + BrainNetworkTransformer(self.dataset) + # An identity embedding widens the node features, so more fit. + model = BrainNetworkTransformer( + self.dataset, + layer_sizes=(NODES, 20), + pos_encoding="identity", + pos_embed_dim=8, + hidden_size=32, + ) + self.assertEqual(model.layer_sizes, [NODES, 20]) + def test_several_keys_raise(self): dataset = _dataset(extra="second") with self.assertRaisesRegex(ValueError, "one feature key"):