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 : Given folder save list of .html, .png files each tensor in that model (recusively) even model tensor may be 1d,2d,3d,4d,5d, tensor we should plot using plotly module
on each plot , x_axis, y_axis, labels, legend , title is mandatory,
note: meaningful plot scatter ,
import torch
from torch import nn
from typing import Optional
from rich.console import Console
from rich.table import Table
from rich.tree import Tree
from rich.panel import Panel
def model_summary(model: nn.Module) -> None:
"""
Generate a detailed summary of a PyTorch model, including the number of total,
trainable, and non-trainable parameters. Also, visually display the model architecture
using a tree structure.
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.
Args:
model (nn.Module): The PyTorch model to summarize.
Raises:
TypeError: If the input is not a PyTorch nn.Module.
"""
if not isinstance(model, nn.Module):
raise TypeError("Input must be a PyTorch nn.Module")
console = Console()
# Compute parameters' stats
total_params = sum(p.numel() for p in model.parameters())
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
non_trainable_params = total_params - trainable_params
# Create a caption for the model
model_caption = f"[bold cyan]{model.__class__.__name__}[/bold cyan]"
console.print(Panel(model_caption, expand=False))
# Create a summary table for the total parameters
total_params_table = Table(
title="Total Parameters Summary",
show_header=True,
header_style="bold magenta"
)
total_params_table.add_column("Category", style="cyan")
total_params_table.add_column("Count", style="green", justify="right")
total_params_table.add_row("Total Parameters", f"{total_params:,}")
total_params_table.add_row("Trainable Parameters", f"{trainable_params:,}")
total_params_table.add_row("Non-trainable Parameters", f"{non_trainable_params:,}")
console.print(total_params_table)
console.print(Panel("[italic]Summary of model's total parameters[/italic]", expand=False))
# Create a detailed table for the parameters
detailed_table = Table(
title="Detailed Parameter Summary",
show_lines=True
)
detailed_table.add_column("Parameter", style="cyan", no_wrap=True)
detailed_table.add_column("Shape", style="magenta")
detailed_table.add_column("Trainable", style="green")
detailed_table.add_column("Num Parameters", style="yellow", justify="right")
def add_module_to_table(module: nn.Module, prefix: Optional[str] = "") -> None:
"""
Recursively add model parameters to the detailed table.
Args:
module (nn.Module): A PyTorch module
prefix (Optional[str]): Prefix for parameter names, used for recursion.
"""
for name, param in module.named_parameters(recurse=False):
full_name = f"{prefix}.{name}" if prefix else name
shape = tuple(param.shape)
trainable = param.requires_grad
num_params = param.numel()
detailed_table.add_row(
full_name,
str(shape),
"[green]✓[/green]" if trainable else "[red]✗[/red]",
f"{num_params:,}"
)
for name, child in module.named_children():
child_prefix = f"{prefix}.{name}" if prefix else name
add_module_to_table(child, child_prefix)
add_module_to_table(model)
console.print(detailed_table)
console.print(Panel("[italic]Detailed breakdown of model's parameters[/italic]", expand=False))
# Create a rich Tree for the model architecture
def build_tree(module: nn.Module, prefix: Optional[str] = "") -> Tree:
"""
Recursively build a tree structure for the model architecture.
Args:
module (nn.Module): The module to represent in the tree.
prefix (Optional[str]): The prefix for the current module.
Returns:
Tree: A rich Tree representing the module architecture.
"""
root_name = prefix if prefix else module.__class__.__name__
tree = Tree(f"[bold]{root_name}[/bold]")
for name, child in module.named_children():
child_tree = build_tree(child, prefix=name)
tree.add(child_tree)
for name, param in module.named_parameters(recurse=False):
param_info = f"{name}: {tuple(param.shape)} {'(Trainable)' if param.requires_grad else '(Non-trainable)'}"
tree.add(f"[cyan]{param_info}[/cyan]")
return tree
architecture_tree = build_tree(model)
console.print("\n[bold yellow]Model Architecture[/bold yellow]")
console.print(architecture_tree)
console.print(Panel("[italic]Visual representation of the model's architecture[/italic]", expand=False))
Certainly! Below is a comprehensive Python module that accomplishes the specified task. This module recursively traverses a PyTorch model's tensors, generates scatter plots for each tensor using Plotly, and saves the plots as both .html and .png files in a specified directory. The code adheres strictly to PEP-8 standards, utilizes type hints for clarity, optimizes performance, and includes robust error handling to ensure reliability.
Overview
Module Structure:
Imports: Necessary standard and third-party libraries.
Helper Functions:
_flatten_tensor: Flattens tensors higher than 2D for plotting.
_ensure_directory: Ensures the output directory exists.
Main Function:
save_model_tensor_plots: The primary function that handles the traversal, plotting, and saving of tensor plots.
Example Usage:
Demonstrates how to use the module with a sample model.
Error Handling:
Comprehensive try-except blocks to catch and handle potential errors gracefully.
Validation of input parameters to prevent runtime issues.
Performance Considerations:
Efficient tensor handling to support large models.
Asynchronous file operations could be integrated for further optimization if needed.
Plot Customization:
Each plot includes mandatory elements: x-axis, y-axis, labels, legend, and title.
Scatter plots are used for meaningful visualization.
Complete Code
python
import os
from typing import Any, Optional, Union
import torch
from torch import nn
import plotly.graph_objs as go
from plotly.subplots import make_subplots
def _flatten_tensor(tensor: torch.Tensor) -> torch.Tensor:
"""
Flattens a tensor to 2D if it's higher than 2D.
Args:
tensor (torch.Tensor): The tensor to flatten.
Returns:
torch.Tensor: A 2D tensor.
"""
if tensor.dim() == 1:
return tensor.unsqueeze(1)
elif tensor.dim() == 2:
return tensor
else:
return tensor.view(tensor.size(0), -1)
def _ensure_directory(path: str) -> None:
"""
Ensures that the given directory exists. Creates it if it does not.
Args:
path (str): The directory path to ensure.
Raises:
OSError: If the directory cannot be created.
"""
try:
os.makedirs(path, exist_ok=True)
except OSError as e:
raise OSError(f"Failed to create directory {path}: {e}") from e
def save_model_tensor_plots(
model: nn.Module,
output_dir: str,
max_dim: int = 2
) -> None:
"""
Recursively traverses the model's tensors, plots each tensor using Plotly,
and saves the plots as .html and .png files in the specified directory.
Args:
model (nn.Module): The PyTorch model to traverse.
output_dir (str): The directory where plots will be saved.
max_dim (int): Maximum dimensions to plot directly. Higher dimensions will be flattened.
Raises:
TypeError: If model is not an instance of nn.Module.
ValueError: If output_dir is not a valid directory path.
"""
if not isinstance(model, nn.Module):
raise TypeError("The model must be an instance of torch.nn.Module.")
if not isinstance(output_dir, str) or not output_dir:
raise ValueError("The output directory must be a non-empty string.")
_ensure_directory(output_dir)
for name, param in model.named_parameters():
tensor = param.data.cpu().detach()
tensor_dim = tensor.dim()
try:
if tensor_dim == 0:
# Scalar tensor
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[0],
y=[tensor.item()],
mode='markers',
name='Scalar Value'
))
title = f"{name} (Scalar)"
fig.update_layout(
title=title,
xaxis_title="Index",
yaxis_title="Value",
legend_title="Legend"
)
else:
# Handle tensors with dimensions up to max_dim
if tensor_dim > max_dim:
tensor = _flatten_tensor(tensor)
current_dim = 2
else:
current_dim = tensor_dim
if current_dim == 1:
x = list(range(tensor.size(0)))
y = tensor.tolist()
fig = go.Figure()
fig.add_trace(go.Scatter(
x=x,
y=y,
mode='markers',
name=name
))
title = f"{name} (1D Tensor)"
fig.update_layout(
title=title,
xaxis_title="Index",
yaxis_title="Value",
legend_title="Legend"
)
elif current_dim == 2:
# For 2D tensors, plot each row as a separate scatter
fig = go.Figure()
num_rows = tensor.size(0)
for i in range(num_rows):
x = list(range(tensor.size(1)))
y = tensor[i].tolist()
fig.add_trace(go.Scatter(
x=x,
y=y,
mode='markers',
name=f"{name} Row {i}"
))
title = f"{name} (2D Tensor)"
fig.update_layout(
title=title,
xaxis_title="Dimension 1",
yaxis_title="Dimension 2",
legend_title="Legend"
)
else:
# For higher dimensions (after flattening)
fig = make_subplots(rows=1, cols=1)
for i in range(tensor.size(0)):
x = list(range(tensor.size(1)))
y = tensor[i].tolist()
fig.add_trace(go.Scatter(
x=x,
y=y,
mode='markers',
name=f"{name} Slice {i}"
))
title = f"{name} (Flattened Tensor)"
fig.update_layout(
title=title,
xaxis_title="Flattened Dimension 1",
yaxis_title="Flattened Dimension 2",
legend_title="Legend"
)
# Define file paths
safe_name = name.replace('.', '_').replace('/', '_')
html_path = os.path.join(output_dir, f"{safe_name}.html")
png_path = os.path.join(output_dir, f"{safe_name}.png")
# Save as HTML
fig.write_html(html_path)
# Save as PNG
fig.write_image(png_path)
except Exception as e:
print(f"Failed to plot tensor '{name}': {e}")
# Example Usage
if __name__ == "__main__":
# Sample model for demonstration
class SampleModel(nn.Module):
def __init__(self):
super(SampleModel, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=3)
self.fc1 = nn.Linear(16 * 6 * 6, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = torch.relu(self.conv1(x))
x = torch.flatten(x, 1)
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# Instantiate the model
model = SampleModel()
# Define output directory
output_directory = "model_tensor_plots"
# Save tensor plots
save_model_tensor_plots(model, output_directory)
Detailed Explanation
Helper Functions:
_flatten_tensor: This function ensures that tensors with dimensions higher than 2D are flattened to 2D for compatible plotting using scatter plots.
_ensure_directory: Before saving any plots, this function verifies that the specified output directory exists. If not, it attempts to create it. If directory creation fails, an OSError is raised with a meaningful message.
Main Function (save_model_tensor_plots):
Parameter Validation: The function first checks if the provided model is indeed an instance of nn.Module and whether the output_dir is a valid string.
Directory Preparation: Utilizes _ensure_directory to prepare the output directory.
Tensor Traversal: Iterates over all named parameters in the model using model.named_parameters().
Tensor Plotting:
Scalar Tensors: For tensors with dim() == 0, it creates a simple scatter plot with a single point.
1D Tensors: Plots each element against its index.
2D Tensors: Plots each row as a separate scatter trace with appropriate labeling.
Higher-Dimensional Tensors: Flattens tensors beyond 2D and plots each slice, ensuring that even high-dimensional tensors are represented meaningfully.
Plot Customization: Every plot includes a title, x-axis and y-axis labels, and a legend, adhering to the user's requirement for meaningful scatter plots.
Saving Plots: Each plot is saved in both .html and .png formats. Filenames are sanitized by replacing dots and slashes with underscores to prevent filesystem issues.
Error Handling: Any exceptions during plotting or saving are caught, and a message is printed indicating which tensor failed to plot, ensuring that the process continues smoothly for other tensors.
Example Usage:
Defines a SampleModel with convolutional and linear layers to demonstrate the module's functionality.
Instantiates the model and specifies an output directory named "model_tensor_plots".
Calls save_model_tensor_plots to generate and save the plots.
Potential Enhancements
Asynchronous Operations: For very large models, integrating asynchronous file operations could enhance performance.
Customization Options: Allow users to customize plot aesthetics (colors, marker sizes, etc.) through additional parameters.
Support for Other Plot Types: Depending on tensor characteristics, other plot types (like heatmaps for 2D tensors) might provide more insights.
Logging: Instead of printing errors, integrating a logging mechanism would be beneficial for larger projects.
Conclusion
This module provides a robust, efficient, and maintainable solution for visualizing and saving the tensors of a PyTorch model. By adhering to best practices and incorporating comprehensive error handling, it ensures reliability and ease of integration into various workflows.