torch_concepts.nn.ConceptWhitening¶
- class ConceptWhitening(in_features: int, num_iterations: int = 5, eps: float = 1e-05, momentum: float = 0.05)[source]¶
Concept Whitening layer (Chen, Bei & Rudin, 2020).
The layer whitens input embeddings with iterative normalization (Newton–Schulz iterations, as in IterNorm) and applies a learned orthogonal rotation
Rso that axisjof the output responds to conceptj. The embedding dimension is preserved, so the layer can replace a BatchNorm anywhere in a backbone orSequentialwithout introducing a bottleneck.The layer itself is concept-agnostic: any output axis can be aligned via
align(). Which (and how many) axes are designated as concepts is decided by the caller — typicallyWhitenedEmbeddingToConcept, which designates the firstout_conceptsaxes and slices them.The concept axes are not supervised by the main loss: the whitening matrix and the rotation are buffers, invisible to the optimizer. The rotation is aligned separately — gradients of the concept-alignment objective are accumulated on auxiliary concept batches (forward passes inside
align()) andRis then updated with a Cayley-transform curvilinear search on the Stiefel manifold (Wen & Yin, 2013), exactly as in the original implementation. As in the original training script, alignment runs in eval mode (align()takes care of this for the layer itself), so concept batches do not pollute the running whitening statistics.Typical training loop:
cw = ConceptWhitening(in_features=64) # ... regular main-objective steps use cw(x) as a normalization layer # periodically, align axes on auxiliary concept datasets: for j, concept_batch in enumerate(concept_loaders): with cw.align(j): cw(concept_batch) # accumulates alignment gradients cw.update_rotation_matrix()
- Parameters:
in_features – Dimension of the input (and output) embeddings.
num_iterations – Newton–Schulz iterations for whitening (T in IterNorm).
eps – Ridge added to the covariance for numerical stability.
momentum – Momentum for running whitening statistics and for the accumulated alignment gradient.
Example
>>> import torch >>> from torch_concepts.nn import ConceptWhitening >>> >>> cw = ConceptWhitening(in_features=16) >>> x = torch.randn(128, 16) >>> z = cw(x) # whitened + rotated, shape (128, 16) >>> concepts = z[:, :4] # concept activations, if axes 0-3 aligned >>> print(z.shape) torch.Size([128, 16])
References
Chen, Bei & Rudin. “Concept whitening for interpretable image
recognition”, Nature Machine Intelligence 2020. https://www.nature.com/articles/s42256-020-00265-z
Huang et al. “Iterative Normalization: Beyond Standardization towards
Efficient Whitening”, CVPR 2019. https://arxiv.org/abs/1904.03441
Wen & Yin. “A feasible method for optimization with orthogonality
constraints”, Mathematical Programming 2013. https://link.springer.com/article/10.1007/s10107-012-0584-1
- __init__(in_features: int, num_iterations: int = 5, eps: float = 1e-05, momentum: float = 0.05)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Methods
__init__(in_features[, num_iterations, eps, ...])Initialize internal Module state, shared by both nn.Module and ScriptModule.
add_module(name, module)Add a child module to the current module.
align(axis_index)Context manager: forward passes inside accumulate alignment gradients for output axis
axis_indexinstead of behaving normally.apply(fn)Apply
fnrecursively to every submodule (as returned by.children()) as well as self.bfloat16()Casts all floating point parameters and buffers to
bfloat16datatype.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
doubledatatype.eval()Set the module in evaluation mode.
extra_repr()Return the extra representation of the module.
float()Casts all floating point parameters and buffers to
floatdatatype.forward(embeddings)Whiten and rotate embeddings.
get_buffer(target)Return the buffer given by
targetif 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
targetif it exists, otherwise throw an error.get_submodule(target)Return the submodule given by
targetif it exists, otherwise throw an error.half()Casts all floating point parameters and buffers to
halfdatatype.ipu([device])Move all model parameters and buffers to the IPU.
load_state_dict(state_dict[, strict, assign])Copy parameters and buffers from
state_dictinto this module and its descendants.modules([remove_duplicate])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
targetif it exists, otherwise throw an error.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.update_rotation_matrix([num_updates])Update the rotation matrix from the accumulated alignment gradients using a Cayley-transform curvilinear search (Wen & Yin, 2013).
xpu([device])Move all model parameters and buffers to the XPU.
zero_grad([set_to_none])Reset gradients of all model parameters.
Attributes
T_destinationcall_super_initdump_patchestraining