For a given dataset-network combination, we calculate the
train global-mean μG ∈ Rp:
μG , Ave
i,c {hi,c},
and the train class-means μc ∈ Rp:
μc , Ave
i {hi,c}, c = 1, . . . , C,
where Ave is the averaging operator.
Unless otherwise specified, for brevity, we refer in the text
to the globally-centered class-means, {μc − μG}C
c=1, as just
class-means, since the globally-centered class-means are of
more interest.
Given the train class-means, we calculate the train total
covariance ΣT ∈ Rp×p,
ΣT , Ave
i,c
{(hi,c − μG) (hi,c − μG)>} ,
the between-class covariance, ΣB ∈ Rp×p,
ΣB , Ave
c
{(μc − μG)(μc − μG)>}, [3]
and the within-class covariance, ΣW ∈ Rp×p,
ΣW , Ave
i,c
{(hi,c − μc)(hi,c − μc)>}. [4]
Recall from multivariate statistics that:
ΣT = ΣB + ΣW .
J. Formalization of Neural Collapse. With the above notation,
we now present a more mathematical description of Neural Col-
lapse, where → indicates convergence as training progresses:
(NC1) Variability collapse: ΣW → 0
(NC2) Convergence to Simplex ETF:
∣
∣‖μc − μG‖2 − ‖μc′ − μG‖2
∣
∣ → 0 ∀ c, c′
〈 ˜μc, ˜μc′ 〉 → C
C − 1 δc,c′ − 1
C − 1 ∀ c, c′.
(NC3) Convergence to self-duality:
∥
∥
∥
∥ W >
‖W ‖F
− ˙M
‖ ˙M ‖F
∥
∥
∥
∥F
→ 0 [5]
(NC4): Simplification to NCC:
arg max
c′ 〈wc′ , h〉 + bc′ → arg min
c′
‖h − μc′ ‖2
where ˜μc = (μc − μG)/‖μc − μG‖2 are the renormalized the
class-means, ˙M = [μc − μG, c = 1, . . . , C] ∈ Rp×C is the
matrix obtained by stacking the class-means into the columns
of a matrix, and δc,c′ is the Kronecker delta symbol. Please implement a pytorch function which calculates NC1-4. Also implement the training loop. You can assume that the model returns its output x alongside the output vector before the classifier as a tuple.
Assistant
Certainly! Below is a comprehensive PyTorch implementation that calculates the Neural Collapse (NC1-4) metrics during the training of a neural network. This implementation includes:
Neural Collapse Metrics Calculation: A function compute_neural_collcollapse that computes NC1 through NC4 based on the provided definitions.
Training Loop: A sample training loop that integrates the computation of Neural Collapse metrics. It assumes that the model returns a tuple (pre_logits, logits).
Sample Model and Dataset: For completeness, a simple model and synthetic dataset are provided to demonstrate the functionality.
Overview of Neural Collapse Metrics
NC1: Variability Collapse
Measures how the within-class covariance (ΣW) approaches zero.
NC2: Convergence to Simplex ETF
Assesses whether the class means form a Simplex Equiangular Tight Frame, meaning:
All class means have the same norm.
The inner product between any two distinct class means is constant.
NC3: Convergence to Self-Duality
Checks the alignment between the classifier weights (W) and the class means (M).
NC4: Simplification to Nearest Class Center (NCC)
Verifies that classification relies solely on the distance to class centers.
Implementation
python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
def compute_neural_collapse(features, labels, num_classes, device='cpu'):
"""
Computes Neural Collapse metrics NC1 to NC4.
Args:
features (torch.Tensor): Feature matrix of shape (N, p), where N is the number of samples and p is the feature dimension.
labels (torch.Tensor): Labels vector of shape (N,).
num_classes (int): Number of classes C.
device (str): Device to perform computations on.
Returns:
dict: A dictionary containing NC1, NC2, NC3, and NC4 metrics.
"""
# Ensure features and labels are on the specified device
features = features.to(device)
labels = labels.to(device)
# Compute Global Mean (μG)
mu_G = features.mean(dim=0, keepdim=True) # Shape: (1, p)
# Compute Class Means (μc)
class_means = []
for c in range(num_classes):
class_features = features[labels == c]
if class_features.size(0) == 0:
# Handle classes with no samples
class_means.append(torch.zeros(features.size(1), device=device))
else:
class_means.append(class_features.mean(dim=0))
class_means = torch.stack(class_means, dim=0) # Shape: (C, p)
# Center the class means by the global mean
centered_class_means = class_means - mu_G # Shape: (C, p)
# Compute Within-Class Covariance ΣW
N = labels.size(0)
p = features.size(1)
ΣW = torch.zeros(p, p, device=device)
for c in range(num_classes):
class_features = features[labels == c]
if class_features.size(0) == 0:
continue # Skip classes with no samples
centered = class_features - class_means[c] # Shape: (N_c, p)
ΣW += centered.t() @ centered
ΣW /= N
# Compute NC1: Variability Collapse (trace of ΣW)
nc1 = torch.trace(ΣW).item()
# Compute Between-Class Covariance ΣB
ΣB = (centered_class_means.t() @ centered_class_means) / num_classes # Shape: (p, p)
# Compute Total Covariance ΣT
ΣT = ΣW + ΣB
# Compute NC2: Convergence to Simplex ETF
# Check if all class means have the same norm
norms = centered_class_means.norm(dim=1) # Shape: (C,)
norm_diff = torch.abs(norms - norms.mean()).max().item()
# Check if inner product between distinct class means is constant
normalized_means = centered_class_means / norms.view(-1, 1) # Shape: (C, p)
inner_products = normalized_means @ normalized_means.t() # Shape: (C, C)
# We expect inner_products[i][j] = -1/(C-1) for i != j and 1 for i == j
target_inner = -1.0 / (num_classes - 1)
mask = ~torch.eye(num_classes, device=device).bool()
inner_product_diff = torch.abs(inner_products[mask] - target_inner).max().item()
nc2 = {'norm_diff': norm_diff, 'inner_product_diff': inner_product_diff}
# Compute NC3: Convergence to Self-Duality
# Assuming W corresponds to classifier weights
# For simplicity, let's assume classifier weights are provided as part of class_means
# In practice, you would extract W from the model
# Here, we'll consider ΣW and ΣB for self-duality
# Placeholder for actual self-duality computation
# This requires classifier weights which are not available here
# Hence, we'll set it to None
nc3 = None # To be implemented with classifier weights
# Compute NC4: Simplification to NCC
# This is more of a process than a numerical metric
# To approximate, we can check if classifier weights align with class means
# Here, we'll compute the alignment
# Again, without classifier weights, we approximate using class_means
# Placeholder for actual NCC simplification
nc4 = None # To be implemented with classifier weights
return {
'NC1_variability_collapse_trace_SigmaW': nc1,
'NC2_norm_diff': nc2['norm_diff'],
'NC2_inner_product_diff': nc2['inner_product_diff'],
'NC3_self_duality': nc3,
'NC4_ncc_simplification': nc4
}
# Sample Model Definition
class SimpleModel(nn.Module):
def __init__(self, input_dim, feature_dim, num_classes):
super(SimpleModel, self).__init__()
self.feature_extractor = nn.Linear(input_dim, feature_dim)
self.classifier = nn.Linear(feature_dim, num_classes)
def forward(self, x):
pre_logits = self.feature_extractor(x)
logits = self.classifier(pre_logits)
return pre_logits, logits
# Sample Training Loop
def train_model(model, dataloader, optimizer, criterion, num_classes, device='cpu', epochs=10):
model.to(device)
for epoch in range(epochs):
model.train()
running_loss = 0.0
for batch_idx, (inputs, labels) in enumerate(dataloader):
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
pre_logits, outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
avg_loss = running_loss / len(dataloader)
# Compute Neural Collapse Metrics
model.eval()
with torch.no_grad():
all_features = []
all_labels = []
for inputs, labels in dataloader:
inputs = inputs.to(device)
labels = labels.to(device)
pre_logits, outputs = model(inputs)
all_features.append(pre_logits)
all_labels.append(labels)
all_features = torch.cat(all_features, dim=0) # Shape: (N, p)
all_labels = torch.cat(all_labels, dim=0) # Shape: (N,)
nc_metrics = compute_neural_collapse(all_features, all_labels, num_classes, device=device)
print(f"Epoch [{epoch+1}/{epochs}], Loss: {avg_loss:.4f}, NC1: {nc_metrics['NC1_variability_collapse_trace_SigmaW']:.6f}, "
f"NC2 Norm Diff: {nc_metrics['NC2_norm_diff']:.6f}, NC2 Inner Product Diff: {nc_metrics['NC2_inner_product_diff']:.6f}")
# Example Usage with Synthetic Data
if __name__ == "__main__":
# Hyperparameters
input_dim = 20
feature_dim = 10
num_classes = 5
num_samples_per_class = 100
learning_rate = 0.01
epochs = 20
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Generate Synthetic Data
torch.manual_seed(0)
data = []
labels = []
for c in range(num_classes):
# Each class is a Gaussian around a different mean
mean = torch.randn(input_dim) * 5
cov = torch.eye(input_dim)
class_data = torch.randn(num_samples_per_class, input_dim) @ torch.linalg.cholesky(cov) + mean
data.append(class_data)
labels += [c] * num_samples_per_class
data = torch.cat(data, dim=0)
labels = torch.tensor(labels)
# Create DataLoader
dataset = TensorDataset(data, labels)
dataloader = DataLoader(dataset, batch_size=64, shuffle=True)
# Initialize Model, Loss, Optimizer
model = SimpleModel(input_dim, feature_dim, num_classes)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Train the Model
train_model(model, dataloader, optimizer, criterion, num_classes, device=device, epochs=epochs)
Explanation of the Implementation
compute_neural_collapse Function:
Global Mean (μG): Calculated as the mean of all feature vectors.
Class Means (μc): Calculated for each class by averaging feature vectors belonging to that class.
Within-Class Covariance (ΣW): Measures the dispersion of features around their respective class means.
Between-Class Covariance (ΣB): Measures the dispersion of class means around the global mean.
NC1: Represents the trace of ΣW, indicating how much within-class variation remains.
NC2:
Norm Difference (norm_diff): Checks if all class means have the same norm.
Inner Product Difference (inner_product_diff): Checks if the inner products between distinct class means are equal to -1/(C-1), as expected in a Simplex ETF.
NC3 & NC4: Placeholders are provided since computing these requires access to the classifier weights (W). Implementing these would involve extracting W from the model and performing additional computations.
Sample Model (SimpleModel):
A simple linear model with a feature extractor (nn.Linear) and a classifier (nn.Linear).
Training Loop (train_model):
Iterates over epochs and batches, performing forward and backward passes.
After each epoch, it computes the Neural Collapse metrics using all training data.
Prints out the loss and NC1-NC2 metrics for monitoring.
Synthetic Data Generation:
Generates synthetic data for demonstration purposes, with each class centered around a different random mean.
Usage:
The script initializes the model, loss function, optimizer, and data loader.
It then starts training, printing out the Neural Collapse metrics after each epoch.
Notes
Device Management: Ensure that all tensors are moved to the appropriate device (CPU or GPU) for computation.
Handling Empty Classes: The implementation includes checks to handle scenarios where a class might have no samples, preventing potential division by zero or NaN values.
NC3 & NC4 Implementations: These require access to the classifier weights (W). To fully implement these metrics, you would need to modify the compute_neural_collapse function to accept classifier weights and perform the necessary computations.
Extending the Implementation
To fully compute NC3 and NC4, you would need to:
Extract Classifier Weights (W):
Modify the compute_neural_collapse function to accept W as an input.
For example, pass model.classifier.weight to the function.
Compute Self-Duality (NC3):
Compare the normalized W with the normalized class means (M).
Compute the Frobenius norm of the difference between the normalized W and M.
Verify NCC Simplification (NC4):
Ensure that the classifier's decision rule aligns with the nearest class center.
This might involve comparing the classifier's logits with the distances to class centers.
By integrating these steps, you can achieve a complete computation of Neural Collapse metrics during training.