Certainly! Below is the enhanced version of your Python script that visualizes neuron contributions in a more interactive and advanced manner. This version adheres strictly to PEP-8 standards, utilizes type hints effectively, optimizes performance, and incorporates comprehensive error handling. Additionally, it leverages Plotly's interactive features to allow users to explore neuron activations across different layers dynamically.
Overview of Enhancements:
- PEP-8 Compliance: The code is formatted according to Python's style guide for improved readability.
- Type Hints and
typing Module: Comprehensive type annotations are added for better clarity and maintainability.
- Performance Optimization: Efficient data handling ensures scalability for larger models and datasets.
- Advanced Visualization: Introduces interactive Plotly features such as dropdown menus and sliders to navigate through layers and highlight significant neuron activations.
- Robust Error Handling: Implements detailed exception management to ensure the program handles unexpected scenarios gracefully.
- Modular Design: Functions are well-organized to promote reusability and ease of understanding.
Enhanced Code:
import sys
from typing import Any, Dict, List, 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):
shape = tuple(param.shape)
trainable = param.requires_grad
num_params = param.numel()
parameters[name] = {
"shape": shape,
"trainable": trainable,
"num_params": num_params,
}
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)
contributions: Dict[str, torch.Tensor] = {}
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 identify_top_neurons(
contributions: torch.Tensor, top_k: int = 10
) -> List[int]:
"""
Identify the top K neurons with the highest activations.
Args:
contributions (torch.Tensor): Neuron activations.
top_k (int): Number of top neurons to identify.
Returns:
List of indices of top K neurons.
"""
try:
top_values, top_indices = torch.topk(contributions, top_k)
return top_indices.tolist()
except Exception as e:
print(f"Error identifying top neurons: {e}", file=sys.stderr)
return []
def visualize_contributions(
contributions: Dict[str, torch.Tensor],
input_text: str,
top_k: int = 10
) -> None:
"""
Visualize neuron contributions using Plotly with interactive controls.
Args:
contributions (Dict[str, torch.Tensor]): Neuron contributions per layer.
input_text (str): The input string.
top_k (int): Number of top neurons to highlight.
"""
try:
layers = list(contributions.keys())
num_layers = len(layers)
# Initialize Plotly figure with subplots
fig = make_subplots(
rows=1,
cols=num_layers,
subplot_titles=layers,
shared_yaxes=True,
horizontal_spacing=0.02,
)
# Store data for all layers
data_traces = []
top_neurons_indices = {}
for idx, layer in enumerate(layers):
data = contributions[layer].numpy()
top_neurons = identify_top_neurons(contributions[layer], top_k)
top_neurons_indices[layer] = top_neurons
trace = go.Bar(
x=list(range(len(data))),
y=data,
marker=dict(
color='rgba(100, 200, 102, 0.6)',
line=dict(color='rgba(100, 200, 102, 1.0)', width=1)
),
name=layer,
showlegend=False,
visible=True,
)
data_traces.append(trace)
# Add all traces to the figure
for trace in data_traces:
fig.add_trace(trace)
# Define buttons for highlighting top neurons
buttons = []
for layer in layers:
visibility = [False] * len(data_traces)
layer_idx = layers.index(layer)
visibility[layer_idx] = True
# Highlight top neurons by changing the color
highlight_trace = go.Bar(
x=list(range(len(contributions[layer]))),
y=contributions[layer].numpy(),
marker=dict(
color=[
'red' if i in top_neurons_indices[layer] else 'rgba(100, 200, 102, 0.6)'
for i in range(len(contributions[layer]))
],
line=dict(color='rgba(100, 200, 102, 1.0)', width=1)
),
name=f"Top {top_k} Neurons in {layer}",
showlegend=False,
visible=False,
)
fig.add_trace(highlight_trace)
# Update visibility for buttons
visibility_highlight = [False] * len(data_traces)
visibility_highlight[layer_idx] = True
visibility_highlight.append(True) # Highlight trace
for i in range(len(data_traces)):
if i != layer_idx:
visibility_highlight[i] = False
buttons.append(
dict(
label=layer,
method="update",
args=[
{"visible": [v for v in visibility_highlight]},
{"title": f"Neuron Contributions in {layer} for Input: \"{input_text}\""},
],
)
)
# Add play button to iterate through layers
sliders = [
{
"active": 0,
"steps": [
{
"label": layer,
"method": "update",
"args": [
{"visible": [layer == l for l in layers]},
{"title": f"Neuron Contributions in {layer} for Input: \"{input_text}\""},
],
}
for layer in layers
],
}
]
# Update layout with buttons and sliders
fig.update_layout(
title=f'Neuron Contributions for Input: "{input_text}"',
updatemenus=[
dict(
active=0,
buttons=buttons,
x=1.15,
y=1,
xanchor='left',
yanchor='top'
)
],
sliders=sliders,
height=600,
showlegend=False,
)
# Adjust axis labels
fig.update_xaxes(title_text="Neuron Index")
fig.update_yaxes(title_text="Activation", row=1, col=1)
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", top_k: int = 10) -> 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.
top_k (int): Number of top neurons to highlight.
"""
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, top_k=top_k)
except Exception as e:
print(f"An error occurred in the main workflow: {e}", file=sys.stderr)
if __name__ == "__main__":
# Example usage:
example_input = "Once upon a time"
main(example_input)
Detailed Explanation:
-
Loading the Model and Tokenizer (load_model_and_tokenizer):
- Functionality: Loads the specified pre-trained language model and its corresponding tokenizer using Hugging Face's
transformers library.
- Enhancements:
- Sets the model to evaluation mode using
model.eval() to deactivate dropout layers and other training-specific modules, ensuring consistent activation behaviors during inference.
- Comprehensive error handling to catch and report issues during loading.
-
Retrieving Neuron Parameters (get_neuron_parameters):
- Functionality: Gathers metadata about the model's parameters, such as shape, trainability, and the number of parameters.
- Enhancements:
- Maintains clarity through detailed documentation and type annotations.
- Robust error management to handle unexpected parameter structures.
-
Computing Neuron Contributions (compute_neuron_contributions):
- Functionality: Processes the input text through the model to obtain hidden states and computes the average activation for each neuron across tokens and batches.
- Enhancements:
- Utilizes
torch.no_grad() to disable gradient calculations, optimizing memory usage and computation speed during inference.
- Returns neuron activations in a CPU-compatible format for seamless integration with Plotly.
- Expanded error handling ensures graceful degradation in case of failures.
-
Identifying Top Neurons (identify_top_neurons):
- Functionality: Determines the top
k neurons with the highest activation values within a given layer.
- Enhancements:
- Parameterized
top_k allows flexibility in specifying the number of top neurons to highlight.
- Error handling ensures that issues during the ranking process are managed appropriately.
-
Visualizing Neuron Contributions (visualize_contributions):
- Functionality: Creates an interactive Plotly visualization displaying neuron activations across different layers. Incorporates features like dropdown menus and sliders to navigate layers and highlight top neurons.
Usage Instructions:
-
Prerequisites:
-
Running the Script:
-
Interacting with the Visualization:
- Upon execution, a Plotly window will display the neuron activations.
- Use the dropdown menu or slider to navigate through different layers.
- Observe the top contributing neurons highlighted in red for each selected layer.
Conclusion
This enhanced script provides a robust and interactive platform for visualizing neuron contributions within transformer-based language models. By adhering to best coding practices and incorporating advanced visualization techniques, it serves as a valuable tool for researchers and developers aiming to delve deeper into the inner workings of large-scale neural networks.