Certainly! Below is the enhanced version of your neuron contribution visualization tool. This version adheres strictly to PEP-8 standards, includes comprehensive type hints, optimizes performance, and incorporates advanced visualization techniques using Plotly. The visualization now highlights neurons based on their activation levels with an interactive color scale, making it easier to identify the most influential neurons.
Key Improvements:
- PEP-8 Compliance: The code is formatted according to PEP-8 standards for better readability and maintenance.
- Type Hints: Comprehensive type annotations are added using the
typing module to enhance code clarity.
- Optimized Performance: Efficient tensor operations are utilized to handle large datasets seamlessly.
- Robust Error Handling: Advanced exception handling ensures that errors are caught gracefully with meaningful messages.
- Enhanced Visualization: Interactive Plotly charts with color gradients highlight neuron activations, providing an intuitive understanding of contributions.
import sys
from typing import Any, Dict, Optional, Tuple
import torch
from torch.nn import Module
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
PreTrainedModel,
PreTrainedTokenizer,
)
import plotly.graph_objs as go
from plotly.subplots import make_subplots
def load_model_and_tokenizer(
model_name: str
) -> Tuple[PreTrainedModel, PreTrainedTokenizer]:
"""
Load the pre-trained model and tokenizer.
Args:
model_name (str): Name of the pre-trained model.
Returns:
Tuple containing the model and tokenizer.
"""
try:
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
model.eval() # Set model to evaluation mode
return model, tokenizer
except Exception as e:
print(f"Error loading model or tokenizer: {e}", file=sys.stderr)
raise
def get_neuron_parameters(
model: PreTrainedModel, recurse: bool = False
) -> Dict[str, Dict[str, Any]]:
"""
Retrieve model parameters with their metadata.
Args:
model (PreTrainedModel): The pre-trained model.
recurse (bool): Whether to recurse through submodules.
Returns:
Dictionary mapping parameter names to their metadata.
"""
parameters = {}
try:
for name, param in model.named_parameters(recurse=recurse):
parameters[name] = {
"shape": tuple(param.shape),
"trainable": param.requires_grad,
"num_params": param.numel(),
}
return parameters
except Exception as e:
print(f"Error retrieving parameters: {e}", file=sys.stderr)
raise
def compute_neuron_contributions(
model: PreTrainedModel, tokenizer: PreTrainedTokenizer, input_text: str
) -> Optional[Dict[str, torch.Tensor]]:
"""
Compute neuron contributions to each token.
Args:
model (PreTrainedModel): The pre-trained model.
tokenizer (PreTrainedTokenizer): The tokenizer.
input_text (str): The input string.
Returns:
Dictionary mapping layer names to their neuron activations.
"""
try:
inputs = tokenizer(input_text, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs, output_hidden_states=True)
hidden_states = outputs.hidden_states # Tuple of (layers + embedding)
# Aggregate neuron activations per layer
contributions = {}
for idx, layer_hidden in enumerate(hidden_states):
layer_name = f"Layer {idx}"
# Mean activation per neuron across tokens and batch
mean_activation = layer_hidden.mean(dim=(0, 1))
contributions[layer_name] = mean_activation.cpu()
return contributions
except Exception as e:
print(f"Error computing neuron contributions: {e}", file=sys.stderr)
return None
def visualize_contributions(
contributions: Dict[str, torch.Tensor], input_text: str
) -> None:
"""
Visualize neuron contributions using Plotly.
Args:
contributions (Dict[str, torch.Tensor]): Neuron contributions per layer.
input_text (str): The input string.
"""
try:
layers = list(contributions.keys())
num_layers = len(layers)
# Determine subplot grid size
cols = 1
rows = num_layers if num_layers <= 10 else 10 # Limit rows for readability
fig = make_subplots(
rows=rows,
cols=cols,
subplot_titles=layers[:rows],
vertical_spacing=0.02,
)
for idx, layer in enumerate(layers[:rows], start=1):
data = contributions[layer].numpy()
fig.add_trace(
go.Bar(
x=list(range(len(data))),
y=data,
marker=dict(
color=data,
colorscale='Viridis',
colorbar=dict(title="Activation"),
showscale=True if idx == 1 else False,
),
name=layer,
showlegend=False,
),
row=idx,
col=cols,
)
fig.update_layout(
title=f'Neuron Contributions for Input: "{input_text}"',
height=300 * rows,
showlegend=False,
template="plotly_dark",
)
fig.update_xaxes(title_text="Neuron Index")
fig.update_yaxes(title_text="Mean Activation")
fig.show()
except Exception as e:
print(f"Error during visualization: {e}", file=sys.stderr)
raise
def main(input_text: str, model_name: str = "gpt2") -> None:
"""
Main function to execute the workflow.
Args:
input_text (str): The input string to process.
model_name (str): The name of the pre-trained model.
"""
try:
model, tokenizer = load_model_and_tokenizer(model_name)
params = get_neuron_parameters(model)
print(f"Loaded model '{model_name}' with {len(params)} parameters.")
contributions = compute_neuron_contributions(model, tokenizer, input_text)
if contributions is None:
print("Failed to compute neuron contributions.", file=sys.stderr)
return
visualize_contributions(contributions, input_text)
except Exception as e:
print(f"An error occurred in the main workflow: {e}", file=sys.stderr)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Visualize neuron contributions in a language model."
)
parser.add_argument(
"input_text",
type=str,
help="The input text to analyze.",
)
parser.add_argument(
"--model_name",
type=str,
default="gpt2",
help="Name of the pre-trained model to use.",
)
args = parser.parse_args()
main(args.input_text, args.model_name)
Enhancements Explained:
-
Command-Line Interface (CLI): The argparse module is used to create a user-friendly CLI, allowing users to specify the input text and optionally choose a different pre-trained model.
-
Model Evaluation Mode: The model is set to evaluation mode using model.eval() to ensure that layers like dropout behave correctly during inference.
-
Interactive Color Scale: The colorscale parameter in Plotly's Bar plots is set to 'Viridis', and a color bar is added to indicate activation levels, enhancing interpretability.
-
Row Limitation in Visualization: To maintain readability, especially for models with many layers, the number of subplot rows is limited to 10. This can be adjusted as needed.
-
Dark Theme: The plotly_dark template is applied for better visual aesthetics, especially in environments where dark themes are preferred.
-
Informative Axis Titles: X and Y axes are labeled with "Neuron Index" and "Mean Activation" respectively to provide clear context to the plots.
-
Optimized Data Handling: Tensor operations are performed without tracking gradients (torch.no_grad()) to save memory and improve performance during inference.
-
Comprehensive Error Messages: Enhanced error handling ensures that any issues during loading, computation, or visualization are reported clearly to the user.
Usage Example:
To use this script, save it to a file (e.g., neuron_contribution_visualizer.py) and run it via the command line:
python neuron_contribution_visualizer.py "Once upon a time"
You can also specify a different model if desired:
python neuron_contribution_visualizer.py "Machine learning is fascinating." --model_name "gpt2-medium"
This will generate interactive bar charts for each layer of the specified model, highlighting neuron contributions to the processing of the input text.