Package: torchexplorer
Made bySamuel Pfrommeras part ofSomayeh Sojoudi's groupat Berkeley.Try it yourself.Curious about what's happening in your network? TorchExplorer is a simple tool that allows you to interactively inspect the inputs, outputs, parameters, and gradients for eachnn.Modulein your network during training. It integrates withweights and biasesand can also operate locally as a standalone solution. If your use case fits (see limitations below), it's very simple to try:torchexplorer.setup()# Call once before wandb.init(), not needed for standalonewandb.init()model=...torchexplorer.watch(model,backend='wandb')# Or 'standalone'# Training loop...InstallInstalling requires one externalgraphvizdependency, which should be available on most package managers.Linux.sudoapt-getinstalllibgraphviz-devgraphviz
pipinstalltorchexplorerIf thepygraphvizwheel build fails because it can't findPython.h, you must install the python header files as describedhere.Mac.brewinstallgraphviz
pipinstalltorchexplorerIf there's an error regarding#include "graphviz/cgraph.h",the followingworked for me on Apple silicon:python-mpipinstall\--global-option=build_ext\--global-option="-I$(brew--prefixgraphviz)/include/"\--global-option="-L$(brew--prefixgraphviz)/lib/"\pygraphvizUsageFor more examples, see/testsand/examples.Examine model structure.TorchExplorer's interactive view of the model structure is also useful in its own right (without the histogram bells-and-whistles). Here's a self-contained example for how to get an interactive view of a ResNet18. Mousing over a particular node reveals input/output tensor shapes and Module parameters. Get a feel for what this looks likewith an interactive demo.importtorchimporttorchvisionimporttorchexplorermodel=torchvision.models.resnet18(pretrained=False)dummy_X=torch.randn(5,3,32,32)# Only log input/output and parameter histograms, if you don't want these set log=[].torchexplorer.watch(model,log_freq=1,log=['io','params'],backend='standalone')# To log also gradients, set log = ['io', 'io_grad', 'params', 'params_grad'] (default).# This doesn't work with in-place operations (see "Common errors #1" in README.md).# So we must disable in-place activations, and ignore modules with residual connections.# Here we're using random data on an untrained model, so gradients aren't very useful.# residual_class = torchvision.models.resnet.BasicBlock# torchexplorer.watch(#     model, log_freq=1, disable_inplace=True,#     log=['io', 'io_grad', 'params', 'params_grad'],#     ignore_io_grad_classes=[residual_class], backend='standalone'# )# Do one forwards and backwards passmodel(dummy_X).sum().backward()# Your model will be available at http://localhost:8080Visualize intermediate tensors.TorchExplorer automatically captures any Module inputs/outputs. Usingtorchexplorer.attach, you can also log any intermediate tensors to the interface.importtorchfromtorchimportnnimporttorchexplorerclassAttachModule(nn.Module):def__init__(self):super().__init__()self.fc1=nn.Linear(10,10)self.fc2=nn.Linear(10,10)defforward(self,x):x=self.fc1(x)x=torchexplorer.attach(x,self,'intermediate')returnself.fc2(x)model=AttachModule()dummy_X=torch.randn(5,10)torchexplorer.watch(model,log_freq=1,backend='standalone')model(dummy_X).sum().backward()# Your model will be available at http://localhost:8080More debugging use cases.TorchExplorer is meant to be a general-purpose tool to see what's happening in your network—somewhat analagous to an oscilloscope in electronics. This section lists some potential use cases.Checking if your model has vanishing / exploding gradients.Checking if inputs to a particular module are nicely distributed (if not, throw in a normalization layer).Catching bugs like using aReLUnonlinearity as the final layer when module outputs could potentially be negative.For multiple submodules whose outputs are combined, checking if gradients are flowing more to one or the other.If a module takes multiple inputs, seeing which input is more important by the relative grad norm size.Ensuring that latent space / embedding distributions look healthy (e.g., VAE latents are approximately normal).Usingtorchexplorer.attachto see whether gradients are mainly flowing through skip connections or the main network path.User interfaceExplorerThe left-hand panel contains a module-level graph of your network architecture, automatically extracted from the autograd graph. Clicking on a module will open its "internal" submodules. To return to a parent module, click on the appropriate element in the top-left expanding list.Nodes.A node in the explorer graph is either a) an input/output placeholder for the visualized module, or b) a specific invocation of a submodule of the visualized module. If the visualized module has multiple inputs to itsforwardfunction, these will appear as multiple nodes ("Input 0", "Input 1", ...). A similar logic applies to outputs. All other nodes represent a distinct submodule invocation. This means that if a particular submodule is called twice in one forwards pass, these two invocations show up separately in the explorer graph. Their histograms and "internal" submodules will also be distinct.Edges.An edge between two nodes means that there exists a autograd trace from some output of the parent node to some input of the child mode.The number of incoming / outgoing edges to a node is unrelated to how many inputs/outputs theforwardfunction takes.To illustrate this, let's consider aLinearnode with two incoming edges from two distinct parent nodes. This can arise if, say, the outputs of the parent modules are added together and then passed to the singleforwardfunction input. Conversely, consider aTransformerEncoderLayernode, which accepts multiple inputs. There may still only be one incoming edge from a parent module, if all the inputs to theTransformerEncoderLayerare computed from this source.Tooltips.Mousing over explorer graph nodes displays a helpful tooltip. The first few lines summarize the shapes of the input / output tensors, recorded once from the first forwards pass through the network. The subsequent lines parse key information frommodule.extra_repr(). This string parsing is designed around common PyTorchextra_repr()implementations (e.g.,nn.Conv2d). The string is first split on commas, with each resulting string becoming one row in the tooltip. If a resulting substring is of the form "{key}={value}", these become the key and value pairs for the tooltip. Otherwise the entire string is treated as a value with an empty key, visualized using a dash. This occurs for thein_channelsandout_channelsattributes forConv2d.PanelsTo inspect a module in more detail, just drag and drop it into one of the columns on the right. The histogram colors don't represent anything intrinsically—they're just to help identify in the explorer which modules are being visualized.HistogramsEach vertical "slice" of a histogram encodes the distribution of values at the corresponding x-axis time. The y-axis displays the minimum / maximum bounds of the histogram. Completely white squares mean that no data fell in that bin. A bin with one entry will be shaded light gray, with the color intensifying as more values fall in that bin (this encodes the "height" of the histogram). The dashed horizontal line is the $y=0$ line.[!NOTE]
The tensors populating histograms are processed in two ways. First, for performance reasons they are randomly subsampled according to thesample_nparameter. This is 100 by default, and passingNonewill disable sub-sampling. Note that this sampling means that histograms that should be the same may look slightly different (e.g., output of parent node and input of child node). Second, a fraction of the most extreme values from the median are rejected to prevent outliers from compressing the histogram. This fraction is 0.1 by default, and can be disabled by passing 0.0 to thereject_outlier_propertionparameter.For the following explanations, I'll be referencing this module:classTestModule(nn.Module):def__init__(self):super().__init__()self.fc=nn.Linear(20,20)self.activation=nn.ReLU()defforward(self,x):x1=self.fc(x)x2=self.activation(x1)returnx2Input/output histograms.These histograms represent the values passed into and out of the module'sforwardmethod, captured using hooks. For instance, if we are visualizing thefclayer in the aboveTestModule, theinput 0histogram will be the histogram ofx, and theoutput 0histogram will be the histogram ofx1. Iffcaccepted two inputsself.fc(x, y), then the histogram would showinput 0andinput 1. Note that theinput 0histogram on theactivationmodule will look very close to theoutput 0histogram on thefcmodule, with some small differences due to random sampling.Input/output gradient norm histograms.These histograms capture tensor gradients frombackwardpasses through the module. Unlike parameter gradients, we record here the $\ell_2$-norm of the gradients, averaged over the batch dimension. This means that if the gradient of the loss with respect to the module input is of dimension $b \times d_1 \times d_2$, we first flatten to a $b \times (d_1 \cdot d_2)$ vector and take the row-wise norm to get a length $b$ vector. These values then populate the histogram. For thefclayer in the above example,input 0 (grad norm)would apply this procedure to the gradient of the loss with respect tox, whileoutput 0 (grad norm)would apply this procedure to the gradient of the loss with respect toy.Parameter histograms.After the input/output histograms are extracted, all submodules will have their immediate parameters (module._parameters) logged as histograms. Note that this is not the same asmodule.parameters(), which would also recurse to include all child parameters. Some modules (particularly activations) have no parameters and nothing will show up in the interface. For instance,TestModuleabove has no trainable immediate parameters;fcwill haveweightandbiasparameters; andactivationwill again have nothing.Parameter gradient histograms.After thebackwardcall is completed, each parameter will have a.gradattribute storing the gradient of the loss with respect to that parameter. This tensor is directly passed to the histogram. Unlike the input/output gradients, no norms are computed.APIAPI documentation is availablehere. For wandb training, make sure to calltorchexplorer.setup()beforewandb.init().Features and limitationsNotes on some corner cases. If something isn't covered here, feel free to open a GitHub issue.SupportedPerforming multiple invocations of the same module is supported. Inputs/outputs will be displayed separately for each invocation, but the parameters and parameter gradients will of course be shared. So something like this should work:classTestModule(nn.Module):def__init__(self):super().__init__()self.fc=nn.Linear(20,20)self.activation=nn.ReLU()defforward(self,x):x=self.activation(x)x=self.fc(x)x=self.activation(x)returnxNondifferentiable operations which break the autograd graph are permissible and should not cause a crash. However, the resulting module-level graph will be correspondingly disconnected.Multiple inputs and outputs will display correctly (i.e., "Input 0", "Input 1", ...)Invoking.forward()multiple times in a single step before backpropping is supported, but you must passdelay_log_multibackward=True(disabled by default). So the following pseudocode should work:torchexplorer.watch(module,delay_log_multibackward=True)# ...# Within a training loop step:y_hat1=module(X1)y_hat2=module(X2)loss=(yhat1-y1).abs().sum()+(yhat2-y2).abs().sum()loss.backward()You'll see the superposition of the input/output histograms and input/output gradient histograms across the calls in the interface.UnsupportedAll logging is disabled while the model is inevalmode, and anyforwardcalls in this state are ignored completely.Recursive operations are not supported,andanything which dynamically changes the module-level control flow over training is not supported. For instance, something like this isn't permissible:ifx>0:returnself.module1(x)else:returnself.module2(x)Inplace operations are not supportedand should be corrected or filtered (see "Common errors" below).Keyword tensor arguments to theforwardmethod are not supported. Only positional arguments will be tracked. Behavior for keyword tensor arguments is untested as of now.The tool isn't usable in the "Workspace" section of wandb when multiple runs are selected. To inspect a model, you must first open the specific run that you want in wandb.Stopping and resumption of training runs is untested.Other notesWhen invoking a module,don't use themodule.forward(x)method. Always call the forward method asmodule(x). The former does not call the hooks thattorchexploreruses.Histograms will only be updated duringtraining, not validation. This is directly checked usingmodule.training. This means that if your validation dataset has a different distribution than your training dataset, what you see in the tool might not tell you what's going on during validation.Common errorsThis section includes some errors that I've run into. For something not covered here, feel free to open a GitHub issue.1. Inplace operations in the computational graphRuntimeError: Output 0 of BackwardHookFunctionBackward is a view and is being modified inplace...This indicates that an inplace operation is occurring somewhere in the computational graph, which messes with the input/output gradient capturing (io_grad) feature. This commonly comes from inplace activations (e.g.nn.ReLU(inplace=True)), or residual inplace additions (e.g.out += identity). If you don't care about gradients you can just omit'io_grad'inlogargument to thewatchfunction. Otherwise, there are two additional tools available. You can use thedisable_inplaceargument to automatically turn off theinplaceflag on all activations. If this still doesn't cut it, you must figure out what submodules are doing inplace operations and either manually fix them or pass those classes to theignore_io_grad_classesargument. For example, theBasicBlockin the torchvision resnet implementation has an inplace residual connection. TheReLUactivations in the resnet also haveinplace=True. So we would do the following:model=torchvision.models.resnet18(pretrained=False)watch(model,disable_inplace=True,ignore_io_grad_classes=[torchvision.models.resnet.BasicBlock])2. Weights and biases chart glitches"No data available." in the Custom Chart.This occasionally shows up for me in the weights and biases interface and seems to be a difficult-to-reproduce bug in their custom charts support. Sometimes waiting fixes it. If possible, just restarting training when you notice this. Also, make sure that your browser is up-to-date. Updating Chrome to the latest version fixed this for me completely."Something went wrong..." and Google Chrome crashes.It happens occasionally that the wandb website crashes with torchexplorer active. Reloading the page seems to always work. Again, this was completely fixed for me when I updated Chrome to the latest version.3. Graphviz overflow errors"Trapezoid overflow" error in the graphviz call.This is aknown bugin Graphviz 2.42.2, an ancient version which is still the default on most package managers. If you're getting this error, you can fix it by installing anewer release.4. Too many open filesOSError: [Errno 24] Too many open files: b'/proc'
...
wandb: WARNING Failed to cache... too many open filesThis is aknown bugin wandb when uploading many tables. The only workaround I have for now is to modify theulimitfrom the default of1024to50000by callingtorchexplorer.setup()beforewandb.init(). You can also try increasinglog_freqso that fewer tables are logged. If you're still getting issues, you might have to edit/etc/security/limits.confasdescribed here.Related toolsA partial list of some related tools. The first section concerns visualizing model structure, and the second section concerns visualizing parameters/activations during training. TorchExplorer combines these in an interactive way. TorchExplorer also stands out by only showing nested submodules if you click into a submodule, keeping the interface a little cleaner in my opinion.Model structure visualization.netrontorchvizhiddenlayertorchviewplotneuralnetParameter/activation visualization.wandb.watchtensorboard histograms