Args:
attributions (Dict[str, torch.Tensor]): Neuron attributions per layer.
input_text (str): The input string.
top_k (int): Number of top neurons visualized per layer.
max_layers (int): Maximum number of layers to visualize.
"""
try:
layers = list(attributions.keys())
num_layers = len(layers)
if num_layers == 0:
print("No attributions to visualize.", file=sys.stderr)
return
# Limit the number of layers to visualize
if num_layers > max_layers:
print(
f"Number of layers ({num_layers}) exceeds max_layers ({max_layers}). "
f"Only the first {max_layers} layers will be visualized.",
file=sys.stderr,
)
layers = layers[:max_layers]
num_layers = max_layers
# Calculate appropriate vertical_spacing
vertical_spacing = min(0.05, 1 / (num_layers - 1)) if num_layers > 1 else 0
fig = make_subplots(
rows=num_layers,
cols=1,
subplot_titles=layers,
vertical_spacing=vertical_spacing,
)
for idx, layer in enumerate(layers, start=1):
data = attributions[layer].numpy()
neurons = list(range(len(data)))
fig.add_trace(
go.Bar(
x=neurons,
y=data,
marker=dict(color=data, colorscale="Viridis"),
showlegend=False,
),
row=idx,
col=1,
)
fig.update_yaxes(title_text="Attribution", row=idx, col=1)
fig.update_xaxes(title_text="Neuron Index", row=idx, col=1)
# Adjust the figure height based on the number of layers
fig.update_layout(
title=f"Top {top_k} Neuron Attributions for Input: \"{input_text}\"",
height=1000 * num_layers if num_layers > 0 else 600,
showlegend=False,
hovermode="closest",
)
fig.show()
except Exception as e:
print(f"Error during visualization: {e}", file=sys.stderr)
raise
Certainly! Below is the refactored visualize_attributions function adhering to your instructions. The improvements include:
PEP-8 Compliance: The code is formatted according to PEP-8 standards for better readability and maintainability.
Type Hinting: Utilized the typing module for clear type annotations.
Optimization: Efficiently handles large datasets by limiting the number of layers and neurons visualized.
Comprehensive Error Handling: Catches and logs specific exceptions with meaningful messages.
Enhanced Plot Aesthetics: Improved the Plotly visualization with better titles, axis labels, and a more professional appearance.
python
import sys
from typing import Dict
import torch
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def visualize_attributions(
attributions: Dict[str, torch.Tensor],
input_text: str,
top_k: int,
max_layers: int = 20
) -> None:
"""
Visualize neuron attributions using Plotly.
Args:
attributions (Dict[str, torch.Tensor]): Neuron attributions per layer.
input_text (str): The input string.
top_k (int): Number of top neurons visualized per layer.
max_layers (int): Maximum number of layers to visualize.
"""
try:
layers = list(attributions.keys())
num_layers = len(layers)
if num_layers == 0:
print("No attributions to visualize.", file=sys.stderr)
return
# Limit the number of layers to visualize
if num_layers > max_layers:
print(
f"Number of layers ({num_layers}) exceeds max_layers ({max_layers}). "
f"Only the first {max_layers} layers will be visualized.",
file=sys.stderr,
)
layers = layers[:max_layers]
num_layers = max_layers
# Calculate appropriate vertical spacing
vertical_spacing = min(0.05, 1 / (num_layers - 1)) if num_layers > 1 else 0
fig = make_subplots(
rows=num_layers,
cols=1,
subplot_titles=layers,
vertical_spacing=vertical_spacing,
)
for idx, layer in enumerate(layers, start=1):
data_tensor = attributions[layer]
if not isinstance(data_tensor, torch.Tensor):
print(
f"Attribution data for layer '{layer}' is not a torch.Tensor.",
file=sys.stderr
)
continue
data = data_tensor.cpu().detach().numpy()
top_indices = data.argsort()[-top_k:][::-1]
top_values = data[top_indices]
neurons = top_indices.tolist()
fig.add_trace(
go.Bar(
x=neurons,
y=top_values,
marker=dict(color=top_values, colorscale="Viridis"),
showlegend=False,
hovertemplate='Neuron %{x}: %{y:.4f}',
),
row=idx,
col=1,
)
fig.update_yaxes(
title_text="Attribution",
row=idx,
col=1,
showgrid=True,
gridcolor='LightGrey',
titlefont=dict(size=12),
tickfont=dict(size=10)
)
fig.update_xaxes(
title_text="Neuron Index",
row=idx,
col=1,
tickmode='linear',
tick0=neurons[0],
dtick=1,
titlefont=dict(size=12),
tickfont=dict(size=10)
)
# Adjust the figure height based on the number of layers
fig.update_layout(
title={
'text': f"Top {top_k} Neuron Attributions for Input: \"{input_text}\"",
'y': 0.95,
'x': 0.5,
'xanchor': 'center',
'yanchor': 'top'
},
height=400 * num_layers if num_layers > 0 else 600,
showlegend=False,
hovermode="closest",
template="plotly_white",
margin=dict(t=100),
)
fig.update_layout(
font=dict(
family="Arial, sans-serif",
size=12,
color="Black"
)
)
fig.show()
except Exception as e:
print(f"Error during visualization: {e}", file=sys.stderr)
raise
Key Enhancements Explained
PEP-8 Compliance:
Proper indentation and spacing.
Line lengths kept within 79 characters where possible.
Meaningful variable names and comments for clarity.
Type Hinting:
Used Dict[str, torch.Tensor] for the attributions parameter to clearly define expected input types.
Error Handling:
Checks if each attribution entry is a torch.Tensor. If not, it logs an error message and continues with the next layer.
General exception handling to catch unexpected errors during visualization.
Optimized Data Handling:
Converts tensors to NumPy arrays using .cpu().detach().numpy() to ensure compatibility and avoid potential GPU memory issues.
Visualizes only the top k neurons by sorting the attributions and selecting the highest values. This reduces clutter and focuses on the most significant neurons.
Enhanced Plot Aesthetics:
Titles and Labels:
Added a centralized and stylized main title.
Updated axis titles with better font sizes and styles.
Colors and Themes:
Used the "Viridis" colorscale for better visual appeal.
Applied the "plotly_white" template for a clean and professional look.
Layout Adjustments:
Dynamically adjusted the figure height based on the number of layers to ensure each subplot has adequate space.
Added grid lines for better readability.
Customized font types and sizes for consistency and professionalism.
Hover Information:
Enhanced hover templates to display neuron index and attribution value with formatting.
Scalability and Performance:
Limits the number of layers to max_layers to prevent performance degradation when dealing with models with a large number of layers.
Limits the number of neurons visualized per layer to top_k for scalability.
Usage Example
python
import torch
# Example attributions
example_attributions = {
'Layer 1': torch.rand(100),
'Layer 2': torch.rand(100),
'Layer 3': torch.rand(100),
# Add more layers as needed
}
input_text_example = "Sample input text for attribution visualization."
top_k_neurons = 10
visualize_attributions(
attributions=example_attributions,
input_text=input_text_example,
top_k=top_k_neurons,
max_layers=5
)
This example will visualize the top 10 neuron attributions for up to 5 layers, providing a clear and professional-looking Plotly visualization.
Dependencies
Ensure you have the necessary libraries installed:
bash
pip install torch plotly
Conclusion
The refactored function is now more robust, readable, and professional. It efficiently handles large datasets, provides meaningful error messages, and produces a visually appealing Plotly graph that adheres to best practices in Python programming.