Below is an example of how you can create a separate Python file (e.g., visualize_layers.py) to register hooks, collect activation statistics from your model’s layers, and generate visualizations. In this example, we register forward hooks for each module (e.g., each GNN layer and the post-readout MLP) and then plot histograms showing the distribution of activations, as well as print out some summary statistics (mean, standard deviation).
Feel free to adapt the code to fit your particular model structure and visualization needs.
# visualize_layers.py
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np
# Import your PreTrainGNN model (assume it's in the file model.py)
# from model import PreTrainGNN
# For illustration, suppose you defined a dummy PreTrainGNN model (replace this with your actual import)
class PreTrainGNN(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim,
heads=[1, 1, 1], layer_types=['gat'],
readout_type='mean', # Options: 'mean', 'max', 'add', or None
post_readout_layers=1):
super().__init__()
# Dummy layers for example purposes, replace with actual GNN layers
self.layers = nn.ModuleList([
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, output_dim)
])
self.post_mlp = nn.Identity()
def forward(self, x):
activations = {}
for idx, layer in enumerate(self.layers):
x = layer(x)
activations[f"layer_{idx}"] = x
x = self.post_mlp(x)
activations["post_mlp"] = x
return x, activations
def register_activation_hooks(model, storage_dict):
"""
Registers forward hooks on modules of interest so that their activations are stored
in storage_dict as {module_name: activation_numpy_array}.
"""
def get_hook(name):
def hook(module, input, output):
# Convert to numpy, flatten batch and other dims as needed.
# Avoid storing the input tuple.
activations = output.detach().cpu().numpy()
storage_dict.setdefault(name, []).append(activations)
return hook
# For demonstration, we hook each layer in model.layers and the post_mlp
for idx, layer in enumerate(model.layers):
layer.register_forward_hook(get_hook(f"layer_{idx}"))
model.post_mlp.register_forward_hook(get_hook("post_mlp"))
print("Activation hooks registered.")
def plot_activation_statistics(activation_storage):
"""
Visualizes activation statistics using histograms and prints basic stats.
"""
num_plots = len(activation_storage)
fig, axes = plt.subplots(num_plots, 1, figsize=(8, 3 * num_plots))
if num_plots == 1:
axes = [axes]
for ax, (layer_name, activations_list) in zip(axes, activation_storage.items()):
# Concatenate all activation arrays over batches
activations = np.concatenate(activations_list, axis=0)
# We'll flatten activation values (ignoring spatial dimensions, if any)
activations_flat = activations.flatten()
mean_val = np.mean(activations_flat)
std_val = np.std(activations_flat)
print(f"{layer_name}: mean={mean_val:.4f}, std={std_val:.4f}, min={np.min(activations_flat):.4f}, max={np.max(activations_flat):.4f}")
ax.hist(activations_flat, bins=50, color="skyblue", edgecolor="black")
ax.set_title(f"Activation Histogram for {layer_name}\n (mean={mean_val:.3f}, std={std_val:.3f})")
ax.set_xlabel("Activation Value")
ax.set_ylabel("Frequency")
plt.tight_layout()
plt.show()
def main():
# Create a dummy synthetic input matching your expected input dimensions.
batch_size = 16
input_dim = 10 # Adjust as needed
dummy_input = torch.randn(batch_size, input_dim)
# Initialize your model. Adjust the parameters as appropriate.
hidden_dim = 32
output_dim = 5
model = PreTrainGNN(input_dim=input_dim,
hidden_dim=hidden_dim,
output_dim=output_dim,
heads=[1, 1, 1],
layer_types=['gat', 'gat'],
readout_type='mean',
post_readout_layers=1)
# Switch the model to evaluation mode
model.eval()
# Dictionary to store activations captured by hooks
activation_storage = {}
# Register hooks into the model layers
register_activation_hooks(model, activation_storage)
# Run a forward pass and trigger the hooks
with torch.no_grad():
_ = model(dummy_input)
# Plot the activation statistics
plot_activation_statistics(activation_storage)
if __name__ == "__main__":
main()