Create inspect_neural_networks.py

#683
Files changed (1) hide show
  1. tools/inspect_neural_networks.py +41 -0
tools/inspect_neural_networks.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from smolagents import tool
4
+
5
+ @tool
6
+ def ml_layer_analyzer(layer_type: str, input_shape: list, **kwargs) -> str:
7
+ """A tool that dynamically instantiates a PyTorch layer, simulates a forward pass,
8
+ and reports output shape and parameter count. Ideal for planning ML code.
9
+
10
+ Args:
11
+ layer_type: The exact string name of the PyTorch layer (e.g., 'Conv2d', 'Linear', 'LSTM').
12
+ input_shape: A list of integers representing the input tensor dimensions (e.g., [1, 3, 224, 224]).
13
+ **kwargs: Arbitrary keyword arguments needed to configure the layer (e.g., in_features=10, out_features=20, out_channels=64, kernel_size=3).
14
+ """
15
+ try:
16
+ # Resolve layer class from torch.nn
17
+ if not hasattr(nn, layer_type):
18
+ return f"Error: '{layer_type}' is not a valid layer type in torch.nn"
19
+
20
+ layer_cls = getattr(nn, layer_type)
21
+ layer_instance = layer_cls(**kwargs)
22
+
23
+ # Create a mock tensor based on input shape
24
+ mock_input = torch.randn(*input_shape)
25
+
26
+ # Simulate forward pass
27
+ with torch.no_grad():
28
+ output = layer_instance(mock_input)
29
+
30
+ # Handle unpacking if the output is a tuple (like RNNs/LSTMs)
31
+ if isinstance(output, tuple):
32
+ out_shape = str([list(o.shape) if hasattr(o, 'shape') else type(o) for o in output])
33
+ else:
34
+ out_shape = list(output.shape)
35
+
36
+ param_count = sum(p.numel() for p in layer_instance.parameters())
37
+
38
+ return f"Success! Layer: {layer_type} | Output Shape: {out_shape} | Total Parameters: {param_count}"
39
+
40
+ except Exception as e:
41
+ return f"Failed to analyze layer configuration. Error encountered: {str(e)}"