pulsatrix 1.1.0
Loading...
Searching...
No Matches
pulsatrix::TorchvisionResNet Class Reference

torchvision's ResNet(BasicBlock, ...): a 7x7 stride-2 convolution, BatchNorm, ReLU and 3x3 stride-2 max pooling; four stages of basic blocks (two 3x3 convolutions with BatchNorm, and a 1x1 convolution with BatchNorm on the shortcut where the shape changes); global average pooling and a linear classifier. Input (N, 3, H, W), output (N, classes). More...

#include <vision_models.hpp>

Inheritance diagram for pulsatrix::TorchvisionResNet:
Collaboration diagram for pulsatrix::TorchvisionResNet:

Public Member Functions

 TorchvisionResNet (const ResNetConfig &config, DeviceBackend *backend)
 
std::vector< Module * > layers ()
 The top-level layers, in order: conv1, bn1, relu, maxpool, one per block, avgpool, flatten, fc. For ExplainerContext.
 
std::vector< std::unique_ptr< BatchNormFold > > fold_batch_norms ()
 Folds every BatchNorm into the convolution before it, until the returned objects are destroyed.
 
Tensor backward (const Tensor &grad_output) override
 Computes the gradient w.r.t. this module's input, given the gradient w.r.t. its output. Must be called after forward() – uses state cached from that call.
 
Tensor propagate_relevance (const Tensor &relevance_out, const LRPRuleConfig &config) override
 Computes this module's contribution to LRP relevance propagation.
 
OpType op_type () const override
 This module's operation-category tag, for ComputationGraph node tagging.
 
std::vector< NamedParamRef > named_parameters () override
 This module's trainable parameters, each with its hierarchical name – the one place a module declares its parameters (roadmap FND-1).
 
std::vector< NamedBufferRef > named_buffers () override
 This module's buffers: state a checkpoint must save that no optimizer updates.
 
std::optional< DeviceType > compute_device () const override
 The device this module computes on, so forward() can reject an input on another device before any kernel sees it (roadmap FND-8).
 
void set_training (bool training) override
 Sets this module's training/eval mode. Defaults to training (matches every mainstream framework's Module default).
 
const ResNetConfig & config () const
 
- Public Member Functions inherited from pulsatrix::Module
virtual ~Module ()=default
 
Tensor forward (const Tensor &input)
 Runs this module's forward computation.
 
std::pair< Tensor, NodeId > forward_traced (const Tensor &input, NodeId input_node, ComputationGraph &graph, Autograd &autograd)
 Runs forward() while also registering a ComputationGraph node (tagged with this module's op_type(), parented to input_node) and wiring an Autograd backward function that reuses this module's own backward() – the opt-in traced/explainable path, per Phase 2 Mission 0.
 
virtual bool supports_lrp_rule (LRPRule rule) const
 Whether propagate_relevance() implements rule (no silent fallback: callers such as ExplainerContext::relevance_pass() throw rather than run a module on a rule it does not implement).
 
virtual std::vector< NamedModuleRef > named_children ()
 This module's direct sub-modules, each under the prefix its parameters carry in named_parameters(), in the same order (TRN-7: how ApplyLora() finds a model's Linear layers). Default: none. NamedModules() walks the whole tree.
 
virtual std::vector< ParamRef > parameters ()
 This module's trainable parameters and their gradients, for an optimizer to update uniformly across module types.
 
void set_requires_grad (bool requires_grad, const std::string &prefix="")
 Freezes (false) or unfreezes (true) parameters by name (roadmap FND-2).
 
bool is_training () const
 Whether this module is currently in training mode.
 
virtual void release_activations ()
 Frees the tensors forward() kept for backward() and the relevance passes; containers release their children too. Inference that only needs the output calls it after each forward, so a deep model holds one layer's activations at a time (a 1024-token ESM-2 650M pass otherwise keeps over 10 GB of them).
 

Static Public Member Functions

static ResNetConfig ResNet18 ()
 ResNet18's config (11.7M parameters).
 

Protected Member Functions

Tensor forward_impl (const Tensor &input) override
 The actual forward computation. Called by forward() after precondition checks.
 

Detailed Description

torchvision's ResNet(BasicBlock, ...): a 7x7 stride-2 convolution, BatchNorm, ReLU and 3x3 stride-2 max pooling; four stages of basic blocks (two 3x3 convolutions with BatchNorm, and a 1x1 convolution with BatchNorm on the shortcut where the shape changes); global average pooling and a linear classifier. Input (N, 3, H, W), output (N, classes).

  • Parameter names are torchvision's (conv1.weight, layer2.0.downsample.0.weight, bn1.running_mean, fc.weight, ...), so LoadTorchvisionWeights() loads a converted state dict. torchvision's convolutions have no bias; theirs stay zero.
  • Explaining it: put it in eval mode, fold its BatchNorms into their convolutions for as long as you explain (fold_batch_norms(), Zennit's canonizer), and explain through ExplainerContext ctx(model.layers()) so a composite sees the stem, each block and the classifier as separate modules. Each block is a ResidualModule: relevance is split between its two branches in proportion to their contributions, as Zennit's ResNet canonizer does.

Constructor & Destructor Documentation

◆ TorchvisionResNet()

pulsatrix::TorchvisionResNet::TorchvisionResNet ( const ResNetConfig &  config,
DeviceBackend *  backend 
)
Exceptions
std::invalid_argumentfor an empty block list or a size < 1.

Member Function Documentation

◆ backward()

Tensor pulsatrix::TorchvisionResNet::backward ( const Tensor &  grad_output)
overridevirtual

Computes the gradient w.r.t. this module's input, given the gradient w.r.t. its output. Must be called after forward() – uses state cached from that call.

Parameters
grad_outputGradient w.r.t. this module's output.
Returns
Gradient w.r.t. this module's input.
Note
Promoted to the base class in Phase 2 Mission 0 – every existing subclass (LinearModule/ReluModule/Conv2DModule) already implemented this exact signature independently; making it virtual lets graph-wiring code (Module::forward_traced) call it polymorphically through a Module* without knowing the concrete subclass, the same way propagate_relevance already works.

Implements pulsatrix::Module.

◆ compute_device()

std::optional< DeviceType > pulsatrix::TorchvisionResNet::compute_device ( ) const
inlineoverridevirtual

The device this module computes on, so forward() can reject an input on another device before any kernel sees it (roadmap FND-8).

Returns
std::nullopt (the default) skips the check: a container whose layers check their own inputs, or a user module written before this existed. Every in-tree layer returns its device; EmbeddingModule doesn't, because it reads its indices through their own backend and so accepts them from any device.

Reimplemented from pulsatrix::Module.

◆ config()

const ResNetConfig & pulsatrix::TorchvisionResNet::config ( ) const
inline

◆ fold_batch_norms()

std::vector< std::unique_ptr< BatchNormFold > > pulsatrix::TorchvisionResNet::fold_batch_norms ( )

Folds every BatchNorm into the convolution before it, until the returned objects are destroyed.

Exceptions
std::invalid_argumentunless in eval mode.

◆ forward_impl()

Tensor pulsatrix::TorchvisionResNet::forward_impl ( const Tensor &  input)
overrideprotectedvirtual

The actual forward computation. Called by forward() after precondition checks.

Implements pulsatrix::Module.

◆ layers()

std::vector< Module * > pulsatrix::TorchvisionResNet::layers ( )

The top-level layers, in order: conv1, bn1, relu, maxpool, one per block, avgpool, flatten, fc. For ExplainerContext.

◆ named_buffers()

std::vector< NamedBufferRef > pulsatrix::TorchvisionResNet::named_buffers ( )
overridevirtual

This module's buffers: state a checkpoint must save that no optimizer updates.

Returns
{name, tensor} entries, named like named_parameters(), in a fixed order. Default: empty. BatchNormModule reports its running statistics; containers prefix their layers' buffers the way they prefix parameters.

Reimplemented from pulsatrix::Module.

◆ named_parameters()

std::vector< NamedParamRef > pulsatrix::TorchvisionResNet::named_parameters ( )
overridevirtual

This module's trainable parameters, each with its hierarchical name – the one place a module declares its parameters (roadmap FND-1).

Returns
{name, {value, grad}} entries pointing directly at this module's own members, in a fixed order. Names are unique within the module tree. Default: empty (a parameterless module like ReluModule needs no override).
Note
Override this, not parameters(): saving, loading, freezing by name and optimizer parameter groups all key on these names.

Reimplemented from pulsatrix::Module.

◆ op_type()

OpType pulsatrix::TorchvisionResNet::op_type ( ) const
inlineoverridevirtual

This module's operation-category tag, for ComputationGraph node tagging.

Returns
This module's OpType (see op_type.hpp's closed set).
Note
Added in Phase 2 Mission 0 alongside backward() – lets graph-wiring code tag nodes generically through a Module* rather than switching on concrete subclass.

Implements pulsatrix::Module.

◆ propagate_relevance()

Tensor pulsatrix::TorchvisionResNet::propagate_relevance ( const Tensor &  relevance_out,
const LRPRuleConfig &  config 
)
overridevirtual

Computes this module's contribution to LRP relevance propagation.

Parameters
relevance_outRelevance at this module's output.
configSelects the LRP rule variant.
Returns
Relevance at this module's input.

Implements pulsatrix::Module.

◆ ResNet18()

static ResNetConfig pulsatrix::TorchvisionResNet::ResNet18 ( )
inlinestatic

ResNet18's config (11.7M parameters).

◆ set_training()

void pulsatrix::TorchvisionResNet::set_training ( bool  training)
overridevirtual

Sets this module's training/eval mode. Defaults to training (matches every mainstream framework's Module default).

Note
Virtual since Phase 6 Mission 6 (SequentialModule) – Mission 5 originally shipped this as plain non-virtual state ("no composite container exists yet to cascade through"); SequentialModule overrides this to cascade to every contained layer, and needs virtual dispatch to do so correctly even when accessed through a Module* base pointer, not just its own concrete type.
BatchNormModule keeps running statistics in training mode and normalizes with them in eval mode; DropoutModule is the identity in eval mode. Call set_training(false) before explaining a model that has either, so a sample's explanation doesn't depend on the rest of its batch.

Reimplemented from pulsatrix::Module.


The documentation for this class was generated from the following file: