torch_concepts.nn.BaseModel

class BaseModel(input_size: int, annotations: Annotations, variable_distributions: Mapping | None = None, backbone: str | Callable[[Tensor], Tensor] | None = None, latent_encoder: Module | None = None, latent_encoder_kwargs: Dict | None = None, **kwargs)[source]

Abstract base class for concept-based models.

Provides common functionality for models that use backbones for feature extraction, and encoders for latent representations. All concrete model implementations should inherit from this class.

BaseModel is flexible and supports two distinct training paradigms:

Mode 1: Standard PyTorch Training (Manual Loop)

Initialize model without loss/optimizer parameters for full manual control. You define the training loop, optimizer, and loss function externally.

Mode 2: PyTorch Lightning Training (Automatic)

Initialize model with loss, optim_class, and optim_kwargs for automatic training via PyTorch Lightning Trainer. The model inherits training logic from Learner classes.

Parameters:
  • input_size (int) – Dimensionality of input features after backbone processing. If no backbone is used (backbone=None), this should match raw input dimensionality.

  • annotations (Annotations) – Concept annotations containing variable names, cardinalities, and optional distribution metadata. Distributions specify how the model represents each concept (e.g., Bernoulli for binary, Categorical for multi-class).

  • variable_distributions (Mapping, optional) – Dictionary mapping concept names to torch.distributions classes (e.g., {'c1': Bernoulli, 'c2': Categorical}). Required if annotations lack ‘distribution’ metadata. If provided, distributions are added to annotations internally. Can also be a GroupConfig object. Defaults to None.

  • backbone (BackboneType, optional) – Feature extraction module (e.g., ResNet, ViT) applied before latent encoder. Can be nn.Module or callable. If None, assumes inputs are pre-computed features. Defaults to None.

  • latent_encoder (nn.Module, optional) – Custom encoder mapping backbone outputs to latent space. If provided, latent_encoder_kwargs are passed to this constructor. If None and latent_encoder_kwargs provided, uses MLP. Defaults to None.

  • latent_encoder_kwargs (Dict, optional) – Arguments for latent encoder construction. Common keys: - ‘hidden_size’ (int): Latent dimension - ‘n_layers’ (int): Number of hidden layers - ‘activation’ (str): Activation function name If None, uses nn.Identity (no encoding). Defaults to None.

  • **kwargs – Additional arguments passed to nn.Module superclass.

concept_annotations

Axis-1 annotations with distribution metadata for each concept.

Type:

AxisAnnotation

concept_names

List of concept variable names from annotations.

Type:

List[str]

backbone

Feature extraction module (None if using pre-computed features).

Type:

BackboneType or None

latent_encoder

Encoder transforming backbone outputs to latent representations.

Type:

nn.Module

latent_size

Dimensionality of latent encoder output (input to concept encoders).

Type:

int

Notes

  • Concept Distributions: The model needs to know which distribution to use for each concept (Bernoulli, Categorical, Normal, etc.). This can be provided in two ways:

    1. In annotations metadata: metadata={'c1': {'distribution': Bernoulli}}

    2. Via variable_distributions parameter at initialization

    If distributions are in annotations, variable_distributions is not needed. If not, variable_distributions is required and will be added to annotations.

  • Subclasses must implement forward(), filter_output_for_loss(), and filter_output_for_metrics() methods.

  • For Lightning training, subclasses typically inherit from both BaseModel and a Learner class (e.g., JointLearner) via multiple inheritance.

  • The latent_size attribute is critical for downstream concept encoders to determine input dimensionality.

Examples

Distributions specify how the model represents concepts. Provide them either in annotations metadata OR via variable_distributions parameter:

>>> import torch
>>> import torch.nn as nn
>>> from torch.distributions import Bernoulli
>>> from torch_concepts.nn import ConceptBottleneckModel
>>> from torch_concepts.annotations import AxisAnnotation, Annotations
>>>
>>> # Option 1: Distributions in annotations metadata
>>> ann = Annotations({
...     1: AxisAnnotation(
...         labels=['c1', 'c2', 'task'],
...         cardinalities=[1, 1, 1],
...         metadata={
...             'c1': {'type': 'binary', 'distribution': Bernoulli},
...             'c2': {'type': 'binary', 'distribution': Bernoulli},
...             'task': {'type': 'binary', 'distribution': Bernoulli}
...         }
...     )
... })
>>> model = ConceptBottleneckModel(
...     input_size=10,
...     annotations=ann,  # Distributions already in metadata
...     task_names=['task']
... )
>>>
>>> # Option 2: Distributions via variable_distributions parameter
>>> ann_no_dist = Annotations({
...     1: AxisAnnotation(
...         labels=['c1', 'c2', 'task'],
...         cardinalities=[1, 1, 1]
...     )
... })
>>> variable_distributions = {'c1': Bernoulli, 'c2': Bernoulli, 'task': Bernoulli}
>>> model = ConceptBottleneckModel(
...     input_size=10,
...     annotations=ann_no_dist,
...     variable_distributions=variable_distributions,  # Added here
...     task_names=['task']
... )
>>>
>>> # Manual training loop
>>> optimizer = torch.optim.AdamW(model.parameters(), lr=0.001)
>>> loss_fn = nn.BCEWithLogitsLoss()
>>> x = torch.randn(32, 10)
>>> y = torch.randint(0, 2, (32, 3)).float()
>>>
>>> for epoch in range(100):
...     optimizer.zero_grad()
...     out = model(x, query=['c1', 'c2', 'task'])
...     loss = loss_fn(out, y)
...     loss.backward()
...     optimizer.step()

See also

torch_concepts.nn.modules.high.models.cbm.ConceptBottleneckModel

Concrete CBM implementation

torch_concepts.nn.modules.high.learners.JointLearner

Lightning training logic for joint models

torch_concepts.annotations.Annotations

Concept annotation container

__init__(input_size: int, annotations: Annotations, variable_distributions: Mapping | None = None, backbone: str | Callable[[Tensor], Tensor] | None = None, latent_encoder: Module | None = None, latent_encoder_kwargs: Dict | None = None, **kwargs) None[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Methods

__init__(input_size, annotations[, ...])

Initialize internal Module state, shared by both nn.Module and ScriptModule.

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Set the module in evaluation mode.

extra_repr()

Return the extra representation of the module.

filter_output_for_loss(out_concepts)

Filter model outputs before passing to loss function.

filter_output_for_metrics(out_concepts)

Filter model outputs before passing to metrics.

float()

Casts all floating point parameters and buffers to float datatype.

forward(*input)

Define the computation performed at every call.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

maybe_apply_backbone(x[, backbone_args])

Apply the backbone to x unless features are pre-computed.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module[, strict])

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

Attributes

T_destination

backbone

The backbone feature extractor.

call_super_init

dump_patches

latent_encoder

The encoder mapping backbone output to latent space.

training