please provide a full implementation for Optimal Transport for Activation Matching, in pytorch. The goal is to generate permuations which leaves the neural network functionally unchanged but improves learning. I would like to apply it every few steps or every epoch when training.
Assistant
Sure! Below is a comprehensive PyTorch implementation for Optimal Transport for Activation Matching. This implementation includes:
Network Definition: A simple neural network with fully connected layers.
Activation Capture: Hooks to capture activations during forward passes.
Optimal Transport Permutation: Using the Hungarian algorithm to find the optimal neuron permutation based on activation statistics.
Permutation Application: Permuting the network's weights and biases to maintain functional equivalence.
Training Loop Integration: Applying the permutation every epoch to potentially improve learning.
Overview
The main idea is to:
Capture Activations: After each epoch, collect the mean activations of each neuron in a specific layer.
Compute Permutation: Use Optimal Transport (via the Hungarian algorithm) to find a permutation of neurons that best aligns the current activations with those from the previous epoch.
Apply Permutation: Reorder the neurons in the chosen layer and adjust connected weights to maintain the network's functionality.
Integrate into Training: Repeat this process every epoch to potentially improve learning dynamics.
Implementation
python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from scipy.optimize import linear_sum_assignment
import numpy as np
# 1. Define the Neural Network
class SimpleMLP(nn.Module):
def __init__(self, input_size=784, hidden_sizes=[256, 128], num_classes=10):
super(SimpleMLP, self).__init__()
self.layers = nn.ModuleList()
prev_size = input_size
for hidden_size in hidden_sizes:
self.layers.append(nn.Linear(prev_size, hidden_size))
self.layers.append(nn.ReLU())
prev_size = hidden_size
self.output_layer = nn.Linear(prev_size, num_classes)
def forward(self, x):
for layer in self.layers:
x = layer(x)
x = self.output_layer(x)
return x
# 2. Activation Hook Class
class ActivationCapturer:
def __init__(self, model, target_layer):
self.model = model
self.target_layer = target_layer
self.activations = None
self.hook = self.target_layer.register_forward_hook(self.save_activation)
def save_activation(self, module, input, output):
# Store the mean activation for each neuron
self.activations = output.detach().mean(dim=0) # Shape: [num_neurons]
def clear(self):
self.activations = None
def remove(self):
self.hook.remove()
# 3. Optimal Transport Permutation Function
def compute_optimal_permutation(activation_prev, activation_current):
"""
Computes the optimal permutation of neurons based on activation similarity.
Uses the Hungarian algorithm to minimize the cost matrix.
Args:
activation_prev (numpy.ndarray): Mean activations from the previous epoch. Shape: [N]
activation_current (numpy.ndarray): Mean activations from the current epoch. Shape: [N]
Returns:
permutation (numpy.ndarray): Permutation array where permutation[i] = j means neuron i -> j
"""
# Normalize activations
a = activation_prev / np.linalg.norm(activation_prev)
b = activation_current / np.linalg.norm(activation_current)
# Compute cost matrix (Euclidean distance)
cost_matrix = np.abs(a[:, np.newaxis] - b[np.newaxis, :])
row_ind, col_ind = linear_sum_assignment(cost_matrix)
permutation = col_ind
return permutation
# 4. Function to Permute Layer Weights and Biases
def permute_layer(layer, permutation):
"""
Permutes the neurons in a Linear or Conv2d layer based on the given permutation.
Args:
layer (nn.Linear or nn.Conv2d): The layer to permute.
permutation (numpy.ndarray): The permutation array.
"""
with torch.no_grad():
if isinstance(layer, nn.Linear):
# Permute output features
layer.weight.data = layer.weight.data[permutation, :]
if layer.bias is not None:
layer.bias.data = layer.bias.data[permutation]
elif isinstance(layer, nn.Conv2d):
# Permute output channels
layer.weight.data = layer.weight.data[permutation, :, :, :]
if layer.bias is not None:
layer.bias.data = layer.bias.data[permutation]
else:
raise NotImplementedError("Layer type not supported for permutation.")
# 5. Function to Permute Connected Layers
def permute_network(model, target_layer, permutation):
"""
Applies permutation to the target layer and adjusts the next linear layer accordingly.
Args:
model (nn.Module): The entire neural network model.
target_layer (nn.Module): The layer to permute.
permutation (numpy.ndarray): The permutation array.
"""
# Permute the target layer
permute_layer(target_layer, permutation)
# Find the index of the target layer in the model
layers = list(model.layers)
target_idx = layers.index(target_layer) if target_layer in layers else None
# If target_layer is found, permute the next Linear layer's input weights
if target_idx is not None and target_idx + 1 < len(layers):
next_layer = layers[target_idx + 1]
if isinstance(next_layer, nn.Linear):
with torch.no_grad():
next_layer.weight.data = next_layer.weight.data[:, permutation]
# Handle permutation for the output layer if target_layer is the last hidden layer
if isinstance(target_layer, nn.Linear) and target_layer == model.layers[-2]:
with torch.no_grad():
model.output_layer.weight.data = model.output_layer.weight.data[:, permutation]
# 6. Sample Data Preparation (Using MNIST-like Data)
def get_dummy_data(num_samples=1000, input_size=784, num_classes=10):
X = torch.randn(num_samples, input_size)
y = torch.randint(0, num_classes, (num_samples,))
dataset = TensorDataset(X, y)
loader = DataLoader(dataset, batch_size=64, shuffle=True)
return loader
# 7. Training Loop with Activation Matching
def train_with_activation_matching(model, dataloader, optimizer, criterion, device,
target_layer, epochs=10):
# Initialize activation capturer
capturer = ActivationCapturer(model, target_layer)
# Store previous activations
activation_prev = None
model.to(device)
model.train()
for epoch in range(epochs):
print(f"Epoch {epoch+1}/{epochs}")
for batch_idx, (data, targets) in enumerate(dataloader):
data, targets = data.to(device), targets.to(device)
optimizer.zero_grad()
outputs = model(data)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
# Clear capturer for the next batch
capturer.clear()
# After epoch, capture the mean activations
# To capture activation, perform a forward pass on the whole dataset
model.eval()
with torch.no_grad():
all_activations = []
for data, _ in dataloader:
data = data.to(device)
outputs = model(data)
if capturer.activations is not None:
all_activations.append(capturer.activations.cpu().numpy())
model.train()
# Compute mean activation for this epoch
if all_activations:
activation_current = np.mean(all_activations, axis=0) # Shape: [num_neurons]
else:
activation_current = None
if activation_prev is not None and activation_current is not None:
# Compute optimal permutation
permutation = compute_optimal_permutation(activation_prev, activation_current)
print(f"Applying permutation: {permutation}")
# Apply permutation to the network
permute_network(model, target_layer, permutation)
# Update previous activation
if activation_current is not None:
activation_prev = activation_current
# Remove the hook
capturer.remove()
# 8. Putting It All Together
def main():
# Hyperparameters
input_size = 784
hidden_sizes = [256, 128]
num_classes = 10
learning_rate = 1e-3
epochs = 10
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Initialize model, criterion, optimizer
model = SimpleMLP(input_size=input_size, hidden_sizes=hidden_sizes, num_classes=num_classes)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Get data
dataloader = get_dummy_data(num_samples=5000, input_size=input_size, num_classes=num_classes)
# Choose target layer for permutation (e.g., first hidden Linear layer)
target_layer = model.layers[0] # Assuming it's nn.Linear
# Train the model with activation matching
train_with_activation_matching(model, dataloader, optimizer, criterion, device,
target_layer, epochs=epochs)
print("Training completed.")
if __name__ == "__main__":
main()
Explanation
Network Definition (SimpleMLP):
A simple multilayer perceptron with two hidden layers and ReLU activations.
The forward method defines the forward pass through the network.
Activation Capturer (ActivationCapturer):
Utilizes forward hooks to capture the mean activation of the target layer after each forward pass.
Stores the activations which are later used to compute the permutation.
Optimal Transport Permutation (compute_optimal_permutation):
Normalizes the activation vectors from the previous and current epochs.
Computes a cost matrix based on the absolute difference between activations.
Uses the Hungarian algorithm (linear_sum_assignment) to find the optimal one-to-one permutation that minimizes the total cost.
permute_layer: Applies the permutation to the weights and biases of a given layer.
permute_network: Not only permutes the target layer but also adjusts the weights of the subsequent layer to maintain the network's functionality.
Data Preparation (get_dummy_data):
Generates dummy data resembling the MNIST dataset for demonstration purposes.
In practice, replace this with actual data loaders.
Training Loop (train_with_activation_matching):
For each epoch:
Trains the model on the entire dataset.
Captures the mean activations of the target layer.
After training, computes the permutation based on activations from the previous epoch.
Applies the permutation to the network.
This process encourages the network to reorder its neurons in a way that aligns activations across epochs, potentially smoothing the optimization landscape.
Main Function (main):
Sets up hyperparameters, initializes the model, optimizer, loss function, and data.
Specifies which layer to target for permutation.
Starts the training process with activation matching.
Notes
Layer Selection: In this example, the first hidden Linear layer is chosen as the target for permutation. Depending on the architecture and goals, you might want to target different layers or multiple layers.
Data Handling: The provided get_dummy_data function uses randomly generated data. Replace this with actual datasets (e.g., MNIST) as needed.
Performance Considerations: The permutation process involves some overhead, especially for large networks. Ensure that this is acceptable for your use case.
Extensibility: This implementation can be extended to handle different layer types (e.g., convolutional layers) and more sophisticated activation statistics beyond mean activations.
Conclusion
This implementation provides a foundational framework for integrating Optimal Transport-based activation matching into neural network training using PyTorch. By periodically permuting neurons to align activations, it aims to maintain functional equivalence while potentially enhancing the learning dynamics. Adjust and extend this framework based on the specific requirements and nuances of your application.