Note
This page is a reference documentation. It only explains the class signature, and not how to use it. Please refer to the user guide for the big picture.
nidl.estimators.ssl.CoMM¶
- class nidl.estimators.ssl.CoMM(encoder, num_modalities, modality_names=None, encoder_kwargs=None, mod_to_encoder=None, adapter=None, freeze_encoder=False, per_modality_adapter=False, embed_dim=2048, num_heads=8, depth=1, add_bias_kv=False, attn_drop_rate=0.0, proj_hidden_dim=512, proj_output_dim=256, temperature=0.1, subset_weights=None, optimizer='adamW', learning_rate=0.0003, weight_decay=0.0005, exclude_bias_and_norm_wd=True, optimizer_kwargs=None, lr_scheduler='warmup_cosine', lr_scheduler_kwargs=None, **kwargs)[source]¶
Bases:
TransformerMixin,BaseEstimatorCoMM [1], with missing modalities.
CoMM is a multimodal model that learns a representation of several modalities with self-supervised contrastive learning. For two augmented views of each sample, it computes
embeddings: one per
modality and a multimodal one. Each embedding of one view is then
aligned with the multimodal embedding of the other view (see
CoMMLoss).The model consists of:
one or several backbones, encoding each modality;
adapters, turning the backbone outputs into tokens;
a fusion transformer, computing the
embeddings from the
tokens of each modality and their multimodal fusion;a projection head, mapping these embeddings to the space of the loss.
CoMM handles missing modalities. Missing ones are masked out of the fusion, of the projection head and of the loss terms: the multimodal embedding only fuses the modalities present.
Data loader. The model is trained with batches of samples collated by
collate_multimodal. Each sample is a dict{modality: data or None}, withNonefor a missing modality, anddataa list of two augmented views of the scan for training, or a single scan at inference.After training, the projection head is discarded:
transformreturns the multimodal embedding of each sample, from the modalities it has.- Parameters:
- encodernn.Module, class of nn.Module or sequence of nn.Module
The backbone encoding all the modalities, or several backbones dispatched by mod_to_encoder (e.g. a CNN for MRI and an MLP for tabular data). A single backbone can also be given as a class, instantiated with encoder_kwargs.
- num_modalitiesint
Number of modalities
, i.e. the length of the
modalitiesgiven to collate_multimodal.- modality_namessequence of str or None, default=None
Names of the
modalities, in the order of modalities(typically the same list, e.g.("t1", "t2", "flair")), used to log the loss and accuracy of each term:ssl_loss_<name>/<stage>andssl_acc_<name>/<stage>, withfusedfor the multimodal term. By default,mod0,mod1…- encoder_kwargsdict or None, default=None
Options for building the encoder. Ignored if encoder is instantiated.
- mod_to_encodersequence of int or None, default=None
With several backbones, the index in encoder of the backbone encoding each of the
modalities, in the order of
modalities:mod_to_encoder[m]encodesmodalities[m]. E.g. withencoder=[cnn, mlp]andmodalities=("t1", "t2", "clinical"),mod_to_encoder=[0, 0, 1]encodes the T1w and T2w MRI with the CNN, and the clinical data with the MLP.- adapternn.Module, sequence of nn.Module or None, default=None
Tokenizer of the backbone outputs, shared by all the modalities, or a list of
adapters, one per modality in the order of
modalities. By default,SimpleFeaturesInputAdapterturns a feature vector into a single token;Patched3DInputAdaptertokenizes a 3D feature map, andIdentityAdapterkeeps the tokens of a transformer.- freeze_encoderbool, default=False
Whether to freeze the backbones (no gradient, eval mode), e.g. when they are pretrained: only the adapters, the fusion and the head are then trained.
- per_modality_adapterbool, default=False
Whether each modality gets its own copy of a single adapter, instead of sharing it.
- embed_dimint, default=2048
Dimension of the tokens and of the embeddings. It must be the token dimension of the adapters, i.e. the output dimension of the backbones with the default adapter.
- num_headsint, default=8
Number of attention heads in the fusion transformer. It must divide embed_dim.
- depthint, default=1
Number of attention blocks in the fusion transformer.
- add_bias_kvbool, default=False
Whether to add a learned bias to the keys and values of the fusion transformer.
- attn_drop_ratefloat, default=0.0
Dropout probability on the attention weights of the fusion transformer.
- proj_hidden_dimint, default=512
Projector hidden dimension.
- proj_output_dimint, default=256
Projector output dimension.
- temperaturefloat, default=0.1
The InfoNCE loss temperature parameter.
- subset_weightssequence of float or None, default=None
Weights of the
loss terms: one per modality, then the
multimodal term. By default, all the terms have the same weight.- optimizer{‘sgd’, ‘adam’, ‘adamW’} or torch.optim.Optimizer or type,
default=”adamW” Optimizer for training the model. If a string is given, it can be:
‘sgd’: Stochastic Gradient Descent (with optional momentum).
‘adam’: First-order gradient-based optimizer.
‘adamW’ (default): Adam with decoupled weight decay regularization (see “Decoupled Weight Decay Regularization”, Loshchilov and Hutter, ICLR 2019).
- learning_ratefloat, default=3e-4
Initial learning rate.
- weight_decayfloat, default=5e-4
Weight decay in the optimizer.
- exclude_bias_and_norm_wdbool, default=True
Whether the bias terms and normalization layers get weight decay during optimization or not.
- optimizer_kwargsdict or None, default=None
Extra named arguments for the optimizer.
- lr_scheduler{“none”, “warmup_cosine”}, LRSchedulerPLType or None,
default=”warmup_cosine” Learning rate scheduler to use.
- lr_scheduler_kwargsdict or None, default=None
Extra named arguments for the scheduler. By default, it is set to {“warmup_epochs”: 10, “warmup_start_lr”: 1e-6, “min_lr”: 0.0, “interval”: “step”}
- **kwargsdict, optional
Additional keyword arguments for the BaseEstimator class, such as max_epochs, max_steps, devices, strategy, callbacks, etc.
- Attributes:
- encoderMissingModMMFusion
The backbones, the adapter(s) and the fusion transformer, mapping the scans of each sample to its
embeddings.- projection_headCoMMProjectionHead
Projector that maps the embeddings to the space of the loss.
- lossCoMMLoss
The CoMM loss function used for training.
References
[1]Benoit Dufumier, Javiera Castillo-Navarro, et al., “What to align in multimodal contrastive learning?”, ICLR 2025. Official code: https://github.com/Duplums/CoMM.
- __init__(encoder, num_modalities, modality_names=None, encoder_kwargs=None, mod_to_encoder=None, adapter=None, freeze_encoder=False, per_modality_adapter=False, embed_dim=2048, num_heads=8, depth=1, add_bias_kv=False, attn_drop_rate=0.0, proj_hidden_dim=512, proj_output_dim=256, temperature=0.1, subset_weights=None, optimizer='adamW', learning_rate=0.0003, weight_decay=0.0005, exclude_bias_and_norm_wd=True, optimizer_kwargs=None, lr_scheduler='warmup_cosine', lr_scheduler_kwargs=None, **kwargs)[source]¶
- forward(batch)[source]¶
Embed and project the two views of a batch.
- Parameters:
- batchdict
A parsed batch with the keys “views”, “sample_idx” and “n_samples”, as built by
collate_multimodal.
- Returns:
- z1, z2list of torch.Tensor
The
projected embeddings of each view, of shape
(n_samples, proj_output_dim): one per modality (zeros for the
samples missing it), then the multimodal one.- presenttorch.Tensor of shape (n_samples, M)
Whether each sample has each modality.
- training_step(batch, batch_idx, dataloader_idx=0)[source]¶
Perform one training step and compute the training loss.
- Parameters:
- batch: dict or tuple of (dict, torch.Tensor)
A batch of data from the train dataloader, built with
collate_multimodalfrom samples holding two views of each modality.- batch_idx: int
The index of the current batch (ignored).
- dataloader_idx: int, default=0
The index of the dataloader (ignored).
- Returns:
- outputsdict
The CoMM loss dict: “loss”, “ssl_acc”, and the per-subset “ssl_loss_i” / “ssl_acc_i”.
- transform_step(batch, batch_idx, dataloader_idx=0)[source]¶
Encode each sample into its multimodal embedding, which fuses the modalities it has (the projection head is discarded).
- Parameters:
- batch: dict or tuple of (dict, torch.Tensor)
A batch of data, built with
collate_multimodalfrom samples holding a single scan of each modality.- batch_idx: int
The index of the current batch (ignored).
- dataloader_idx: int, default=0
The index of the dataloader (ignored).
- Returns:
- features: torch.Tensor of shape (n_samples, embed_dim)
The multimodal embeddings.
- validation_step(batch, batch_idx, dataloader_idx=0)[source]¶
Perform one validation step and compute the validation loss.
- Parameters:
- batch: dict or tuple of (dict, torch.Tensor)
A batch of data from the validation dataloader, in the same format as in
training_step.- batch_idx: int
The index of the current batch (ignored).
- dataloader_idx: int, default=0
The index of the dataloader (ignored).
- Returns:
- outputsdict
The CoMM loss dict, as in
training_step.
Examples using nidl.estimators.ssl.CoMM¶
Multimodal pretraining with missing modalities: CoMM on OpenMind