Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK : use we have advanced develop model visualization tools save in directory(all image all .html format) each and every 1d,2d,3d,4d,
generalised any model , nlp or computer vision
properly legend , labelling , colouring plots , very professional ,resuable code
reference code :
import torch
import torch.nn as nn
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import plotly.graph_objs as go
from plotly.subplots import make_subplots
from typing import Any, Dict
import logging
Configure logging for debugging and error tracking
class DynamicTensorModel(nn.Module):
"""
A PyTorch model that accepts a recursive key input and returns a tensor of varying dimensions.
It also visualizes the tensor using Plotly based on its dimensionality.
"""
code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
def __init__(self) -> None:
super(DynamicTensorModel, self).__init__()
def forward(self, key_input: Dict[str, Any]) -> torch.Tensor:
"""
Processes the recursive key input to generate a tensor.
Args:
key_input (Dict[str, Any]): A nested dictionary input.
Returns:
torch.Tensor: A tensor with dimensions based on the key input.
"""
try:
tensor = self.generate_tensor(key_input)
self.visualize_tensor(tensor, key_input)
return tensor
except Exception as e:
logger.error(f"Error in forward pass: {e}")
raise
def generate_tensor(self, key_input: Dict[str, Any], depth: int = 1) -> torch.Tensor:
"""
Recursively processes the key input to generate a tensor with varying dimensions.
Args:
key_input (Dict[str, Any]): A nested dictionary input.
depth (int, optional): Current depth of recursion. Defaults to 1.
Returns:
torch.Tensor: A tensor with dimensions based on recursion depth.
"""
if not isinstance(key_input, dict):
raise ValueError("Key input must be a dictionary.")
if not key_input:
raise ValueError("Key input dictionary is empty.")
# Base case: when the value is not a dictionary
for key, value in key_input.items():
if isinstance(value, dict):
return self.generate_tensor(value, depth + 1)
else:
# Create a tensor with dimension based on depth
size = 10 # arbitrary size for each dimension
dims = min(depth, 4) # Limit to 4D
shape = tuple([size] * dims)
logger.info(f"Generating a {dims}D tensor with shape {shape} based on key '{key}'.")
return torch.randn(shape)
# If all values are dictionaries, increase depth
size = 10
dims = min(depth, 4)
shape = tuple([size] * dims)
logger.info(f"Generating a {dims}D tensor with shape {shape} based on nested keys.")
return torch.randn(shape)
def visualize_tensor(self, tensor: torch.Tensor, key_input: Dict[str, Any]) -> None:
"""
Visualizes the tensor using Plotly based on its dimensionality.
Args:
tensor (torch.Tensor): The tensor to visualize.
key_input (Dict[str, Any]): The original key input for dynamic naming.
"""
dim = tensor.dim()
logger.info(f"Visualizing a tensor with {dim} dimensions.")
if dim == 1:
self._plot_1d(tensor, key_input)
elif dim == 2:
self._plot_2d(tensor, key_input)
elif dim == 3:
self._plot_3d(tensor, key_input)
elif dim == 4:
self._plot_4d(tensor, key_input)
else:
logger.warning(f"Tensors with {dim} dimensions are not supported for visualization.")
def _plot_1d(self, tensor: torch.Tensor, key_input: Dict[str, Any]) -> None:
"""Generates a simple 1D scatter plot."""
try:
x = torch.arange(tensor.size(0)).numpy()
y = tensor.numpy()
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='markers', name='1D Scatter'))
title = self._generate_title(key_input, "1D Scatter Plot")
fig.update_layout(title=title, xaxis_title='Index', yaxis_title='Value')
fig.show()
logger.info("1D scatter plot generated successfully.")
except Exception as e:
logger.error(f"Error plotting 1D tensor: {e}")
def _plot_2d(self, tensor: torch.Tensor, key_input: Dict[str, Any]) -> None:
"""Generates a standard 2D scatter plot."""
try:
if tensor.size(1) < 2:
raise ValueError("2D tensor must have at least two features for plotting.")
x = tensor[:, 0].numpy()
y = tensor[:, 1].numpy()
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='markers', name='2D Scatter'))
title = self._generate_title(key_input, "2D Scatter Plot")
fig.update_layout(title=title, xaxis_title='Feature 1', yaxis_title='Feature 2')
fig.show()
logger.info("2D scatter plot generated successfully.")
except Exception as e:
logger.error(f"Error plotting 2D tensor: {e}")
def _plot_3d(self, tensor: torch.Tensor, key_input: Dict[str, Any]) -> None:
"""Generates an interactive 3D scatter plot."""
try:
if tensor.size(1) < 3:
raise ValueError("3D tensor must have at least three features for plotting.")
x = tensor[:, 0].numpy()
y = tensor[:, 1].numpy()
z = tensor[:, 2].numpy()
fig = go.Figure(data=go.Scatter3d(
x=x, y=y, z=z,
mode='markers',
marker=dict(size=5),
name='3D Scatter'
))
title = self._generate_title(key_input, "3D Scatter Plot")
fig.update_layout(title=title,
scene=dict(
xaxis_title='Feature 1',
yaxis_title='Feature 2',
zaxis_title='Feature 3'
))
fig.show()
logger.info("3D scatter plot generated successfully.")
except Exception as e:
logger.error(f"Error plotting 3D tensor: {e}")
def _plot_4d(self, tensor: torch.Tensor, key_input: Dict[str, Any]) -> None:
"""Generates an advanced 3D scatter plot with a dynamic legend based on the key input."""
try:
if tensor.size(1) < 4:
raise ValueError("4D tensor must have at least four features for plotting.")
x = tensor[:, 0].numpy()
y = tensor[:, 1].numpy()
z = tensor[:, 2].numpy()
color_feature = tensor[:, 3].numpy()
# Create a color scale based on the fourth dimension
colorscale = 'Viridis'
fig = go.Figure(data=go.Scatter3d(
x=x, y=y, z=z,
mode='markers',
marker=dict(
size=5,
color=color_feature,
colorscale=colorscale,
opacity=0.8,
colorbar=dict(title='Feature 4')
),
name='4D Scatter'
))
title = self._generate_title(key_input, "4D Scatter Plot with Dynamic Legend")
fig.update_layout(title=title,
scene=dict(
xaxis_title='Feature 1',
yaxis_title='Feature 2',
zaxis_title='Feature 3'
))
fig.show()
logger.info("4D scatter plot generated successfully.")
except Exception as e:
logger.error(f"Error plotting 4D tensor: {e}")
def _generate_title(self, key_input: Dict[str, Any], plot_type: str) -> str:
"""
Generates a descriptive title based on the key input.
Args:
key_input (Dict[str, Any]): The original key input.
plot_type (str): The type of plot.
Returns:
str: A descriptive title.
"""
flat_keys = self._flatten_keys(key_input)
key_str = "_".join(flat_keys)
title = f"{plot_type} - Keys: {key_str}"
return title
def _flatten_keys(self, d: Dict[str, Any], parent_key: str = '', sep: str = '_') -> list:
"""
Flattens nested dictionary keys.
Args:
d (Dict[str, Any]): The dictionary to flatten.
parent_key (str, optional): The base key string. Defaults to ''.
sep (str, optional): Separator between keys. Defaults to '_'.
Returns:
list: A list of flattened key strings.
"""
items = []
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.extend(self._flatten_keys(v, new_key, sep=sep))
else:
items.append(new_key)
return items
class GPT2LayerVisualizer:
"""
A class to visualize activations of each layer in GPT2LMHeadModel using DynamicTensorModel.
"""
code
def __init__(self, model: GPT2LMHeadModel, tokenizer: GPT2Tokenizer) -> None:
self.model = model
self.tokenizer = tokenizer
self.dynamic_visualizer = DynamicTensorModel()
self.activations = {}
self.register_hooks()
def register_hooks(self) -> None:
"""
Registers forward hooks to capture activations from each layer.
"""
for name, module in self.model.named_modules():
if isinstance(module, (nn.Linear, nn.Embedding, nn.LayerNorm)):
module.register_forward_hook(self.get_activation(name))
logger.info(f"Hook registered for layer: {name}")
def get_activation(self, name: str):
"""
Returns a hook function that captures the output of a layer.
Args:
name (str): Name of the layer.
Returns:
function: A hook function.
"""
def hook(module, input, output):
self.activations[name] = output.detach().cpu()
logger.info(f"Activation captured for layer: {name}")
return hook
def visualize_activations(self, input_text: str) -> None:
"""
Processes the input text through the model and visualizes activations.
Args:
input_text (str): The input text to process.
"""
try:
inputs = self.tokenizer(input_text, return_tensors='pt')
logger.info(f"Input tokens: {inputs}")
with torch.no_grad():
self.model(**inputs)
for layer_name, activation in self.activations.items():
key_input = {'layer': layer_name}
tensor = self.process_activation(activation)
self.dynamic_visualizer.visualize_tensor(tensor, key_input)
except Exception as e:
logger.error(f"Error during visualization: {e}")
def process_activation(self, activation: torch.Tensor) -> torch.Tensor:
"""
Processes the activation tensor to match the visualization requirements.
Since GPT-2 activations are typically high-dimensional (e.g., [batch, sequence, hidden]),
we'll perform some aggregation or slicing to reduce dimensionality.
Args:
activation (torch.Tensor): The activation tensor.
Returns:
torch.Tensor: A processed tensor suitable for visualization.
"""
try:
# Example processing: take the first element in batch and sequence
tensor = activation[0, 0, :]
# If tensor is still multi-dimensional, apply mean across certain dimensions
if tensor.dim() > 1:
tensor = tensor.mean(dim=0)
# Ensure tensor is 1D for simplicity; adjust as needed
if tensor.dim() > 1:
tensor = tensor.view(-1)
return tensor
except Exception as e:
logger.error(f"Error processing activation tensor: {e}")
# Return a random tensor to avoid breaking visualization
return torch.randn(10)
def main():
# Initialize tokenizer and model
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')
model.eval()
code
# Initialize visualizer
visualizer = GPT2LayerVisualizer(model, tokenizer)
# Sample input text
input_text = "Once upon a time, in a land far away,"
# Visualize activations
visualizer.visualize_activations(input_text)
if name == "main":
main()
Certainly! Below is a comprehensive Python module designed to visualize model activations or outputs across various dimensions (1D to 4D) for any model, whether it's for Natural Language Processing (NLP) or Computer Vision (CV). This module adheres strictly to PEP-8 standards, utilizes appropriate typing for clarity, optimizes performance, includes robust error handling, and ensures scalability and maintainability.
Overview
Generality: The module is designed to work with any PyTorch model, capturing and visualizing activations or outputs from its layers.
Visualization: Supports 1D to 4D visualizations using Plotly, saving the plots as both image files (.png) and interactive HTML files.
Reusability: Offers a flexible framework that can be integrated into various projects with minimal adjustments.
Professional Quality: Ensures plots have proper legends, labels, and color schemes for clear and professional presentations.
import os
import torch
import torch.nn as nn
from typing import Any, Callable, Dict, List, Optional, Union
import plotly.graph_objs as go
import plotly.io as pio
from datetime import datetime
import logging
# Configure logging for debugging and error tracking
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ModelVisualizer:
"""
A class to capture activations from any PyTorch model's layers and visualize them.
"""
def __init__(
self,
model: nn.Module,
save_directory: str = "model_visualizations",
max_dimensions: int = 4,
color_scheme: str = "Viridis",
) -> None:
"""
Initializes the ModelVisualizer.
Args:
model (nn.Module): The PyTorch model to visualize.
save_directory (str, optional): Directory to save visualizations. Defaults to "model_visualizations".
max_dimensions (int, optional): Maximum dimensions to visualize. Defaults to 4.
color_scheme (str, optional): Color scheme for plots. Defaults to "Viridis".
"""
self.model = model
self.save_directory = save_directory
self.max_dimensions = max_dimensions
self.color_scheme = color_scheme
self.activations: Dict[str, torch.Tensor] = {}
self._validate_save_directory()
self.register_hooks()
def _validate_save_directory(self) -> None:
"""
Validates and creates the save directory if it does not exist.
"""
try:
os.makedirs(self.save_directory, exist_ok=True)
logger.info(f"Save directory '{self.save_directory}' is ready.")
except Exception as e:
logger.error(f"Failed to create save directory '{self.save_directory}': {e}")
raise
def register_hooks(self) -> None:
"""
Registers forward hooks to capture activations from eligible layers.
"""
for name, module in self.model.named_modules():
if isinstance(module, (nn.Linear, nn.Conv2d, nn.Embedding, nn.LayerNorm)):
module.register_forward_hook(self._get_activation(name))
logger.info(f"Hook registered for layer: {name}")
def _get_activation(self, layer_name: str) -> Callable:
"""
Creates a hook function to capture activations.
Args:
layer_name (str): Name of the layer.
Returns:
Callable: The hook function.
"""
def hook(module: nn.Module, input: Any, output: Any) -> None:
self.activations[layer_name] = output.detach().cpu()
logger.info(f"Activation captured for layer: {layer_name}")
return hook
def visualize_activations(self, input_data: Union[torch.Tensor, Any]) -> None:
"""
Processes the input data through the model and visualizes captured activations.
Args:
input_data (Union[torch.Tensor, Any]): The input data for the model.
"""
try:
self.model.eval()
with torch.no_grad():
if isinstance(input_data, torch.Tensor):
self.model(input_data)
else:
self.model(**input_data)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
layer_dir = os.path.join(self.save_directory, f"activations_{timestamp}")
os.makedirs(layer_dir, exist_ok=True)
for layer_name, activation in self.activations.items():
processed_tensor = self._process_activation(activation)
if processed_tensor is not None:
self._visualize_tensor(
tensor=processed_tensor,
layer_name=layer_name,
save_path=layer_dir,
)
except Exception as e:
logger.error(f"Error during visualization: {e}")
raise
def _process_activation(self, activation: torch.Tensor) -> Optional[torch.Tensor]:
"""
Processes the activation tensor to reduce dimensionality if necessary.
Args:
activation (torch.Tensor): The activation tensor.
Returns:
Optional[torch.Tensor]: The processed tensor suitable for visualization.
"""
try:
tensor = activation
# Remove batch dimension if present
if tensor.dim() > 1 and tensor.size(0) == 1:
tensor = tensor.squeeze(0)
# Further reduce dimensionality based on the maximum allowed dimensions
while tensor.dim() > self.max_dimensions:
tensor = tensor.mean(dim=0)
logger.info("Reduced tensor dimensionality by averaging.")
return tensor
except Exception as e:
logger.error(f"Error processing activation tensor: {e}")
return None
def _visualize_tensor(
self, tensor: torch.Tensor, layer_name: str, save_path: str
) -> None:
"""
Visualizes the tensor based on its dimensionality and saves the plot.
Args:
tensor (torch.Tensor): The tensor to visualize.
layer_name (str): Name of the layer.
save_path (str): Directory to save the visualization.
"""
try:
dim = tensor.dim()
if dim < 1 or dim > self.max_dimensions:
logger.warning(
f"Tensor with {dim} dimensions is not supported for visualization."
)
return
plot_function = {
1: self._plot_1d,
2: self._plot_2d,
3: self._plot_3d,
4: self._plot_4d,
}.get(dim, None)
if plot_function:
plot_function(tensor, layer_name, save_path)
logger.info(f"{dim}D plot for layer '{layer_name}' generated successfully.")
else:
logger.warning(
f"No plotting function available for tensor with {dim} dimensions."
)
except Exception as e:
logger.error(f"Error during tensor visualization: {e}")
def _plot_1d(
self, tensor: torch.Tensor, layer_name: str, save_path: str
) -> None:
"""
Generates and saves a 1D scatter plot.
Args:
tensor (torch.Tensor): 1D tensor.
layer_name (str): Name of the layer.
save_path (str): Directory to save the plot.
"""
try:
x = torch.arange(tensor.size(0)).numpy()
y = tensor.numpy()
fig = go.Figure(
data=go.Scatter(x=x, y=y, mode='markers', name='1D Scatter'),
layout=go.Layout(
title=f"1D Scatter Plot - Layer: {layer_name}",
xaxis_title='Index',
yaxis_title='Value',
),
)
self._save_plot(fig, layer_name, save_path, '1d_scatter')
except Exception as e:
logger.error(f"Error plotting 1D tensor for layer '{layer_name}': {e}")
def _plot_2d(
self, tensor: torch.Tensor, layer_name: str, save_path: str
) -> None:
"""
Generates and saves a 2D scatter plot.
Args:
tensor (torch.Tensor): 2D tensor.
layer_name (str): Name of the layer.
save_path (str): Directory to save the plot.
"""
try:
if tensor.size(0) < 2 and tensor.size(1) < 2:
raise ValueError("2D tensor must have at least two features for plotting.")
if tensor.dim() != 2:
raise ValueError("2D plot requires a 2-dimensional tensor.")
x = tensor[:, 0].numpy()
y = tensor[:, 1].numpy()
fig = go.Figure(
data=go.Scatter(x=x, y=y, mode='markers', name='2D Scatter'),
layout=go.Layout(
title=f"2D Scatter Plot - Layer: {layer_name}",
xaxis_title='Feature 1',
yaxis_title='Feature 2',
),
)
self._save_plot(fig, layer_name, save_path, '2d_scatter')
except Exception as e:
logger.error(f"Error plotting 2D tensor for layer '{layer_name}': {e}")
def _plot_3d(
self, tensor: torch.Tensor, layer_name: str, save_path: str
) -> None:
"""
Generates and saves a 3D scatter plot.
Args:
tensor (torch.Tensor): 3D tensor.
layer_name (str): Name of the layer.
save_path (str): Directory to save the plot.
"""
try:
if tensor.size(0) < 3 and tensor.size(1) < 3:
raise ValueError("3D tensor must have at least three features for plotting.")
if tensor.dim() != 2 or tensor.size(1) < 3:
raise ValueError("3D plot requires a 2-dimensional tensor with at least three features.")
x = tensor[:, 0].numpy()
y = tensor[:, 1].numpy()
z = tensor[:, 2].numpy()
fig = go.Figure(
data=go.Scatter3d(
x=x,
y=y,
z=z,
mode='markers',
marker=dict(size=5, color='blue', opacity=0.8),
name='3D Scatter'
),
layout=go.Layout(
title=f"3D Scatter Plot - Layer: {layer_name}",
scene=dict(
xaxis_title='Feature 1',
yaxis_title='Feature 2',
zaxis_title='Feature 3',
),
),
)
self._save_plot(fig, layer_name, save_path, '3d_scatter')
except Exception as e:
logger.error(f"Error plotting 3D tensor for layer '{layer_name}': {e}")
def _plot_4d(
self, tensor: torch.Tensor, layer_name: str, save_path: str
) -> None:
"""
Generates and saves a 4D scatter plot with color mapping based on the fourth dimension.
Args:
tensor (torch.Tensor): 4D tensor.
layer_name (str): Name of the layer.
save_path (str): Directory to save the plot.
"""
try:
if tensor.size(0) < 4 and tensor.size(1) < 4:
raise ValueError("4D tensor must have at least four features for plotting.")
if tensor.dim() != 2 or tensor.size(1) < 4:
raise ValueError("4D plot requires a 2-dimensional tensor with at least four features.")
x = tensor[:, 0].numpy()
y = tensor[:, 1].numpy()
z = tensor[:, 2].numpy()
color_feature = tensor[:, 3].numpy()
fig = go.Figure(
data=go.Scatter3d(
x=x,
y=y,
z=z,
mode='markers',
marker=dict(
size=5,
color=color_feature,
colorscale=self.color_scheme,
opacity=0.8,
colorbar=dict(title='Feature 4')
),
name='4D Scatter'
),
layout=go.Layout(
title=f"4D Scatter Plot - Layer: {layer_name}",
scene=dict(
xaxis_title='Feature 1',
yaxis_title='Feature 2',
zaxis_title='Feature 3',
),
),
)
self._save_plot(fig, layer_name, save_path, '4d_scatter')
except Exception as e:
logger.error(f"Error plotting 4D tensor for layer '{layer_name}': {e}")
def _save_plot(
self, fig: go.Figure, layer_name: str, save_path: str, plot_type: str
) -> None:
"""
Saves the plot as both PNG image and HTML file.
Args:
fig (go.Figure): The Plotly figure to save.
layer_name (str): Name of the layer.
save_path (str): Directory to save the plot.
plot_type (str): Type of plot (e.g., '1d_scatter').
"""
try:
# Sanitize layer name for file naming
sanitized_layer_name = layer_name.replace(".", "_").replace("/", "_")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Define file paths
png_filename = f"{sanitized_layer_name}_{plot_type}_{timestamp}.png"
html_filename = f"{sanitized_layer_name}_{plot_type}_{timestamp}.html"
png_path = os.path.join(save_path, png_filename)
html_path = os.path.join(save_path, html_filename)
# Save PNG image
pio.write_image(fig, png_path, format='png')
logger.info(f"Plot saved as image: {png_path}")
# Save HTML interactive plot
pio.write_html(fig, html_path, include_plotlyjs='cdn')
logger.info(f"Plot saved as HTML: {html_path}")
except Exception as e:
logger.error(f"Error saving plot for layer '{layer_name}': {e}")
def main():
"""
Demonstrates the usage of ModelVisualizer with a sample model and input.
"""
try:
# Example with GPT-2 (NLP Model)
from transformers import GPT2LMHeadModel, GPT2Tokenizer
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')
model.eval()
visualizer_nlp = ModelVisualizer(model=model, save_directory="visualizations_nlp")
input_text = "Once upon a time, in a land far away,"
inputs = tokenizer(input_text, return_tensors='pt')
visualizer_nlp.visualize_activations(inputs)
# Example with ResNet (Computer Vision Model)
from torchvision import models, transforms
from PIL import Image
# Initialize ResNet model
resnet = models.resnet18(pretrained=True)
resnet.eval()
# Define a sample input image
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
])
# Replace with your own image path
image_path = "sample_image.jpg"
if os.path.exists(image_path):
image = Image.open(image_path)
image_tensor = transform(image).unsqueeze(0) # Add batch dimension
else:
# Create a dummy image tensor if the image does not exist
image_tensor = torch.randn(1, 3, 224, 224)
visualizer_cv = ModelVisualizer(model=resnet, save_directory="visualizations_cv")
visualizer_cv.visualize_activations(image_tensor)
except ImportError as ie:
logger.error(f"Required modules are missing: {ie}")
except Exception as e:
logger.error(f"An error occurred in the main execution: {e}")
if __name__ == "__main__":
main()
Detailed Explanation
Imports and Logging Configuration:
Standard Libraries:os for directory operations, datetime for timestamps, and logging for logging events.
PyTorch Modules: Necessary for model operations and handling tensors.
Plotly: For creating interactive and static visualizations.
Type Hinting: Ensures clarity and better maintainability.
ModelVisualizer Class:
Initialization (__init__): Sets up the model, ensures the save directory exists, and registers hooks to capture activations from eligible layers (e.g., nn.Linear, nn.Conv2d, etc.).
Hook Registration (register_hooks & _get_activation): Attaches forward hooks to the model's layers to capture their outputs during the forward pass.
Activation Visualization (visualize_activations): Processes input data through the model, captures activations, and delegates visualization based on tensor dimensionality.
Tensor Processing (_process_activation): Reduces tensor dimensionality if it exceeds the maximum allowed dimensions, ensuring compatibility with visualization functions.
Visualization Functions (_plot_1d, _plot_2d, _plot_3d, _plot_4d): Create respective Plotly visualizations based on tensor dimensions, ensuring proper labeling, coloring, and legends.
Saving Plots (_save_plot): Saves each plot as both a PNG image and an interactive HTML file, organizing them within a timestamped directory for easy access.
main Function:
NLP Example: Demonstrates visualization using GPT-2 from the Hugging Face Transformers library. It tokenizes a sample input sentence and visualizes the activations.
CV Example: Demonstrates visualization using ResNet from PyTorch's torchvision models. It processes a sample image (or a dummy tensor if the image is absent) and visualizes the activations.
Error Handling: Catches and logs import errors or any unexpected exceptions during execution.
Execution Guard ():
Usage Instructions
Dependencies:
Ensure you have the necessary Python packages installed. You can install them using pip:
For the Computer Vision example using ResNet, replace "sample_image.jpg" with the path to your desired image. If the image is not found, the code will generate a dummy tensor for demonstration.
Running the Script:
Execute the script using Python:
bash
python model_visualizer.py
This will generate visualizations for both the NLP and CV models and save them in respective directories (visualizations_nlp and visualizations_cv).
Viewing the Visualizations:
Navigate to the respective directories to view the saved PNG images or open the HTML files in a browser for interactive visualizations.
Extensibility
Custom Models: You can integrate any PyTorch model by initializing the ModelVisualizer with your model instance.
Customization: Modify the ModelVisualizer parameters (like max_dimensions, color_scheme, and save_directory) as needed to fit your project's requirements.
Additional Plot Types: Extend the visualization capabilities by adding more plotting functions if you require support beyond 4D or different visualization styles.
Conclusion
This module provides a robust and flexible framework for visualizing model activations across different layers and dimensions. By adhering to Python's best practices and ensuring high code quality, it serves as a valuable tool for developers and researchers aiming to understand and interpret their machine learning models effectively.